1
0
mirror of https://github.com/d47081/qBittorrent.git synced 2025-02-02 18:04:32 +00:00

Combine qAsConst() with copyAsConst() to asConst()

This commit is contained in:
thalieht 2018-11-27 22:15:04 +02:00
parent 6b1d26d555
commit 1f36b8b89f
57 changed files with 199 additions and 202 deletions

View File

@ -498,7 +498,7 @@ QString wrapText(const QString &text, int initialIndentation = USAGE_TEXT_COLUMN
QStringList lines = {words.first()}; QStringList lines = {words.first()};
int currentLineMaxLength = wrapAtColumn - initialIndentation; int currentLineMaxLength = wrapAtColumn - initialIndentation;
for (const QString &word : copyAsConst(words.mid(1))) { for (const QString &word : asConst(words.mid(1))) {
if (lines.last().length() + word.length() + 1 < currentLineMaxLength) { if (lines.last().length() + word.length() + 1 < currentLineMaxLength) {
lines.last().append(' ' + word); lines.last().append(' ' + word);
} }

View File

@ -51,7 +51,7 @@ FileLogger::FileLogger(const QString &path, const bool backup, const int maxSize
this->deleteOld(age, ageType); this->deleteOld(age, ageType);
const Logger *const logger = Logger::instance(); const Logger *const logger = Logger::instance();
for (const Log::Msg &msg : copyAsConst(logger->getMessages())) for (const Log::Msg &msg : asConst(logger->getMessages()))
addLogMessage(msg); addLogMessage(msg);
connect(logger, &Logger::newLogMessage, this, &FileLogger::addLogMessage); connect(logger, &Logger::newLogMessage, this, &FileLogger::addLogMessage);
@ -88,7 +88,7 @@ void FileLogger::deleteOld(const int age, const FileLogAgeType ageType)
QDateTime date = QDateTime::currentDateTime(); QDateTime date = QDateTime::currentDateTime();
QDir dir(Utils::Fs::branchPath(m_path)); QDir dir(Utils::Fs::branchPath(m_path));
for (const QFileInfo &file : copyAsConst(dir.entryInfoList(QStringList("qbittorrent.log.bak*"), QDir::Files | QDir::Writable, QDir::Time | QDir::Reversed))) { for (const QFileInfo &file : asConst(dir.entryInfoList(QStringList("qbittorrent.log.bak*"), QDir::Files | QDir::Writable, QDir::Time | QDir::Reversed))) {
QDateTime modificationDate = file.lastModified(); QDateTime modificationDate = file.lastModified();
switch (ageType) { switch (ageType) {
case DAYS: case DAYS:

View File

@ -199,7 +199,7 @@ namespace
for (auto i = categories.cbegin(); i != categories.cend(); ++i) { for (auto i = categories.cbegin(); i != categories.cend(); ++i) {
const QString &category = i.key(); const QString &category = i.key();
for (const QString &subcat : copyAsConst(Session::expandCategory(category))) { for (const QString &subcat : asConst(Session::expandCategory(category))) {
if (!expanded.contains(subcat)) if (!expanded.contains(subcat))
expanded[subcat] = ""; expanded[subcat] = "";
} }
@ -610,7 +610,7 @@ void Session::setTempPathEnabled(bool enabled)
{ {
if (enabled != isTempPathEnabled()) { if (enabled != isTempPathEnabled()) {
m_isTempPathEnabled = enabled; m_isTempPathEnabled = enabled;
for (TorrentHandle *const torrent : qAsConst(m_torrents)) for (TorrentHandle *const torrent : asConst(m_torrents))
torrent->handleTempPathChanged(); torrent->handleTempPathChanged();
} }
} }
@ -624,7 +624,7 @@ void Session::setAppendExtensionEnabled(bool enabled)
{ {
if (isAppendExtensionEnabled() != enabled) { if (isAppendExtensionEnabled() != enabled) {
// append or remove .!qB extension for incomplete files // append or remove .!qB extension for incomplete files
for (TorrentHandle *const torrent : qAsConst(m_torrents)) for (TorrentHandle *const torrent : asConst(m_torrents))
torrent->handleAppendExtensionToggled(); torrent->handleAppendExtensionToggled();
m_isAppendExtensionEnabled = enabled; m_isAppendExtensionEnabled = enabled;
@ -752,7 +752,7 @@ bool Session::addCategory(const QString &name, const QString &savePath)
return false; return false;
if (isSubcategoriesEnabled()) { if (isSubcategoriesEnabled()) {
for (const QString &parent : copyAsConst(expandCategory(name))) { for (const QString &parent : asConst(expandCategory(name))) {
if ((parent != name) && !m_categories.contains(parent)) { if ((parent != name) && !m_categories.contains(parent)) {
m_categories[parent] = ""; m_categories[parent] = "";
emit categoryAdded(parent); emit categoryAdded(parent);
@ -775,12 +775,12 @@ bool Session::editCategory(const QString &name, const QString &savePath)
m_categories[name] = savePath; m_categories[name] = savePath;
m_storedCategories = map_cast(m_categories); m_storedCategories = map_cast(m_categories);
if (isDisableAutoTMMWhenCategorySavePathChanged()) { if (isDisableAutoTMMWhenCategorySavePathChanged()) {
for (TorrentHandle *const torrent : copyAsConst(torrents())) for (TorrentHandle *const torrent : asConst(torrents()))
if (torrent->category() == name) if (torrent->category() == name)
torrent->setAutoTMMEnabled(false); torrent->setAutoTMMEnabled(false);
} }
else { else {
for (TorrentHandle *const torrent : copyAsConst(torrents())) for (TorrentHandle *const torrent : asConst(torrents()))
if (torrent->category() == name) if (torrent->category() == name)
torrent->handleCategorySavePathChanged(); torrent->handleCategorySavePathChanged();
} }
@ -790,7 +790,7 @@ bool Session::editCategory(const QString &name, const QString &savePath)
bool Session::removeCategory(const QString &name) bool Session::removeCategory(const QString &name)
{ {
for (TorrentHandle *const torrent : copyAsConst(torrents())) for (TorrentHandle *const torrent : asConst(torrents()))
if (torrent->belongsToCategory(name)) if (torrent->belongsToCategory(name))
torrent->setCategory(""); torrent->setCategory("");
@ -877,7 +877,7 @@ bool Session::addTag(const QString &tag)
bool Session::removeTag(const QString &tag) bool Session::removeTag(const QString &tag)
{ {
if (m_tags.remove(tag)) { if (m_tags.remove(tag)) {
for (TorrentHandle *const torrent : copyAsConst(torrents())) for (TorrentHandle *const torrent : asConst(torrents()))
torrent->removeTag(tag); torrent->removeTag(tag);
m_storedTags = m_tags.toList(); m_storedTags = m_tags.toList();
emit tagRemoved(tag); emit tagRemoved(tag);
@ -1085,7 +1085,7 @@ void Session::configure()
void Session::processBannedIPs(libt::ip_filter &filter) void Session::processBannedIPs(libt::ip_filter &filter)
{ {
// First, import current filter // First, import current filter
for (const QString &ip : copyAsConst(m_bannedIPs.value())) { for (const QString &ip : asConst(m_bannedIPs.value())) {
boost::system::error_code ec; boost::system::error_code ec;
libt::address addr = libt::address::from_string(ip.toLatin1().constData(), ec); libt::address addr = libt::address::from_string(ip.toLatin1().constData(), ec);
Q_ASSERT(!ec); Q_ASSERT(!ec);
@ -1770,7 +1770,7 @@ void Session::enableBandwidthScheduler()
void Session::populateAdditionalTrackers() void Session::populateAdditionalTrackers()
{ {
m_additionalTrackerList.clear(); m_additionalTrackerList.clear();
for (QString tracker : copyAsConst(additionalTrackers().split('\n'))) { for (QString tracker : asConst(additionalTrackers().split('\n'))) {
tracker = tracker.trimmed(); tracker = tracker.trimmed();
if (!tracker.isEmpty()) if (!tracker.isEmpty())
m_additionalTrackerList << tracker; m_additionalTrackerList << tracker;
@ -1781,7 +1781,7 @@ void Session::processShareLimits()
{ {
qDebug("Processing share limits..."); qDebug("Processing share limits...");
for (TorrentHandle *const torrent : copyAsConst(torrents())) { for (TorrentHandle *const torrent : asConst(torrents())) {
if (torrent->isSeed() && !torrent->isForced()) { if (torrent->isSeed() && !torrent->isForced()) {
if (torrent->ratioLimit() != TorrentHandle::NO_RATIO_LIMIT) { if (torrent->ratioLimit() != TorrentHandle::NO_RATIO_LIMIT) {
const qreal ratio = torrent->realRatio(); 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); m_nativeSession->remove_torrent(torrent->nativeHandle(), libt::session::delete_partfile);
#endif #endif
// Remove unwanted and incomplete files // Remove unwanted and incomplete files
for (const QString &unwantedFile : qAsConst(unwantedFiles)) { for (const QString &unwantedFile : asConst(unwantedFiles)) {
qDebug("Removing unwanted file: %s", qUtf8Printable(unwantedFile)); qDebug("Removing unwanted file: %s", qUtf8Printable(unwantedFile));
Utils::Fs::forceRemove(unwantedFile); Utils::Fs::forceRemove(unwantedFile);
const QString parentFolder = Utils::Fs::branchPath(unwantedFile); const QString parentFolder = Utils::Fs::branchPath(unwantedFile);
@ -2367,7 +2367,7 @@ void Session::exportTorrentFile(TorrentHandle *const torrent, TorrentExportFolde
void Session::generateResumeData(bool final) void Session::generateResumeData(bool final)
{ {
for (TorrentHandle *const torrent : qAsConst(m_torrents)) { for (TorrentHandle *const torrent : asConst(m_torrents)) {
if (!torrent->isValid()) continue; if (!torrent->isValid()) continue;
if (torrent->isChecking() || torrent->isPaused()) continue; if (torrent->isChecking() || torrent->isPaused()) continue;
if (!final && !torrent->needSaveResumeData()) continue; if (!final && !torrent->needSaveResumeData()) continue;
@ -2414,7 +2414,7 @@ void Session::saveResumeData()
void Session::saveTorrentsQueue() void Session::saveTorrentsQueue()
{ {
QMap<int, QString> queue; // Use QMap since it should be ordered by key QMap<int, QString> queue; // Use QMap since it should be ordered by key
for (const TorrentHandle *torrent : copyAsConst(torrents())) { for (const TorrentHandle *torrent : asConst(torrents())) {
// We require actual (non-cached) queue position here! // We require actual (non-cached) queue position here!
const int queuePos = torrent->nativeHandle().queue_position(); const int queuePos = torrent->nativeHandle().queue_position();
if (queuePos >= 0) if (queuePos >= 0)
@ -2422,7 +2422,7 @@ void Session::saveTorrentsQueue()
} }
QByteArray data; QByteArray data;
for (const QString &hash : qAsConst(queue)) for (const QString &hash : asConst(queue))
data += (hash.toLatin1() + '\n'); data += (hash.toLatin1() + '\n');
const QString filename = QLatin1String {"queue"}; const QString filename = QLatin1String {"queue"};
@ -2444,10 +2444,10 @@ void Session::setDefaultSavePath(QString path)
m_defaultSavePath = path; m_defaultSavePath = path;
if (isDisableAutoTMMWhenDefaultSavePathChanged()) if (isDisableAutoTMMWhenDefaultSavePathChanged())
for (TorrentHandle *const torrent : copyAsConst(torrents())) for (TorrentHandle *const torrent : asConst(torrents()))
torrent->setAutoTMMEnabled(false); torrent->setAutoTMMEnabled(false);
else else
for (TorrentHandle *const torrent : copyAsConst(torrents())) for (TorrentHandle *const torrent : asConst(torrents()))
torrent->handleCategorySavePathChanged(); torrent->handleCategorySavePathChanged();
} }
@ -2458,7 +2458,7 @@ void Session::setTempPath(QString path)
m_tempPath = path; m_tempPath = path;
for (TorrentHandle *const torrent : qAsConst(m_torrents)) for (TorrentHandle *const torrent : asConst(m_torrents))
torrent->handleTempPathChanged(); torrent->handleTempPathChanged();
} }
@ -3776,7 +3776,7 @@ void Session::handleTorrentTrackerWarning(TorrentHandle *const torrent, const QS
bool Session::hasPerTorrentRatioLimit() const bool Session::hasPerTorrentRatioLimit() const
{ {
for (TorrentHandle *const torrent : qAsConst(m_torrents)) for (TorrentHandle *const torrent : asConst(m_torrents))
if (torrent->ratioLimit() >= 0) return true; if (torrent->ratioLimit() >= 0) return true;
return false; return false;
@ -3784,7 +3784,7 @@ bool Session::hasPerTorrentRatioLimit() const
bool Session::hasPerTorrentSeedingTimeLimit() const bool Session::hasPerTorrentSeedingTimeLimit() const
{ {
for (TorrentHandle *const torrent : qAsConst(m_torrents)) for (TorrentHandle *const torrent : asConst(m_torrents))
if (torrent->seedingTimeLimit() >= 0) return true; if (torrent->seedingTimeLimit() >= 0) return true;
return false; return false;
@ -3928,7 +3928,7 @@ void Session::startUpTorrents()
QMap<int, TorrentResumeData> queuedResumeData; QMap<int, TorrentResumeData> queuedResumeData;
int nextQueuePosition = 1; int nextQueuePosition = 1;
int numOfRemappedFiles = 0; int numOfRemappedFiles = 0;
for (const QString &fastresumeName : qAsConst(fastresumes)) { for (const QString &fastresumeName : asConst(fastresumes)) {
const QRegularExpressionMatch rxMatch = rx.match(fastresumeName); const QRegularExpressionMatch rxMatch = rx.match(fastresumeName);
if (!rxMatch.hasMatch()) continue; if (!rxMatch.hasMatch()) continue;
@ -3967,7 +3967,7 @@ void Session::startUpTorrents()
} }
// starting up downloading torrents (queue position > 0) // starting up downloading torrents (queue position > 0)
for (const TorrentResumeData &torrentResumeData : qAsConst(queuedResumeData)) for (const TorrentResumeData &torrentResumeData : asConst(queuedResumeData))
startupTorrent(torrentResumeData); startupTorrent(torrentResumeData);
return; return;
@ -3989,7 +3989,7 @@ void Session::startUpTorrents()
fastresumes = queue + fastresumes.toSet().subtract(queue.toSet()).toList(); fastresumes = queue + fastresumes.toSet().subtract(queue.toSet()).toList();
} }
for (const QString &fastresumeName : qAsConst(fastresumes)) { for (const QString &fastresumeName : asConst(fastresumes)) {
const QRegularExpressionMatch rxMatch = rx.match(fastresumeName); const QRegularExpressionMatch rxMatch = rx.match(fastresumeName);
if (!rxMatch.hasMatch()) continue; if (!rxMatch.hasMatch()) continue;
@ -4554,7 +4554,7 @@ void Session::handleStateUpdateAlert(libt::state_update_alert *p)
} }
m_torrentStatusReport = TorrentStatusReport(); m_torrentStatusReport = TorrentStatusReport();
for (TorrentHandle *const torrent : qAsConst(m_torrents)) { for (TorrentHandle *const torrent : asConst(m_torrents)) {
if (torrent->isDownloading()) if (torrent->isDownloading())
++m_torrentStatusReport.nbDownloading; ++m_torrentStatusReport.nbDownloading;
if (torrent->isUploading()) if (torrent->isUploading())

View File

@ -110,7 +110,7 @@ void TorrentCreatorThread::run()
QStringList fileNames; QStringList fileNames;
QHash<QString, boost::int64_t> fileSizeMap; QHash<QString, boost::int64_t> fileSizeMap;
for (const auto &dir : qAsConst(dirs)) { for (const auto &dir : asConst(dirs)) {
QStringList tmpNames; // natural sort files within each dir QStringList tmpNames; // natural sort files within each dir
QDirIterator fileIter(dir, QDir::Files); QDirIterator fileIter(dir, QDir::Files);
@ -126,7 +126,7 @@ void TorrentCreatorThread::run()
fileNames += tmpNames; fileNames += tmpNames;
} }
for (const auto &fileName : qAsConst(fileNames)) for (const auto &fileName : asConst(fileNames))
fs.add_file(fileName.toStdString(), fileSizeMap[fileName]); fs.add_file(fileName.toStdString(), fileSizeMap[fileName]);
} }
@ -141,14 +141,14 @@ void TorrentCreatorThread::run()
#endif #endif
// Add url seeds // Add url seeds
for (QString seed : qAsConst(m_params.urlSeeds)) { for (QString seed : asConst(m_params.urlSeeds)) {
seed = seed.trimmed(); seed = seed.trimmed();
if (!seed.isEmpty()) if (!seed.isEmpty())
newTorrent.add_url_seed(seed.toStdString()); newTorrent.add_url_seed(seed.toStdString());
} }
int tier = 0; int tier = 0;
for (const QString &tracker : qAsConst(m_params.trackers)) { for (const QString &tracker : asConst(m_params.trackers)) {
if (tracker.isEmpty()) if (tracker.isEmpty())
++tier; ++tier;
else else

View File

@ -596,7 +596,7 @@ bool TorrentHandle::removeTag(const QString &tag)
void TorrentHandle::removeAllTags() void TorrentHandle::removeAllTags()
{ {
for (const QString &tag : copyAsConst(tags())) for (const QString &tag : asConst(tags()))
removeTag(tag); removeTag(tag);
} }

View File

@ -136,7 +136,7 @@ void Tracker::respondToAnnounceRequest()
QMap<QString, QByteArray> queryParams; QMap<QString, QByteArray> queryParams;
// Parse GET parameters // Parse GET parameters
using namespace Utils::ByteArray; using namespace Utils::ByteArray;
for (const QByteArray &param : copyAsConst(splitToViews(m_request.query, "&"))) { for (const QByteArray &param : asConst(splitToViews(m_request.query, "&"))) {
const int sepPos = param.indexOf('='); const int sepPos = param.indexOf('=');
if (sepPos <= 0) continue; // ignores params without name if (sepPos <= 0) continue; // ignores params without name

View File

@ -64,7 +64,7 @@ FileSystemWatcher::FileSystemWatcher(QObject *parent)
QStringList FileSystemWatcher::directories() const QStringList FileSystemWatcher::directories() const
{ {
QStringList dirs = QFileSystemWatcher::directories(); QStringList dirs = QFileSystemWatcher::directories();
for (const QDir &dir : qAsConst(m_watchedFolders)) for (const QDir &dir : asConst(m_watchedFolders))
dirs << dir.canonicalPath(); dirs << dir.canonicalPath();
return dirs; return dirs;
} }
@ -113,7 +113,7 @@ void FileSystemWatcher::scanLocalFolder(const QString &path)
void FileSystemWatcher::scanNetworkFolders() void FileSystemWatcher::scanNetworkFolders()
{ {
for (const QDir &dir : qAsConst(m_watchedFolders)) for (const QDir &dir : asConst(m_watchedFolders))
processTorrentsInDir(dir); processTorrentsInDir(dir);
} }

View File

@ -33,16 +33,13 @@
const char C_TORRENT_FILE_EXTENSION[] = ".torrent"; const char C_TORRENT_FILE_EXTENSION[] = ".torrent";
#if QT_VERSION < QT_VERSION_CHECK(5, 7, 0)
template <typename T> template <typename T>
constexpr typename std::add_const<T>::type &qAsConst(T &t) noexcept { return t; } constexpr typename std::add_const<T>::type &asConst(T &t) noexcept { return t; }
// prevent rvalue arguments: // Forward rvalue as const
template <typename T> template <typename T>
void qAsConst(const T &&) = delete; constexpr typename std::add_const<T>::type asConst(T &&t) noexcept { return std::move(t); }
#endif
// returns a const object copy // Prevent const rvalue arguments
template <typename T> template <typename T>
constexpr typename std::add_const<T>::type copyAsConst(T &&t) noexcept { return std::move(t); } void asConst(const T &&) = delete;

View File

@ -57,7 +57,7 @@ namespace
{ {
QDateTime now = QDateTime::currentDateTime(); QDateTime now = QDateTime::currentDateTime();
QList<QNetworkCookie> cookies = Preferences::instance()->getNetworkCookies(); QList<QNetworkCookie> cookies = Preferences::instance()->getNetworkCookies();
for (const QNetworkCookie &cookie : copyAsConst(Preferences::instance()->getNetworkCookies())) { for (const QNetworkCookie &cookie : asConst(Preferences::instance()->getNetworkCookies())) {
if (cookie.isSessionCookie() || (cookie.expirationDate() <= now)) if (cookie.isSessionCookie() || (cookie.expirationDate() <= now))
cookies.removeAll(cookie); cookies.removeAll(cookie);
} }
@ -69,7 +69,7 @@ namespace
{ {
QDateTime now = QDateTime::currentDateTime(); QDateTime now = QDateTime::currentDateTime();
QList<QNetworkCookie> cookies = allCookies(); QList<QNetworkCookie> cookies = allCookies();
for (const QNetworkCookie &cookie : copyAsConst(allCookies())) { for (const QNetworkCookie &cookie : asConst(allCookies())) {
if (cookie.isSessionCookie() || (cookie.expirationDate() <= now)) if (cookie.isSessionCookie() || (cookie.expirationDate() <= now))
cookies.removeAll(cookie); cookies.removeAll(cookie);
} }
@ -84,7 +84,7 @@ namespace
{ {
QDateTime now = QDateTime::currentDateTime(); QDateTime now = QDateTime::currentDateTime();
QList<QNetworkCookie> cookies = QNetworkCookieJar::cookiesForUrl(url); QList<QNetworkCookie> cookies = QNetworkCookieJar::cookiesForUrl(url);
for (const QNetworkCookie &cookie : copyAsConst(QNetworkCookieJar::cookiesForUrl(url))) { for (const QNetworkCookie &cookie : asConst(QNetworkCookieJar::cookiesForUrl(url))) {
if (!cookie.isSessionCookie() && (cookie.expirationDate() <= now)) if (!cookie.isSessionCookie() && (cookie.expirationDate() <= now))
cookies.removeAll(cookie); cookies.removeAll(cookie);
} }

View File

@ -292,7 +292,7 @@ QByteArray Smtp::encodeMimeHeader(const QString &key, const QString &value, QTex
if (!prefix.isEmpty()) line += prefix; if (!prefix.isEmpty()) line += prefix;
if (!value.contains("=?") && latin1->canEncode(value)) { if (!value.contains("=?") && latin1->canEncode(value)) {
bool firstWord = true; bool firstWord = true;
for (const QByteArray &word : copyAsConst(value.toLatin1().split(' '))) { for (const QByteArray &word : asConst(value.toLatin1().split(' '))) {
if (line.size() > 78) { if (line.size() > 78) {
rv = rv + line + "\r\n"; rv = rv + line + "\r\n";
line.clear(); line.clear();

View File

@ -506,7 +506,7 @@ void Preferences::setWebUiAuthSubnetWhitelistEnabled(bool enabled)
QList<Utils::Net::Subnet> Preferences::getWebUiAuthSubnetWhitelist() const QList<Utils::Net::Subnet> Preferences::getWebUiAuthSubnetWhitelist() const
{ {
QList<Utils::Net::Subnet> subnets; QList<Utils::Net::Subnet> subnets;
for (const QString &rawSubnet : copyAsConst(value("Preferences/WebUI/AuthSubnetWhitelist").toStringList())) { for (const QString &rawSubnet : asConst(value("Preferences/WebUI/AuthSubnetWhitelist").toStringList())) {
bool ok = false; bool ok = false;
const Utils::Net::Subnet subnet = Utils::Net::parseSubnet(rawSubnet.trimmed(), &ok); const Utils::Net::Subnet subnet = Utils::Net::parseSubnet(rawSubnet.trimmed(), &ok);
if (ok) if (ok)

View File

@ -241,7 +241,7 @@ void AutoDownloader::importRules(const QByteArray &data, AutoDownloader::RulesFi
QByteArray AutoDownloader::exportRulesToJSONFormat() const QByteArray AutoDownloader::exportRulesToJSONFormat() const
{ {
QJsonObject jsonObj; QJsonObject jsonObj;
for (const auto &rule : copyAsConst(rules())) for (const auto &rule : asConst(rules()))
jsonObj.insert(rule.name(), rule.toJsonObject()); jsonObj.insert(rule.name(), rule.toJsonObject());
return QJsonDocument(jsonObj).toJson(); return QJsonDocument(jsonObj).toJson();
@ -249,14 +249,14 @@ QByteArray AutoDownloader::exportRulesToJSONFormat() const
void AutoDownloader::importRulesFromJSONFormat(const QByteArray &data) void AutoDownloader::importRulesFromJSONFormat(const QByteArray &data)
{ {
for (const auto &rule : copyAsConst(rulesFromJSON(data))) for (const auto &rule : asConst(rulesFromJSON(data)))
insertRule(rule); insertRule(rule);
} }
QByteArray AutoDownloader::exportRulesToLegacyFormat() const QByteArray AutoDownloader::exportRulesToLegacyFormat() const
{ {
QVariantHash dict; QVariantHash dict;
for (const auto &rule : copyAsConst(rules())) for (const auto &rule : asConst(rules()))
dict[rule.name()] = rule.toLegacyDict(); dict[rule.name()] = rule.toLegacyDict();
QByteArray data; QByteArray data;
@ -276,7 +276,7 @@ void AutoDownloader::importRulesFromLegacyFormat(const QByteArray &data)
if (in.status() != QDataStream::Ok) if (in.status() != QDataStream::Ok)
throw ParsingError(tr("Invalid data format")); throw ParsingError(tr("Invalid data format"));
for (const QVariant &val : qAsConst(dict)) for (const QVariant &val : asConst(dict))
insertRule(AutoDownloadRule::fromLegacyDict(val.toHash())); insertRule(AutoDownloadRule::fromLegacyDict(val.toHash()));
} }
@ -451,7 +451,7 @@ void AutoDownloader::store()
m_savingTimer.stop(); m_savingTimer.stop();
QJsonObject jsonObj; QJsonObject jsonObj;
for (const auto &rule : qAsConst(m_rules)) for (const auto &rule : asConst(m_rules))
jsonObj.insert(rule.name(), rule.toJsonObject()); jsonObj.insert(rule.name(), rule.toJsonObject());
m_fileStorage->store(RulesFileName, QJsonDocument(jsonObj).toJson()); m_fileStorage->store(RulesFileName, QJsonDocument(jsonObj).toJson());
@ -473,7 +473,7 @@ void AutoDownloader::resetProcessingQueue()
m_processingQueue.clear(); m_processingQueue.clear();
if (!m_processingEnabled) return; if (!m_processingEnabled) return;
for (Article *article : copyAsConst(Session::instance()->rootFolder()->articles())) { for (Article *article : asConst(Session::instance()->rootFolder()->articles())) {
if (!article->isRead() && !article->torrentUrl().isEmpty()) if (!article->isRead() && !article->torrentUrl().isEmpty())
addJobForArticle(article); addJobForArticle(article);
} }

View File

@ -237,7 +237,7 @@ bool AutoDownloadRule::matchesMustContainExpression(const QString &articleTitle)
// Each expression is either a regex, or a set of wildcards separated by whitespace. // Each expression is either a regex, or a set of wildcards separated by whitespace.
// Accept if any complete expression matches. // Accept if any complete expression matches.
for (const QString &expression : qAsConst(m_dataPtr->mustContain)) { for (const QString &expression : asConst(m_dataPtr->mustContain)) {
// A regex of the form "expr|" will always match, so do the same for wildcards // A regex of the form "expr|" will always match, so do the same for wildcards
if (matchesExpression(articleTitle, expression)) if (matchesExpression(articleTitle, expression))
return true; return true;
@ -253,7 +253,7 @@ bool AutoDownloadRule::matchesMustNotContainExpression(const QString &articleTit
// Each expression is either a regex, or a set of wildcards separated by whitespace. // Each expression is either a regex, or a set of wildcards separated by whitespace.
// Reject if any complete expression matches. // Reject if any complete expression matches.
for (const QString &expression : qAsConst(m_dataPtr->mustNotContain)) { for (const QString &expression : asConst(m_dataPtr->mustNotContain)) {
// A regex of the form "expr|" will always match, so do the same for wildcards // A regex of the form "expr|" will always match, so do the same for wildcards
if (matchesExpression(articleTitle, expression)) if (matchesExpression(articleTitle, expression))
return false; return false;
@ -442,7 +442,7 @@ AutoDownloadRule AutoDownloadRule::fromJsonObject(const QJsonObject &jsonObj, co
QStringList feedURLs; QStringList feedURLs;
if (feedsVal.isString()) if (feedsVal.isString())
feedURLs << feedsVal.toString(); feedURLs << feedsVal.toString();
else for (const QJsonValue &urlVal : copyAsConst(feedsVal.toArray())) else for (const QJsonValue &urlVal : asConst(feedsVal.toArray()))
feedURLs << urlVal.toString(); feedURLs << urlVal.toString();
rule.setFeedURLs(feedURLs); rule.setFeedURLs(feedURLs);
@ -452,7 +452,7 @@ AutoDownloadRule AutoDownloadRule::fromJsonObject(const QJsonObject &jsonObj, co
previouslyMatched << previouslyMatchedVal.toString(); previouslyMatched << previouslyMatchedVal.toString();
} }
else { else {
for (const QJsonValue &val : copyAsConst(previouslyMatchedVal.toArray())) for (const QJsonValue &val : asConst(previouslyMatchedVal.toArray()))
previouslyMatched << val.toString(); previouslyMatched << val.toString();
} }
rule.setPreviouslyMatchedEpisodes(previouslyMatched); rule.setPreviouslyMatchedEpisodes(previouslyMatched);

View File

@ -109,7 +109,7 @@ QList<Article *> Feed::articles() const
void Feed::markAsRead() void Feed::markAsRead()
{ {
auto oldUnreadCount = m_unreadCount; auto oldUnreadCount = m_unreadCount;
for (Article *article : qAsConst(m_articles)) { for (Article *article : asConst(m_articles)) {
if (!article->isRead()) { if (!article->isRead()) {
article->disconnect(this); article->disconnect(this);
article->markAsRead(); article->markAsRead();
@ -306,7 +306,7 @@ void Feed::loadArticlesLegacy()
SettingsPtr qBTRSSFeeds = Profile::instance().applicationSettings(QStringLiteral("qBittorrent-rss-feeds")); SettingsPtr qBTRSSFeeds = Profile::instance().applicationSettings(QStringLiteral("qBittorrent-rss-feeds"));
const QVariantHash allOldItems = qBTRSSFeeds->value("old_items").toHash(); const QVariantHash allOldItems = qBTRSSFeeds->value("old_items").toHash();
for (const QVariant &var : copyAsConst(allOldItems.value(m_url).toList())) { for (const QVariant &var : asConst(allOldItems.value(m_url).toList())) {
auto hash = var.toHash(); auto hash = var.toHash();
// update legacy keys // update legacy keys
hash[Article::KeyLink] = hash.take(QLatin1String("news_link")); hash[Article::KeyLink] = hash.take(QLatin1String("news_link"));
@ -329,7 +329,7 @@ void Feed::store()
m_savingTimer.stop(); m_savingTimer.stop();
QJsonArray jsonArr; QJsonArray jsonArr;
for (Article *article :qAsConst(m_articles)) for (Article *article :asConst(m_articles))
jsonArr << article->toJsonObject(); jsonArr << article->toJsonObject();
m_session->dataFileStorage()->store(m_dataFileName, QJsonDocument(jsonArr).toJson()); m_session->dataFileStorage()->store(m_dataFileName, QJsonDocument(jsonArr).toJson());
@ -507,7 +507,7 @@ QJsonValue Feed::toJsonValue(bool withData) const
jsonObj.insert(KEY_HASERROR, hasError()); jsonObj.insert(KEY_HASERROR, hasError());
QJsonArray jsonArr; QJsonArray jsonArr;
for (Article *article : qAsConst(m_articles)) for (Article *article : asConst(m_articles))
jsonArr << article->toJsonObject(); jsonArr << article->toJsonObject();
jsonObj.insert(KEY_ARTICLES, jsonArr); jsonObj.insert(KEY_ARTICLES, jsonArr);
} }

View File

@ -47,7 +47,7 @@ Folder::~Folder()
{ {
emit aboutToBeDestroyed(this); emit aboutToBeDestroyed(this);
for (auto item : copyAsConst(items())) for (auto item : asConst(items()))
delete item; delete item;
} }
@ -55,7 +55,7 @@ QList<Article *> Folder::articles() const
{ {
QList<Article *> news; QList<Article *> news;
for (Item *item : copyAsConst(items())) { for (Item *item : asConst(items())) {
int n = news.size(); int n = news.size();
news << item->articles(); news << item->articles();
std::inplace_merge(news.begin(), news.begin() + n, news.end() std::inplace_merge(news.begin(), news.begin() + n, news.end()
@ -70,20 +70,20 @@ QList<Article *> Folder::articles() const
int Folder::unreadCount() const int Folder::unreadCount() const
{ {
int count = 0; int count = 0;
for (Item *item : copyAsConst(items())) for (Item *item : asConst(items()))
count += item->unreadCount(); count += item->unreadCount();
return count; return count;
} }
void Folder::markAsRead() void Folder::markAsRead()
{ {
for (Item *item : copyAsConst(items())) for (Item *item : asConst(items()))
item->markAsRead(); item->markAsRead();
} }
void Folder::refresh() void Folder::refresh()
{ {
for (Item *item : copyAsConst(items())) for (Item *item : asConst(items()))
item->refresh(); item->refresh();
} }
@ -95,7 +95,7 @@ QList<Item *> Folder::items() const
QJsonValue Folder::toJsonValue(bool withData) const QJsonValue Folder::toJsonValue(bool withData) const
{ {
QJsonObject jsonObj; QJsonObject jsonObj;
for (Item *item : copyAsConst(items())) for (Item *item : asConst(items()))
jsonObj.insert(item->name(), item->toJsonValue(withData)); jsonObj.insert(item->name(), item->toJsonValue(withData));
return jsonObj; return jsonObj;
@ -108,7 +108,7 @@ void Folder::handleItemUnreadCountChanged()
void Folder::cleanup() void Folder::cleanup()
{ {
for (Item *item : copyAsConst(items())) for (Item *item : asConst(items()))
item->cleanup(); item->cleanup();
} }
@ -123,7 +123,7 @@ void Folder::addItem(Item *item)
connect(item, &Item::articleAboutToBeRemoved, this, &Item::articleAboutToBeRemoved); connect(item, &Item::articleAboutToBeRemoved, this, &Item::articleAboutToBeRemoved);
connect(item, &Item::unreadCountChanged, this, &Folder::handleItemUnreadCountChanged); connect(item, &Item::unreadCountChanged, this, &Folder::handleItemUnreadCountChanged);
for (auto article : copyAsConst(item->articles())) for (auto article : asConst(item->articles()))
emit newArticle(article); emit newArticle(article);
if (item->unreadCount() > 0) if (item->unreadCount() > 0)
@ -134,7 +134,7 @@ void Folder::removeItem(Item *item)
{ {
Q_ASSERT(m_items.contains(item)); Q_ASSERT(m_items.contains(item));
for (auto article : copyAsConst(item->articles())) for (auto article : asConst(item->articles()))
emit articleAboutToBeRemoved(article); emit articleAboutToBeRemoved(article);
item->disconnect(this); item->disconnect(this);

View File

@ -284,7 +284,7 @@ void Session::load()
void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder) void Session::loadFolder(const QJsonObject &jsonObj, Folder *folder)
{ {
bool updated = false; bool updated = false;
for (const QString &key : copyAsConst(jsonObj.keys())) { for (const QString &key : asConst(jsonObj.keys())) {
const QJsonValue val {jsonObj[key]}; const QJsonValue val {jsonObj[key]};
if (val.isString()) { if (val.isString()) {
// previous format (reduced form) doesn't contain UID // previous format (reduced form) doesn't contain UID
@ -356,7 +356,7 @@ void Session::loadLegacy()
const QString parentFolderPath = Item::parentPath(legacyPath); const QString parentFolderPath = Item::parentPath(legacyPath);
const QString feedUrl = Item::relativeName(legacyPath); const QString feedUrl = Item::relativeName(legacyPath);
for (const QString &folderPath : copyAsConst(Item::expandPath(parentFolderPath))) for (const QString &folderPath : asConst(Item::expandPath(parentFolderPath)))
addFolder(folderPath); addFolder(folderPath);
const QString feedPath = feedAliases[i].isEmpty() const QString feedPath = feedAliases[i].isEmpty()

View File

@ -327,7 +327,7 @@ void ScanFoldersModel::makePersistent()
{ {
QVariantHash dirs; QVariantHash dirs;
for (const PathData *pathData : qAsConst(m_pathList)) { for (const PathData *pathData : asConst(m_pathList)) {
if (pathData->downloadType == CUSTOM_LOCATION) if (pathData->downloadType == CUSTOM_LOCATION)
dirs.insert(Utils::Fs::fromNativePath(pathData->watchPath), Utils::Fs::fromNativePath(pathData->downloadPath)); dirs.insert(Utils::Fs::fromNativePath(pathData->watchPath), Utils::Fs::fromNativePath(pathData->downloadPath));
else else

View File

@ -139,7 +139,7 @@ void SearchHandler::readSearchOutput()
m_searchResultLineTruncated = lines.takeLast().trimmed(); m_searchResultLineTruncated = lines.takeLast().trimmed();
QList<SearchResult> searchResultList; QList<SearchResult> searchResultList;
for (const QByteArray &line : qAsConst(lines)) { for (const QByteArray &line : asConst(lines)) {
SearchResult searchResult; SearchResult searchResult;
if (parseSearchResult(QString::fromUtf8(line), searchResult)) if (parseSearchResult(QString::fromUtf8(line), searchResult))
searchResultList << searchResult; searchResultList << searchResult;

View File

@ -65,7 +65,7 @@ namespace
while (iter.hasNext()) while (iter.hasNext())
dirs += iter.next(); dirs += iter.next();
for (const QString &dir : qAsConst(dirs)) { for (const QString &dir : asConst(dirs)) {
// python 3: remove "__pycache__" folders // python 3: remove "__pycache__" folders
if (dir.endsWith("/__pycache__")) { if (dir.endsWith("/__pycache__")) {
Utils::Fs::removeDirRecursive(dir); Utils::Fs::removeDirRecursive(dir);
@ -120,7 +120,7 @@ QStringList SearchPluginManager::allPlugins() const
QStringList SearchPluginManager::enabledPlugins() const QStringList SearchPluginManager::enabledPlugins() const
{ {
QStringList plugins; QStringList plugins;
for (const PluginInfo *plugin : qAsConst(m_plugins)) { for (const PluginInfo *plugin : asConst(m_plugins)) {
if (plugin->enabled) if (plugin->enabled)
plugins << plugin->name; plugins << plugin->name;
} }
@ -131,7 +131,7 @@ QStringList SearchPluginManager::enabledPlugins() const
QStringList SearchPluginManager::supportedCategories() const QStringList SearchPluginManager::supportedCategories() const
{ {
QStringList result; QStringList result;
for (const PluginInfo *plugin : qAsConst(m_plugins)) { for (const PluginInfo *plugin : asConst(m_plugins)) {
if (plugin->enabled) { if (plugin->enabled) {
for (const QString &cat : plugin->supportedCategories) { for (const QString &cat : plugin->supportedCategories) {
if (!result.contains(cat)) if (!result.contains(cat))
@ -154,7 +154,7 @@ QStringList SearchPluginManager::getPluginCategories(const QString &pluginName)
plugins << pluginName.trimmed(); plugins << pluginName.trimmed();
QSet<QString> categories; QSet<QString> categories;
for (const QString &name : qAsConst(plugins)) { for (const QString &name : asConst(plugins)) {
const PluginInfo *plugin = pluginInfo(name); const PluginInfo *plugin = pluginInfo(name);
if (!plugin) continue; // plugin wasn't found if (!plugin) continue; // plugin wasn't found
for (const QString &category : plugin->supportedCategories) for (const QString &category : plugin->supportedCategories)

View File

@ -287,7 +287,7 @@ QString TransactionalSettings::deserialize(const QString &name, QVariantHash &da
// Copy everything into memory. This means even keys inserted in the file manually // 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 // 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. // that they will be copied over when save our settings to disk.
for (const QString &key : copyAsConst(settings->allKeys())) for (const QString &key : asConst(settings->allKeys()))
data.insert(key, settings->value(key)); data.insert(key, settings->value(key));
return settings->fileName(); return settings->fileName();

View File

@ -133,7 +133,7 @@ bool Utils::Fs::smartRemoveEmptyFolderTree(const QString &path)
std::sort(dirList.begin(), dirList.end() std::sort(dirList.begin(), dirList.end()
, [](const QString &l, const QString &r) { return l.count('/') > r.count('/'); }); , [](const QString &l, const QString &r) { return l.count('/') > r.count('/'); });
for (const QString &p : qAsConst(dirList)) { for (const QString &p : asConst(dirList)) {
// remove unwanted files // remove unwanted files
for (const QString &f : deleteFilesList) { for (const QString &f : deleteFilesList) {
forceRemove(p + f); forceRemove(p + f);

View File

@ -143,7 +143,7 @@ AddNewTorrentDialog::AddNewTorrentDialog(const BitTorrent::AddTorrentParams &inP
m_ui->categoryComboBox->addItem(defaultCategory); m_ui->categoryComboBox->addItem(defaultCategory);
m_ui->categoryComboBox->addItem(""); m_ui->categoryComboBox->addItem("");
for (const QString &category : qAsConst(categories)) for (const QString &category : asConst(categories))
if (category != defaultCategory && category != m_torrentParams.category) if (category != defaultCategory && category != m_torrentParams.category)
m_ui->categoryComboBox->addItem(category); m_ui->categoryComboBox->addItem(category);
@ -398,7 +398,7 @@ void AddNewTorrentDialog::saveSavePathHistory() const
// Get current history // Get current history
QStringList history = settings()->loadValue(KEY_SAVEPATHHISTORY).toStringList(); QStringList history = settings()->loadValue(KEY_SAVEPATHHISTORY).toStringList();
QVector<QDir> historyDirs; QVector<QDir> historyDirs;
for (const QString &path : qAsConst(history)) for (const QString &path : asConst(history))
historyDirs << QDir {path}; historyDirs << QDir {path};
const QDir selectedSavePath {m_ui->savePath->selectedPath()}; const QDir selectedSavePath {m_ui->savePath->selectedPath()};

View File

@ -287,7 +287,7 @@ void AdvancedSettings::updateInterfaceAddressCombo()
}; };
if (ifaceName.isEmpty()) { if (ifaceName.isEmpty()) {
for (const QHostAddress &ip : copyAsConst(QNetworkInterface::allAddresses())) for (const QHostAddress &ip : asConst(QNetworkInterface::allAddresses()))
populateCombo(ip.toString(), ip.protocol()); populateCombo(ip.toString(), ip.protocol());
} }
else { else {
@ -426,7 +426,7 @@ void AdvancedSettings::loadAdvancedSettings()
const QString currentInterface = session->networkInterface(); const QString currentInterface = session->networkInterface();
bool interfaceExists = currentInterface.isEmpty(); bool interfaceExists = currentInterface.isEmpty();
int i = 1; int i = 1;
for (const QNetworkInterface &iface : copyAsConst(QNetworkInterface::allInterfaces())) { for (const QNetworkInterface &iface : asConst(QNetworkInterface::allInterfaces())) {
// This line fixes a Qt bug => https://bugreports.qt.io/browse/QTBUG-52633 // This line fixes a Qt bug => https://bugreports.qt.io/browse/QTBUG-52633
// Tested in Qt 5.6.0. For more info see: // Tested in Qt 5.6.0. For more info see:
// https://github.com/qbittorrent/qBittorrent/issues/5131 // https://github.com/qbittorrent/qBittorrent/issues/5131

View File

@ -408,7 +408,7 @@ void CategoryFilterModel::populate()
const QString &category = i.key(); const QString &category = i.key();
if (m_isSubcategoriesEnabled) { if (m_isSubcategoriesEnabled) {
CategoryModelItem *parent = m_rootItem; CategoryModelItem *parent = m_rootItem;
for (const QString &subcat : copyAsConst(session->expandCategory(category))) { for (const QString &subcat : asConst(session->expandCategory(category))) {
const QString subcatName = shortName(subcat); const QString subcatName = shortName(subcat);
if (!parent->hasChild(subcatName)) { if (!parent->hasChild(subcatName)) {
new CategoryModelItem( new CategoryModelItem(
@ -437,7 +437,7 @@ CategoryModelItem *CategoryFilterModel::findItem(const QString &fullName) const
return m_rootItem->child(fullName); return m_rootItem->child(fullName);
CategoryModelItem *item = m_rootItem; CategoryModelItem *item = m_rootItem;
for (const QString &subcat : copyAsConst(BitTorrent::Session::expandCategory(fullName))) { for (const QString &subcat : asConst(BitTorrent::Session::expandCategory(fullName))) {
const QString subcatName = shortName(subcat); const QString subcatName = shortName(subcat);
if (!item->hasChild(subcatName)) return nullptr; if (!item->hasChild(subcatName)) return nullptr;
item = item->child(subcatName); item = item->child(subcatName);

View File

@ -231,7 +231,7 @@ void CategoryFilterWidget::removeCategory()
void CategoryFilterWidget::removeUnusedCategories() void CategoryFilterWidget::removeUnusedCategories()
{ {
auto session = BitTorrent::Session::instance(); auto session = BitTorrent::Session::instance();
for (const QString &category : copyAsConst(session->categories().keys())) { for (const QString &category : asConst(session->categories().keys())) {
if (model()->data(static_cast<CategoryFilterProxyModel *>(model())->index(category), Qt::UserRole) == 0) if (model()->data(static_cast<CategoryFilterProxyModel *>(model())->index(category), Qt::UserRole) == 0)
session->removeCategory(category); session->removeCategory(category);
} }

View File

@ -101,6 +101,6 @@ void CookiesDialog::onButtonDeleteClicked()
} }
); );
for (const QModelIndex &idx : qAsConst(idxs)) for (const QModelIndex &idx : asConst(idxs))
m_cookiesModel->removeRow(idx.row()); m_cookiesModel->removeRow(idx.row());
} }

View File

@ -53,9 +53,9 @@ ExecutionLogWidget::ExecutionLogWidget(QWidget *parent, const Log::MsgTypes &typ
m_ui->tabBan->layout()->addWidget(m_peerList); m_ui->tabBan->layout()->addWidget(m_peerList);
const Logger *const logger = Logger::instance(); const Logger *const logger = Logger::instance();
for (const Log::Msg &msg : copyAsConst(logger->getMessages())) for (const Log::Msg &msg : asConst(logger->getMessages()))
addLogMessage(msg); addLogMessage(msg);
for (const Log::Peer &peer : copyAsConst(logger->getPeers())) for (const Log::Peer &peer : asConst(logger->getPeers()))
addPeerMessage(peer); addPeerMessage(peer);
connect(logger, &Logger::newLogMessage, this, &ExecutionLogWidget::addLogMessage); connect(logger, &Logger::newLogMessage, this, &ExecutionLogWidget::addLogMessage);
connect(logger, &Logger::newLogPeer, this, &ExecutionLogWidget::addPeerMessage); connect(logger, &Logger::newLogPeer, this, &ExecutionLogWidget::addPeerMessage);

View File

@ -46,7 +46,7 @@ IPSubnetWhitelistOptionsDialog::IPSubnetWhitelistOptionsDialog(QWidget *parent)
m_ui->setupUi(this); m_ui->setupUi(this);
QStringList authSubnetWhitelistStringList; QStringList authSubnetWhitelistStringList;
for (const Utils::Net::Subnet &subnet : copyAsConst(Preferences::instance()->getWebUiAuthSubnetWhitelist())) for (const Utils::Net::Subnet &subnet : asConst(Preferences::instance()->getWebUiAuthSubnetWhitelist()))
authSubnetWhitelistStringList << Utils::Net::subnetToString(subnet); authSubnetWhitelistStringList << Utils::Net::subnetToString(subnet);
m_model = new QStringListModel(authSubnetWhitelistStringList, this); m_model = new QStringListModel(authSubnetWhitelistStringList, this);
@ -99,7 +99,7 @@ void IPSubnetWhitelistOptionsDialog::on_buttonWhitelistIPSubnet_clicked()
void IPSubnetWhitelistOptionsDialog::on_buttonDeleteIPSubnet_clicked() void IPSubnetWhitelistOptionsDialog::on_buttonDeleteIPSubnet_clicked()
{ {
for (const auto &i : copyAsConst(m_ui->whitelistedIPSubnetList->selectionModel()->selectedIndexes())) for (const auto &i : asConst(m_ui->whitelistedIPSubnetList->selectionModel()->selectedIndexes()))
m_sortFilter->removeRow(i.row()); m_sortFilter->removeRow(i.row());
m_modified = true; m_modified = true;

View File

@ -98,7 +98,7 @@ void LogListWidget::copySelection()
{ {
static const QRegularExpression htmlTag("<[^>]+>"); static const QRegularExpression htmlTag("<[^>]+>");
QStringList strings; QStringList strings;
for (QListWidgetItem* it : copyAsConst(selectedItems())) for (QListWidgetItem* it : asConst(selectedItems()))
strings << static_cast<QLabel*>(itemWidget(it))->text().remove(htmlTag); strings << static_cast<QLabel*>(itemWidget(it))->text().remove(htmlTag);
QApplication::clipboard()->setText(strings.join('\n')); QApplication::clipboard()->setText(strings.join('\n'));

View File

@ -284,7 +284,7 @@ MainWindow::MainWindow(QWidget *parent)
m_prioSeparatorMenu = m_ui->menuEdit->insertSeparator(m_ui->actionTopPriority); m_prioSeparatorMenu = m_ui->menuEdit->insertSeparator(m_ui->actionTopPriority);
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
for (QAction *action : copyAsConst(m_ui->toolBar->actions())) { for (QAction *action : asConst(m_ui->toolBar->actions())) {
if (action->isSeparator()) { if (action->isSeparator()) {
QWidget *spacer = new QWidget(this); QWidget *spacer = new QWidget(this);
spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
@ -1239,7 +1239,7 @@ bool MainWindow::event(QEvent *e)
qDebug() << "Has active window:" << (qApp->activeWindow() != nullptr); qDebug() << "Has active window:" << (qApp->activeWindow() != nullptr);
// Check if there is a modal window // Check if there is a modal window
bool hasModalWindow = false; bool hasModalWindow = false;
for (QWidget *widget : copyAsConst(QApplication::allWidgets())) { for (QWidget *widget : asConst(QApplication::allWidgets())) {
if (widget->isModal()) { if (widget->isModal()) {
hasModalWindow = true; hasModalWindow = true;
break; break;
@ -1285,7 +1285,7 @@ void MainWindow::dropEvent(QDropEvent *event)
// remove scheme // remove scheme
QStringList files; QStringList files;
if (event->mimeData()->hasUrls()) { if (event->mimeData()->hasUrls()) {
for (const QUrl &url : copyAsConst(event->mimeData()->urls())) { for (const QUrl &url : asConst(event->mimeData()->urls())) {
if (url.isEmpty()) if (url.isEmpty())
continue; continue;
@ -1300,7 +1300,7 @@ void MainWindow::dropEvent(QDropEvent *event)
// differentiate ".torrent" files/links & magnet links from others // differentiate ".torrent" files/links & magnet links from others
QStringList torrentFiles, otherFiles; QStringList torrentFiles, otherFiles;
for (const QString &file : qAsConst(files)) { for (const QString &file : asConst(files)) {
const bool isTorrentLink = (file.startsWith("magnet:", Qt::CaseInsensitive) const bool isTorrentLink = (file.startsWith("magnet:", Qt::CaseInsensitive)
|| file.endsWith(C_TORRENT_FILE_EXTENSION, Qt::CaseInsensitive) || file.endsWith(C_TORRENT_FILE_EXTENSION, Qt::CaseInsensitive)
|| Utils::Misc::isUrl(file)); || Utils::Misc::isUrl(file));
@ -1312,7 +1312,7 @@ void MainWindow::dropEvent(QDropEvent *event)
// Download torrents // Download torrents
const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled(); const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled();
for (const QString &file : qAsConst(torrentFiles)) { for (const QString &file : asConst(torrentFiles)) {
if (useTorrentAdditionDialog) if (useTorrentAdditionDialog)
AddNewTorrentDialog::show(file, this); AddNewTorrentDialog::show(file, this);
else else
@ -1321,7 +1321,7 @@ void MainWindow::dropEvent(QDropEvent *event)
if (!torrentFiles.isEmpty()) return; if (!torrentFiles.isEmpty()) return;
// Create torrent // Create torrent
for (const QString &file : qAsConst(otherFiles)) { for (const QString &file : asConst(otherFiles)) {
createTorrentTriggered(file); createTorrentTriggered(file);
// currently only hande the first entry // currently only hande the first entry
@ -1333,7 +1333,7 @@ void MainWindow::dropEvent(QDropEvent *event)
// Decode if we accept drag 'n drop or not // Decode if we accept drag 'n drop or not
void MainWindow::dragEnterEvent(QDragEnterEvent *event) void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{ {
for (const QString &mime : copyAsConst(event->mimeData()->formats())) for (const QString &mime : asConst(event->mimeData()->formats()))
qDebug("mimeData: %s", mime.toLocal8Bit().data()); qDebug("mimeData: %s", mime.toLocal8Bit().data());
if (event->mimeData()->hasFormat("text/plain") || event->mimeData()->hasFormat("text/uri-list")) if (event->mimeData()->hasFormat("text/plain") || event->mimeData()->hasFormat("text/uri-list"))
event->acceptProposedAction(); event->acceptProposedAction();

View File

@ -439,9 +439,9 @@ OptionsDialog::OptionsDialog(QWidget *parent)
// disable mouse wheel event on widgets to avoid mis-selection // disable mouse wheel event on widgets to avoid mis-selection
WheelEventEater *wheelEventEater = new WheelEventEater(this); WheelEventEater *wheelEventEater = new WheelEventEater(this);
for (QComboBox *widget : copyAsConst(findChildren<QComboBox *>())) for (QComboBox *widget : asConst(findChildren<QComboBox *>()))
widget->installEventFilter(wheelEventEater); widget->installEventFilter(wheelEventEater);
for (QSpinBox *widget : copyAsConst(findChildren<QSpinBox *>())) for (QSpinBox *widget : asConst(findChildren<QSpinBox *>()))
widget->installEventFilter(wheelEventEater); widget->installEventFilter(wheelEventEater);
loadWindowState(); loadWindowState();
@ -479,7 +479,7 @@ OptionsDialog::~OptionsDialog()
saveWindowState(); saveWindowState();
for (const QString &path : qAsConst(m_addedScanDirs)) for (const QString &path : asConst(m_addedScanDirs))
ScanFoldersModel::instance()->removePath(path); ScanFoldersModel::instance()->removePath(path);
ScanFoldersModel::instance()->configure(); // reloads "removed" paths ScanFoldersModel::instance()->configure(); // reloads "removed" paths
delete m_ui; delete m_ui;

View File

@ -62,7 +62,7 @@ void PeersAdditionDialog::validateInput()
QMessageBox::Ok); QMessageBox::Ok);
return; return;
} }
for (const QString &peer : copyAsConst(m_ui->textEditPeers->toPlainText().trimmed().split('\n'))) { for (const QString &peer : asConst(m_ui->textEditPeers->toPlainText().trimmed().split('\n'))) {
BitTorrent::PeerAddress addr = parsePeer(peer); BitTorrent::PeerAddress addr = parsePeer(peer);
if (!addr.ip.isNull()) { if (!addr.ip.isNull()) {
m_peersList.append(addr); m_peersList.append(addr);

View File

@ -103,7 +103,7 @@ PropTabBar::PropTabBar(QWidget *parent)
connect(m_btnGroup, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked) connect(m_btnGroup, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked)
, this, &PropTabBar::setCurrentIndex); , this, &PropTabBar::setCurrentIndex);
// Disable buttons focus // Disable buttons focus
for (QAbstractButton *btn : copyAsConst(m_btnGroup->buttons())) for (QAbstractButton *btn : asConst(m_btnGroup->buttons()))
btn->setFocusPolicy(Qt::NoFocus); btn->setFocusPolicy(Qt::NoFocus);
} }

View File

@ -348,7 +348,7 @@ void SpeedPlotView::paintEvent(QPaintEvent *)
double legendHeight = 0; double legendHeight = 0;
int legendWidth = 0; int legendWidth = 0;
for (const auto &property : qAsConst(m_properties)) { for (const auto &property : asConst(m_properties)) {
if (!property.enable) if (!property.enable)
continue; continue;
@ -363,7 +363,7 @@ void SpeedPlotView::paintEvent(QPaintEvent *)
painter.fillRect(legendBackgroundRect, legendBackgroundColor); painter.fillRect(legendBackgroundRect, legendBackgroundColor);
i = 0; i = 0;
for (const auto &property : qAsConst(m_properties)) { for (const auto &property : asConst(m_properties)) {
if (!property.enable) if (!property.enable)
continue; continue;

View File

@ -290,7 +290,7 @@ void TrackerListWidget::loadStickyItems(BitTorrent::TorrentHandle *const torrent
// XXX: libtorrent should provide this info... // XXX: libtorrent should provide this info...
// Count peers from DHT, PeX, LSD // Count peers from DHT, PeX, LSD
uint seedsDHT = 0, seedsPeX = 0, seedsLSD = 0, peersDHT = 0, peersPeX = 0, peersLSD = 0; uint seedsDHT = 0, seedsPeX = 0, seedsLSD = 0, peersDHT = 0, peersPeX = 0, peersLSD = 0;
for (const BitTorrent::PeerInfo &peer : copyAsConst(torrent->peers())) { for (const BitTorrent::PeerInfo &peer : asConst(torrent->peers())) {
if (peer.isConnecting()) continue; if (peer.isConnecting()) continue;
if (peer.fromDHT()) { if (peer.fromDHT()) {
@ -332,7 +332,7 @@ void TrackerListWidget::loadTrackers()
// Load actual trackers information // Load actual trackers information
QHash<QString, BitTorrent::TrackerInfo> trackerData = torrent->trackerInfos(); QHash<QString, BitTorrent::TrackerInfo> trackerData = torrent->trackerInfos();
QStringList oldTrackerURLs = m_trackerItems.keys(); QStringList oldTrackerURLs = m_trackerItems.keys();
for (const BitTorrent::TrackerEntry &entry : copyAsConst(torrent->trackers())) { for (const BitTorrent::TrackerEntry &entry : asConst(torrent->trackers())) {
QString trackerURL = entry.url(); QString trackerURL = entry.url();
QTreeWidgetItem *item = m_trackerItems.value(trackerURL, nullptr); QTreeWidgetItem *item = m_trackerItems.value(trackerURL, nullptr);
if (!item) { if (!item) {
@ -384,7 +384,7 @@ void TrackerListWidget::loadTrackers()
item->setTextAlignment(COL_DOWNLOADED, (Qt::AlignRight | Qt::AlignVCenter)); item->setTextAlignment(COL_DOWNLOADED, (Qt::AlignRight | Qt::AlignVCenter));
} }
// Remove old trackers // Remove old trackers
for (const QString &tracker : qAsConst(oldTrackerURLs)) for (const QString &tracker : asConst(oldTrackerURLs))
delete m_trackerItems.take(tracker); delete m_trackerItems.take(tracker);
} }
@ -395,7 +395,7 @@ void TrackerListWidget::askForTrackers()
if (!torrent) return; if (!torrent) return;
QList<BitTorrent::TrackerEntry> trackers; QList<BitTorrent::TrackerEntry> trackers;
for (const QString &tracker : copyAsConst(TrackersAdditionDialog::askForTrackers(this, torrent))) for (const QString &tracker : asConst(TrackersAdditionDialog::askForTrackers(this, torrent)))
trackers << tracker; trackers << tracker;
torrent->addTrackers(trackers); torrent->addTrackers(trackers);

View File

@ -60,7 +60,7 @@ TrackersAdditionDialog::~TrackersAdditionDialog()
QStringList TrackersAdditionDialog::newTrackers() const QStringList TrackersAdditionDialog::newTrackers() const
{ {
QStringList cleanTrackers; QStringList cleanTrackers;
for (QString url : copyAsConst(m_ui->textEditTrackersList->toPlainText().split('\n'))) { for (QString url : asConst(m_ui->textEditTrackersList->toPlainText().split('\n'))) {
url = url.trimmed(); url = url.trimmed();
if (!url.isEmpty()) if (!url.isEmpty())
cleanTrackers << url; cleanTrackers << url;

View File

@ -69,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::articleRead, this, &ArticleListWidget::handleArticleRead);
connect(m_rssItem, &RSS::Item::articleAboutToBeRemoved, this, &ArticleListWidget::handleArticleAboutToBeRemoved); connect(m_rssItem, &RSS::Item::articleAboutToBeRemoved, this, &ArticleListWidget::handleArticleAboutToBeRemoved);
for (const auto article : copyAsConst(rssItem->articles())) { for (const auto article : asConst(rssItem->articles())) {
if (!(m_unreadOnly && article->isRead())) { if (!(m_unreadOnly && article->isRead())) {
auto item = createItem(article); auto item = createItem(article);
addItem(item); addItem(item);

View File

@ -132,7 +132,7 @@ AutomatedRssDownloader::AutomatedRssDownloader(QWidget *parent)
loadFeedList(); loadFeedList();
m_ui->listRules->blockSignals(true); m_ui->listRules->blockSignals(true);
for (const RSS::AutoDownloadRule &rule : copyAsConst(RSS::AutoDownloader::instance()->rules())) for (const RSS::AutoDownloadRule &rule : asConst(RSS::AutoDownloader::instance()->rules()))
createRuleItem(rule); createRuleItem(rule);
m_ui->listRules->blockSignals(false); m_ui->listRules->blockSignals(false);
@ -182,7 +182,7 @@ void AutomatedRssDownloader::loadFeedList()
{ {
const QSignalBlocker feedListSignalBlocker(m_ui->listFeeds); const QSignalBlocker feedListSignalBlocker(m_ui->listFeeds);
for (const auto feed : copyAsConst(RSS::Session::instance()->feeds())) { for (const auto feed : asConst(RSS::Session::instance()->feeds())) {
QListWidgetItem *item = new QListWidgetItem(feed->name(), m_ui->listFeeds); QListWidgetItem *item = new QListWidgetItem(feed->name(), m_ui->listFeeds);
item->setData(Qt::UserRole, feed->url()); item->setData(Qt::UserRole, feed->url());
item->setFlags(item->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsTristate); item->setFlags(item->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsTristate);
@ -212,7 +212,7 @@ void AutomatedRssDownloader::updateFeedList()
bool allEnabled = true; bool allEnabled = true;
bool anyEnabled = false; bool anyEnabled = false;
for (const QListWidgetItem *ruleItem : qAsConst(selection)) { for (const QListWidgetItem *ruleItem : asConst(selection)) {
auto rule = RSS::AutoDownloader::instance()->ruleByName(ruleItem->text()); auto rule = RSS::AutoDownloader::instance()->ruleByName(ruleItem->text());
if (rule.feedURLs().contains(feedURL)) if (rule.feedURLs().contains(feedURL))
anyEnabled = true; anyEnabled = true;
@ -549,7 +549,7 @@ void AutomatedRssDownloader::clearSelectedRuleDownloadedEpisodeList()
void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feedItem) void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feedItem)
{ {
const QString feedURL = feedItem->data(Qt::UserRole).toString(); const QString feedURL = feedItem->data(Qt::UserRole).toString();
for (QListWidgetItem *ruleItem : copyAsConst(m_ui->listRules->selectedItems())) { for (QListWidgetItem *ruleItem : asConst(m_ui->listRules->selectedItems())) {
RSS::AutoDownloadRule rule = (ruleItem == m_currentRuleItem RSS::AutoDownloadRule rule = (ruleItem == m_currentRuleItem
? m_currentRule ? m_currentRule
: RSS::AutoDownloader::instance()->ruleByName(ruleItem->text())); : RSS::AutoDownloader::instance()->ruleByName(ruleItem->text()));
@ -573,16 +573,16 @@ void AutomatedRssDownloader::updateMatchingArticles()
{ {
m_ui->treeMatchingArticles->clear(); m_ui->treeMatchingArticles->clear();
for (const QListWidgetItem *ruleItem : copyAsConst(m_ui->listRules->selectedItems())) { for (const QListWidgetItem *ruleItem : asConst(m_ui->listRules->selectedItems())) {
RSS::AutoDownloadRule rule = (ruleItem == m_currentRuleItem RSS::AutoDownloadRule rule = (ruleItem == m_currentRuleItem
? m_currentRule ? m_currentRule
: RSS::AutoDownloader::instance()->ruleByName(ruleItem->text())); : RSS::AutoDownloader::instance()->ruleByName(ruleItem->text()));
for (const QString &feedURL : copyAsConst(rule.feedURLs())) { for (const QString &feedURL : asConst(rule.feedURLs())) {
auto feed = RSS::Session::instance()->feedByURL(feedURL); auto feed = RSS::Session::instance()->feedByURL(feedURL);
if (!feed) continue; // feed doesn't exist if (!feed) continue; // feed doesn't exist
QStringList matchingArticles; QStringList matchingArticles;
for (const auto article : copyAsConst(feed->articles())) for (const auto article : asConst(feed->articles()))
if (rule.matches(article->data())) if (rule.matches(article->data()))
matchingArticles << article->title(); matchingArticles << article->title();
if (!matchingArticles.isEmpty()) if (!matchingArticles.isEmpty())
@ -676,10 +676,10 @@ void AutomatedRssDownloader::updateMustLineValidity()
if (isRegex) if (isRegex)
tokens << text; tokens << text;
else else
for (const QString &token : copyAsConst(text.split('|'))) for (const QString &token : asConst(text.split('|')))
tokens << Utils::String::wildcardToRegex(token); tokens << Utils::String::wildcardToRegex(token);
for (const QString &token : qAsConst(tokens)) { for (const QString &token : asConst(tokens)) {
QRegularExpression reg(token, QRegularExpression::CaseInsensitiveOption); QRegularExpression reg(token, QRegularExpression::CaseInsensitiveOption);
if (!reg.isValid()) { if (!reg.isValid()) {
if (isRegex) if (isRegex)
@ -714,10 +714,10 @@ void AutomatedRssDownloader::updateMustNotLineValidity()
if (isRegex) if (isRegex)
tokens << text; tokens << text;
else else
for (const QString &token : copyAsConst(text.split('|'))) for (const QString &token : asConst(text.split('|')))
tokens << Utils::String::wildcardToRegex(token); tokens << Utils::String::wildcardToRegex(token);
for (const QString &token : qAsConst(tokens)) { for (const QString &token : asConst(tokens)) {
QRegularExpression reg(token, QRegularExpression::CaseInsensitiveOption); QRegularExpression reg(token, QRegularExpression::CaseInsensitiveOption);
if (!reg.isValid()) { if (!reg.isValid()) {
if (isRegex) if (isRegex)

View File

@ -220,7 +220,7 @@ void FeedListWidget::dropEvent(QDropEvent *event)
: RSS::Session::instance()->rootFolder()); : RSS::Session::instance()->rootFolder());
// move as much items as possible // move as much items as possible
for (QTreeWidgetItem *srcItem : copyAsConst(selectedItems())) { for (QTreeWidgetItem *srcItem : asConst(selectedItems())) {
auto rssItem = getRSSItem(srcItem); auto rssItem = getRSSItem(srcItem);
RSS::Session::instance()->moveItem(rssItem, RSS::Item::joinPath(destFolder->path(), rssItem->name())); RSS::Session::instance()->moveItem(rssItem, RSS::Item::joinPath(destFolder->path(), rssItem->name()));
} }
@ -265,7 +265,7 @@ QTreeWidgetItem *FeedListWidget::createItem(RSS::Item *rssItem, QTreeWidgetItem
void FeedListWidget::fill(QTreeWidgetItem *parent, RSS::Folder *rssParent) void FeedListWidget::fill(QTreeWidgetItem *parent, RSS::Folder *rssParent)
{ {
for (const auto rssItem : copyAsConst(rssParent->items())) { for (const auto rssItem : asConst(rssParent->items())) {
QTreeWidgetItem *item = createItem(rssItem, parent); QTreeWidgetItem *item = createItem(rssItem, parent);
// Recursive call if this is a folder. // Recursive call if this is a folder.
if (auto folder = qobject_cast<RSS::Folder *>(rssItem)) if (auto folder = qobject_cast<RSS::Folder *>(rssItem))

View File

@ -187,7 +187,7 @@ void RSSWidget::displayItemsListMenu(const QPoint &)
{ {
bool hasTorrent = false; bool hasTorrent = false;
bool hasLink = false; bool hasLink = false;
for (const QListWidgetItem *item : copyAsConst(m_articleListWidget->selectedItems())) { for (const QListWidgetItem *item : asConst(m_articleListWidget->selectedItems())) {
auto article = reinterpret_cast<RSS::Article *>(item->data(Qt::UserRole).value<quintptr>()); auto article = reinterpret_cast<RSS::Article *>(item->data(Qt::UserRole).value<quintptr>());
Q_ASSERT(article); Q_ASSERT(article);
@ -309,7 +309,7 @@ void RSSWidget::loadFoldersOpenState()
const QStringList openedFolders = Preferences::instance()->getRssOpenFolders(); const QStringList openedFolders = Preferences::instance()->getRssOpenFolders();
for (const QString &varPath : openedFolders) { for (const QString &varPath : openedFolders) {
QTreeWidgetItem *parent = nullptr; QTreeWidgetItem *parent = nullptr;
for (const QString &name : copyAsConst(varPath.split('\\'))) { for (const QString &name : asConst(varPath.split('\\'))) {
int nbChildren = (parent ? parent->childCount() : m_feedListWidget->topLevelItemCount()); int nbChildren = (parent ? parent->childCount() : m_feedListWidget->topLevelItemCount());
for (int i = 0; i < nbChildren; ++i) { for (int i = 0; i < nbChildren; ++i) {
QTreeWidgetItem *child = (parent ? parent->child(i) : m_feedListWidget->topLevelItem(i)); QTreeWidgetItem *child = (parent ? parent->child(i) : m_feedListWidget->topLevelItem(i));
@ -326,7 +326,7 @@ void RSSWidget::loadFoldersOpenState()
void RSSWidget::saveFoldersOpenState() void RSSWidget::saveFoldersOpenState()
{ {
QStringList openedFolders; QStringList openedFolders;
for (QTreeWidgetItem *item : copyAsConst(m_feedListWidget->getAllOpenedFolders())) for (QTreeWidgetItem *item : asConst(m_feedListWidget->getAllOpenedFolders()))
openedFolders << m_feedListWidget->itemPath(item); openedFolders << m_feedListWidget->itemPath(item);
Preferences::instance()->setRssOpenFolders(openedFolders); Preferences::instance()->setRssOpenFolders(openedFolders);
} }
@ -338,7 +338,7 @@ void RSSWidget::refreshAllFeeds()
void RSSWidget::downloadSelectedTorrents() void RSSWidget::downloadSelectedTorrents()
{ {
for (QListWidgetItem *item : copyAsConst(m_articleListWidget->selectedItems())) { for (QListWidgetItem *item : asConst(m_articleListWidget->selectedItems())) {
auto article = reinterpret_cast<RSS::Article *>(item->data(Qt::UserRole).value<quintptr>()); auto article = reinterpret_cast<RSS::Article *>(item->data(Qt::UserRole).value<quintptr>());
Q_ASSERT(article); Q_ASSERT(article);
@ -357,7 +357,7 @@ void RSSWidget::downloadSelectedTorrents()
// open the url of the selected RSS articles in the Web browser // open the url of the selected RSS articles in the Web browser
void RSSWidget::openSelectedArticlesUrls() void RSSWidget::openSelectedArticlesUrls()
{ {
for (QListWidgetItem *item : copyAsConst(m_articleListWidget->selectedItems())) { for (QListWidgetItem *item : asConst(m_articleListWidget->selectedItems())) {
auto article = reinterpret_cast<RSS::Article *>(item->data(Qt::UserRole).value<quintptr>()); auto article = reinterpret_cast<RSS::Article *>(item->data(Qt::UserRole).value<quintptr>());
Q_ASSERT(article); Q_ASSERT(article);
@ -398,7 +398,7 @@ void RSSWidget::renameSelectedRSSItem()
void RSSWidget::refreshSelectedItems() void RSSWidget::refreshSelectedItems()
{ {
for (QTreeWidgetItem *item : copyAsConst(m_feedListWidget->selectedItems())) { for (QTreeWidgetItem *item : asConst(m_feedListWidget->selectedItems())) {
if (item == m_feedListWidget->stickyUnreadItem()) { if (item == m_feedListWidget->stickyUnreadItem()) {
refreshAllFeeds(); refreshAllFeeds();
return; return;
@ -411,7 +411,7 @@ void RSSWidget::refreshSelectedItems()
void RSSWidget::copySelectedFeedsURL() void RSSWidget::copySelectedFeedsURL()
{ {
QStringList URLs; QStringList URLs;
for (QTreeWidgetItem *item : copyAsConst(m_feedListWidget->selectedItems())) { for (QTreeWidgetItem *item : asConst(m_feedListWidget->selectedItems())) {
if (auto feed = qobject_cast<RSS::Feed *>(m_feedListWidget->getRSSItem(item))) if (auto feed = qobject_cast<RSS::Feed *>(m_feedListWidget->getRSSItem(item)))
URLs << feed->url(); URLs << feed->url();
} }
@ -426,7 +426,7 @@ void RSSWidget::handleCurrentFeedItemChanged(QTreeWidgetItem *currentItem)
void RSSWidget::on_markReadButton_clicked() void RSSWidget::on_markReadButton_clicked()
{ {
for (QTreeWidgetItem *item : copyAsConst(m_feedListWidget->selectedItems())) { for (QTreeWidgetItem *item : asConst(m_feedListWidget->selectedItems())) {
m_feedListWidget->getRSSItem(item)->markAsRead(); m_feedListWidget->getRSSItem(item)->markAsRead();
if (item == m_feedListWidget->stickyUnreadItem()) if (item == m_feedListWidget->stickyUnreadItem())
break; // all items was read break; // all items was read

View File

@ -111,7 +111,7 @@ void PluginSelectDialog::dropEvent(QDropEvent *event)
QStringList files; QStringList files;
if (event->mimeData()->hasUrls()) { if (event->mimeData()->hasUrls()) {
for (const QUrl &url : copyAsConst(event->mimeData()->urls())) { for (const QUrl &url : asConst(event->mimeData()->urls())) {
if (!url.isEmpty()) { if (!url.isEmpty()) {
if (url.scheme().compare("file", Qt::CaseInsensitive) == 0) if (url.scheme().compare("file", Qt::CaseInsensitive) == 0)
files << url.toLocalFile(); files << url.toLocalFile();
@ -126,7 +126,7 @@ void PluginSelectDialog::dropEvent(QDropEvent *event)
if (files.isEmpty()) return; if (files.isEmpty()) return;
for (const QString &file : qAsConst(files)) { for (const QString &file : asConst(files)) {
qDebug("dropped %s", qUtf8Printable(file)); qDebug("dropped %s", qUtf8Printable(file));
startAsyncOp(); startAsyncOp();
m_pluginManager->installPlugin(file); m_pluginManager->installPlugin(file);
@ -136,7 +136,7 @@ void PluginSelectDialog::dropEvent(QDropEvent *event)
// Decode if we accept drag 'n drop or not // Decode if we accept drag 'n drop or not
void PluginSelectDialog::dragEnterEvent(QDragEnterEvent *event) void PluginSelectDialog::dragEnterEvent(QDragEnterEvent *event)
{ {
for (const QString &mime : copyAsConst(event->mimeData()->formats())) { for (const QString &mime : asConst(event->mimeData()->formats())) {
qDebug("mimeData: %s", qUtf8Printable(mime)); qDebug("mimeData: %s", qUtf8Printable(mime));
} }
@ -188,7 +188,7 @@ void PluginSelectDialog::on_closeButton_clicked()
void PluginSelectDialog::on_actionUninstall_triggered() void PluginSelectDialog::on_actionUninstall_triggered()
{ {
bool error = false; bool error = false;
for (QTreeWidgetItem *item : copyAsConst(m_ui->pluginsTree->selectedItems())) { for (QTreeWidgetItem *item : asConst(m_ui->pluginsTree->selectedItems())) {
int index = m_ui->pluginsTree->indexOfTopLevelItem(item); int index = m_ui->pluginsTree->indexOfTopLevelItem(item);
Q_ASSERT(index != -1); Q_ASSERT(index != -1);
QString id = item->text(PLUGIN_ID); QString id = item->text(PLUGIN_ID);
@ -212,7 +212,7 @@ void PluginSelectDialog::on_actionUninstall_triggered()
void PluginSelectDialog::enableSelection(bool enable) void PluginSelectDialog::enableSelection(bool enable)
{ {
for (QTreeWidgetItem *item : copyAsConst(m_ui->pluginsTree->selectedItems())) { for (QTreeWidgetItem *item : asConst(m_ui->pluginsTree->selectedItems())) {
int index = m_ui->pluginsTree->indexOfTopLevelItem(item); int index = m_ui->pluginsTree->indexOfTopLevelItem(item);
Q_ASSERT(index != -1); Q_ASSERT(index != -1);
QString id = item->text(PLUGIN_ID); QString id = item->text(PLUGIN_ID);
@ -265,7 +265,7 @@ void PluginSelectDialog::loadSupportedSearchPlugins()
{ {
// Some clean up first // Some clean up first
m_ui->pluginsTree->clear(); m_ui->pluginsTree->clear();
for (const QString &name : copyAsConst(m_pluginManager->allPlugins())) for (const QString &name : asConst(m_pluginManager->allPlugins()))
addNewPlugin(name); addNewPlugin(name);
} }
@ -380,7 +380,7 @@ void PluginSelectDialog::iconDownloaded(const QString &url, QString filePath)
QList<QSize> sizes = icon.availableSizes(); QList<QSize> sizes = icon.availableSizes();
bool invalid = (sizes.isEmpty() || icon.pixmap(sizes.first()).isNull()); bool invalid = (sizes.isEmpty() || icon.pixmap(sizes.first()).isNull());
if (!invalid) { if (!invalid) {
for (QTreeWidgetItem *item : copyAsConst(findItemsWithUrl(url))) { for (QTreeWidgetItem *item : asConst(findItemsWithUrl(url))) {
QString id = item->text(PLUGIN_ID); QString id = item->text(PLUGIN_ID);
PluginInfo *plugin = m_pluginManager->pluginInfo(id); PluginInfo *plugin = m_pluginManager->pluginInfo(id);
if (!plugin) continue; if (!plugin) continue;

View File

@ -128,7 +128,7 @@ bool SearchSortModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceP
const QAbstractItemModel *const sourceModel = this->sourceModel(); const QAbstractItemModel *const sourceModel = this->sourceModel();
if (m_isNameFilterEnabled && !m_searchTerm.isEmpty()) { if (m_isNameFilterEnabled && !m_searchTerm.isEmpty()) {
QString name = sourceModel->data(sourceModel->index(sourceRow, NAME, sourceParent)).toString(); QString name = sourceModel->data(sourceModel->index(sourceRow, NAME, sourceParent)).toString();
for (const QString &word : qAsConst(m_searchTermWords)) { for (const QString &word : asConst(m_searchTermWords)) {
int i = name.indexOf(word, 0, Qt::CaseInsensitive); int i = name.indexOf(word, 0, Qt::CaseInsensitive);
if (i == -1) { if (i == -1) {
return false; return false;

View File

@ -167,11 +167,11 @@ void SearchWidget::fillCatCombobox()
using QStrPair = QPair<QString, QString>; using QStrPair = QPair<QString, QString>;
QList<QStrPair> tmpList; QList<QStrPair> tmpList;
for (const QString &cat : copyAsConst(SearchPluginManager::instance()->getPluginCategories(selectedPlugin()))) for (const QString &cat : asConst(SearchPluginManager::instance()->getPluginCategories(selectedPlugin())))
tmpList << qMakePair(SearchPluginManager::categoryFullName(cat), cat); 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); }); std::sort(tmpList.begin(), tmpList.end(), [](const QStrPair &l, const QStrPair &r) { return (QString::localeAwareCompare(l.first, r.first) < 0); });
for (const QStrPair &p : qAsConst(tmpList)) { for (const QStrPair &p : asConst(tmpList)) {
qDebug("Supported category: %s", qUtf8Printable(p.second)); qDebug("Supported category: %s", qUtf8Printable(p.second));
m_ui->comboCategory->addItem(p.first, QVariant(p.second)); m_ui->comboCategory->addItem(p.first, QVariant(p.second));
} }
@ -189,11 +189,11 @@ void SearchWidget::fillPluginComboBox()
using QStrPair = QPair<QString, QString>; using QStrPair = QPair<QString, QString>;
QList<QStrPair> tmpList; QList<QStrPair> tmpList;
for (const QString &name : copyAsConst(SearchPluginManager::instance()->enabledPlugins())) for (const QString &name : asConst(SearchPluginManager::instance()->enabledPlugins()))
tmpList << qMakePair(SearchPluginManager::instance()->pluginFullName(name), name); tmpList << qMakePair(SearchPluginManager::instance()->pluginFullName(name), name);
std::sort(tmpList.begin(), tmpList.end(), [](const QStrPair &l, const QStrPair &r) { return (l.first < r.first); } ); std::sort(tmpList.begin(), tmpList.end(), [](const QStrPair &l, const QStrPair &r) { return (l.first < r.first); } );
for (const QStrPair &p : qAsConst(tmpList)) for (const QStrPair &p : asConst(tmpList))
m_ui->selectPlugin->addItem(p.first, QVariant(p.second)); m_ui->selectPlugin->addItem(p.first, QVariant(p.second));
if (m_ui->selectPlugin->count() > 3) if (m_ui->selectPlugin->count() > 3)

View File

@ -90,7 +90,7 @@ void StatsDialog::update()
// num_peers is not reliable (adds up peers, which didn't even overcome tcp handshake) // num_peers is not reliable (adds up peers, which didn't even overcome tcp handshake)
quint32 peers = 0; quint32 peers = 0;
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(BitTorrent::Session::instance()->torrents()))
peers += torrent->peersCount(); peers += torrent->peersCount();
m_ui->labelWriteStarve->setText(QString("%1%") m_ui->labelWriteStarve->setText(QString("%1%")

View File

@ -248,7 +248,7 @@ void TagFilterModel::torrentAboutToBeRemoved(BitTorrent::TorrentHandle *const to
if (torrent->tags().isEmpty()) if (torrent->tags().isEmpty())
untaggedItem()->decreaseTorrentsCount(); untaggedItem()->decreaseTorrentsCount();
for (TagModelItem *item : copyAsConst(findItems(torrent->tags()))) for (TagModelItem *item : asConst(findItems(torrent->tags())))
item->decreaseTorrentsCount(); item->decreaseTorrentsCount();
} }
@ -275,7 +275,7 @@ void TagFilterModel::populate()
[](Torrent *torrent) { return torrent->tags().isEmpty(); }); [](Torrent *torrent) { return torrent->tags().isEmpty(); });
addToModel(getSpecialUntaggedTag(), untaggedCount); addToModel(getSpecialUntaggedTag(), untaggedCount);
for (const QString &tag : copyAsConst(session->tags())) { for (const QString &tag : asConst(session->tags())) {
const int count = std::count_if(torrents.begin(), torrents.end(), const int count = std::count_if(torrents.begin(), torrents.end(),
[tag](Torrent *torrent) { return torrent->hasTag(tag); }); [tag](Torrent *torrent) { return torrent->hasTag(tag); });
addToModel(tag, count); addToModel(tag, count);

View File

@ -223,7 +223,7 @@ void TagFilterWidget::removeTag()
void TagFilterWidget::removeUnusedTags() void TagFilterWidget::removeUnusedTags()
{ {
auto session = BitTorrent::Session::instance(); auto session = BitTorrent::Session::instance();
for (const QString &tag : copyAsConst(session->tags())) for (const QString &tag : asConst(session->tags()))
if (model()->data(static_cast<TagFilterProxyModel *>(model())->index(tag), Qt::UserRole) == 0) if (model()->data(static_cast<TagFilterProxyModel *>(model())->index(tag), Qt::UserRole) == 0)
session->removeTag(tag); session->removeTag(tag);
updateGeometry(); updateGeometry();

View File

@ -267,14 +267,14 @@ QVector<int> TorrentContentModel::getFilePriorities() const
{ {
QVector<int> prio; QVector<int> prio;
prio.reserve(m_filesIndex.size()); prio.reserve(m_filesIndex.size());
for (const TorrentContentModelFile *file : qAsConst(m_filesIndex)) for (const TorrentContentModelFile *file : asConst(m_filesIndex))
prio.push_back(file->priority()); prio.push_back(file->priority());
return prio; return prio;
} }
bool TorrentContentModel::allFiltered() const bool TorrentContentModel::allFiltered() const
{ {
for (const TorrentContentModelFile *fileItem : qAsConst(m_filesIndex)) for (const TorrentContentModelFile *fileItem : asConst(m_filesIndex))
if (fileItem->priority() != prio::IGNORED) if (fileItem->priority() != prio::IGNORED)
return false; return false;
return true; return true;
@ -477,7 +477,7 @@ void TorrentContentModel::setupModelData(const BitTorrent::TorrentInfo &info)
// Iterate of parts of the path to create necessary folders // Iterate of parts of the path to create necessary folders
QStringList pathFolders = path.split('/', QString::SkipEmptyParts); QStringList pathFolders = path.split('/', QString::SkipEmptyParts);
pathFolders.removeLast(); pathFolders.removeLast();
for (const QString &pathPart : qAsConst(pathFolders)) { for (const QString &pathPart : asConst(pathFolders)) {
if (pathPart == ".unwanted") if (pathPart == ".unwanted")
continue; continue;
TorrentContentModelFolder* newParent = currentParent->childFolderWithName(pathPart); TorrentContentModelFolder* newParent = currentParent->childFolderWithName(pathPart);

View File

@ -86,7 +86,7 @@ TorrentContentModelItem *TorrentContentModelFolder::child(int row) const
TorrentContentModelFolder *TorrentContentModelFolder::childFolderWithName(const QString &name) const TorrentContentModelFolder *TorrentContentModelFolder::childFolderWithName(const QString &name) const
{ {
for (TorrentContentModelItem *child : qAsConst(m_childItems)) for (TorrentContentModelItem *child : asConst(m_childItems))
if ((child->itemType() == FolderType) && (child->name() == name)) if ((child->itemType() == FolderType) && (child->name() == name))
return static_cast<TorrentContentModelFolder *>(child); return static_cast<TorrentContentModelFolder *>(child);
return nullptr; return nullptr;
@ -133,7 +133,7 @@ void TorrentContentModelFolder::setPriority(int newPriority, bool updateParent)
// Update children // Update children
if (m_priority != prio::MIXED) if (m_priority != prio::MIXED)
for (TorrentContentModelItem *child : qAsConst(m_childItems)) for (TorrentContentModelItem *child : asConst(m_childItems))
child->setPriority(m_priority, false); child->setPriority(m_priority, false);
} }
@ -142,7 +142,7 @@ void TorrentContentModelFolder::recalculateProgress()
qreal tProgress = 0; qreal tProgress = 0;
qulonglong tSize = 0; qulonglong tSize = 0;
qulonglong tRemaining = 0; qulonglong tRemaining = 0;
for (TorrentContentModelItem *child : qAsConst(m_childItems)) { for (TorrentContentModelItem *child : asConst(m_childItems)) {
if (child->priority() == prio::IGNORED) if (child->priority() == prio::IGNORED)
continue; continue;
@ -165,7 +165,7 @@ void TorrentContentModelFolder::recalculateAvailability()
qreal tAvailability = 0; qreal tAvailability = 0;
qulonglong tSize = 0; qulonglong tSize = 0;
bool foundAnyData = false; bool foundAnyData = false;
for (TorrentContentModelItem *child : qAsConst(m_childItems)) { for (TorrentContentModelItem *child : asConst(m_childItems)) {
if (child->priority() == prio::IGNORED) if (child->priority() == prio::IGNORED)
continue; continue;

View File

@ -220,7 +220,7 @@ TrackerFiltersList::TrackerFiltersList(QWidget *parent, TransferListWidget *tran
TrackerFiltersList::~TrackerFiltersList() TrackerFiltersList::~TrackerFiltersList()
{ {
for (const QString &iconPath : qAsConst(m_iconPaths)) for (const QString &iconPath : asConst(m_iconPaths))
Utils::Fs::forceRemove(iconPath); Utils::Fs::forceRemove(iconPath);
} }

View File

@ -62,7 +62,7 @@ TransferListModel::TransferListModel(QObject *parent)
{ {
// Load the torrents // Load the torrents
using namespace BitTorrent; using namespace BitTorrent;
for (TorrentHandle *const torrent : copyAsConst(Session::instance()->torrents())) for (TorrentHandle *const torrent : asConst(Session::instance()->torrents()))
addTorrent(torrent); addTorrent(torrent);
// Listen for torrent changes // Listen for torrent changes

View File

@ -382,7 +382,7 @@ void TransferListWidget::torrentDoubleClicked()
QList<BitTorrent::TorrentHandle *> TransferListWidget::getSelectedTorrents() const QList<BitTorrent::TorrentHandle *> TransferListWidget::getSelectedTorrents() const
{ {
QList<BitTorrent::TorrentHandle *> torrents; QList<BitTorrent::TorrentHandle *> torrents;
for (const QModelIndex &index : copyAsConst(selectionModel()->selectedRows())) for (const QModelIndex &index : asConst(selectionModel()->selectedRows()))
torrents << m_listModel->torrentHandle(mapToSource(index)); torrents << m_listModel->torrentHandle(mapToSource(index));
return torrents; return torrents;
@ -413,25 +413,25 @@ void TransferListWidget::setSelectedTorrentsLocation()
void TransferListWidget::pauseAllTorrents() void TransferListWidget::pauseAllTorrents()
{ {
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(BitTorrent::Session::instance()->torrents()))
torrent->pause(); torrent->pause();
} }
void TransferListWidget::resumeAllTorrents() void TransferListWidget::resumeAllTorrents()
{ {
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(BitTorrent::Session::instance()->torrents()))
torrent->resume(); torrent->resume();
} }
void TransferListWidget::startSelectedTorrents() void TransferListWidget::startSelectedTorrents()
{ {
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents()))
torrent->resume(); torrent->resume();
} }
void TransferListWidget::forceStartSelectedTorrents() void TransferListWidget::forceStartSelectedTorrents()
{ {
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents()))
torrent->resume(true); torrent->resume(true);
} }
@ -446,7 +446,7 @@ void TransferListWidget::startVisibleTorrents()
void TransferListWidget::pauseSelectedTorrents() void TransferListWidget::pauseSelectedTorrents()
{ {
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents()))
torrent->pause(); torrent->pause();
} }
@ -496,7 +496,7 @@ void TransferListWidget::deleteVisibleTorrents()
&& !DeletionConfirmationDialog::askForDeletionConfirmation(this, deleteLocalFiles, torrents.size(), torrents[0]->name())) && !DeletionConfirmationDialog::askForDeletionConfirmation(this, deleteLocalFiles, torrents.size(), torrents[0]->name()))
return; return;
for (BitTorrent::TorrentHandle *const torrent : qAsConst(torrents)) for (BitTorrent::TorrentHandle *const torrent : asConst(torrents))
BitTorrent::Session::instance()->deleteTorrent(torrent->hash(), deleteLocalFiles); BitTorrent::Session::instance()->deleteTorrent(torrent->hash(), deleteLocalFiles);
} }
@ -529,7 +529,7 @@ void TransferListWidget::bottomPrioSelectedTorrents()
void TransferListWidget::copySelectedMagnetURIs() const void TransferListWidget::copySelectedMagnetURIs() const
{ {
QStringList magnetUris; QStringList magnetUris;
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents()))
magnetUris << torrent->toMagnetUri(); magnetUris << torrent->toMagnetUri();
qApp->clipboard()->setText(magnetUris.join('\n')); qApp->clipboard()->setText(magnetUris.join('\n'));
@ -538,7 +538,7 @@ void TransferListWidget::copySelectedMagnetURIs() const
void TransferListWidget::copySelectedNames() const void TransferListWidget::copySelectedNames() const
{ {
QStringList torrentNames; QStringList torrentNames;
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents()))
torrentNames << torrent->name(); torrentNames << torrent->name();
qApp->clipboard()->setText(torrentNames.join('\n')); qApp->clipboard()->setText(torrentNames.join('\n'));
@ -547,7 +547,7 @@ void TransferListWidget::copySelectedNames() const
void TransferListWidget::copySelectedHashes() const void TransferListWidget::copySelectedHashes() const
{ {
QStringList torrentHashes; QStringList torrentHashes;
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents()))
torrentHashes << torrent->hash(); torrentHashes << torrent->hash();
qApp->clipboard()->setText(torrentHashes.join('\n')); qApp->clipboard()->setText(torrentHashes.join('\n'));
@ -567,13 +567,13 @@ void TransferListWidget::openSelectedTorrentsFolder() const
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
// On macOS you expect both the files and folders to be opened in their parent // 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. // folders prehilighted for opening, so we use a custom method.
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) { for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) {
QString path = torrent->contentPath(true); QString path = torrent->contentPath(true);
pathsList.insert(path); pathsList.insert(path);
} }
MacUtils::openFiles(pathsList); MacUtils::openFiles(pathsList);
#else #else
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) { for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) {
QString path = torrent->contentPath(true); QString path = torrent->contentPath(true);
if (!pathsList.contains(path)) { if (!pathsList.contains(path)) {
if (torrent->filesCount() == 1) if (torrent->filesCount() == 1)
@ -588,7 +588,7 @@ void TransferListWidget::openSelectedTorrentsFolder() const
void TransferListWidget::previewSelectedTorrents() void TransferListWidget::previewSelectedTorrents()
{ {
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) { for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) {
if (torrent->hasMetadata()) if (torrent->hasMetadata())
new PreviewSelectDialog(this, torrent); new PreviewSelectDialog(this, torrent);
} }
@ -597,7 +597,7 @@ void TransferListWidget::previewSelectedTorrents()
void TransferListWidget::setDlLimitSelectedTorrents() void TransferListWidget::setDlLimitSelectedTorrents()
{ {
QList<BitTorrent::TorrentHandle *> torrentsList; QList<BitTorrent::TorrentHandle *> torrentsList;
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) { for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) {
if (torrent->isSeed()) if (torrent->isSeed())
continue; continue;
torrentsList += torrent; torrentsList += torrent;
@ -605,7 +605,7 @@ void TransferListWidget::setDlLimitSelectedTorrents()
if (torrentsList.empty()) return; if (torrentsList.empty()) return;
int oldLimit = torrentsList.first()->downloadLimit(); int oldLimit = torrentsList.first()->downloadLimit();
for (BitTorrent::TorrentHandle *const torrent : qAsConst(torrentsList)) { for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) {
if (torrent->downloadLimit() != oldLimit) { if (torrent->downloadLimit() != oldLimit) {
oldLimit = -1; oldLimit = -1;
break; break;
@ -618,7 +618,7 @@ void TransferListWidget::setDlLimitSelectedTorrents()
, BitTorrent::Session::instance()->globalDownloadSpeedLimit()); , BitTorrent::Session::instance()->globalDownloadSpeedLimit());
if (!ok) return; if (!ok) return;
for (BitTorrent::TorrentHandle *const torrent : qAsConst(torrentsList)) { for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) {
qDebug("Applying download speed limit of %ld Kb/s to torrent %s", (newLimit / 1024l), qUtf8Printable(torrent->hash())); qDebug("Applying download speed limit of %ld Kb/s to torrent %s", (newLimit / 1024l), qUtf8Printable(torrent->hash()));
torrent->setDownloadLimit(newLimit); torrent->setDownloadLimit(newLimit);
} }
@ -630,7 +630,7 @@ void TransferListWidget::setUpLimitSelectedTorrents()
if (torrentsList.empty()) return; if (torrentsList.empty()) return;
int oldLimit = torrentsList.first()->uploadLimit(); int oldLimit = torrentsList.first()->uploadLimit();
for (BitTorrent::TorrentHandle *const torrent : qAsConst(torrentsList)) { for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) {
if (torrent->uploadLimit() != oldLimit) { if (torrent->uploadLimit() != oldLimit) {
oldLimit = -1; oldLimit = -1;
break; break;
@ -643,7 +643,7 @@ void TransferListWidget::setUpLimitSelectedTorrents()
, BitTorrent::Session::instance()->globalUploadSpeedLimit()); , BitTorrent::Session::instance()->globalUploadSpeedLimit());
if (!ok) return; if (!ok) return;
for (BitTorrent::TorrentHandle *const torrent : qAsConst(torrentsList)) { for (BitTorrent::TorrentHandle *const torrent : asConst(torrentsList)) {
qDebug("Applying upload speed limit of %ld Kb/s to torrent %s", (newLimit / 1024l), qUtf8Printable(torrent->hash())); qDebug("Applying upload speed limit of %ld Kb/s to torrent %s", (newLimit / 1024l), qUtf8Printable(torrent->hash()));
torrent->setUploadLimit(newLimit); torrent->setUploadLimit(newLimit);
} }
@ -687,13 +687,13 @@ void TransferListWidget::recheckSelectedTorrents()
if (ret != QMessageBox::Yes) return; if (ret != QMessageBox::Yes) return;
} }
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents()))
torrent->forceRecheck(); torrent->forceRecheck();
} }
void TransferListWidget::reannounceSelectedTorrents() void TransferListWidget::reannounceSelectedTorrents()
{ {
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents()))
torrent->forceReannounce(); torrent->forceReannounce();
} }
@ -739,7 +739,7 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&)
void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const
{ {
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) { for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents())) {
if (torrent->hasMetadata()) if (torrent->hasMetadata())
torrent->setSuperSeeding(!torrent->superSeeding()); torrent->setSuperSeeding(!torrent->superSeeding());
} }
@ -747,19 +747,19 @@ void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const
void TransferListWidget::toggleSelectedTorrentsSequentialDownload() const void TransferListWidget::toggleSelectedTorrentsSequentialDownload() const
{ {
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents()))
torrent->toggleSequentialDownload(); torrent->toggleSequentialDownload();
} }
void TransferListWidget::toggleSelectedFirstLastPiecePrio() const void TransferListWidget::toggleSelectedFirstLastPiecePrio() const
{ {
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents()))
torrent->toggleFirstLastPiecePriority(); torrent->toggleFirstLastPiecePriority();
} }
void TransferListWidget::setSelectedAutoTMMEnabled(bool enabled) const void TransferListWidget::setSelectedAutoTMMEnabled(bool enabled) const
{ {
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(getSelectedTorrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(getSelectedTorrents()))
torrent->setAutoTMMEnabled(enabled); torrent->setAutoTMMEnabled(enabled);
} }
@ -812,7 +812,7 @@ QStringList TransferListWidget::askTagsForSelection(const QString &dialogTitle)
void TransferListWidget::applyToSelectedTorrents(const std::function<void (BitTorrent::TorrentHandle *const)> &fn) void TransferListWidget::applyToSelectedTorrents(const std::function<void (BitTorrent::TorrentHandle *const)> &fn)
{ {
for (const QModelIndex &index : copyAsConst(selectionModel()->selectedRows())) { for (const QModelIndex &index : asConst(selectionModel()->selectedRows())) {
BitTorrent::TorrentHandle *const torrent = m_listModel->torrentHandle(mapToSource(index)); BitTorrent::TorrentHandle *const torrent = m_listModel->torrentHandle(mapToSource(index));
Q_ASSERT(torrent); Q_ASSERT(torrent);
fn(torrent); fn(torrent);
@ -840,7 +840,7 @@ void TransferListWidget::renameSelectedTorrent()
void TransferListWidget::setSelectionCategory(QString category) void TransferListWidget::setSelectionCategory(QString category)
{ {
for (const QModelIndex &index : copyAsConst(selectionModel()->selectedRows())) for (const QModelIndex &index : asConst(selectionModel()->selectedRows()))
m_listModel->setData(m_listModel->index(mapToSource(index).row(), TransferListModel::TR_CATEGORY), category, Qt::DisplayRole); m_listModel->setData(m_listModel->index(mapToSource(index).row(), TransferListModel::TR_CATEGORY), category, Qt::DisplayRole);
} }
@ -1023,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("list-add"), tr("New...", "New category..."));
categoryActions << categoryMenu->addAction(GuiIconProvider::instance()->getIcon("edit-clear"), tr("Reset", "Reset category")); categoryActions << categoryMenu->addAction(GuiIconProvider::instance()->getIcon("edit-clear"), tr("Reset", "Reset category"));
categoryMenu->addSeparator(); categoryMenu->addSeparator();
for (QString category : qAsConst(categories)) { for (QString category : asConst(categories)) {
category.replace('&', "&&"); // avoid '&' becomes accelerator key category.replace('&', "&&"); // avoid '&' becomes accelerator key
QAction *cat = new QAction(GuiIconProvider::instance()->getIcon("inode-directory"), category, categoryMenu); QAction *cat = new QAction(GuiIconProvider::instance()->getIcon("inode-directory"), category, categoryMenu);
if (allSameCategory && (category == firstCategory)) { if (allSameCategory && (category == firstCategory)) {
@ -1042,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("list-add"), tr("Add...", "Add / assign multiple tags..."));
tagsActions << tagsMenu->addAction(GuiIconProvider::instance()->getIcon("edit-clear"), tr("Remove All", "Remove all tags")); tagsActions << tagsMenu->addAction(GuiIconProvider::instance()->getIcon("edit-clear"), tr("Remove All", "Remove all tags"));
tagsMenu->addSeparator(); tagsMenu->addSeparator();
for (const QString &tag : qAsConst(tags)) { for (const QString &tag : asConst(tags)) {
const Qt::CheckState initialState = tagsInAll.contains(tag) ? Qt::Checked const Qt::CheckState initialState = tagsInAll.contains(tag) ? Qt::Checked
: tagsInAny.contains(tag) ? Qt::PartiallyChecked : tagsInAny.contains(tag) ? Qt::PartiallyChecked
: Qt::Unchecked; : Qt::Unchecked;

View File

@ -202,7 +202,7 @@ void AppController::preferencesAction()
data["bypass_local_auth"] = !pref->isWebUiLocalAuthEnabled(); data["bypass_local_auth"] = !pref->isWebUiLocalAuthEnabled();
data["bypass_auth_subnet_whitelist_enabled"] = pref->isWebUiAuthSubnetWhitelistEnabled(); data["bypass_auth_subnet_whitelist_enabled"] = pref->isWebUiAuthSubnetWhitelistEnabled();
QStringList authSubnetWhitelistStringList; QStringList authSubnetWhitelistStringList;
for (const Utils::Net::Subnet &subnet : copyAsConst(pref->getWebUiAuthSubnetWhitelist())) for (const Utils::Net::Subnet &subnet : asConst(pref->getWebUiAuthSubnetWhitelist()))
authSubnetWhitelistStringList << Utils::Net::subnetToString(subnet); authSubnetWhitelistStringList << Utils::Net::subnetToString(subnet);
data["bypass_auth_subnet_whitelist"] = authSubnetWhitelistStringList.join("\n"); data["bypass_auth_subnet_whitelist"] = authSubnetWhitelistStringList.join("\n");
// Security // Security

View File

@ -72,7 +72,7 @@ void LogController::mainAction()
Logger *const logger = Logger::instance(); Logger *const logger = Logger::instance();
QVariantList msgList; QVariantList msgList;
for (const Log::Msg &msg : copyAsConst(logger->getMessages(lastKnownId))) { for (const Log::Msg &msg : asConst(logger->getMessages(lastKnownId))) {
if (!((msg.type == Log::NORMAL && isNormal) if (!((msg.type == Log::NORMAL && isNormal)
|| (msg.type == Log::INFO && isInfo) || (msg.type == Log::INFO && isInfo)
|| (msg.type == Log::WARNING && isWarning) || (msg.type == Log::WARNING && isWarning)
@ -111,7 +111,7 @@ void LogController::peersAction()
Logger *const logger = Logger::instance(); Logger *const logger = Logger::instance();
QVariantList peerList; QVariantList peerList;
for (const Log::Peer &peer : copyAsConst(logger->getPeers(lastKnownId))) { for (const Log::Peer &peer : asConst(logger->getPeers(lastKnownId))) {
QVariantMap map; QVariantMap map;
map[KEY_LOG_ID] = peer.id; map[KEY_LOG_ID] = peer.id;
map[KEY_LOG_TIMESTAMP] = peer.timestamp; map[KEY_LOG_TIMESTAMP] = peer.timestamp;

View File

@ -202,7 +202,7 @@ void SearchController::categoriesAction()
const QString name = params()["pluginName"].trimmed(); const QString name = params()["pluginName"].trimmed();
categories << SearchPluginManager::categoryFullName("all"); categories << SearchPluginManager::categoryFullName("all");
for (const QString &category : copyAsConst(SearchPluginManager::instance()->getPluginCategories(name))) for (const QString &category : asConst(SearchPluginManager::instance()->getPluginCategories(name)))
categories << SearchPluginManager::categoryFullName(category); categories << SearchPluginManager::categoryFullName(category);
const QJsonArray result = QJsonArray::fromStringList(categories); const QJsonArray result = QJsonArray::fromStringList(categories);
@ -263,7 +263,7 @@ void SearchController::checkForUpdatesFinished(const QHash<QString, PluginVersio
LogMsg(tr("Updating %1 plugins").arg(updateInfo.size()), Log::INFO); LogMsg(tr("Updating %1 plugins").arg(updateInfo.size()), Log::INFO);
SearchPluginManager *const pluginManager = SearchPluginManager::instance(); SearchPluginManager *const pluginManager = SearchPluginManager::instance();
for (const QString &pluginName : copyAsConst(updateInfo.keys())) { for (const QString &pluginName : asConst(updateInfo.keys())) {
LogMsg(tr("Updating plugin %1").arg(pluginName), Log::INFO); LogMsg(tr("Updating plugin %1").arg(pluginName), Log::INFO);
pluginManager->updatePlugin(pluginName); pluginManager->updatePlugin(pluginName);
} }

View File

@ -134,7 +134,7 @@ namespace
// num_peers is not reliable (adds up peers, which didn't even overcome tcp handshake) // num_peers is not reliable (adds up peers, which didn't even overcome tcp handshake)
quint32 peers = 0; quint32 peers = 0;
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) for (BitTorrent::TorrentHandle *const torrent : asConst(BitTorrent::Session::instance()->torrents()))
peers += torrent->peersCount(); 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_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"; map[KEY_TRANSFER_READ_CACHE_OVERLOAD] = ((sessionStatus.diskReadQueue > 0) && (peers > 0)) ? Utils::String::fromDouble((100. * sessionStatus.diskReadQueue) / peers, 2) : "0";
@ -410,7 +410,7 @@ void SyncController::maindataAction()
BitTorrent::Session *const session = BitTorrent::Session::instance(); BitTorrent::Session *const session = BitTorrent::Session::instance();
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(session->torrents())) { for (BitTorrent::TorrentHandle *const torrent : asConst(session->torrents())) {
QVariantMap map = serialize(*torrent); QVariantMap map = serialize(*torrent);
map.remove(KEY_TORRENT_HASH); map.remove(KEY_TORRENT_HASH);

View File

@ -113,7 +113,7 @@ namespace
void applyToTorrents(const QStringList &hashes, const std::function<void (BitTorrent::TorrentHandle *torrent)> &func) void applyToTorrents(const QStringList &hashes, const std::function<void (BitTorrent::TorrentHandle *torrent)> &func)
{ {
if ((hashes.size() == 1) && (hashes[0] == QLatin1String("all"))) { if ((hashes.size() == 1) && (hashes[0] == QLatin1String("all"))) {
for (BitTorrent::TorrentHandle *torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) for (BitTorrent::TorrentHandle *torrent : asConst(BitTorrent::Session::instance()->torrents()))
func(torrent); func(torrent);
} }
else { else {
@ -167,7 +167,7 @@ void TorrentsController::infoAction()
QVariantList torrentList; QVariantList torrentList;
TorrentFilter torrentFilter(filter, (hashSet.isEmpty() ? TorrentFilter::AnyHash : hashSet), category); TorrentFilter torrentFilter(filter, (hashSet.isEmpty() ? TorrentFilter::AnyHash : hashSet), category);
for (BitTorrent::TorrentHandle *const torrent : copyAsConst(BitTorrent::Session::instance()->torrents())) { for (BitTorrent::TorrentHandle *const torrent : asConst(BitTorrent::Session::instance()->torrents())) {
if (torrentFilter.match(torrent)) if (torrentFilter.match(torrent))
torrentList.append(serialize(*torrent)); torrentList.append(serialize(*torrent));
} }
@ -307,7 +307,7 @@ void TorrentsController::trackersAction()
throw APIError(APIErrorType::NotFound); throw APIError(APIErrorType::NotFound);
QHash<QString, BitTorrent::TrackerInfo> trackersData = torrent->trackerInfos(); QHash<QString, BitTorrent::TrackerInfo> trackersData = torrent->trackerInfos();
for (const BitTorrent::TrackerEntry &tracker : copyAsConst(torrent->trackers())) { for (const BitTorrent::TrackerEntry &tracker : asConst(torrent->trackers())) {
QVariantMap trackerDict; QVariantMap trackerDict;
trackerDict[KEY_TRACKER_URL] = tracker.url(); trackerDict[KEY_TRACKER_URL] = tracker.url();
const BitTorrent::TrackerInfo data = trackersData.value(tracker.url()); const BitTorrent::TrackerInfo data = trackersData.value(tracker.url());
@ -346,7 +346,7 @@ void TorrentsController::webseedsAction()
if (!torrent) if (!torrent)
throw APIError(APIErrorType::NotFound); throw APIError(APIErrorType::NotFound);
for (const QUrl &webseed : copyAsConst(torrent->urlSeeds())) { for (const QUrl &webseed : asConst(torrent->urlSeeds())) {
QVariantMap webSeedDict; QVariantMap webSeedDict;
webSeedDict[KEY_WEBSEED_URL] = webseed.toString(); webSeedDict[KEY_WEBSEED_URL] = webseed.toString();
webSeedList.append(webSeedDict); webSeedList.append(webSeedDict);
@ -498,7 +498,7 @@ void TorrentsController::addAction()
params.downloadLimit = (dlLimit > 0) ? dlLimit : -1; params.downloadLimit = (dlLimit > 0) ? dlLimit : -1;
bool partialSuccess = false; bool partialSuccess = false;
for (QString url : copyAsConst(urls.split('\n'))) { for (QString url : asConst(urls.split('\n'))) {
url = url.trimmed(); url = url.trimmed();
if (!url.isEmpty()) { if (!url.isEmpty()) {
Net::DownloadManager::instance()->setCookiesFromUrl(cookies, QUrl::fromEncoded(url.toUtf8())); Net::DownloadManager::instance()->setCookiesFromUrl(cookies, QUrl::fromEncoded(url.toUtf8()));
@ -531,7 +531,7 @@ void TorrentsController::addTrackersAction()
BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(hash); BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(hash);
if (torrent) { if (torrent) {
QList<BitTorrent::TrackerEntry> trackers; QList<BitTorrent::TrackerEntry> trackers;
for (QString url : copyAsConst(params()["urls"].split('\n'))) { for (QString url : asConst(params()["urls"].split('\n'))) {
url = url.trimmed(); url = url.trimmed();
if (!url.isEmpty()) if (!url.isEmpty())
trackers << url; trackers << url;

View File

@ -525,7 +525,7 @@ Http::Response WebApplication::processRequest(const Http::Request &request, cons
if (m_request.method == Http::METHOD_GET) { if (m_request.method == Http::METHOD_GET) {
// Parse GET parameters // Parse GET parameters
using namespace Utils::ByteArray; using namespace Utils::ByteArray;
for (const QByteArray &param : copyAsConst(splitToViews(m_request.query, "&"))) { for (const QByteArray &param : asConst(splitToViews(m_request.query, "&"))) {
const int sepPos = param.indexOf('='); const int sepPos = param.indexOf('=');
if (sepPos <= 0) continue; // ignores params without name if (sepPos <= 0) continue; // ignores params without name