Add const to many vars and arguments

Also remove const in declarations' arguments that are passed by value
This commit is contained in:
thalieht 2019-02-09 17:40:14 +02:00
parent fc534e88a3
commit ca3ce87e06
21 changed files with 217 additions and 219 deletions

View file

@ -127,7 +127,7 @@ Application::Application(const QString &id, int &argc, char **argv)
setApplicationName("qBittorrent"); setApplicationName("qBittorrent");
validateCommandLineParameters(); validateCommandLineParameters();
QString profileDir = m_commandLineArgs.portableMode const QString profileDir = m_commandLineArgs.portableMode
? QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(DEFAULT_PORTABLE_MODE_PROFILE_DIR) ? QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(DEFAULT_PORTABLE_MODE_PROFILE_DIR)
: m_commandLineArgs.profileDir; : m_commandLineArgs.profileDir;
@ -185,7 +185,7 @@ bool Application::isFileLoggerEnabled() const
return settings()->loadValue(KEY_FILELOGGER_ENABLED, true).toBool(); return settings()->loadValue(KEY_FILELOGGER_ENABLED, true).toBool();
} }
void Application::setFileLoggerEnabled(bool value) void Application::setFileLoggerEnabled(const bool value)
{ {
if (value && !m_fileLogger) if (value && !m_fileLogger)
m_fileLogger = new FileLogger(fileLoggerPath(), isFileLoggerBackup(), fileLoggerMaxSize(), isFileLoggerDeleteOld(), fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType())); m_fileLogger = new FileLogger(fileLoggerPath(), isFileLoggerBackup(), fileLoggerMaxSize(), isFileLoggerDeleteOld(), fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType()));
@ -212,7 +212,7 @@ bool Application::isFileLoggerBackup() const
return settings()->loadValue(KEY_FILELOGGER_BACKUP, true).toBool(); return settings()->loadValue(KEY_FILELOGGER_BACKUP, true).toBool();
} }
void Application::setFileLoggerBackup(bool value) void Application::setFileLoggerBackup(const bool value)
{ {
if (m_fileLogger) if (m_fileLogger)
m_fileLogger->setBackup(value); m_fileLogger->setBackup(value);
@ -224,7 +224,7 @@ bool Application::isFileLoggerDeleteOld() const
return settings()->loadValue(KEY_FILELOGGER_DELETEOLD, true).toBool(); return settings()->loadValue(KEY_FILELOGGER_DELETEOLD, true).toBool();
} }
void Application::setFileLoggerDeleteOld(bool value) void Application::setFileLoggerDeleteOld(const bool value)
{ {
if (value && m_fileLogger) if (value && m_fileLogger)
m_fileLogger->deleteOld(fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType())); m_fileLogger->deleteOld(fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType()));
@ -233,13 +233,13 @@ void Application::setFileLoggerDeleteOld(bool value)
int Application::fileLoggerMaxSize() const int Application::fileLoggerMaxSize() const
{ {
int val = settings()->loadValue(KEY_FILELOGGER_MAXSIZEBYTES, DEFAULT_FILELOG_SIZE).toInt(); const int val = settings()->loadValue(KEY_FILELOGGER_MAXSIZEBYTES, DEFAULT_FILELOG_SIZE).toInt();
return std::min(std::max(val, MIN_FILELOG_SIZE), MAX_FILELOG_SIZE); return std::min(std::max(val, MIN_FILELOG_SIZE), MAX_FILELOG_SIZE);
} }
void Application::setFileLoggerMaxSize(const int bytes) void Application::setFileLoggerMaxSize(const int bytes)
{ {
int clampedValue = std::min(std::max(bytes, MIN_FILELOG_SIZE), MAX_FILELOG_SIZE); const int clampedValue = std::min(std::max(bytes, MIN_FILELOG_SIZE), MAX_FILELOG_SIZE);
if (m_fileLogger) if (m_fileLogger)
m_fileLogger->setMaxSize(clampedValue); m_fileLogger->setMaxSize(clampedValue);
settings()->storeValue(KEY_FILELOGGER_MAXSIZEBYTES, clampedValue); settings()->storeValue(KEY_FILELOGGER_MAXSIZEBYTES, clampedValue);
@ -247,7 +247,7 @@ void Application::setFileLoggerMaxSize(const int bytes)
int Application::fileLoggerAge() const int Application::fileLoggerAge() const
{ {
int val = settings()->loadValue(KEY_FILELOGGER_AGE, 1).toInt(); const int val = settings()->loadValue(KEY_FILELOGGER_AGE, 1).toInt();
return std::min(std::max(val, 1), 365); return std::min(std::max(val, 1), 365);
} }
@ -258,7 +258,7 @@ void Application::setFileLoggerAge(const int value)
int Application::fileLoggerAgeType() const int Application::fileLoggerAgeType() const
{ {
int val = settings()->loadValue(KEY_FILELOGGER_AGETYPE, 1).toInt(); const int val = settings()->loadValue(KEY_FILELOGGER_AGETYPE, 1).toInt();
return ((val < 0) || (val > 2)) ? 1 : val; return ((val < 0) || (val > 2)) ? 1 : val;
} }
@ -269,7 +269,7 @@ void Application::setFileLoggerAgeType(const int value)
void Application::processMessage(const QString &message) void Application::processMessage(const QString &message)
{ {
QStringList params = message.split(PARAMS_SEPARATOR, QString::SkipEmptyParts); const QStringList params = message.split(PARAMS_SEPARATOR, QString::SkipEmptyParts);
// If Application is not running (i.e., other // If Application is not running (i.e., other
// components are not ready) store params // components are not ready) store params
if (m_running) if (m_running)
@ -572,7 +572,7 @@ int Application::exec(const QStringList &params)
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
bool Application::isRunning() bool Application::isRunning()
{ {
bool running = BaseApplication::isRunning(); const bool running = BaseApplication::isRunning();
QSharedMemory *sharedMem = new QSharedMemory(id() + QLatin1String("-shared-memory-key"), this); QSharedMemory *sharedMem = new QSharedMemory(id() + QLatin1String("-shared-memory-key"), this);
if (!running) { if (!running) {
// First instance creates shared memory and store PID // First instance creates shared memory and store PID
@ -622,7 +622,7 @@ void Application::initializeTranslation()
{ {
Preferences *const pref = Preferences::instance(); Preferences *const pref = Preferences::instance();
// Load translation // Load translation
QString localeStr = pref->getLocale(); const QString localeStr = pref->getLocale();
if (m_qtTranslator.load(QLatin1String("qtbase_") + localeStr, QLibraryInfo::location(QLibraryInfo::TranslationsPath)) || if (m_qtTranslator.load(QLatin1String("qtbase_") + localeStr, QLibraryInfo::location(QLibraryInfo::TranslationsPath)) ||
m_qtTranslator.load(QLatin1String("qt_") + localeStr, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) m_qtTranslator.load(QLatin1String("qt_") + localeStr, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))

View file

@ -99,11 +99,11 @@ public:
bool isFileLoggerDeleteOld() const; bool isFileLoggerDeleteOld() const;
void setFileLoggerDeleteOld(bool value); void setFileLoggerDeleteOld(bool value);
int fileLoggerMaxSize() const; int fileLoggerMaxSize() const;
void setFileLoggerMaxSize(const int bytes); void setFileLoggerMaxSize(int bytes);
int fileLoggerAge() const; int fileLoggerAge() const;
void setFileLoggerAge(const int value); void setFileLoggerAge(int value);
int fileLoggerAgeType() const; int fileLoggerAgeType() const;
void setFileLoggerAgeType(const int value); void setFileLoggerAgeType(int value);
protected: protected:
#ifndef DISABLE_GUI #ifndef DISABLE_GUI

View file

@ -276,7 +276,7 @@ namespace
TriStateBool value(const QProcessEnvironment &env) const TriStateBool value(const QProcessEnvironment &env) const
{ {
QString val = env.value(envVarName(), "-1"); const QString val = env.value(envVarName(), "-1");
if (val.isEmpty()) { if (val.isEmpty()) {
return TriStateBool(m_defaultValue); return TriStateBool(m_defaultValue);

View file

@ -85,8 +85,8 @@ void FileLogger::changePath(const QString &newPath)
void FileLogger::deleteOld(const int age, const FileLogAgeType ageType) void FileLogger::deleteOld(const int age, const FileLogAgeType ageType)
{ {
QDateTime date = QDateTime::currentDateTime(); const QDateTime date = QDateTime::currentDateTime();
QDir dir(Utils::Fs::branchPath(m_path)); const QDir dir(Utils::Fs::branchPath(m_path));
for (const QFileInfo &file : asConst(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();
@ -111,7 +111,7 @@ void FileLogger::setBackup(bool value)
m_backup = value; m_backup = value;
} }
void FileLogger::setMaxSize(int value) void FileLogger::setMaxSize(const int value)
{ {
m_maxSize = value; m_maxSize = value;
} }

View file

@ -52,11 +52,11 @@ public:
YEARS YEARS
}; };
FileLogger(const QString &path, const bool backup, const int maxSize, const bool deleteOld, const int age, const FileLogAgeType ageType); FileLogger(const QString &path, bool backup, int maxSize, bool deleteOld, int age, FileLogAgeType ageType);
~FileLogger(); ~FileLogger();
void changePath(const QString &newPath); void changePath(const QString &newPath);
void deleteOld(const int age, const FileLogAgeType ageType); void deleteOld(int age, FileLogAgeType ageType);
void setBackup(bool value); void setBackup(bool value);
void setMaxSize(int value); void setMaxSize(int value);

View file

@ -115,7 +115,7 @@ int main(int argc, char *argv[])
try { try {
// Create Application // Create Application
QString appId = QLatin1String("qBittorrent-") + Utils::Misc::getUserIDString(); const QString appId = QLatin1String("qBittorrent-") + Utils::Misc::getUserIDString();
QScopedPointer<Application> app(new Application(appId, argc, argv)); QScopedPointer<Application> app(new Application(appId, argc, argv));
const QBtCommandLineParameters params = app->commandLineArgs(); const QBtCommandLineParameters params = app->commandLineArgs();
@ -254,7 +254,7 @@ void reportToUser(const char *str)
{ {
const size_t strLen = strlen(str); const size_t strLen = strlen(str);
if (write(STDERR_FILENO, str, strLen) < static_cast<ssize_t>(strLen)) { if (write(STDERR_FILENO, str, strLen) < static_cast<ssize_t>(strLen)) {
auto dummy = write(STDOUT_FILENO, str, strLen); const auto dummy = write(STDOUT_FILENO, str, strLen);
Q_UNUSED(dummy); Q_UNUSED(dummy);
} }
} }
@ -304,7 +304,7 @@ void showSplashScreen()
{ {
QPixmap splashImg(":/icons/skin/splash.png"); QPixmap splashImg(":/icons/skin/splash.png");
QPainter painter(&splashImg); QPainter painter(&splashImg);
QString version = QBT_VERSION; const QString version = QBT_VERSION;
painter.setPen(QPen(Qt::white)); painter.setPen(QPen(Qt::white));
painter.setFont(QFont("Arial", 22, QFont::Black)); painter.setFont(QFont("Arial", 22, QFont::Black));
painter.drawText(224 - painter.fontMetrics().width(version), 270, version); painter.drawText(224 - painter.fontMetrics().width(version), 270, version);
@ -322,7 +322,7 @@ void displayVersion()
void displayBadArgMessage(const QString &message) void displayBadArgMessage(const QString &message)
{ {
QString help = QObject::tr("Run application with -h option to read about command line parameters."); const QString help = QObject::tr("Run application with -h option to read about command line parameters.");
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
QMessageBox msgBox(QMessageBox::Critical, QObject::tr("Bad command line"), QMessageBox msgBox(QMessageBox::Critical, QObject::tr("Bad command line"),
message + QLatin1Char('\n') + help, QMessageBox::Ok); message + QLatin1Char('\n') + help, QMessageBox::Ok);
@ -350,7 +350,7 @@ bool userAgreesWithLegalNotice()
+ QObject::tr("Press %1 key to accept and continue...").arg("'y'") + '\n'; + QObject::tr("Press %1 key to accept and continue...").arg("'y'") + '\n';
printf("%s", qUtf8Printable(eula)); printf("%s", qUtf8Printable(eula));
char ret = getchar(); // Read pressed key const char ret = getchar(); // Read pressed key
if ((ret == 'y') || (ret == 'Y')) { if ((ret == 'y') || (ret == 'Y')) {
// Save the answer // Save the answer
pref->setAcceptedLegal(true); pref->setAcceptedLegal(true);
@ -361,7 +361,7 @@ bool userAgreesWithLegalNotice()
msgBox.setText(QObject::tr("qBittorrent is a file sharing program. When you run a torrent, its data will be made available to others by means of upload. Any content you share is your sole responsibility.\n\nNo further notices will be issued.")); msgBox.setText(QObject::tr("qBittorrent is a file sharing program. When you run a torrent, its data will be made available to others by means of upload. Any content you share is your sole responsibility.\n\nNo further notices will be issued."));
msgBox.setWindowTitle(QObject::tr("Legal notice")); msgBox.setWindowTitle(QObject::tr("Legal notice"));
msgBox.addButton(QObject::tr("Cancel"), QMessageBox::RejectRole); msgBox.addButton(QObject::tr("Cancel"), QMessageBox::RejectRole);
QAbstractButton *agreeButton = msgBox.addButton(QObject::tr("I Agree"), QMessageBox::AcceptRole); const QAbstractButton *agreeButton = msgBox.addButton(QObject::tr("I Agree"), QMessageBox::AcceptRole);
msgBox.show(); // Need to be shown or to moveToCenter does not work msgBox.show(); // Need to be shown or to moveToCenter does not work
msgBox.move(Utils::Misc::screenCenter(&msgBox)); msgBox.move(Utils::Misc::screenCenter(&msgBox));
msgBox.exec(); msgBox.exec();

View file

@ -93,7 +93,7 @@ bool BandwidthScheduler::isTimeForAlternative() const
void BandwidthScheduler::onTimeout() void BandwidthScheduler::onTimeout()
{ {
bool alternative = isTimeForAlternative(); const bool alternative = isTimeForAlternative();
if (alternative != m_lastAlternative) { if (alternative != m_lastAlternative) {
m_lastAlternative = alternative; m_lastAlternative = alternative;

View file

@ -50,7 +50,7 @@ namespace
char *endptr; char *endptr;
for (; *str; ++str) { for (; *str; ++str) {
if (*str == '.') { if (*str == '.') {
long int extractedNum = strtol(octetStart, &endptr, 10); const long int extractedNum = strtol(octetStart, &endptr, 10);
if ((extractedNum >= 0L) && (extractedNum <= 255L)) if ((extractedNum >= 0L) && (extractedNum <= 255L))
m_buf[octetIndex++] = static_cast<unsigned char>(extractedNum); m_buf[octetIndex++] = static_cast<unsigned char>(extractedNum);
else else
@ -66,7 +66,7 @@ namespace
} }
if (str != octetStart) { if (str != octetStart) {
long int extractedNum = strtol(octetStart, &endptr, 10); const long int extractedNum = strtol(octetStart, &endptr, 10);
if ((extractedNum >= 0L) && (extractedNum <= 255L)) if ((extractedNum >= 0L) && (extractedNum <= 255L))
m_buf[octetIndex] = static_cast<unsigned char>(strtol(octetStart, &endptr, 10)); m_buf[octetIndex] = static_cast<unsigned char>(strtol(octetStart, &endptr, 10));
else else
@ -146,7 +146,7 @@ int FilterParserThread::parseDATFilterFile()
bytesRead = file.read(buffer.data() + offset, BUFFER_SIZE - offset - 1); bytesRead = file.read(buffer.data() + offset, BUFFER_SIZE - offset - 1);
if (bytesRead < 0) if (bytesRead < 0)
break; break;
int dataSize = bytesRead + offset; const int dataSize = bytesRead + offset;
if ((bytesRead == 0) && (dataSize == 0)) if ((bytesRead == 0) && (dataSize == 0))
break; break;
@ -190,7 +190,7 @@ int FilterParserThread::parseDATFilterFile()
// Each line should follow this format: // Each line should follow this format:
// 001.009.096.105 - 001.009.096.105 , 000 , Some organization // 001.009.096.105 - 001.009.096.105 , 000 , Some organization
// The 3rd entry is access level and if above 127 the IP range isn't blocked. // The 3rd entry is access level and if above 127 the IP range isn't blocked.
int firstComma = findAndNullDelimiter(buffer.data(), ',', start, endOfLine); const int firstComma = findAndNullDelimiter(buffer.data(), ',', start, endOfLine);
if (firstComma != -1) if (firstComma != -1)
findAndNullDelimiter(buffer.data(), ',', firstComma + 1, endOfLine); findAndNullDelimiter(buffer.data(), ',', firstComma + 1, endOfLine);
@ -206,8 +206,8 @@ int FilterParserThread::parseDATFilterFile()
} }
// IP Range should be split by a dash // IP Range should be split by a dash
int endOfIPRange = ((firstComma == -1) ? (endOfLine - 1) : (firstComma - 1)); const int endOfIPRange = ((firstComma == -1) ? (endOfLine - 1) : (firstComma - 1));
int delimIP = findAndNullDelimiter(buffer.data(), '-', start, endOfIPRange); const int delimIP = findAndNullDelimiter(buffer.data(), '-', start, endOfIPRange);
if (delimIP == -1) { if (delimIP == -1) {
++parseErrorCount; ++parseErrorCount;
addLog(tr("IP filter line %1 is malformed.").arg(nbLine)); addLog(tr("IP filter line %1 is malformed.").arg(nbLine));
@ -294,7 +294,7 @@ int FilterParserThread::parseP2PFilterFile()
bytesRead = file.read(buffer.data() + offset, BUFFER_SIZE - offset - 1); bytesRead = file.read(buffer.data() + offset, BUFFER_SIZE - offset - 1);
if (bytesRead < 0) if (bytesRead < 0)
break; break;
int dataSize = bytesRead + offset; const int dataSize = bytesRead + offset;
if ((bytesRead == 0) && (dataSize == 0)) if ((bytesRead == 0) && (dataSize == 0))
break; break;
@ -338,7 +338,7 @@ int FilterParserThread::parseP2PFilterFile()
// Each line should follow this format: // Each line should follow this format:
// Some organization:1.0.0.0-1.255.255.255 // Some organization:1.0.0.0-1.255.255.255
// The "Some organization" part might contain a ':' char itself so we find the last occurrence // The "Some organization" part might contain a ':' char itself so we find the last occurrence
int partsDelimiter = findAndNullDelimiter(buffer.data(), ':', start, endOfLine, true); const int partsDelimiter = findAndNullDelimiter(buffer.data(), ':', start, endOfLine, true);
if (partsDelimiter == -1) { if (partsDelimiter == -1) {
++parseErrorCount; ++parseErrorCount;
addLog(tr("IP filter line %1 is malformed.").arg(nbLine)); addLog(tr("IP filter line %1 is malformed.").arg(nbLine));
@ -347,7 +347,7 @@ int FilterParserThread::parseP2PFilterFile()
} }
// IP Range should be split by a dash // IP Range should be split by a dash
int delimIP = findAndNullDelimiter(buffer.data(), '-', partsDelimiter + 1, endOfLine); const int delimIP = findAndNullDelimiter(buffer.data(), '-', partsDelimiter + 1, endOfLine);
if (delimIP == -1) { if (delimIP == -1) {
++parseErrorCount; ++parseErrorCount;
addLog(tr("IP filter line %1 is malformed.").arg(nbLine)); addLog(tr("IP filter line %1 is malformed.").arg(nbLine));
@ -404,7 +404,7 @@ int FilterParserThread::parseP2PFilterFile()
return ruleCount; return ruleCount;
} }
int FilterParserThread::getlineInStream(QDataStream &stream, std::string &name, char delim) int FilterParserThread::getlineInStream(QDataStream &stream, std::string &name, const char delim)
{ {
char c; char c;
int totalRead = 0; int totalRead = 0;
@ -465,8 +465,8 @@ int FilterParserThread::parseP2BFilterFile()
// Network byte order to Host byte order // Network byte order to Host byte order
// asio address_v4 constructor expects it // asio address_v4 constructor expects it
// that way // that way
libt::address_v4 first(ntohl(start)); const libt::address_v4 first(ntohl(start));
libt::address_v4 last(ntohl(end)); const libt::address_v4 last(ntohl(end));
// Apply to bittorrent session // Apply to bittorrent session
try { try {
m_filter.add_rule(first, last, libt::ip_filter::blocked); m_filter.add_rule(first, last, libt::ip_filter::blocked);
@ -515,8 +515,8 @@ int FilterParserThread::parseP2BFilterFile()
// Network byte order to Host byte order // Network byte order to Host byte order
// asio address_v4 constructor expects it // asio address_v4 constructor expects it
// that way // that way
libt::address_v4 first(ntohl(start)); const libt::address_v4 first(ntohl(start));
libt::address_v4 last(ntohl(end)); const libt::address_v4 last(ntohl(end));
// Apply to bittorrent session // Apply to bittorrent session
try { try {
m_filter.add_rule(first, last, libt::ip_filter::blocked); m_filter.add_rule(first, last, libt::ip_filter::blocked);
@ -588,7 +588,7 @@ void FilterParserThread::run()
qDebug("IP Filter thread: finished parsing, filter applied"); qDebug("IP Filter thread: finished parsing, filter applied");
} }
int FilterParserThread::findAndNullDelimiter(char *const data, char delimiter, int start, int end, bool reverse) int FilterParserThread::findAndNullDelimiter(char *const data, const char delimiter, const int start, const int end, const bool reverse)
{ {
if (!reverse) { if (!reverse) {
for (int i = start; i <= end; ++i) { for (int i = start; i <= end; ++i) {
@ -610,7 +610,7 @@ int FilterParserThread::findAndNullDelimiter(char *const data, char delimiter, i
return -1; return -1;
} }
int FilterParserThread::trim(char *const data, int start, int end) int FilterParserThread::trim(char *const data, const int start, const int end)
{ {
if (start >= end) return start; if (start >= end) return start;
int newStart = start; int newStart = start;

View file

@ -49,7 +49,7 @@ SpeedSampleAvg SpeedMonitor::average() const
if (m_speedSamples.empty()) if (m_speedSamples.empty())
return SpeedSampleAvg(); return SpeedSampleAvg();
qreal k = qreal(1.) / m_speedSamples.size(); const qreal k = qreal(1.) / m_speedSamples.size();
return SpeedSampleAvg(m_sum.download * k, m_sum.upload * k); return SpeedSampleAvg(m_sum.download * k, m_sum.upload * k);
} }

View file

@ -60,7 +60,7 @@ void Statistics::gather()
void Statistics::save() const void Statistics::save() const
{ {
qint64 now = QDateTime::currentMSecsSinceEpoch(); const qint64 now = QDateTime::currentMSecsSinceEpoch();
if (!m_dirty || ((now - m_lastWrite) < SAVE_INTERVAL)) if (!m_dirty || ((now - m_lastWrite) < SAVE_INTERVAL))
return; return;
@ -76,8 +76,8 @@ void Statistics::save() const
void Statistics::load() void Statistics::load()
{ {
SettingsPtr s = Profile::instance().applicationSettings(QLatin1String("qBittorrent-data")); const SettingsPtr s = Profile::instance().applicationSettings(QLatin1String("qBittorrent-data"));
QVariantHash v = s->value("Stats/AllStats").toHash(); const QVariantHash v = s->value("Stats/AllStats").toHash();
m_alltimeDL = v["AlltimeDL"].toULongLong(); m_alltimeDL = v["AlltimeDL"].toULongLong();
m_alltimeUL = v["AlltimeUL"].toULongLong(); m_alltimeUL = v["AlltimeUL"].toULongLong();

View file

@ -520,7 +520,7 @@ bool Session::isLSDEnabled() const
return m_isLSDEnabled; return m_isLSDEnabled;
} }
void Session::setLSDEnabled(bool enabled) void Session::setLSDEnabled(const bool enabled)
{ {
if (enabled != m_isLSDEnabled) { if (enabled != m_isLSDEnabled) {
m_isLSDEnabled = enabled; m_isLSDEnabled = enabled;
@ -536,7 +536,7 @@ bool Session::isPeXEnabled() const
return m_isPeXEnabled; return m_isPeXEnabled;
} }
void Session::setPeXEnabled(bool enabled) void Session::setPeXEnabled(const bool enabled)
{ {
m_isPeXEnabled = enabled; m_isPeXEnabled = enabled;
if (m_wasPexEnabled != enabled) if (m_wasPexEnabled != enabled)
@ -548,7 +548,7 @@ bool Session::isTempPathEnabled() const
return m_isTempPathEnabled; return m_isTempPathEnabled;
} }
void Session::setTempPathEnabled(bool enabled) void Session::setTempPathEnabled(const bool enabled)
{ {
if (enabled != isTempPathEnabled()) { if (enabled != isTempPathEnabled()) {
m_isTempPathEnabled = enabled; m_isTempPathEnabled = enabled;
@ -562,7 +562,7 @@ bool Session::isAppendExtensionEnabled() const
return m_isAppendExtensionEnabled; return m_isAppendExtensionEnabled;
} }
void Session::setAppendExtensionEnabled(bool enabled) void Session::setAppendExtensionEnabled(const bool enabled)
{ {
if (isAppendExtensionEnabled() != enabled) { if (isAppendExtensionEnabled() != enabled) {
// append or remove .!qB extension for incomplete files // append or remove .!qB extension for incomplete files
@ -578,7 +578,7 @@ uint Session::refreshInterval() const
return m_refreshInterval; return m_refreshInterval;
} }
void Session::setRefreshInterval(uint value) void Session::setRefreshInterval(const uint value)
{ {
if (value != refreshInterval()) { if (value != refreshInterval()) {
m_refreshTimer->setInterval(value); m_refreshTimer->setInterval(value);
@ -591,7 +591,7 @@ bool Session::isPreallocationEnabled() const
return m_isPreallocationEnabled; return m_isPreallocationEnabled;
} }
void Session::setPreallocationEnabled(bool enabled) void Session::setPreallocationEnabled(const bool enabled)
{ {
m_isPreallocationEnabled = enabled; m_isPreallocationEnabled = enabled;
} }
@ -674,7 +674,7 @@ const QStringMap &Session::categories() const
QString Session::categorySavePath(const QString &categoryName) const QString Session::categorySavePath(const QString &categoryName) const
{ {
QString basePath = m_defaultSavePath; const QString basePath = m_defaultSavePath;
if (categoryName.isEmpty()) return basePath; if (categoryName.isEmpty()) return basePath;
QString path = m_categories.value(categoryName); QString path = m_categories.value(categoryName);
@ -768,7 +768,7 @@ bool Session::isSubcategoriesEnabled() const
return m_isSubcategoriesEnabled; return m_isSubcategoriesEnabled;
} }
void Session::setSubcategoriesEnabled(bool value) void Session::setSubcategoriesEnabled(const bool value)
{ {
if (isSubcategoriesEnabled() == value) return; if (isSubcategoriesEnabled() == value) return;
@ -833,7 +833,7 @@ bool Session::isAutoTMMDisabledByDefault() const
return m_isAutoTMMDisabledByDefault; return m_isAutoTMMDisabledByDefault;
} }
void Session::setAutoTMMDisabledByDefault(bool value) void Session::setAutoTMMDisabledByDefault(const bool value)
{ {
m_isAutoTMMDisabledByDefault = value; m_isAutoTMMDisabledByDefault = value;
} }
@ -843,7 +843,7 @@ bool Session::isDisableAutoTMMWhenCategoryChanged() const
return m_isDisableAutoTMMWhenCategoryChanged; return m_isDisableAutoTMMWhenCategoryChanged;
} }
void Session::setDisableAutoTMMWhenCategoryChanged(bool value) void Session::setDisableAutoTMMWhenCategoryChanged(const bool value)
{ {
m_isDisableAutoTMMWhenCategoryChanged = value; m_isDisableAutoTMMWhenCategoryChanged = value;
} }
@ -853,7 +853,7 @@ bool Session::isDisableAutoTMMWhenDefaultSavePathChanged() const
return m_isDisableAutoTMMWhenDefaultSavePathChanged; return m_isDisableAutoTMMWhenDefaultSavePathChanged;
} }
void Session::setDisableAutoTMMWhenDefaultSavePathChanged(bool value) void Session::setDisableAutoTMMWhenDefaultSavePathChanged(const bool value)
{ {
m_isDisableAutoTMMWhenDefaultSavePathChanged = value; m_isDisableAutoTMMWhenDefaultSavePathChanged = value;
} }
@ -863,7 +863,7 @@ bool Session::isDisableAutoTMMWhenCategorySavePathChanged() const
return m_isDisableAutoTMMWhenCategorySavePathChanged; return m_isDisableAutoTMMWhenCategorySavePathChanged;
} }
void Session::setDisableAutoTMMWhenCategorySavePathChanged(bool value) void Session::setDisableAutoTMMWhenCategorySavePathChanged(const bool value)
{ {
m_isDisableAutoTMMWhenCategorySavePathChanged = value; m_isDisableAutoTMMWhenCategorySavePathChanged = value;
} }
@ -873,7 +873,7 @@ bool Session::isAddTorrentPaused() const
return m_isAddTorrentPaused; return m_isAddTorrentPaused;
} }
void Session::setAddTorrentPaused(bool value) void Session::setAddTorrentPaused(const bool value)
{ {
m_isAddTorrentPaused = value; m_isAddTorrentPaused = value;
} }
@ -883,7 +883,7 @@ bool Session::isTrackerEnabled() const
return m_isTrackerEnabled; return m_isTrackerEnabled;
} }
void Session::setTrackerEnabled(bool enabled) void Session::setTrackerEnabled(const bool enabled)
{ {
if (isTrackerEnabled() != enabled) { if (isTrackerEnabled() != enabled) {
enableTracker(enabled); enableTracker(enabled);
@ -1011,7 +1011,7 @@ void Session::processBannedIPs(libt::ip_filter &filter)
// First, import current filter // First, import current filter
for (const QString &ip : asConst(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); const libt::address addr = libt::address::from_string(ip.toLatin1().constData(), ec);
Q_ASSERT(!ec); Q_ASSERT(!ec);
if (!ec) if (!ec)
filter.add_rule(addr, addr, libt::ip_filter::blocked); filter.add_rule(addr, addr, libt::ip_filter::blocked);
@ -1021,8 +1021,8 @@ void Session::processBannedIPs(libt::ip_filter &filter)
void Session::adjustLimits(libt::settings_pack &settingsPack) void Session::adjustLimits(libt::settings_pack &settingsPack)
{ {
// Internally increase the queue limits to ensure that the magnet is started // Internally increase the queue limits to ensure that the magnet is started
int maxDownloads = maxActiveDownloads(); const int maxDownloads = maxActiveDownloads();
int maxActive = maxActiveTorrents(); const int maxActive = maxActiveTorrents();
settingsPack.set_int(libt::settings_pack::active_downloads settingsPack.set_int(libt::settings_pack::active_downloads
, maxDownloads > -1 ? maxDownloads + m_extraLimit : maxDownloads); , maxDownloads > -1 ? maxDownloads + m_extraLimit : maxDownloads);
@ -1125,7 +1125,7 @@ void Session::configure(libtorrent::settings_pack &settingsPack)
if (m_listenInterfaceChanged) { if (m_listenInterfaceChanged) {
const ushort port = this->port(); const ushort port = this->port();
std::pair<int, int> ports(port, port); const std::pair<int, int> ports(port, port);
settingsPack.set_int(libt::settings_pack::max_retry_port_bind, ports.second - ports.first); settingsPack.set_int(libt::settings_pack::max_retry_port_bind, ports.second - ports.first);
for (QString ip : getListeningIPs()) { for (QString ip : getListeningIPs()) {
libt::error_code ec; libt::error_code ec;
@ -1143,7 +1143,7 @@ void Session::configure(libtorrent::settings_pack &settingsPack)
break; break;
} }
libt::address addr = libt::address::from_string(ip.toLatin1().constData(), ec); const libt::address addr = libt::address::from_string(ip.toLatin1().constData(), ec);
if (!ec) { if (!ec) {
interfacesStr = std::string((addr.is_v6() ? QString("[%1]:%2") : QString("%1:%2")) interfacesStr = std::string((addr.is_v6() ? QString("[%1]:%2") : QString("%1:%2"))
.arg(ip).arg(port).toLatin1().constData()); .arg(ip).arg(port).toLatin1().constData());
@ -1164,7 +1164,7 @@ void Session::configure(libtorrent::settings_pack &settingsPack)
// the interface's Luid and not the GUID. // the interface's Luid and not the GUID.
// Libtorrent expects GUIDs for the 'outgoing_interfaces' setting. // Libtorrent expects GUIDs for the 'outgoing_interfaces' setting.
if (!networkInterface().isEmpty()) { if (!networkInterface().isEmpty()) {
QString guid = convertIfaceNameToGuid(networkInterface()); const QString guid = convertIfaceNameToGuid(networkInterface());
if (!guid.isEmpty()) { if (!guid.isEmpty()) {
settingsPack.set_str(libt::settings_pack::outgoing_interfaces, guid.toStdString()); settingsPack.set_str(libt::settings_pack::outgoing_interfaces, guid.toStdString());
} }
@ -1199,8 +1199,8 @@ void Session::configure(libtorrent::settings_pack &settingsPack)
settingsPack.set_int(libt::settings_pack::in_enc_policy, libt::settings_pack::pe_disabled); settingsPack.set_int(libt::settings_pack::in_enc_policy, libt::settings_pack::pe_disabled);
} }
auto proxyManager = Net::ProxyConfigurationManager::instance(); const auto proxyManager = Net::ProxyConfigurationManager::instance();
Net::ProxyConfiguration proxyConfig = proxyManager->proxyConfiguration(); const Net::ProxyConfiguration proxyConfig = proxyManager->proxyConfiguration();
if (m_useProxy || (proxyConfig.type != Net::ProxyType::None)) { if (m_useProxy || (proxyConfig.type != Net::ProxyType::None)) {
if (proxyConfig.type != Net::ProxyType::None) { if (proxyConfig.type != Net::ProxyType::None) {
settingsPack.set_str(libt::settings_pack::proxy_hostname, proxyConfig.ip.toStdString()); settingsPack.set_str(libt::settings_pack::proxy_hostname, proxyConfig.ip.toStdString());
@ -1444,7 +1444,7 @@ void Session::configurePeerClasses()
m_nativeSession->set_peer_class_type_filter(peerClassTypeFilter); m_nativeSession->set_peer_class_type_filter(peerClassTypeFilter);
} }
void Session::enableTracker(bool enable) void Session::enableTracker(const bool enable)
{ {
Logger *const logger = Logger::instance(); Logger *const logger = Logger::instance();
@ -1596,7 +1596,7 @@ void Session::banIP(const QString &ip)
if (!bannedIPs.contains(ip)) { if (!bannedIPs.contains(ip)) {
libt::ip_filter filter = m_nativeSession->get_ip_filter(); libt::ip_filter filter = m_nativeSession->get_ip_filter();
boost::system::error_code ec; boost::system::error_code ec;
libt::address addr = libt::address::from_string(ip.toLatin1().constData(), ec); const libt::address addr = libt::address::from_string(ip.toLatin1().constData(), ec);
Q_ASSERT(!ec); Q_ASSERT(!ec);
if (ec) return; if (ec) return;
filter.add_rule(addr, addr, libt::ip_filter::blocked); filter.add_rule(addr, addr, libt::ip_filter::blocked);
@ -1610,7 +1610,7 @@ void Session::banIP(const QString &ip)
// Delete a torrent from the session, given its hash // Delete a torrent from the session, given its hash
// deleteLocalFiles = true means that the torrent will be removed from the hard-drive too // deleteLocalFiles = true means that the torrent will be removed from the hard-drive too
bool Session::deleteTorrent(const QString &hash, bool deleteLocalFiles) bool Session::deleteTorrent(const QString &hash, const bool deleteLocalFiles)
{ {
TorrentHandle *const torrent = m_torrents.take(hash); TorrentHandle *const torrent = m_torrents.take(hash);
if (!torrent) return false; if (!torrent) return false;
@ -1620,7 +1620,7 @@ bool Session::deleteTorrent(const QString &hash, bool deleteLocalFiles)
// Remove it from session // Remove it from session
if (deleteLocalFiles) { if (deleteLocalFiles) {
QString rootPath = torrent->rootPath(true); const QString rootPath = torrent->rootPath(true);
if (!rootPath.isEmpty()) if (!rootPath.isEmpty())
// torrent with root folder // torrent with root folder
m_removingTorrents[torrent->hash()] = {torrent->name(), rootPath, deleteLocalFiles}; m_removingTorrents[torrent->hash()] = {torrent->name(), rootPath, deleteLocalFiles};
@ -1648,7 +1648,7 @@ bool Session::deleteTorrent(const QString &hash, bool deleteLocalFiles)
} }
// Remove it from torrent resume directory // Remove it from torrent resume directory
QDir resumeDataDir(m_resumeFolderPath); const QDir resumeDataDir(m_resumeFolderPath);
QStringList filters; QStringList filters;
filters << QString("%1.*").arg(torrent->hash()); filters << QString("%1.*").arg(torrent->hash());
const QStringList files = resumeDataDir.entryList(filters, QDir::Files, QDir::Unsorted); const QStringList files = resumeDataDir.entryList(filters, QDir::Files, QDir::Unsorted);
@ -1665,7 +1665,7 @@ bool Session::cancelLoadMetadata(const InfoHash &hash)
if (!m_loadedMetadata.contains(hash)) return false; if (!m_loadedMetadata.contains(hash)) return false;
m_loadedMetadata.remove(hash); m_loadedMetadata.remove(hash);
libt::torrent_handle torrent = m_nativeSession->find_torrent(hash); const libt::torrent_handle torrent = m_nativeSession->find_torrent(hash);
if (!torrent.is_valid()) return false; if (!torrent.is_valid()) return false;
if (!torrent.status(0).has_metadata) { if (!torrent.status(0).has_metadata) {
@ -1795,7 +1795,7 @@ bool Session::addTorrent(const QString &source, const AddTorrentParams &params)
if (Net::DownloadManager::hasSupportedScheme(source)) { if (Net::DownloadManager::hasSupportedScheme(source)) {
LogMsg(tr("Downloading '%1', please wait...", "e.g: Downloading 'xxx.torrent', please wait...").arg(source)); LogMsg(tr("Downloading '%1', please wait...", "e.g: Downloading 'xxx.torrent', please wait...").arg(source));
// Launch downloader // Launch downloader
Net::DownloadHandler *handler = const Net::DownloadHandler *handler =
Net::DownloadManager::instance()->download(Net::DownloadRequest(source).limit(10485760 /* 10MB */).handleRedirectToMagnet(true)); Net::DownloadManager::instance()->download(Net::DownloadRequest(source).limit(10485760 /* 10MB */).handleRedirectToMagnet(true));
connect(handler, static_cast<void (Net::DownloadHandler::*)(const QString &, const QByteArray &)>(&Net::DownloadHandler::downloadFinished) connect(handler, static_cast<void (Net::DownloadHandler::*)(const QString &, const QByteArray &)>(&Net::DownloadHandler::downloadFinished)
, this, &Session::handleDownloadFinished); , this, &Session::handleDownloadFinished);
@ -1999,8 +1999,8 @@ bool Session::loadMetadata(const MagnetUri &magnetUri)
{ {
if (!magnetUri.isValid()) return false; if (!magnetUri.isValid()) return false;
InfoHash hash = magnetUri.hash(); const InfoHash hash = magnetUri.hash();
QString name = magnetUri.name(); const QString name = magnetUri.name();
// We should not add torrent if it's already // We should not add torrent if it's already
// processed or adding to session // processed or adding to session
@ -2052,11 +2052,11 @@ void Session::exportTorrentFile(TorrentHandle *const torrent, TorrentExportFolde
Q_ASSERT(((folder == TorrentExportFolder::Regular) && !torrentExportDirectory().isEmpty()) || Q_ASSERT(((folder == TorrentExportFolder::Regular) && !torrentExportDirectory().isEmpty()) ||
((folder == TorrentExportFolder::Finished) && !finishedTorrentExportDirectory().isEmpty())); ((folder == TorrentExportFolder::Finished) && !finishedTorrentExportDirectory().isEmpty()));
QString validName = Utils::Fs::toValidFileSystemName(torrent->name()); const QString validName = Utils::Fs::toValidFileSystemName(torrent->name());
QString torrentFilename = QString("%1.torrent").arg(torrent->hash()); const QString torrentFilename = QString("%1.torrent").arg(torrent->hash());
QString torrentExportFilename = QString("%1.torrent").arg(validName); QString torrentExportFilename = QString("%1.torrent").arg(validName);
QString torrentPath = QDir(m_resumeFolderPath).absoluteFilePath(torrentFilename); const QString torrentPath = QDir(m_resumeFolderPath).absoluteFilePath(torrentFilename);
QDir exportPath(folder == TorrentExportFolder::Regular ? torrentExportDirectory() : finishedTorrentExportDirectory()); const QDir exportPath(folder == TorrentExportFolder::Regular ? torrentExportDirectory() : finishedTorrentExportDirectory());
if (exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) { if (exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) {
QString newTorrentPath = exportPath.absoluteFilePath(torrentExportFilename); QString newTorrentPath = exportPath.absoluteFilePath(torrentExportFilename);
int counter = 0; int counter = 0;
@ -2071,7 +2071,7 @@ void Session::exportTorrentFile(TorrentHandle *const torrent, TorrentExportFolde
} }
} }
void Session::generateResumeData(bool final) void Session::generateResumeData(const bool final)
{ {
for (TorrentHandle *const torrent : asConst(m_torrents)) { for (TorrentHandle *const torrent : asConst(m_torrents)) {
if (!torrent->isValid()) continue; if (!torrent->isValid()) continue;
@ -2406,7 +2406,7 @@ bool Session::isBandwidthSchedulerEnabled() const
return m_isBandwidthSchedulerEnabled; return m_isBandwidthSchedulerEnabled;
} }
void Session::setBandwidthSchedulerEnabled(bool enabled) void Session::setBandwidthSchedulerEnabled(const bool enabled)
{ {
if (enabled != isBandwidthSchedulerEnabled()) { if (enabled != isBandwidthSchedulerEnabled()) {
m_isBandwidthSchedulerEnabled = enabled; m_isBandwidthSchedulerEnabled = enabled;
@ -2446,7 +2446,7 @@ int Session::port() const
return m_port; return m_port;
} }
void Session::setPort(int port) void Session::setPort(const int port)
{ {
if (port != this->port()) { if (port != this->port()) {
m_port = port; m_port = port;
@ -2459,7 +2459,7 @@ bool Session::useRandomPort() const
return m_useRandomPort; return m_useRandomPort;
} }
void Session::setUseRandomPort(bool value) void Session::setUseRandomPort(const bool value)
{ {
m_useRandomPort = value; m_useRandomPort = value;
} }
@ -2505,7 +2505,7 @@ bool Session::isIPv6Enabled() const
return m_isIPv6Enabled; return m_isIPv6Enabled;
} }
void Session::setIPv6Enabled(bool enabled) void Session::setIPv6Enabled(const bool enabled)
{ {
if (enabled != isIPv6Enabled()) { if (enabled != isIPv6Enabled()) {
m_isIPv6Enabled = enabled; m_isIPv6Enabled = enabled;
@ -2518,7 +2518,7 @@ int Session::encryption() const
return m_encryption; return m_encryption;
} }
void Session::setEncryption(int state) void Session::setEncryption(const int state)
{ {
if (state != encryption()) { if (state != encryption()) {
m_encryption = state; m_encryption = state;
@ -2535,7 +2535,7 @@ bool Session::isForceProxyEnabled() const
return m_isForceProxyEnabled; return m_isForceProxyEnabled;
} }
void Session::setForceProxyEnabled(bool enabled) void Session::setForceProxyEnabled(const bool enabled)
{ {
if (enabled != isForceProxyEnabled()) { if (enabled != isForceProxyEnabled()) {
m_isForceProxyEnabled = enabled; m_isForceProxyEnabled = enabled;
@ -2548,7 +2548,7 @@ bool Session::isProxyPeerConnectionsEnabled() const
return m_isProxyPeerConnectionsEnabled; return m_isProxyPeerConnectionsEnabled;
} }
void Session::setProxyPeerConnectionsEnabled(bool enabled) void Session::setProxyPeerConnectionsEnabled(const bool enabled)
{ {
if (enabled != isProxyPeerConnectionsEnabled()) { if (enabled != isProxyPeerConnectionsEnabled()) {
m_isProxyPeerConnectionsEnabled = enabled; m_isProxyPeerConnectionsEnabled = enabled;
@ -2561,7 +2561,7 @@ ChokingAlgorithm Session::chokingAlgorithm() const
return m_chokingAlgorithm; return m_chokingAlgorithm;
} }
void Session::setChokingAlgorithm(ChokingAlgorithm mode) void Session::setChokingAlgorithm(const ChokingAlgorithm mode)
{ {
if (mode == m_chokingAlgorithm) return; if (mode == m_chokingAlgorithm) return;
@ -2574,7 +2574,7 @@ SeedChokingAlgorithm Session::seedChokingAlgorithm() const
return m_seedChokingAlgorithm; return m_seedChokingAlgorithm;
} }
void Session::setSeedChokingAlgorithm(SeedChokingAlgorithm mode) void Session::setSeedChokingAlgorithm(const SeedChokingAlgorithm mode)
{ {
if (mode == m_seedChokingAlgorithm) return; if (mode == m_seedChokingAlgorithm) return;
@ -2587,7 +2587,7 @@ bool Session::isAddTrackersEnabled() const
return m_isAddTrackersEnabled; return m_isAddTrackersEnabled;
} }
void Session::setAddTrackersEnabled(bool enabled) void Session::setAddTrackersEnabled(const bool enabled)
{ {
m_isAddTrackersEnabled = enabled; m_isAddTrackersEnabled = enabled;
} }
@ -2610,7 +2610,7 @@ bool Session::isIPFilteringEnabled() const
return m_isIPFilteringEnabled; return m_isIPFilteringEnabled;
} }
void Session::setIPFilteringEnabled(bool enabled) void Session::setIPFilteringEnabled(const bool enabled)
{ {
if (enabled != m_isIPFilteringEnabled) { if (enabled != m_isIPFilteringEnabled) {
m_isIPFilteringEnabled = enabled; m_isIPFilteringEnabled = enabled;
@ -2722,7 +2722,7 @@ bool Session::announceToAllTrackers() const
return m_announceToAllTrackers; return m_announceToAllTrackers;
} }
void Session::setAnnounceToAllTrackers(bool val) void Session::setAnnounceToAllTrackers(const bool val)
{ {
if (val != m_announceToAllTrackers) { if (val != m_announceToAllTrackers) {
m_announceToAllTrackers = val; m_announceToAllTrackers = val;
@ -2735,7 +2735,7 @@ bool Session::announceToAllTiers() const
return m_announceToAllTiers; return m_announceToAllTiers;
} }
void Session::setAnnounceToAllTiers(bool val) void Session::setAnnounceToAllTiers(const bool val)
{ {
if (val != m_announceToAllTiers) { if (val != m_announceToAllTiers) {
m_announceToAllTiers = val; m_announceToAllTiers = val;
@ -2806,7 +2806,7 @@ int Session::diskCacheTTL() const
return m_diskCacheTTL; return m_diskCacheTTL;
} }
void Session::setDiskCacheTTL(int ttl) void Session::setDiskCacheTTL(const int ttl)
{ {
if (ttl != m_diskCacheTTL) { if (ttl != m_diskCacheTTL) {
m_diskCacheTTL = ttl; m_diskCacheTTL = ttl;
@ -2819,7 +2819,7 @@ bool Session::useOSCache() const
return m_useOSCache; return m_useOSCache;
} }
void Session::setUseOSCache(bool use) void Session::setUseOSCache(const bool use)
{ {
if (use != m_useOSCache) { if (use != m_useOSCache) {
m_useOSCache = use; m_useOSCache = use;
@ -2832,7 +2832,7 @@ bool Session::isGuidedReadCacheEnabled() const
return m_guidedReadCacheEnabled; return m_guidedReadCacheEnabled;
} }
void Session::setGuidedReadCacheEnabled(bool enabled) void Session::setGuidedReadCacheEnabled(const bool enabled)
{ {
if (enabled == m_guidedReadCacheEnabled) return; if (enabled == m_guidedReadCacheEnabled) return;
@ -2845,7 +2845,7 @@ bool Session::isCoalesceReadWriteEnabled() const
return m_coalesceReadWriteEnabled; return m_coalesceReadWriteEnabled;
} }
void Session::setCoalesceReadWriteEnabled(bool enabled) void Session::setCoalesceReadWriteEnabled(const bool enabled)
{ {
if (enabled == m_coalesceReadWriteEnabled) return; if (enabled == m_coalesceReadWriteEnabled) return;
@ -2858,7 +2858,7 @@ bool Session::isSuggestModeEnabled() const
return m_isSuggestMode; return m_isSuggestMode;
} }
void Session::setSuggestMode(bool mode) void Session::setSuggestMode(const bool mode)
{ {
if (mode == m_isSuggestMode) return; if (mode == m_isSuggestMode) return;
@ -2871,7 +2871,7 @@ int Session::sendBufferWatermark() const
return m_sendBufferWatermark; return m_sendBufferWatermark;
} }
void Session::setSendBufferWatermark(int value) void Session::setSendBufferWatermark(const int value)
{ {
if (value == m_sendBufferWatermark) return; if (value == m_sendBufferWatermark) return;
@ -2884,7 +2884,7 @@ int Session::sendBufferLowWatermark() const
return m_sendBufferLowWatermark; return m_sendBufferLowWatermark;
} }
void Session::setSendBufferLowWatermark(int value) void Session::setSendBufferLowWatermark(const int value)
{ {
if (value == m_sendBufferLowWatermark) return; if (value == m_sendBufferLowWatermark) return;
@ -2897,7 +2897,7 @@ int Session::sendBufferWatermarkFactor() const
return m_sendBufferWatermarkFactor; return m_sendBufferWatermarkFactor;
} }
void Session::setSendBufferWatermarkFactor(int value) void Session::setSendBufferWatermarkFactor(const int value)
{ {
if (value == m_sendBufferWatermarkFactor) return; if (value == m_sendBufferWatermarkFactor) return;
@ -2910,7 +2910,7 @@ bool Session::isAnonymousModeEnabled() const
return m_isAnonymousModeEnabled; return m_isAnonymousModeEnabled;
} }
void Session::setAnonymousModeEnabled(bool enabled) void Session::setAnonymousModeEnabled(const bool enabled)
{ {
if (enabled != m_isAnonymousModeEnabled) { if (enabled != m_isAnonymousModeEnabled) {
m_isAnonymousModeEnabled = enabled; m_isAnonymousModeEnabled = enabled;
@ -2926,7 +2926,7 @@ bool Session::isQueueingSystemEnabled() const
return m_isQueueingEnabled; return m_isQueueingEnabled;
} }
void Session::setQueueingSystemEnabled(bool enabled) void Session::setQueueingSystemEnabled(const bool enabled)
{ {
if (enabled != m_isQueueingEnabled) { if (enabled != m_isQueueingEnabled) {
m_isQueueingEnabled = enabled; m_isQueueingEnabled = enabled;
@ -2986,7 +2986,7 @@ bool Session::ignoreSlowTorrentsForQueueing() const
return m_ignoreSlowTorrentsForQueueing; return m_ignoreSlowTorrentsForQueueing;
} }
void Session::setIgnoreSlowTorrentsForQueueing(bool ignore) void Session::setIgnoreSlowTorrentsForQueueing(const bool ignore)
{ {
if (ignore != m_ignoreSlowTorrentsForQueueing) { if (ignore != m_ignoreSlowTorrentsForQueueing) {
m_ignoreSlowTorrentsForQueueing = ignore; m_ignoreSlowTorrentsForQueueing = ignore;
@ -2999,7 +2999,7 @@ int Session::downloadRateForSlowTorrents() const
return m_downloadRateForSlowTorrents; return m_downloadRateForSlowTorrents;
} }
void Session::setDownloadRateForSlowTorrents(int rateInKibiBytes) void Session::setDownloadRateForSlowTorrents(const int rateInKibiBytes)
{ {
if (rateInKibiBytes == m_downloadRateForSlowTorrents) if (rateInKibiBytes == m_downloadRateForSlowTorrents)
return; return;
@ -3013,7 +3013,7 @@ int Session::uploadRateForSlowTorrents() const
return m_uploadRateForSlowTorrents; return m_uploadRateForSlowTorrents;
} }
void Session::setUploadRateForSlowTorrents(int rateInKibiBytes) void Session::setUploadRateForSlowTorrents(const int rateInKibiBytes)
{ {
if (rateInKibiBytes == m_uploadRateForSlowTorrents) if (rateInKibiBytes == m_uploadRateForSlowTorrents)
return; return;
@ -3027,7 +3027,7 @@ int Session::slowTorrentsInactivityTimer() const
return m_slowTorrentsInactivityTimer; return m_slowTorrentsInactivityTimer;
} }
void Session::setSlowTorrentsInactivityTimer(int timeInSeconds) void Session::setSlowTorrentsInactivityTimer(const int timeInSeconds)
{ {
if (timeInSeconds == m_slowTorrentsInactivityTimer) if (timeInSeconds == m_slowTorrentsInactivityTimer)
return; return;
@ -3041,7 +3041,7 @@ int Session::outgoingPortsMin() const
return m_outgoingPortsMin; return m_outgoingPortsMin;
} }
void Session::setOutgoingPortsMin(int min) void Session::setOutgoingPortsMin(const int min)
{ {
if (min != m_outgoingPortsMin) { if (min != m_outgoingPortsMin) {
m_outgoingPortsMin = min; m_outgoingPortsMin = min;
@ -3054,7 +3054,7 @@ int Session::outgoingPortsMax() const
return m_outgoingPortsMax; return m_outgoingPortsMax;
} }
void Session::setOutgoingPortsMax(int max) void Session::setOutgoingPortsMax(const int max)
{ {
if (max != m_outgoingPortsMax) { if (max != m_outgoingPortsMax) {
m_outgoingPortsMax = max; m_outgoingPortsMax = max;
@ -3067,7 +3067,7 @@ bool Session::ignoreLimitsOnLAN() const
return m_ignoreLimitsOnLAN; return m_ignoreLimitsOnLAN;
} }
void Session::setIgnoreLimitsOnLAN(bool ignore) void Session::setIgnoreLimitsOnLAN(const bool ignore)
{ {
if (ignore != m_ignoreLimitsOnLAN) { if (ignore != m_ignoreLimitsOnLAN) {
m_ignoreLimitsOnLAN = ignore; m_ignoreLimitsOnLAN = ignore;
@ -3080,7 +3080,7 @@ bool Session::includeOverheadInLimits() const
return m_includeOverheadInLimits; return m_includeOverheadInLimits;
} }
void Session::setIncludeOverheadInLimits(bool include) void Session::setIncludeOverheadInLimits(const bool include)
{ {
if (include != m_includeOverheadInLimits) { if (include != m_includeOverheadInLimits) {
m_includeOverheadInLimits = include; m_includeOverheadInLimits = include;
@ -3106,7 +3106,7 @@ bool Session::isSuperSeedingEnabled() const
return m_isSuperSeedingEnabled; return m_isSuperSeedingEnabled;
} }
void Session::setSuperSeedingEnabled(bool enabled) void Session::setSuperSeedingEnabled(const bool enabled)
{ {
if (enabled != m_isSuperSeedingEnabled) { if (enabled != m_isSuperSeedingEnabled) {
m_isSuperSeedingEnabled = enabled; m_isSuperSeedingEnabled = enabled;
@ -3161,7 +3161,7 @@ BTProtocol Session::btProtocol() const
return m_btProtocol; return m_btProtocol;
} }
void Session::setBTProtocol(BTProtocol protocol) void Session::setBTProtocol(const BTProtocol protocol)
{ {
if ((protocol < BTProtocol::Both) || (BTProtocol::UTP < protocol)) if ((protocol < BTProtocol::Both) || (BTProtocol::UTP < protocol))
return; return;
@ -3177,7 +3177,7 @@ bool Session::isUTPRateLimited() const
return m_isUTPRateLimited; return m_isUTPRateLimited;
} }
void Session::setUTPRateLimited(bool limited) void Session::setUTPRateLimited(const bool limited)
{ {
if (limited != m_isUTPRateLimited) { if (limited != m_isUTPRateLimited) {
m_isUTPRateLimited = limited; m_isUTPRateLimited = limited;
@ -3190,7 +3190,7 @@ MixedModeAlgorithm Session::utpMixedMode() const
return m_utpMixedMode; return m_utpMixedMode;
} }
void Session::setUtpMixedMode(MixedModeAlgorithm mode) void Session::setUtpMixedMode(const MixedModeAlgorithm mode)
{ {
if (mode == m_utpMixedMode) return; if (mode == m_utpMixedMode) return;
@ -3203,7 +3203,7 @@ bool Session::multiConnectionsPerIpEnabled() const
return m_multiConnectionsPerIpEnabled; return m_multiConnectionsPerIpEnabled;
} }
void Session::setMultiConnectionsPerIpEnabled(bool enabled) void Session::setMultiConnectionsPerIpEnabled(const bool enabled)
{ {
if (enabled == m_multiConnectionsPerIpEnabled) return; if (enabled == m_multiConnectionsPerIpEnabled) return;
@ -3216,7 +3216,7 @@ bool Session::isTrackerFilteringEnabled() const
return m_isTrackerFilteringEnabled; return m_isTrackerFilteringEnabled;
} }
void Session::setTrackerFilteringEnabled(bool enabled) void Session::setTrackerFilteringEnabled(const bool enabled)
{ {
if (enabled != m_isTrackerFilteringEnabled) { if (enabled != m_isTrackerFilteringEnabled) {
m_isTrackerFilteringEnabled = enabled; m_isTrackerFilteringEnabled = enabled;
@ -3234,7 +3234,7 @@ MaxRatioAction Session::maxRatioAction() const
return static_cast<MaxRatioAction>(m_maxRatioAction.value()); return static_cast<MaxRatioAction>(m_maxRatioAction.value());
} }
void Session::setMaxRatioAction(MaxRatioAction act) void Session::setMaxRatioAction(const MaxRatioAction act)
{ {
m_maxRatioAction = static_cast<int>(act); m_maxRatioAction = static_cast<int>(act);
} }
@ -3483,7 +3483,7 @@ bool Session::hasPerTorrentSeedingTimeLimit() const
void Session::initResumeFolder() void Session::initResumeFolder()
{ {
m_resumeFolderPath = Utils::Fs::expandPathAbs(specialFolderLocation(SpecialFolder::Data) + RESUME_FOLDER); m_resumeFolderPath = Utils::Fs::expandPathAbs(specialFolderLocation(SpecialFolder::Data) + RESUME_FOLDER);
QDir resumeFolderDir(m_resumeFolderPath); const QDir resumeFolderDir(m_resumeFolderPath);
if (resumeFolderDir.exists() || resumeFolderDir.mkpath(resumeFolderDir.absolutePath())) { if (resumeFolderDir.exists() || resumeFolderDir.mkpath(resumeFolderDir.absolutePath())) {
m_resumeFolderLock.setFileName(resumeFolderDir.absoluteFilePath("session.lock")); m_resumeFolderLock.setFileName(resumeFolderDir.absoluteFilePath("session.lock"));
if (!m_resumeFolderLock.open(QFile::WriteOnly)) { if (!m_resumeFolderLock.open(QFile::WriteOnly)) {
@ -3525,7 +3525,7 @@ void Session::disableIPFilter()
{ {
qDebug("Disabling IPFilter"); qDebug("Disabling IPFilter");
if (m_filterParser) { if (m_filterParser) {
disconnect(m_filterParser.data(), 0, this, 0); disconnect(m_filterParser.data(), nullptr, this, nullptr);
delete m_filterParser; delete m_filterParser;
} }
@ -3591,7 +3591,7 @@ void Session::startUpTorrents()
int resumedTorrentsCount = 0; int resumedTorrentsCount = 0;
const auto startupTorrent = [this, logger, &resumeDataDir, &resumedTorrentsCount](const TorrentResumeData &params) const auto startupTorrent = [this, logger, &resumeDataDir, &resumedTorrentsCount](const TorrentResumeData &params)
{ {
QString filePath = resumeDataDir.filePath(QString("%1.torrent").arg(params.hash)); const QString filePath = resumeDataDir.filePath(QString("%1.torrent").arg(params.hash));
qDebug() << "Starting up torrent" << params.hash << "..."; qDebug() << "Starting up torrent" << params.hash << "...";
if (!addTorrent_impl(params.addTorrentData, params.magnetUri, TorrentInfo::loadFromFile(filePath), params.data)) if (!addTorrent_impl(params.addTorrentData, params.magnetUri, TorrentInfo::loadFromFile(filePath), params.data))
logger->addMessage(tr("Unable to resume torrent '%1'.", "e.g: Unable to resume torrent 'hash'.") logger->addMessage(tr("Unable to resume torrent '%1'.", "e.g: Unable to resume torrent 'hash'.")
@ -3712,7 +3712,7 @@ void Session::refresh()
m_nativeSession->post_session_stats(); m_nativeSession->post_session_stats();
} }
void Session::handleIPFilterParsed(int ruleCount) void Session::handleIPFilterParsed(const int ruleCount)
{ {
if (m_filterParser) { if (m_filterParser) {
libt::ip_filter filter = m_filterParser->IPfilter(); libt::ip_filter filter = m_filterParser->IPfilter();
@ -3733,7 +3733,7 @@ void Session::handleIPFilterError()
emit IPFilterParsed(true, 0); emit IPFilterParsed(true, 0);
} }
void Session::getPendingAlerts(std::vector<libt::alert *> &out, ulong time) void Session::getPendingAlerts(std::vector<libt::alert *> &out, const ulong time)
{ {
Q_ASSERT(out.empty()); Q_ASSERT(out.empty());
@ -3747,7 +3747,7 @@ bool Session::isCreateTorrentSubfolder() const
return m_isCreateTorrentSubfolder; return m_isCreateTorrentSubfolder;
} }
void Session::setCreateTorrentSubfolder(bool value) void Session::setCreateTorrentSubfolder(const bool value)
{ {
m_isCreateTorrentSubfolder = value; m_isCreateTorrentSubfolder = value;
} }
@ -3841,7 +3841,7 @@ void Session::handleAlert(libt::alert *a)
void Session::dispatchTorrentAlert(libt::alert *a) void Session::dispatchTorrentAlert(libt::alert *a)
{ {
TorrentHandle *const torrent = m_torrents.value(static_cast<libt::torrent_alert*>(a)->handle.info_hash()); TorrentHandle *const torrent = m_torrents.value(static_cast<const libt::torrent_alert*>(a)->handle.info_hash());
if (torrent) if (torrent)
torrent->handleAlert(a); torrent->handleAlert(a);
} }
@ -3851,14 +3851,14 @@ void Session::createTorrentHandle(const libt::torrent_handle &nativeHandle)
// Magnet added for preload its metadata // Magnet added for preload its metadata
if (!m_addingTorrents.contains(nativeHandle.info_hash())) return; if (!m_addingTorrents.contains(nativeHandle.info_hash())) return;
CreateTorrentParams params = m_addingTorrents.take(nativeHandle.info_hash()); const CreateTorrentParams params = m_addingTorrents.take(nativeHandle.info_hash());
TorrentHandle *const torrent = new TorrentHandle(this, nativeHandle, params); TorrentHandle *const torrent = new TorrentHandle(this, nativeHandle, params);
m_torrents.insert(torrent->hash(), torrent); m_torrents.insert(torrent->hash(), torrent);
Logger *const logger = Logger::instance(); Logger *const logger = Logger::instance();
bool fromMagnetUri = !torrent->hasMetadata(); const bool fromMagnetUri = !torrent->hasMetadata();
if (params.restored) { if (params.restored) {
logger->addMessage(tr("'%1' restored.", "'torrent name' restored.").arg(torrent->name())); logger->addMessage(tr("'%1' restored.", "'torrent name' restored.").arg(torrent->name()));
@ -4002,7 +4002,7 @@ void Session::handlePortmapAlert(libt::portmap_alert *p)
void Session::handlePeerBlockedAlert(libt::peer_blocked_alert *p) void Session::handlePeerBlockedAlert(libt::peer_blocked_alert *p)
{ {
boost::system::error_code ec; boost::system::error_code ec;
std::string ip = p->ip.to_string(ec); const std::string ip = p->ip.to_string(ec);
QString reason; QString reason;
switch (p->reason) { switch (p->reason) {
case libt::peer_blocked_alert::ip_filter: case libt::peer_blocked_alert::ip_filter:
@ -4032,7 +4032,7 @@ void Session::handlePeerBlockedAlert(libt::peer_blocked_alert *p)
void Session::handlePeerBanAlert(libt::peer_ban_alert *p) void Session::handlePeerBanAlert(libt::peer_ban_alert *p)
{ {
boost::system::error_code ec; boost::system::error_code ec;
std::string ip = p->ip.address().to_string(ec); const std::string ip = p->ip.address().to_string(ec);
if (!ec) if (!ec)
Logger::instance()->addPeer(QString::fromLatin1(ip.c_str()), false); Logger::instance()->addPeer(QString::fromLatin1(ip.c_str()), false);
} }
@ -4098,7 +4098,7 @@ void Session::handleExternalIPAlert(libt::external_ip_alert *p)
void Session::handleSessionStatsAlert(libt::session_stats_alert *p) void Session::handleSessionStatsAlert(libt::session_stats_alert *p)
{ {
qreal interval = m_statsUpdateTimer.restart() / 1000.; const qreal interval = m_statsUpdateTimer.restart() / 1000.;
m_status.hasIncomingConnections = static_cast<bool>(p->values[m_metricIndices.net.hasIncomingConnections]); m_status.hasIncomingConnections = static_cast<bool>(p->values[m_metricIndices.net.hasIncomingConnections]);
@ -4113,7 +4113,7 @@ void Session::handleSessionStatsAlert(libt::session_stats_alert *p)
const auto dhtDownload = p->values[m_metricIndices.dht.dhtBytesIn]; const auto dhtDownload = p->values[m_metricIndices.dht.dhtBytesIn];
const auto dhtUpload = p->values[m_metricIndices.dht.dhtBytesOut]; const auto dhtUpload = p->values[m_metricIndices.dht.dhtBytesOut];
auto calcRate = [interval](quint64 previous, quint64 current) auto calcRate = [interval](const quint64 previous, const quint64 current)
{ {
Q_ASSERT(current >= previous); Q_ASSERT(current >= previous);
return static_cast<quint64>((current - previous) / interval); return static_cast<quint64>((current - previous) / interval);
@ -4153,7 +4153,7 @@ void Session::handleSessionStatsAlert(libt::session_stats_alert *p)
m_cacheStatus.readRatio = static_cast<qreal>(numBlocksCacheHits) / std::max(numBlocksCacheHits + numBlocksRead, 1); m_cacheStatus.readRatio = static_cast<qreal>(numBlocksCacheHits) / std::max(numBlocksCacheHits + numBlocksRead, 1);
m_cacheStatus.jobQueueLength = p->values[m_metricIndices.disk.queuedDiskJobs]; m_cacheStatus.jobQueueLength = p->values[m_metricIndices.disk.queuedDiskJobs];
quint64 totalJobs = p->values[m_metricIndices.disk.writeJobs] + p->values[m_metricIndices.disk.readJobs] const quint64 totalJobs = p->values[m_metricIndices.disk.writeJobs] + p->values[m_metricIndices.disk.readJobs]
+ p->values[m_metricIndices.disk.hashJobs]; + p->values[m_metricIndices.disk.hashJobs];
m_cacheStatus.averageJobTime = totalJobs > 0 m_cacheStatus.averageJobTime = totalJobs > 0
? (p->values[m_metricIndices.disk.diskJobTime] / totalJobs) : 0; ? (p->values[m_metricIndices.disk.diskJobTime] / totalJobs) : 0;
@ -4312,7 +4312,7 @@ namespace
if (!ConvertIfaceLuidToGuid) return QString(); if (!ConvertIfaceLuidToGuid) return QString();
NET_LUID luid; NET_LUID luid;
LONG res = ConvertIfaceNameToLuid(name.toStdWString().c_str(), &luid); const LONG res = ConvertIfaceNameToLuid(name.toStdWString().c_str(), &luid);
if (res == 0) { if (res == 0) {
GUID guid; GUID guid;
if (ConvertIfaceLuidToGuid(&luid, &guid) == 0) if (ConvertIfaceLuidToGuid(&luid, &guid) == 0)

View file

@ -543,7 +543,7 @@ namespace BitTorrent
void handleRedirectedToMagnet(const QString &url, const QString &magnetUri); void handleRedirectedToMagnet(const QString &url, const QString &magnetUri);
// Session reconfiguration triggers // Session reconfiguration triggers
void networkOnlineStateChanged(const bool online); void networkOnlineStateChanged(bool online);
void networkConfigurationChange(const QNetworkConfiguration&); void networkConfigurationChange(const QNetworkConfiguration&);
private: private:

View file

@ -57,7 +57,7 @@ namespace BitTorrent
void create(const TorrentCreatorParams &params); void create(const TorrentCreatorParams &params);
static int calculateTotalPieces(const QString &inputPath, const int pieceSize, const bool isAlignmentOptimized); static int calculateTotalPieces(const QString &inputPath, int pieceSize, bool isAlignmentOptimized);
protected: protected:
void run(); void run();

View file

@ -299,7 +299,7 @@ QString TorrentHandle::rootPath(bool actual) const
if ((filesCount() > 1) && !hasRootFolder()) if ((filesCount() > 1) && !hasRootFolder())
return QString(); return QString();
QString firstFilePath = filePath(0); const QString firstFilePath = filePath(0);
const int slashIndex = firstFilePath.indexOf('/'); const int slashIndex = firstFilePath.indexOf('/');
if (slashIndex >= 0) if (slashIndex >= 0)
return QDir(savePath(actual)).absoluteFilePath(firstFilePath.left(slashIndex)); return QDir(savePath(actual)).absoluteFilePath(firstFilePath.left(slashIndex));
@ -462,10 +462,10 @@ bool TorrentHandle::removeUrlSeed(const QUrl &urlSeed)
bool TorrentHandle::connectPeer(const PeerAddress &peerAddress) bool TorrentHandle::connectPeer(const PeerAddress &peerAddress)
{ {
libt::error_code ec; libt::error_code ec;
libt::address addr = libt::address::from_string(peerAddress.ip.toString().toStdString(), ec); const libt::address addr = libt::address::from_string(peerAddress.ip.toString().toStdString(), ec);
if (ec) return false; if (ec) return false;
boost::asio::ip::tcp::endpoint ep(addr, peerAddress.port); const boost::asio::ip::tcp::endpoint ep(addr, peerAddress.port);
m_nativeHandle.connect_peer(ep); m_nativeHandle.connect_peer(ep);
return true; return true;
} }
@ -504,7 +504,7 @@ qreal TorrentHandle::progress() const
if (m_nativeStatus.total_wanted_done == m_nativeStatus.total_wanted) if (m_nativeStatus.total_wanted_done == m_nativeStatus.total_wanted)
return 1.; return 1.;
qreal progress = static_cast<qreal>(m_nativeStatus.total_wanted_done) / m_nativeStatus.total_wanted; const qreal progress = static_cast<qreal>(m_nativeStatus.total_wanted_done) / m_nativeStatus.total_wanted;
Q_ASSERT((progress >= 0.f) && (progress <= 1.f)); Q_ASSERT((progress >= 0.f) && (progress <= 1.f));
return progress; return progress;
} }
@ -608,7 +608,7 @@ QStringList TorrentHandle::absoluteFilePaths() const
{ {
if (!hasMetadata()) return QStringList(); if (!hasMetadata()) return QStringList();
QDir saveDir(savePath(true)); const QDir saveDir(savePath(true));
QStringList res; QStringList res;
for (int i = 0; i < filesCount(); ++i) for (int i = 0; i < filesCount(); ++i)
res << Utils::Fs::expandPathAbs(saveDir.absoluteFilePath(filePath(i))); res << Utils::Fs::expandPathAbs(saveDir.absoluteFilePath(filePath(i)));
@ -619,12 +619,11 @@ QStringList TorrentHandle::absoluteFilePathsUnwanted() const
{ {
if (!hasMetadata()) return QStringList(); if (!hasMetadata()) return QStringList();
QDir saveDir(savePath(true)); const QDir saveDir(savePath(true));
QStringList res; QStringList res;
std::vector<int> fp; const std::vector<int> fp = m_nativeHandle.file_priorities();
fp = m_nativeHandle.file_priorities();
int count = static_cast<int>(fp.size()); const int count = static_cast<int>(fp.size());
for (int i = 0; i < count; ++i) { for (int i = 0; i < count; ++i) {
if (fp[i] == 0) { if (fp[i] == 0) {
const QString path = Utils::Fs::expandPathAbs(saveDir.absoluteFilePath(filePath(i))); const QString path = Utils::Fs::expandPathAbs(saveDir.absoluteFilePath(filePath(i)));
@ -638,8 +637,7 @@ QStringList TorrentHandle::absoluteFilePathsUnwanted() const
QVector<int> TorrentHandle::filePriorities() const QVector<int> TorrentHandle::filePriorities() const
{ {
std::vector<int> fp; const std::vector<int> fp = m_nativeHandle.file_priorities();
fp = m_nativeHandle.file_priorities();
return QVector<int>::fromStdVector(fp); return QVector<int>::fromStdVector(fp);
} }
@ -892,8 +890,8 @@ qulonglong TorrentHandle::eta() const
const SpeedSampleAvg speedAverage = m_speedMonitor.average(); const SpeedSampleAvg speedAverage = m_speedMonitor.average();
if (isSeed()) { if (isSeed()) {
qreal maxRatioValue = maxRatio(); const qreal maxRatioValue = maxRatio();
int maxSeedingTimeValue = maxSeedingTime(); const int maxSeedingTimeValue = maxSeedingTime();
if ((maxRatioValue < 0) && (maxSeedingTimeValue < 0)) return MAX_ETA; if ((maxRatioValue < 0) && (maxSeedingTimeValue < 0)) return MAX_ETA;
qlonglong ratioEta = MAX_ETA; qlonglong ratioEta = MAX_ETA;
@ -964,7 +962,7 @@ int TorrentHandle::totalSeedsCount() const
int TorrentHandle::totalPeersCount() const int TorrentHandle::totalPeersCount() const
{ {
int peers = m_nativeStatus.num_complete + m_nativeStatus.num_incomplete; const int peers = m_nativeStatus.num_complete + m_nativeStatus.num_incomplete;
return (peers > 0) ? peers : m_nativeStatus.list_peers; return (peers > 0) ? peers : m_nativeStatus.list_peers;
} }
@ -1102,14 +1100,14 @@ int TorrentHandle::maxSeedingTime() const
qreal TorrentHandle::realRatio() const qreal TorrentHandle::realRatio() const
{ {
boost::int64_t upload = m_nativeStatus.all_time_upload; const boost::int64_t upload = m_nativeStatus.all_time_upload;
// special case for a seeder who lost its stats, also assume nobody will import a 99% done torrent // special case for a seeder who lost its stats, also assume nobody will import a 99% done torrent
boost::int64_t download = (m_nativeStatus.all_time_download < m_nativeStatus.total_done * 0.01) ? m_nativeStatus.total_done : m_nativeStatus.all_time_download; const boost::int64_t download = (m_nativeStatus.all_time_download < m_nativeStatus.total_done * 0.01) ? m_nativeStatus.total_done : m_nativeStatus.all_time_download;
if (download == 0) if (download == 0)
return (upload == 0) ? 0.0 : MAX_RATIO; return (upload == 0) ? 0.0 : MAX_RATIO;
qreal ratio = upload / static_cast<qreal>(download); const qreal ratio = upload / static_cast<qreal>(download);
Q_ASSERT(ratio >= 0.0); Q_ASSERT(ratio >= 0.0);
return (ratio > MAX_RATIO) ? MAX_RATIO : ratio; return (ratio > MAX_RATIO) ? MAX_RATIO : ratio;
} }
@ -1163,7 +1161,7 @@ bool TorrentHandle::setCategory(const QString &category)
if (!category.isEmpty() && !m_session->categories().contains(category)) if (!category.isEmpty() && !m_session->categories().contains(category))
return false; return false;
QString oldCategory = m_category; const QString oldCategory = m_category;
m_category = category; m_category = category;
m_session->handleTorrentCategoryChanged(this, oldCategory); m_session->handleTorrentCategoryChanged(this, oldCategory);
@ -1229,7 +1227,7 @@ void TorrentHandle::forceRecheck()
} }
} }
void TorrentHandle::setSequentialDownload(bool b) void TorrentHandle::setSequentialDownload(const bool b)
{ {
if (b != isSequentialDownload()) { if (b != isSequentialDownload()) {
m_nativeHandle.set_sequential_download(b); m_nativeHandle.set_sequential_download(b);
@ -1354,8 +1352,8 @@ bool TorrentHandle::saveTorrentFile(const QString &path)
{ {
if (!m_torrentInfo.isValid()) return false; if (!m_torrentInfo.isValid()) return false;
libt::create_torrent torrentCreator = libt::create_torrent(*(m_torrentInfo.nativeInfo()), true); const libt::create_torrent torrentCreator = libt::create_torrent(*(m_torrentInfo.nativeInfo()), true);
libt::entry torrentEntry = torrentCreator.generate(); const libt::entry torrentEntry = torrentCreator.generate();
QVector<char> out; QVector<char> out;
libt::bencode(std::back_inserter(out), torrentEntry); libt::bencode(std::back_inserter(out), torrentEntry);
@ -1436,7 +1434,7 @@ void TorrentHandle::handleStorageMovedFailedAlert(const libtorrent::storage_move
void TorrentHandle::handleTrackerReplyAlert(const libtorrent::tracker_reply_alert *p) void TorrentHandle::handleTrackerReplyAlert(const libtorrent::tracker_reply_alert *p)
{ {
QString trackerUrl(p->tracker_url()); const QString trackerUrl(p->tracker_url());
qDebug("Received a tracker reply from %s (Num_peers = %d)", qUtf8Printable(trackerUrl), p->num_peers); qDebug("Received a tracker reply from %s (Num_peers = %d)", qUtf8Printable(trackerUrl), p->num_peers);
// Connection was successful now. Remove possible old errors // Connection was successful now. Remove possible old errors
m_trackerInfos[trackerUrl].lastMessage.clear(); // Reset error/warning message m_trackerInfos[trackerUrl].lastMessage.clear(); // Reset error/warning message
@ -1568,7 +1566,7 @@ void TorrentHandle::handleSaveResumeDataAlert(const libtorrent::save_resume_data
resumeData["qBt-sequential"] = isSequentialDownload(); resumeData["qBt-sequential"] = isSequentialDownload();
} }
else { else {
auto savePath = resumeData.find_key("save_path")->string(); const auto savePath = resumeData.find_key("save_path")->string();
resumeData["save_path"] = Profile::instance().toPortablePath(QString::fromStdString(savePath)).toStdString(); resumeData["save_path"] = Profile::instance().toPortablePath(QString::fromStdString(savePath)).toStdString();
} }
resumeData["qBt-savePath"] = m_useAutoTMM ? "" : Profile::instance().toPortablePath(m_savePath).toStdString(); resumeData["qBt-savePath"] = m_useAutoTMM ? "" : Profile::instance().toPortablePath(m_savePath).toStdString();
@ -1610,7 +1608,7 @@ void TorrentHandle::handleFastResumeRejectedAlert(const libtorrent::fastresume_r
void TorrentHandle::handleFileRenamedAlert(const libtorrent::file_renamed_alert *p) void TorrentHandle::handleFileRenamedAlert(const libtorrent::file_renamed_alert *p)
{ {
QString newName = Utils::Fs::fromNativePath(p->new_name()); const QString newName = Utils::Fs::fromNativePath(p->new_name());
// TODO: Check this! // TODO: Check this!
if (filesCount() > 1) { if (filesCount() > 1) {
@ -1620,7 +1618,7 @@ void TorrentHandle::handleFileRenamedAlert(const libtorrent::file_renamed_alert
QString oldPath = oldPathParts.join('/'); QString oldPath = oldPathParts.join('/');
QStringList newPathParts = newName.split('/'); QStringList newPathParts = newName.split('/');
newPathParts.removeLast(); newPathParts.removeLast();
QString newPath = newPathParts.join('/'); const QString newPath = newPathParts.join('/');
if (!newPathParts.isEmpty() && (oldPath != newPath)) { if (!newPathParts.isEmpty() && (oldPath != newPath)) {
qDebug("oldPath(%s) != newPath(%s)", qUtf8Printable(oldPath), qUtf8Printable(newPath)); qDebug("oldPath(%s) != newPath(%s)", qUtf8Printable(oldPath), qUtf8Printable(newPath));
oldPath = QString("%1/%2").arg(savePath(true), oldPath); oldPath = QString("%1/%2").arg(savePath(true), oldPath);
@ -1668,7 +1666,7 @@ void TorrentHandle::handleFileCompletedAlert(const libtorrent::file_completed_al
void TorrentHandle::handleStatsAlert(const libtorrent::stats_alert *p) void TorrentHandle::handleStatsAlert(const libtorrent::stats_alert *p)
{ {
Q_ASSERT(p->interval >= 1000); Q_ASSERT(p->interval >= 1000);
SpeedSample transferred(p->transferred[libt::stats_alert::download_payload] * 1000LL / p->interval, const SpeedSample transferred(p->transferred[libt::stats_alert::download_payload] * 1000LL / p->interval,
p->transferred[libt::stats_alert::upload_payload] * 1000LL / p->interval); p->transferred[libt::stats_alert::upload_payload] * 1000LL / p->interval);
m_speedMonitor.addSample(transferred); m_speedMonitor.addSample(transferred);
} }
@ -1723,55 +1721,55 @@ void TorrentHandle::handleAlert(libtorrent::alert *a)
{ {
switch (a->type()) { switch (a->type()) {
case libt::stats_alert::alert_type: case libt::stats_alert::alert_type:
handleStatsAlert(static_cast<libt::stats_alert*>(a)); handleStatsAlert(static_cast<const libt::stats_alert*>(a));
break; break;
case libt::file_renamed_alert::alert_type: case libt::file_renamed_alert::alert_type:
handleFileRenamedAlert(static_cast<libt::file_renamed_alert*>(a)); handleFileRenamedAlert(static_cast<const libt::file_renamed_alert*>(a));
break; break;
case libt::file_rename_failed_alert::alert_type: case libt::file_rename_failed_alert::alert_type:
handleFileRenameFailedAlert(static_cast<libt::file_rename_failed_alert*>(a)); handleFileRenameFailedAlert(static_cast<const libt::file_rename_failed_alert*>(a));
break; break;
case libt::file_completed_alert::alert_type: case libt::file_completed_alert::alert_type:
handleFileCompletedAlert(static_cast<libt::file_completed_alert*>(a)); handleFileCompletedAlert(static_cast<const libt::file_completed_alert*>(a));
break; break;
case libt::torrent_finished_alert::alert_type: case libt::torrent_finished_alert::alert_type:
handleTorrentFinishedAlert(static_cast<libt::torrent_finished_alert*>(a)); handleTorrentFinishedAlert(static_cast<const libt::torrent_finished_alert*>(a));
break; break;
case libt::save_resume_data_alert::alert_type: case libt::save_resume_data_alert::alert_type:
handleSaveResumeDataAlert(static_cast<libt::save_resume_data_alert*>(a)); handleSaveResumeDataAlert(static_cast<const libt::save_resume_data_alert*>(a));
break; break;
case libt::save_resume_data_failed_alert::alert_type: case libt::save_resume_data_failed_alert::alert_type:
handleSaveResumeDataFailedAlert(static_cast<libt::save_resume_data_failed_alert*>(a)); handleSaveResumeDataFailedAlert(static_cast<const libt::save_resume_data_failed_alert*>(a));
break; break;
case libt::storage_moved_alert::alert_type: case libt::storage_moved_alert::alert_type:
handleStorageMovedAlert(static_cast<libt::storage_moved_alert*>(a)); handleStorageMovedAlert(static_cast<const libt::storage_moved_alert*>(a));
break; break;
case libt::storage_moved_failed_alert::alert_type: case libt::storage_moved_failed_alert::alert_type:
handleStorageMovedFailedAlert(static_cast<libt::storage_moved_failed_alert*>(a)); handleStorageMovedFailedAlert(static_cast<const libt::storage_moved_failed_alert*>(a));
break; break;
case libt::torrent_paused_alert::alert_type: case libt::torrent_paused_alert::alert_type:
handleTorrentPausedAlert(static_cast<libt::torrent_paused_alert*>(a)); handleTorrentPausedAlert(static_cast<const libt::torrent_paused_alert*>(a));
break; break;
case libt::torrent_resumed_alert::alert_type: case libt::torrent_resumed_alert::alert_type:
handleTorrentResumedAlert(static_cast<libt::torrent_resumed_alert*>(a)); handleTorrentResumedAlert(static_cast<const libt::torrent_resumed_alert*>(a));
break; break;
case libt::tracker_error_alert::alert_type: case libt::tracker_error_alert::alert_type:
handleTrackerErrorAlert(static_cast<libt::tracker_error_alert*>(a)); handleTrackerErrorAlert(static_cast<const libt::tracker_error_alert*>(a));
break; break;
case libt::tracker_reply_alert::alert_type: case libt::tracker_reply_alert::alert_type:
handleTrackerReplyAlert(static_cast<libt::tracker_reply_alert*>(a)); handleTrackerReplyAlert(static_cast<const libt::tracker_reply_alert*>(a));
break; break;
case libt::tracker_warning_alert::alert_type: case libt::tracker_warning_alert::alert_type:
handleTrackerWarningAlert(static_cast<libt::tracker_warning_alert*>(a)); handleTrackerWarningAlert(static_cast<const libt::tracker_warning_alert*>(a));
break; break;
case libt::metadata_received_alert::alert_type: case libt::metadata_received_alert::alert_type:
handleMetadataReceivedAlert(static_cast<libt::metadata_received_alert*>(a)); handleMetadataReceivedAlert(static_cast<const libt::metadata_received_alert*>(a));
break; break;
case libt::fastresume_rejected_alert::alert_type: case libt::fastresume_rejected_alert::alert_type:
handleFastResumeRejectedAlert(static_cast<libt::fastresume_rejected_alert*>(a)); handleFastResumeRejectedAlert(static_cast<const libt::fastresume_rejected_alert*>(a));
break; break;
case libt::torrent_checked_alert::alert_type: case libt::torrent_checked_alert::alert_type:
handleTorrentCheckedAlert(static_cast<libt::torrent_checked_alert*>(a)); handleTorrentCheckedAlert(static_cast<const libt::torrent_checked_alert*>(a));
break; break;
} }
} }
@ -1779,7 +1777,7 @@ void TorrentHandle::handleAlert(libtorrent::alert *a)
void TorrentHandle::manageIncompleteFiles() void TorrentHandle::manageIncompleteFiles()
{ {
const bool isAppendExtensionEnabled = m_session->isAppendExtensionEnabled(); const bool isAppendExtensionEnabled = m_session->isAppendExtensionEnabled();
QVector<qreal> fp = filesProgress(); const QVector<qreal> fp = filesProgress();
if (fp.size() != filesCount()) { if (fp.size() != filesCount()) {
qDebug() << "skip manageIncompleteFiles because of invalid torrent meta-data or empty file-progress"; qDebug() << "skip manageIncompleteFiles because of invalid torrent meta-data or empty file-progress";
return; return;
@ -1898,17 +1896,17 @@ void TorrentHandle::setSeedingTimeLimit(int limit)
} }
} }
void TorrentHandle::setUploadLimit(int limit) void TorrentHandle::setUploadLimit(const int limit)
{ {
m_nativeHandle.set_upload_limit(limit); m_nativeHandle.set_upload_limit(limit);
} }
void TorrentHandle::setDownloadLimit(int limit) void TorrentHandle::setDownloadLimit(const int limit)
{ {
m_nativeHandle.set_download_limit(limit); m_nativeHandle.set_download_limit(limit);
} }
void TorrentHandle::setSuperSeeding(bool enable) void TorrentHandle::setSuperSeeding(const bool enable)
{ {
m_nativeHandle.super_seeding(enable); m_nativeHandle.super_seeding(enable);
} }
@ -1933,8 +1931,8 @@ void TorrentHandle::prioritizeFiles(const QVector<int> &priorities)
// Reset 'm_hasSeedStatus' if needed in order to react again to // Reset 'm_hasSeedStatus' if needed in order to react again to
// 'torrent_finished_alert' and eg show tray notifications // 'torrent_finished_alert' and eg show tray notifications
QVector<qreal> progress = filesProgress(); const QVector<qreal> progress = filesProgress();
QVector<int> oldPriorities = filePriorities(); const QVector<int> oldPriorities = filePriorities();
for (int i = 0; i < oldPriorities.size(); ++i) { for (int i = 0; i < oldPriorities.size(); ++i) {
if ((oldPriorities[i] == 0) && (priorities[i] > 0) && (progress[i] < 1.0)) { if ((oldPriorities[i] == 0) && (priorities[i] > 0) && (progress[i] < 1.0)) {
m_hasSeedStatus = false; m_hasSeedStatus = false;
@ -1946,24 +1944,24 @@ void TorrentHandle::prioritizeFiles(const QVector<int> &priorities)
m_nativeHandle.prioritize_files(priorities.toStdVector()); m_nativeHandle.prioritize_files(priorities.toStdVector());
qDebug() << Q_FUNC_INFO << "Moving unwanted files to .unwanted folder and conversely..."; qDebug() << Q_FUNC_INFO << "Moving unwanted files to .unwanted folder and conversely...";
QString spath = savePath(true); const QString spath = savePath(true);
for (int i = 0; i < priorities.size(); ++i) { for (int i = 0; i < priorities.size(); ++i) {
QString filepath = filePath(i); const QString filepath = filePath(i);
// Move unwanted files to a .unwanted subfolder // Move unwanted files to a .unwanted subfolder
if (priorities[i] == 0) { if (priorities[i] == 0) {
QString oldAbsPath = QDir(spath).absoluteFilePath(filepath); const QString oldAbsPath = QDir(spath).absoluteFilePath(filepath);
QString parentAbsPath = Utils::Fs::branchPath(oldAbsPath); const QString parentAbsPath = Utils::Fs::branchPath(oldAbsPath);
// Make sure the file does not already exists // Make sure the file does not already exists
if (QDir(parentAbsPath).dirName() != ".unwanted") { if (QDir(parentAbsPath).dirName() != ".unwanted") {
QString unwantedAbsPath = parentAbsPath + "/.unwanted"; const QString unwantedAbsPath = parentAbsPath + "/.unwanted";
QString newAbsPath = unwantedAbsPath + '/' + Utils::Fs::fileName(filepath); const QString newAbsPath = unwantedAbsPath + '/' + Utils::Fs::fileName(filepath);
qDebug() << "Unwanted path is" << unwantedAbsPath; qDebug() << "Unwanted path is" << unwantedAbsPath;
if (QFile::exists(newAbsPath)) { if (QFile::exists(newAbsPath)) {
qWarning() << "File" << newAbsPath << "already exists at destination."; qWarning() << "File" << newAbsPath << "already exists at destination.";
continue; continue;
} }
bool created = QDir().mkpath(unwantedAbsPath); const bool created = QDir().mkpath(unwantedAbsPath);
qDebug() << "unwanted folder was created:" << created; qDebug() << "unwanted folder was created:" << created;
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
if (created) { if (created) {
@ -1984,10 +1982,10 @@ void TorrentHandle::prioritizeFiles(const QVector<int> &priorities)
// Move wanted files back to their original folder // Move wanted files back to their original folder
if (priorities[i] > 0) { if (priorities[i] > 0) {
QString parentRelPath = Utils::Fs::branchPath(filepath); const QString parentRelPath = Utils::Fs::branchPath(filepath);
if (QDir(parentRelPath).dirName() == ".unwanted") { if (QDir(parentRelPath).dirName() == ".unwanted") {
QString oldName = Utils::Fs::fileName(filepath); const QString oldName = Utils::Fs::fileName(filepath);
QString newRelPath = Utils::Fs::branchPath(parentRelPath); const QString newRelPath = Utils::Fs::branchPath(parentRelPath);
if (newRelPath.isEmpty()) if (newRelPath.isEmpty())
renameFile(i, oldName); renameFile(i, oldName);
else else

View file

@ -146,7 +146,7 @@ QString TorrentInfo::name() const
QDateTime TorrentInfo::creationDate() const QDateTime TorrentInfo::creationDate() const
{ {
if (!isValid()) return QDateTime(); if (!isValid()) return QDateTime();
boost::optional<time_t> t = m_nativeInfo->creation_date(); const boost::optional<time_t> t = m_nativeInfo->creation_date();
return t ? QDateTime::fromTime_t(*t) : QDateTime(); return t ? QDateTime::fromTime_t(*t) : QDateTime();
} }
@ -186,7 +186,7 @@ int TorrentInfo::pieceLength() const
return m_nativeInfo->piece_length(); return m_nativeInfo->piece_length();
} }
int TorrentInfo::pieceLength(int index) const int TorrentInfo::pieceLength(const int index) const
{ {
if (!isValid()) return -1; if (!isValid()) return -1;
return m_nativeInfo->piece_size(index); return m_nativeInfo->piece_size(index);
@ -198,7 +198,7 @@ int TorrentInfo::piecesCount() const
return m_nativeInfo->num_pieces(); return m_nativeInfo->num_pieces();
} }
QString TorrentInfo::filePath(int index) const QString TorrentInfo::filePath(const int index) const
{ {
if (!isValid()) return QString(); if (!isValid()) return QString();
return Utils::Fs::fromNativePath(QString::fromStdString(m_nativeInfo->files().file_path(index))); return Utils::Fs::fromNativePath(QString::fromStdString(m_nativeInfo->files().file_path(index)));
@ -213,24 +213,24 @@ QStringList TorrentInfo::filePaths() const
return list; return list;
} }
QString TorrentInfo::fileName(int index) const QString TorrentInfo::fileName(const int index) const
{ {
return Utils::Fs::fileName(filePath(index)); return Utils::Fs::fileName(filePath(index));
} }
QString TorrentInfo::origFilePath(int index) const QString TorrentInfo::origFilePath(const int index) const
{ {
if (!isValid()) return QString(); if (!isValid()) return QString();
return Utils::Fs::fromNativePath(QString::fromStdString(m_nativeInfo->orig_files().file_path(index))); return Utils::Fs::fromNativePath(QString::fromStdString(m_nativeInfo->orig_files().file_path(index)));
} }
qlonglong TorrentInfo::fileSize(int index) const qlonglong TorrentInfo::fileSize(const int index) const
{ {
if (!isValid()) return -1; if (!isValid()) return -1;
return m_nativeInfo->files().file_size(index); return m_nativeInfo->files().file_size(index);
} }
qlonglong TorrentInfo::fileOffset(int index) const qlonglong TorrentInfo::fileOffset(const int index) const
{ {
if (!isValid()) return -1; if (!isValid()) return -1;
return m_nativeInfo->files().file_offset(index); return m_nativeInfo->files().file_offset(index);
@ -265,10 +265,10 @@ QByteArray TorrentInfo::metadata() const
return QByteArray(m_nativeInfo->metadata().get(), m_nativeInfo->metadata_size()); return QByteArray(m_nativeInfo->metadata().get(), m_nativeInfo->metadata_size());
} }
QStringList TorrentInfo::filesForPiece(int pieceIndex) const QStringList TorrentInfo::filesForPiece(const int pieceIndex) const
{ {
// no checks here because fileIndicesForPiece() will return an empty list // no checks here because fileIndicesForPiece() will return an empty list
QVector<int> fileIndices = fileIndicesForPiece(pieceIndex); const QVector<int> fileIndices = fileIndicesForPiece(pieceIndex);
QStringList res; QStringList res;
res.reserve(fileIndices.size()); res.reserve(fileIndices.size());
@ -278,12 +278,12 @@ QStringList TorrentInfo::filesForPiece(int pieceIndex) const
return res; return res;
} }
QVector<int> TorrentInfo::fileIndicesForPiece(int pieceIndex) const QVector<int> TorrentInfo::fileIndicesForPiece(const int pieceIndex) const
{ {
if (!isValid() || (pieceIndex < 0) || (pieceIndex >= piecesCount())) if (!isValid() || (pieceIndex < 0) || (pieceIndex >= piecesCount()))
return QVector<int>(); return QVector<int>();
std::vector<libt::file_slice> files( const std::vector<libt::file_slice> files(
nativeInfo()->map_block(pieceIndex, 0, nativeInfo()->piece_size(pieceIndex))); nativeInfo()->map_block(pieceIndex, 0, nativeInfo()->piece_size(pieceIndex)));
QVector<int> res; QVector<int> res;
res.reserve(int(files.size())); res.reserve(int(files.size()));
@ -313,7 +313,7 @@ TorrentInfo::PieceRange TorrentInfo::filePieces(const QString &file) const
if (!isValid()) // if we do not check here the debug message will be printed, which would be not correct if (!isValid()) // if we do not check here the debug message will be printed, which would be not correct
return {}; return {};
int index = fileIndex(file); const int index = fileIndex(file);
if (index == -1) { if (index == -1) {
qDebug() << "Filename" << file << "was not found in torrent" << name(); qDebug() << "Filename" << file << "was not found in torrent" << name();
return {}; return {};
@ -321,7 +321,7 @@ TorrentInfo::PieceRange TorrentInfo::filePieces(const QString &file) const
return filePieces(index); return filePieces(index);
} }
TorrentInfo::PieceRange TorrentInfo::filePieces(int fileIndex) const TorrentInfo::PieceRange TorrentInfo::filePieces(const int fileIndex) const
{ {
if (!isValid()) if (!isValid())
return {}; return {};
@ -387,7 +387,7 @@ void TorrentInfo::stripRootFolder()
libtorrent::file_storage files = m_nativeInfo->files(); libtorrent::file_storage files = m_nativeInfo->files();
// Solution for case of renamed root folder // Solution for case of renamed root folder
std::string testName = filePath(0).split('/').value(0).toStdString(); const std::string testName = filePath(0).split('/').value(0).toStdString();
if (files.name() != testName) { if (files.name() != testName) {
files.set_name(testName); files.set_name(testName);
for (int i = 0; i < files.num_files(); ++i) for (int i = 0; i < files.num_files(); ++i)

View file

@ -63,7 +63,7 @@ QString Peer::uid() const
return ip.toString() + ':' + QString::number(port); return ip.toString() + ':' + QString::number(port);
} }
libtorrent::entry Peer::toEntry(bool noPeerId) const libtorrent::entry Peer::toEntry(const bool noPeerId) const
{ {
libtorrent::entry::dictionary_type peerMap; libtorrent::entry::dictionary_type peerMap;
if (!noPeerId) if (!noPeerId)

View file

@ -120,9 +120,9 @@ int PropTabBar::currentIndex() const
void PropTabBar::setCurrentIndex(int index) void PropTabBar::setCurrentIndex(int index)
{ {
if (index >= m_btnGroup->buttons().size()) if (index >= m_btnGroup->buttons().size())
index = 0; index = 0;
// If asked to hide or if the currently selected tab is clicked // If asked to hide or if the currently selected tab is clicked
if (index < 0 || m_currentIndex == index) { if ((index < 0) || (m_currentIndex == index)) {
if (m_currentIndex >= 0) { if (m_currentIndex >= 0) {
m_btnGroup->button(m_currentIndex)->setDown(false); m_btnGroup->button(m_currentIndex)->setDown(false);
m_currentIndex = -1; m_currentIndex = -1;

View file

@ -149,7 +149,7 @@ QList<QTreeWidgetItem*> TrackerListWidget::getSelectedTrackerItems() const
return selectedTrackers; return selectedTrackers;
} }
void TrackerListWidget::setRowColor(int row, QColor color) void TrackerListWidget::setRowColor(const int row, QColor color)
{ {
const int nbColumns = columnCount(); const int nbColumns = columnCount();
QTreeWidgetItem *item = topLevelItem(row); QTreeWidgetItem *item = topLevelItem(row);

View file

@ -228,7 +228,7 @@ void PluginSelectDialog::enableSelection(bool enable)
} }
// Set the color of a row in data model // Set the color of a row in data model
void PluginSelectDialog::setRowColor(int row, QString color) void PluginSelectDialog::setRowColor(const int row, QString color)
{ {
QTreeWidgetItem *item = m_ui->pluginsTree->topLevelItem(row); QTreeWidgetItem *item = m_ui->pluginsTree->topLevelItem(row);
for (int i = 0; i < m_ui->pluginsTree->columnCount(); ++i) { for (int i = 0; i < m_ui->pluginsTree->columnCount(); ++i) {

View file

@ -466,8 +466,8 @@ QIcon getErrorIcon()
bool isDarkTheme() bool isDarkTheme()
{ {
QPalette pal = QApplication::palette(); const QPalette pal = QApplication::palette();
// QPalette::Base is used for the background of the Treeview // QPalette::Base is used for the background of the Treeview
QColor color = pal.color(QPalette::Active, QPalette::Base); const QColor color = pal.color(QPalette::Active, QPalette::Base);
return (color.lightness() < 127); return (color.lightness() < 127);
} }

View file

@ -321,7 +321,7 @@ void AppController::setPreferencesAction()
// Update deleted folders // Update deleted folders
for (auto i = oldScanDirs.cbegin(); i != oldScanDirs.cend(); ++i) { for (auto i = oldScanDirs.cbegin(); i != oldScanDirs.cend(); ++i) {
QString folder = i.key(); const QString folder = i.key();
if (!scanDirs.contains(folder)) { if (!scanDirs.contains(folder)) {
model->removePath(folder); model->removePath(folder);
qDebug("Removed watched folder %s", qUtf8Printable(folder)); qDebug("Removed watched folder %s", qUtf8Printable(folder));