diff --git a/src/about_imp.h b/src/about_imp.h index 47e5ac70b..03ffee7ff 100644 --- a/src/about_imp.h +++ b/src/about_imp.h @@ -100,7 +100,7 @@ class about : public QDialog, private Ui::AboutDlg{ // License te_license->append(QString::fromUtf8("")); QFile licensefile(":/gpl.html"); - if(licensefile.open(QIODevice::ReadOnly|QIODevice::Text)) { + if (licensefile.open(QIODevice::ReadOnly|QIODevice::Text)) { te_license->setHtml(licensefile.readAll()); licensefile.close(); } diff --git a/src/deletionconfirmationdlg.h b/src/deletionconfirmationdlg.h index 186ebc0fc..7959c74d1 100644 --- a/src/deletionconfirmationdlg.h +++ b/src/deletionconfirmationdlg.h @@ -59,7 +59,7 @@ class DeletionConfirmationDlg : public QDialog, private Ui::confirmDeletionDlg { static bool askForDeletionConfirmation(bool *delete_local_files) { DeletionConfirmationDlg dlg; - if(dlg.exec() == QDialog::Accepted) { + if (dlg.exec() == QDialog::Accepted) { *delete_local_files = dlg.shouldDeleteLocalFiles(); return true; } diff --git a/src/dnsupdater.cpp b/src/dnsupdater.cpp index d4b4ef284..f1d945ea5 100644 --- a/src/dnsupdater.cpp +++ b/src/dnsupdater.cpp @@ -50,7 +50,7 @@ DNSUpdater::DNSUpdater(QObject *parent) : m_ipCheckTimer.start(); // Check lastUpdate to avoid flooding - if(!m_lastIPCheckTime.isValid() || + if (!m_lastIPCheckTime.isValid() || m_lastIPCheckTime.secsTo(QDateTime::currentDateTime())*1000 > IP_CHECK_INTERVAL_MS) { checkPublicIP(); } @@ -79,19 +79,19 @@ void DNSUpdater::checkPublicIP() void DNSUpdater::ipRequestFinished(QNetworkReply *reply) { qDebug() << Q_FUNC_INFO; - if(reply->error()) { + if (reply->error()) { // Error qWarning() << Q_FUNC_INFO << "Error:" << reply->errorString(); } else { // Parse response QRegExp ipregex("Current IP Address:\\s+([^<]+)"); QString ret = reply->readAll(); - if(ipregex.indexIn(ret) >= 0) { + if (ipregex.indexIn(ret) >= 0) { QString ip_str = ipregex.cap(1); qDebug() << Q_FUNC_INFO << "Regular expression captured the following IP:" << ip_str; QHostAddress new_ip(ip_str); - if(!new_ip.isNull()) { - if(m_lastIP != new_ip) { + if (!new_ip.isNull()) { + if (m_lastIP != new_ip) { qDebug() << Q_FUNC_INFO << "The IP address changed, report the change to DynDNS..."; qDebug() << m_lastIP.toString() << "->" << new_ip.toString(); m_lastIP = new_ip; @@ -157,7 +157,7 @@ QUrl DNSUpdater::getUpdateUrl() const void DNSUpdater::ipUpdateFinished(QNetworkReply *reply) { - if(reply->error()) { + if (reply->error()) { // Error qWarning() << Q_FUNC_INFO << "Error:" << reply->errorString(); } else { @@ -174,11 +174,11 @@ void DNSUpdater::processIPUpdateReply(const QString &reply) qDebug() << Q_FUNC_INFO << reply; QString code = reply.split(" ").first(); qDebug() << Q_FUNC_INFO << "Code:" << code; - if(code == "good" || code == "nochg") { + if (code == "good" || code == "nochg") { QBtSession::instance()->addConsoleMessage(tr("Your dynamic DNS was successfuly updated."), "green"); return; } - if(code == "911" || code == "dnserr") { + if (code == "911" || code == "dnserr") { QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: The service is temporarily unavailable, it will be retried in 30 minutes."), "red"); m_lastIP.clear(); @@ -188,30 +188,30 @@ void DNSUpdater::processIPUpdateReply(const QString &reply) // Everything bellow is an error, stop updating until the user updates something m_ipCheckTimer.stop(); m_lastIP.clear(); - if(code == "nohost") { + if (code == "nohost") { QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: hostname supplied does not exist under specified account."), "red"); m_state = INVALID_CREDS; return; } - if(code == "badauth") { + if (code == "badauth") { QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: Invalid username/password."), "red"); m_state = INVALID_CREDS; return; } - if(code == "badagent") { + if (code == "badagent") { QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: qBittorrent was blacklisted by the service, please report a bug at http://bugs.qbittorrent.org."), "red"); m_state = FATAL; return; } - if(code == "!donator") { + if (code == "!donator") { QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: %1 was returned by the service, please report a bug at http://bugs.qbittorrent.org.").arg("!donator"), "red"); m_state = FATAL; return; } - if(code == "abuse") { + if (code == "abuse") { QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: Your username was blocked due to abuse."), "red"); m_state = FATAL; @@ -221,18 +221,18 @@ void DNSUpdater::processIPUpdateReply(const QString &reply) void DNSUpdater::updateCredentials() { - if(m_state == FATAL) return; + if (m_state == FATAL) return; Preferences pref; bool change = false; // Get DNS service information - if(m_service != pref.getDynDNSService()) { + if (m_service != pref.getDynDNSService()) { m_service = pref.getDynDNSService(); change = true; } - if(m_domain != pref.getDynDomainName()) { + if (m_domain != pref.getDynDomainName()) { m_domain = pref.getDynDomainName(); QRegExp domain_regex("^(?:(?!\\d|-)[a-zA-Z0-9\\-]{1,63}\\.)+[a-zA-Z]{2,}$"); - if(domain_regex.indexIn(m_domain) < 0) { + if (domain_regex.indexIn(m_domain) < 0) { QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied domain name is invalid."), "red"); m_lastIP.clear(); @@ -242,9 +242,9 @@ void DNSUpdater::updateCredentials() } change = true; } - if(m_username != pref.getDynDNSUsername()) { + if (m_username != pref.getDynDNSUsername()) { m_username = pref.getDynDNSUsername(); - if(m_username.length() < 4) { + if (m_username.length() < 4) { QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied username is too short."), "red"); m_lastIP.clear(); @@ -254,9 +254,9 @@ void DNSUpdater::updateCredentials() } change = true; } - if(m_password != pref.getDynDNSPassword()) { + if (m_password != pref.getDynDNSPassword()) { m_password = pref.getDynDNSPassword(); - if(m_password.length() < 4) { + if (m_password.length() < 4) { QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied password is too short."), "red"); m_lastIP.clear(); @@ -267,7 +267,7 @@ void DNSUpdater::updateCredentials() change = true; } - if(m_state == INVALID_CREDS && change) { + if (m_state == INVALID_CREDS && change) { m_state = OK; // Try again m_ipCheckTimer.start(); checkPublicIP(); diff --git a/src/downloadfromurldlg.h b/src/downloadfromurldlg.h index 364c49b77..370431d9a 100644 --- a/src/downloadfromurldlg.h +++ b/src/downloadfromurldlg.h @@ -50,7 +50,7 @@ class downloadFromURL : public QDialog, private Ui::downloadFromURL{ show(); // Paste clipboard if there is an URL in it QString clip_txt = qApp->clipboard()->text(); - if(clip_txt.startsWith("http://", Qt::CaseInsensitive) || clip_txt.startsWith("https://", Qt::CaseInsensitive) || clip_txt.startsWith("ftp://", Qt::CaseInsensitive) || clip_txt.startsWith("magnet:", Qt::CaseInsensitive) || clip_txt.startsWith("bc://bt/", Qt::CaseInsensitive)) { + if (clip_txt.startsWith("http://", Qt::CaseInsensitive) || clip_txt.startsWith("https://", Qt::CaseInsensitive) || clip_txt.startsWith("ftp://", Qt::CaseInsensitive) || clip_txt.startsWith("magnet:", Qt::CaseInsensitive) || clip_txt.startsWith("bc://bt/", Qt::CaseInsensitive)) { textUrls->setText(clip_txt); } } @@ -66,15 +66,15 @@ class downloadFromURL : public QDialog, private Ui::downloadFromURL{ QStringList url_list = urls.split(QString::fromUtf8("\n")); QString url; QStringList url_list_cleaned; - foreach(url, url_list){ + foreach (url, url_list){ url = url.trimmed(); - if(!url.isEmpty()){ - if(url_list_cleaned.indexOf(QRegExp(url, Qt::CaseInsensitive, QRegExp::FixedString)) < 0){ + if (!url.isEmpty()){ + if (url_list_cleaned.indexOf(QRegExp(url, Qt::CaseInsensitive, QRegExp::FixedString)) < 0){ url_list_cleaned << url; } } } - if(!url_list_cleaned.size()){ + if (!url_list_cleaned.size()){ QMessageBox::critical(0, tr("No URL entered"), tr("Please type at least one URL.")); return; } diff --git a/src/downloadthread.cpp b/src/downloadthread.cpp index ee355e3cc..ed58bf179 100644 --- a/src/downloadthread.cpp +++ b/src/downloadthread.cpp @@ -55,7 +55,7 @@ void DownloadThread::processDlFinished(QNetworkReply* reply) { QString url = reply->url().toString(); qDebug("Download finished: %s", qPrintable(url)); // Check if the request was successful - if(reply->error() != QNetworkReply::NoError) { + if (reply->error() != QNetworkReply::NoError) { // Failure qDebug("Download failure (%s), reason: %s", qPrintable(url), qPrintable(errorCodeToString(reply->error()))); emit downloadFailure(url, errorCodeToString(reply->error())); @@ -64,7 +64,7 @@ void DownloadThread::processDlFinished(QNetworkReply* reply) { } // Check if the server ask us to redirect somewhere lese const QVariant redirection = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); - if(redirection.isValid()) { + if (redirection.isValid()) { // We should redirect QUrl newUrl = redirection.toUrl(); // Resolve relative urls @@ -78,7 +78,7 @@ void DownloadThread::processDlFinished(QNetworkReply* reply) { return; } // Checking if it was redirected, restoring initial URL - if(m_redirectMapping.contains(url)) { + if (m_redirectMapping.contains(url)) { url = m_redirectMapping.take(url); } // Success @@ -87,7 +87,7 @@ void DownloadThread::processDlFinished(QNetworkReply* reply) { if (tmpfile->open()) { QString filePath = tmpfile->fileName(); qDebug("Temporary filename is: %s", qPrintable(filePath)); - if(reply->isOpen() || reply->open(QIODevice::ReadOnly)) { + if (reply->isOpen() || reply->open(QIODevice::ReadOnly)) { // TODO: Support GZIP compression tmpfile->write(reply->readAll()); tmpfile->close(); @@ -115,9 +115,9 @@ void DownloadThread::loadCookies(const QString &host_name, QString url) { QNetworkCookieJar *cookie_jar = m_networkManager.cookieJar(); QList cookies; qDebug("Loading cookies for host name: %s", qPrintable(host_name)); - foreach(const QByteArray& raw_cookie, raw_cookies) { + foreach (const QByteArray& raw_cookie, raw_cookies) { QList cookie_parts = raw_cookie.split('='); - if(cookie_parts.size() == 2) { + if (cookie_parts.size() == 2) { qDebug("Loading cookie: %s", raw_cookie.constData()); cookies << QNetworkCookie(cookie_parts.first(), cookie_parts.last()); } @@ -139,7 +139,7 @@ QNetworkReply* DownloadThread::downloadUrl(const QString &url){ #ifndef DISABLE_GUI // Load cookies QString host_name = QUrl::fromEncoded(url.toUtf8()).host(); - if(!host_name.isEmpty()) + if (!host_name.isEmpty()) loadCookies(host_name, url); #endif // Process download request @@ -151,7 +151,7 @@ QNetworkReply* DownloadThread::downloadUrl(const QString &url){ request.setRawHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5"); qDebug("Downloading %s...", request.url().toEncoded().data()); qDebug("%d cookies for this URL", m_networkManager.cookieJar()->cookiesForUrl(url).size()); - for(int i=0; icookiesForUrl(url).size(); ++i) { + for (int i=0; icookiesForUrl(url).size(); ++i) { qDebug("%s=%s", m_networkManager.cookieJar()->cookiesForUrl(url).at(i).name().data(), m_networkManager.cookieJar()->cookiesForUrl(url).at(i).value().data()); qDebug("Domain: %s, Path: %s", qPrintable(m_networkManager.cookieJar()->cookiesForUrl(url).at(i).domain()), qPrintable(m_networkManager.cookieJar()->cookiesForUrl(url).at(i).path())); } @@ -160,10 +160,10 @@ QNetworkReply* DownloadThread::downloadUrl(const QString &url){ void DownloadThread::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal) { QNetworkReply *reply = qobject_cast(sender()); - if(!reply) return; - if(bytesTotal > 0) { + if (!reply) return; + if (bytesTotal > 0) { // Total number of bytes is available - if(bytesTotal > 1048576) { + if (bytesTotal > 1048576) { // More than 1MB, this is probably not a torrent file, aborting... reply->abort(); reply->deleteLater(); @@ -171,7 +171,7 @@ void DownloadThread::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal) disconnect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(checkDownloadSize(qint64,qint64))); } } else { - if(bytesReceived > 1048576) { + if (bytesReceived > 1048576) { // More than 1MB, this is probably not a torrent file, aborting... reply->abort(); reply->deleteLater(); @@ -182,13 +182,13 @@ void DownloadThread::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal) void DownloadThread::applyProxySettings() { QNetworkProxy proxy; const Preferences pref; - if(pref.isProxyEnabled()) { + if (pref.isProxyEnabled()) { // Proxy enabled proxy.setHostName(pref.getProxyIp()); proxy.setPort(pref.getProxyPort()); // Default proxy type is HTTP, we must change if it is SOCKS5 const int proxy_type = pref.getProxyType(); - if(proxy_type == Proxy::SOCKS5 || proxy_type == Proxy::SOCKS5_PW) { + if (proxy_type == Proxy::SOCKS5 || proxy_type == Proxy::SOCKS5_PW) { qDebug() << Q_FUNC_INFO << "using SOCKS proxy"; proxy.setType(QNetworkProxy::Socks5Proxy); } else { @@ -196,7 +196,7 @@ void DownloadThread::applyProxySettings() { proxy.setType(QNetworkProxy::HttpProxy); } // Authentication? - if(pref.isProxyAuthEnabled()) { + if (pref.isProxyAuthEnabled()) { qDebug("Proxy requires authentication, authenticating"); proxy.setUser(pref.getProxyUsername()); proxy.setPassword(pref.getProxyPassword()); diff --git a/src/executionlog.cpp b/src/executionlog.cpp index 8927f27ed..734003750 100644 --- a/src/executionlog.cpp +++ b/src/executionlog.cpp @@ -50,10 +50,10 @@ ExecutionLog::ExecutionLog(QWidget *parent) : ui->tabBan->layout()->addWidget(m_banList); const QStringList log_msgs = QBtSession::instance()->getConsoleMessages(); - foreach(const QString& msg, log_msgs) + foreach (const QString& msg, log_msgs) addLogMessage(msg); const QStringList ban_msgs = QBtSession::instance()->getPeerBanMessages(); - foreach(const QString& msg, ban_msgs) + foreach (const QString& msg, ban_msgs) addBanMessage(msg); connect(QBtSession::instance(), SIGNAL(newConsoleMessage(QString)), SLOT(addLogMessage(QString))); connect(QBtSession::instance(), SIGNAL(newBanMessage(QString)), SLOT(addBanMessage(QString))); diff --git a/src/filesystemwatcher.h b/src/filesystemwatcher.h index a16ac0d9b..827f8ad8c 100644 --- a/src/filesystemwatcher.h +++ b/src/filesystemwatcher.h @@ -59,11 +59,11 @@ private: private: static bool isNetworkFileSystem(QString path) { QString file = path; - if(!file.endsWith(QDir::separator())) + if (!file.endsWith(QDir::separator())) file += QDir::separator(); file += "."; struct statfs buf; - if(!statfs(file.toLocal8Bit().constData(), &buf)) { + if (!statfs(file.toLocal8Bit().constData(), &buf)) { #ifdef Q_WS_MAC // XXX: should we make sure HAVE_STRUCT_FSSTAT_F_FSTYPENAME is defined? return (strcmp(buf.f_fstypename, "nfs") == 0 || strcmp(buf.f_fstypename, "cifs") == 0 || strcmp(buf.f_fstypename, "smbfs") == 0); @@ -124,17 +124,17 @@ public: ~FileSystemWatcher() { #ifndef Q_WS_WIN - if(watch_timer) + if (watch_timer) delete watch_timer; #endif - if(m_partialTorrentTimer) + if (m_partialTorrentTimer) delete m_partialTorrentTimer; } QStringList directories() const { QStringList dirs; #ifndef Q_WS_WIN - if(watch_timer) { + if (watch_timer) { foreach (const QDir &dir, watched_folders) dirs << dir.canonicalPath(); } @@ -149,7 +149,7 @@ public: if (!dir.exists()) return; // Check if the path points to a network file system or not - if(isNetworkFileSystem(path)) { + if (isNetworkFileSystem(path)) { // Network mode qDebug("Network folder detected: %s", qPrintable(path)); qDebug("Using file polling mode instead of inotify..."); @@ -194,7 +194,7 @@ protected slots: // Local folders scan addTorrentsFromDir(QDir(path), torrents); // Report detected torrent files - if(!torrents.empty()) { + if (!torrents.empty()) { qDebug("The following files are being reported: %s", qPrintable(torrents.join("\n"))); emit torrentsAdded(torrents); } @@ -210,7 +210,7 @@ protected slots: addTorrentsFromDir(dir, torrents); } // Report detected torrent files - if(!torrents.empty()) { + if (!torrents.empty()) { qDebug("The following files are being reported: %s", qPrintable(torrents.join("\n"))); emit torrentsAdded(torrents); } @@ -221,16 +221,16 @@ protected slots: QStringList no_longer_partial; // Check which torrents are still partial - foreach(const QString& torrent_path, m_partialTorrents.keys()) { - if(!QFile::exists(torrent_path)) { + foreach (const QString& torrent_path, m_partialTorrents.keys()) { + if (!QFile::exists(torrent_path)) { m_partialTorrents.remove(torrent_path); continue; } - if(misc::isValidTorrentFile(torrent_path)) { + if (misc::isValidTorrentFile(torrent_path)) { no_longer_partial << torrent_path; m_partialTorrents.remove(torrent_path); } else { - if(m_partialTorrents[torrent_path] >= MAX_PARTIAL_RETRIES) { + if (m_partialTorrents[torrent_path] >= MAX_PARTIAL_RETRIES) { m_partialTorrents.remove(torrent_path); QFile::rename(torrent_path, torrent_path+".invalid"); } else { @@ -240,7 +240,7 @@ protected slots: } // Stop the partial timer if necessary - if(m_partialTorrents.empty()) { + if (m_partialTorrents.empty()) { m_partialTorrentTimer->stop(); m_partialTorrentTimer->deleteLater(); qDebug("No longer any partial torrent."); @@ -249,7 +249,7 @@ protected slots: m_partialTorrentTimer->start(WATCH_INTERVAL); } // Notify of new torrents - if(!no_longer_partial.isEmpty()) + if (!no_longer_partial.isEmpty()) emit torrentsAdded(no_longer_partial); } @@ -259,7 +259,7 @@ signals: private: void startPartialTorrentTimer() { Q_ASSERT(!m_partialTorrents.isEmpty()); - if(!m_partialTorrentTimer) { + if (!m_partialTorrentTimer) { m_partialTorrentTimer = new QTimer(); connect(m_partialTorrentTimer, SIGNAL(timeout()), SLOT(processPartialTorrents())); m_partialTorrentTimer->setSingleShot(true); @@ -269,19 +269,19 @@ private: void addTorrentsFromDir(const QDir &dir, QStringList &torrents) { const QStringList files = dir.entryList(m_filters, QDir::Files, QDir::Unsorted); - foreach(const QString &file, files) { + foreach (const QString &file, files) { const QString file_abspath = dir.absoluteFilePath(file); - if(misc::isValidTorrentFile(file_abspath)) { + if (misc::isValidTorrentFile(file_abspath)) { torrents << file_abspath; } else { - if(!m_partialTorrents.contains(file_abspath)) { + if (!m_partialTorrents.contains(file_abspath)) { qDebug("Partial torrent detected at: %s", qPrintable(file_abspath)); qDebug("Delay the file's processing..."); m_partialTorrents.insert(file_abspath, 0); } } } - if(!m_partialTorrents.empty()) + if (!m_partialTorrents.empty()) startPartialTorrentTimer(); } diff --git a/src/geoip/geoipmanager.cpp b/src/geoip/geoipmanager.cpp index 148b504f4..d934e66de 100644 --- a/src/geoip/geoipmanager.cpp +++ b/src/geoip/geoipmanager.cpp @@ -70,14 +70,14 @@ using namespace libtorrent; QString GeoIPManager::geoipFolder(bool embedded) { #ifdef WITH_GEOIP_EMBEDDED - if(embedded) + if (embedded) return ":/geoip/"; return misc::QDesktopServicesDataLocation()+"geoip"+QDir::separator(); #else Q_UNUSED(embedded); - if(QFile::exists("/usr/local/share/GeoIP/GeoIP.dat")) + if (QFile::exists("/usr/local/share/GeoIP/GeoIP.dat")) return "/usr/local/share/GeoIP/"; - if(QFile::exists("/var/lib/GeoIP/GeoIP.dat")) + if (QFile::exists("/var/lib/GeoIP/GeoIP.dat")) return "/var/lib/GeoIP/"; return "/usr/share/GeoIP/"; #endif @@ -89,22 +89,22 @@ QString GeoIPManager::geoipDBpath(bool embedded) { #ifdef WITH_GEOIP_EMBEDDED void GeoIPManager::exportEmbeddedDb() { - if(!QFile::exists(geoipDBpath(false)) || QFile(geoipDBpath(false)).size() != QFile(geoipDBpath(true)).size()) { // Export is required + if (!QFile::exists(geoipDBpath(false)) || QFile(geoipDBpath(false)).size() != QFile(geoipDBpath(true)).size()) { // Export is required qDebug("A local Geoip database update is required, proceeding..."); // Create geoip folder is necessary QDir gfolder(geoipFolder(false)); - if(!gfolder.exists()) { - if(!gfolder.mkpath(geoipFolder(false))) { + if (!gfolder.exists()) { + if (!gfolder.mkpath(geoipFolder(false))) { std::cerr << "Failed to create geoip folder at " << qPrintable(geoipFolder(false)) << std::endl; return; } } // Remove destination files - if(QFile::exists(geoipDBpath(false))) + if (QFile::exists(geoipDBpath(false))) QFile::remove(geoipDBpath(false)); // Copy from executable to hard disk qDebug("%s -> %s", qPrintable(geoipDBpath(true)), qPrintable(geoipDBpath(false))); - if(!QFile::copy(geoipDBpath(true), geoipDBpath(false))) { + if (!QFile::copy(geoipDBpath(true), geoipDBpath(false))) { std::cerr << "ERROR: Failed to copy geoip.dat from executable to hard disk" << std::endl; } qDebug("Local Geoip database was updated"); @@ -116,7 +116,7 @@ void GeoIPManager::loadDatabase(session *s) { #ifdef WITH_GEOIP_EMBEDDED exportEmbeddedDb(); #endif - if(QFile::exists(geoipDBpath(false))) { + if (QFile::exists(geoipDBpath(false))) { qDebug("Loading GeoIP database from %s...", qPrintable(geoipDBpath(false))); s->load_country_db(geoipDBpath(false).toLocal8Bit().constData()); } else { @@ -183,9 +183,9 @@ const char * country_name[253] = "Saint Barthelemy","Saint Martin"}; QString GeoIPManager::CountryISOCodeToName(const char* iso) { - if(iso[0] == 0) return "N/A"; - for(uint i = 0; i < num_countries; ++i) { - if(iso[0] == country_code[i][0] && iso[1] == country_code[i][1]) { + if (iso[0] == 0) return "N/A"; + for (uint i = 0; i < num_countries; ++i) { + if (iso[0] == country_code[i][0] && iso[1] == country_code[i][1]) { return QLatin1String(country_name[i]); } } @@ -195,7 +195,7 @@ QString GeoIPManager::CountryISOCodeToName(const char* iso) { // http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm QIcon GeoIPManager::CountryISOCodeToIcon(const char* iso) { - if(iso[0] == 0 || iso[0] == '!') return QIcon(); + if (iso[0] == 0 || iso[0] == '!') return QIcon(); const QString isoStr = QString(QByteArray(iso, 2)).toLower(); return QIcon(":/Icons/flags/"+isoStr+".png"); } diff --git a/src/headlessloader.h b/src/headlessloader.h index f66a186ad..c84c0eb72 100644 --- a/src/headlessloader.h +++ b/src/headlessloader.h @@ -55,7 +55,7 @@ public: std::cout << qPrintable(tr("To control qBittorrent, access the Web UI at http://localhost:%1").arg(QString::number(pref.getWebUiPort()))) << std::endl; std::cout << qPrintable(tr("The Web UI administrator user name is: %1").arg(pref.getWebUiUsername())) << std::endl; qDebug() << "Password:" << pref.getWebUiPassword(); - if(pref.getWebUiPassword() == "32fe0bd2bb001911bb8bcfe23fc92b63") { + if (pref.getWebUiPassword() == "32fe0bd2bb001911bb8bcfe23fc92b63") { std::cout << qPrintable(tr("The Web UI administrator password is still the default one: %1").arg("adminadmin")) << std::endl; std::cout << qPrintable(tr("This is a security risk, please consider changing your password from program preferences.")) << std::endl; } @@ -85,16 +85,16 @@ public slots: // the right addTorrent function, considering // the parameter type. void processParams(const QStringList& params) { - foreach(QString param, params) { + foreach (QString param, params) { param = param.trimmed(); - if(param.startsWith(QString::fromUtf8("http://"), Qt::CaseInsensitive) || param.startsWith(QString::fromUtf8("ftp://"), Qt::CaseInsensitive) || param.startsWith(QString::fromUtf8("https://"), Qt::CaseInsensitive)) { + if (param.startsWith(QString::fromUtf8("http://"), Qt::CaseInsensitive) || param.startsWith(QString::fromUtf8("ftp://"), Qt::CaseInsensitive) || param.startsWith(QString::fromUtf8("https://"), Qt::CaseInsensitive)) { QBtSession::instance()->downloadFromUrl(param); }else{ - if(param.startsWith("bc://bt/", Qt::CaseInsensitive)) { + if (param.startsWith("bc://bt/", Qt::CaseInsensitive)) { qDebug("Converting bc link to magnet link"); param = misc::bcLinkToMagnet(param); } - if(param.startsWith("magnet:", Qt::CaseInsensitive)) { + if (param.startsWith("magnet:", Qt::CaseInsensitive)) { QBtSession::instance()->addMagnetUri(param); } else { QBtSession::instance()->addTorrent(param); diff --git a/src/hidabletabwidget.h b/src/hidabletabwidget.h index 0f941ec65..9d87e850e 100644 --- a/src/hidabletabwidget.h +++ b/src/hidabletabwidget.h @@ -44,7 +44,7 @@ public: protected: void tabInserted(int index) { QTabWidget::tabInserted(index); - if(count() == 1) { + if (count() == 1) { showTabBar(false); } else { showTabBar(true); @@ -53,7 +53,7 @@ protected: void tabRemoved(int index) { QTabWidget::tabInserted(index); - if(count() == 1) { + if (count() == 1) { showTabBar(false); } else { showTabBar(true); diff --git a/src/iconprovider.cpp b/src/iconprovider.cpp index 3954c843a..08a536470 100644 --- a/src/iconprovider.cpp +++ b/src/iconprovider.cpp @@ -42,14 +42,14 @@ IconProvider::IconProvider() IconProvider * IconProvider::instance() { - if(!m_instance) + if (!m_instance) m_instance = new IconProvider; return m_instance; } void IconProvider::drop() { - if(m_instance) { + if (m_instance) { delete m_instance; m_instance = 0; } @@ -58,7 +58,7 @@ void IconProvider::drop() QIcon IconProvider::getIcon(const QString &iconId) { #if defined(Q_WS_X11) && (QT_VERSION >= QT_VERSION_CHECK(4,6,0)) - if(m_useSystemTheme) { + if (m_useSystemTheme) { QIcon icon = QIcon::fromTheme(iconId, QIcon(":/Icons/oxygen/"+iconId+".png")); icon = generateDifferentSizes(icon); return icon; @@ -84,14 +84,14 @@ QIcon IconProvider::generateDifferentSizes(const QIcon &icon) required_sizes << QSize(16, 16) << QSize(24, 24); QList modes; modes << QIcon::Normal << QIcon::Active << QIcon::Selected << QIcon::Disabled; - foreach(const QSize& size, required_sizes) { - foreach(QIcon::Mode mode, modes) { + foreach (const QSize& size, required_sizes) { + foreach (QIcon::Mode mode, modes) { QPixmap pixoff = icon.pixmap(size, mode, QIcon::Off); - if(pixoff.height() > size.height()) + if (pixoff.height() > size.height()) pixoff = pixoff.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation); new_icon.addPixmap(pixoff, mode, QIcon::Off); QPixmap pixon = icon.pixmap(size, mode, QIcon::On); - if(pixon.height() > size.height()) + if (pixon.height() > size.height()) pixon = pixoff.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation); new_icon.addPixmap(pixon, mode, QIcon::On); } @@ -103,11 +103,11 @@ QIcon IconProvider::generateDifferentSizes(const QIcon &icon) QString IconProvider::getIconPath(const QString &iconId) { #if defined(Q_WS_X11) && (QT_VERSION >= QT_VERSION_CHECK(4,6,0)) - if(m_useSystemTheme) { + if (m_useSystemTheme) { QString path = QDir::temp().absoluteFilePath(iconId+".png"); - if(!QFile::exists(path)) { + if (!QFile::exists(path)) { const QIcon icon = QIcon::fromTheme(iconId); - if(icon.isNull()) return ":/Icons/oxygen/"+iconId+".png"; + if (icon.isNull()) return ":/Icons/oxygen/"+iconId+".png"; QPixmap px = icon.pixmap(32); px.save(path); } diff --git a/src/loglistwidget.cpp b/src/loglistwidget.cpp index 084b18bb5..62b904c42 100644 --- a/src/loglistwidget.cpp +++ b/src/loglistwidget.cpp @@ -73,7 +73,7 @@ void LogListWidget::appendLine(const QString &line) setItemWidget(item, lbl); const int nbLines = count(); // Limit log size - if(nbLines > m_maxLines) + if (nbLines > m_maxLines) delete takeItem(nbLines - 1); } @@ -82,7 +82,7 @@ void LogListWidget::copySelection() static QRegExp html_tag("<[^>]+>"); QList items = selectedItems(); QStringList strings; - foreach(QListWidgetItem* it, items) + foreach (QListWidgetItem* it, items) strings << static_cast(itemWidget(it))->text().replace(html_tag, ""); QApplication::clipboard()->setText(strings.join("\n")); diff --git a/src/main.cpp b/src/main.cpp index 46634f514..a45998b2e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -87,14 +87,14 @@ class LegalNotice: public QObject { public: static bool userAgreesWithNotice() { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); - if(settings.value(QString::fromUtf8("LegalNotice/Accepted"), false).toBool()) // Already accepted once + if (settings.value(QString::fromUtf8("LegalNotice/Accepted"), false).toBool()) // Already accepted once return true; #ifdef DISABLE_GUI std::cout << std::endl << "*** " << qPrintable(tr("Legal Notice")) << " ***" << std::endl; std::cout << qPrintable(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.")) << std::endl << std::endl; std::cout << qPrintable(tr("Press %1 key to accept and continue...").arg("'y'")) << std::endl; char ret = getchar(); // Read pressed key - if(ret == 'y' || ret == 'Y') { + if (ret == 'y' || ret == 'Y') { // Save the answer settings.setValue(QString::fromUtf8("LegalNotice/Accepted"), true); return true; @@ -109,7 +109,7 @@ public: msgBox.show(); // Need to be shown or to moveToCenter does not work msgBox.move(misc::screenCenter(&msgBox)); msgBox.exec(); - if(msgBox.clickedButton() == agree_button) { + if (msgBox.clickedButton() == agree_button) { // Save the answer settings.setValue(QString::fromUtf8("LegalNotice/Accepted"), true); return true; @@ -164,18 +164,18 @@ int main(int argc, char *argv[]){ #endif // Check if qBittorrent is already running for this user - if(app.isRunning()) { + if (app.isRunning()) { qDebug("qBittorrent is already running for this user."); //Pass program parameters if any QString message; for (int a = 1; a < argc; ++a) { QString p = QString::fromLocal8Bit(argv[a]); - if(p.startsWith("--")) continue; + if (p.startsWith("--")) continue; message += p; if (a < argc-1) message += "|"; } - if(!message.isEmpty()) { + if (!message.isEmpty()) { qDebug("Passing program parameters to running instance..."); qDebug("Message: %s", qPrintable(message)); app.sendMessage(message); @@ -192,11 +192,11 @@ int main(int argc, char *argv[]){ QString locale = pref.getLocale(); QTranslator qtTranslator; QTranslator translator; - if(locale.isEmpty()){ + if (locale.isEmpty()){ locale = QLocale::system().name(); pref.setLocale(locale); } - if(qtTranslator.load( + if (qtTranslator.load( QString::fromUtf8("qt_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath) )){ qDebug("Qt %s locale recognized, using translation.", qPrintable(locale)); @@ -204,14 +204,14 @@ int main(int argc, char *argv[]){ qDebug("Qt %s locale unrecognized, using default (en_GB).", qPrintable(locale)); } app.installTranslator(&qtTranslator); - if(translator.load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){ + if (translator.load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){ qDebug("%s locale recognized, using translation.", qPrintable(locale)); }else{ qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale)); } app.installTranslator(&translator); #ifndef DISABLE_GUI - if(locale.startsWith("ar")) { + if (locale.startsWith("ar")) { qDebug("Right to Left mode"); app.setLayoutDirection(Qt::RightToLeft); } else { @@ -221,28 +221,28 @@ int main(int argc, char *argv[]){ app.setApplicationName(QString::fromUtf8("qBittorrent")); // Check for executable parameters - if(argc > 1){ - if(QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--version")){ + if (argc > 1){ + if (QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--version")){ std::cout << "qBittorrent " << VERSION << '\n'; return 0; } - if(QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--help")){ + if (QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--help")){ UsageDisplay::displayUsage(argv[0]); return 0; } - for(int i=1; i 0 && new_port <= 65535) { + if (ok && new_port > 0 && new_port <= 65535) { Preferences().setWebUiPort(new_port); } } @@ -254,11 +254,11 @@ int main(int argc, char *argv[]){ } #ifndef DISABLE_GUI - if(pref.isSlashScreenDisabled()) { + if (pref.isSlashScreenDisabled()) { no_splash = true; } QSplashScreen *splash = 0; - if(!no_splash) { + if (!no_splash) { QPixmap splash_img(":/Icons/skin/splash.png"); QPainter painter(&splash_img); QString version = VERSION; @@ -280,7 +280,7 @@ int main(int argc, char *argv[]){ app.setStyleSheet("QStatusBar::item { border-width: 0; }"); #endif - if(!LegalNotice::userAgreesWithNotice()) { + if (!LegalNotice::userAgreesWithNotice()) { return 0; } #ifndef DISABLE_GUI @@ -297,7 +297,7 @@ int main(int argc, char *argv[]){ // Remove first argument (program name) torrentCmdLine.removeFirst(); #ifndef QT_NO_DEBUG_OUTPUT - foreach(const QString &argument, torrentCmdLine) { + foreach (const QString &argument, torrentCmdLine) { qDebug() << "Command line argument:" << argument; } #endif diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 26e263f40..6c40bc8f5 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -247,14 +247,14 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo #endif actionAutoExit_qBittorrent->setChecked(pref.shutdownqBTWhenDownloadsComplete()); - if(!autoShutdownGroup->checkedAction()) + if (!autoShutdownGroup->checkedAction()) actionAutoShutdown_Disabled->setChecked(true); // Load Window state and sizes readSettings(); - if(!ui_locked) { - if(pref.startMinimized() && systrayIcon) + if (!ui_locked) { + if (pref.startMinimized() && systrayIcon) showMinimized(); else { show(); @@ -285,8 +285,8 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo qDebug("GUI Built"); #ifdef Q_WS_WIN - if(!pref.neverCheckFileAssoc() && (!Preferences::isTorrentFileAssocSet() || !Preferences::isMagnetLinkAssocSet())) { - if(QMessageBox::question(0, tr("Torrent file association"), + if (!pref.neverCheckFileAssoc() && (!Preferences::isTorrentFileAssocSet() || !Preferences::isMagnetLinkAssocSet())) { + if (QMessageBox::question(0, tr("Torrent file association"), tr("qBittorrent is not the default application to open torrent files or Magnet links.\nDo you want to associate qBittorrent to torrent files and Magnet links?"), QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { Preferences::setTorrentFileAssoc(true); @@ -301,7 +301,7 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo #endif #if defined(Q_WS_WIN) || defined(Q_WS_MAC) // Check for update - if(pref.isUpdateCheckEnabled()) { + if (pref.isUpdateCheckEnabled()) { ProgramUpdater *updater = new ProgramUpdater(this); connect(updater, SIGNAL(updateCheckFinished(bool, QString)), SLOT(handleUpdateCheckFinished(bool, QString))); updater->checkForUpdates(); @@ -337,37 +337,37 @@ MainWindow::~MainWindow() { #endif disconnect(tabs, SIGNAL(currentChanged(int)), this, SLOT(tab_changed(int))); // Delete other GUI objects - if(executable_watcher) + if (executable_watcher) delete executable_watcher; delete status_bar; delete search_filter; delete transferList; delete guiUpdater; - if(createTorrentDlg) + if (createTorrentDlg) delete createTorrentDlg; - if(m_executionLog) + if (m_executionLog) delete m_executionLog; - if(aboutDlg) + if (aboutDlg) delete aboutDlg; - if(options) + if (options) delete options; - if(downloadFromURLDialog) + if (downloadFromURLDialog) delete downloadFromURLDialog; - if(rssWidget) + if (rssWidget) delete rssWidget; - if(searchEngine) + if (searchEngine) delete searchEngine; delete transferListFilters; delete properties; delete hSplitter; delete vSplitter; - if(systrayCreator) { + if (systrayCreator) { delete systrayCreator; } - if(systrayIcon) { + if (systrayIcon) { delete systrayIcon; } - if(myTrayIconMenu) { + if (myTrayIconMenu) { delete myTrayIconMenu; } delete tabs; @@ -386,16 +386,16 @@ MainWindow::~MainWindow() { void MainWindow::defineUILockPassword() { QString old_pass_md5 = Preferences().getUILockPasswordMD5(); - if(old_pass_md5.isNull()) old_pass_md5 = ""; + if (old_pass_md5.isNull()) old_pass_md5 = ""; bool ok = false; QString new_clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, old_pass_md5, &ok); - if(ok) { + if (ok) { new_clear_password = new_clear_password.trimmed(); - if(new_clear_password.size() < 3) { + if (new_clear_password.size() < 3) { QMessageBox::warning(this, tr("Invalid password"), tr("The password should contain at least 3 characters")); return; } - if(new_clear_password != old_pass_md5) { + if (new_clear_password != old_pass_md5) { Preferences().setUILockPassword(new_clear_password); } QMessageBox::information(this, tr("Password update"), tr("The UI lock password has been successfully updated")); @@ -405,11 +405,11 @@ void MainWindow::defineUILockPassword() { void MainWindow::on_actionLock_qBittorrent_triggered() { Preferences pref; // Check if there is a password - if(pref.getUILockPasswordMD5().isEmpty()) { + if (pref.getUILockPasswordMD5().isEmpty()) { // Ask for a password bool ok = false; QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok); - if(!ok) return; + if (!ok) return; pref.setUILockPassword(clear_password); } // Lock the interface @@ -420,29 +420,29 @@ void MainWindow::on_actionLock_qBittorrent_triggered() { } void MainWindow::displayRSSTab(bool enable) { - if(enable) { + if (enable) { // RSS tab - if(!rssWidget) { + if (!rssWidget) { rssWidget = new RSSImp(tabs); int index_tab = tabs->addTab(rssWidget, tr("RSS")); tabs->setTabIcon(index_tab, IconProvider::instance()->getIcon("application-rss+xml")); } } else { - if(rssWidget) { + if (rssWidget) { delete rssWidget; } } } void MainWindow::displaySearchTab(bool enable) { - if(enable) { + if (enable) { // RSS tab - if(!searchEngine) { + if (!searchEngine) { searchEngine = new SearchEngine(this); tabs->insertTab(1, searchEngine, IconProvider::instance()->getIcon("edit-find"), tr("Search")); } } else { - if(searchEngine) { + if (searchEngine) { delete searchEngine; } } @@ -468,12 +468,12 @@ void MainWindow::tab_changed(int new_tab) { Q_UNUSED(new_tab); // We cannot rely on the index new_tab // because the tab order is undetermined now - if(tabs->currentWidget() == vSplitter) { + if (tabs->currentWidget() == vSplitter) { qDebug("Changed tab to transfer list, refreshing the list"); properties->loadDynamicData(); return; } - if(tabs->currentWidget() == searchEngine) { + if (tabs->currentWidget() == searchEngine) { qDebug("Changed tab to search engine, giving focus to search input"); searchEngine->giveFocusToSearchInput(); } @@ -492,12 +492,12 @@ void MainWindow::writeSettings() { void MainWindow::readSettings() { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); settings.beginGroup(QString::fromUtf8("MainWindow")); - if(settings.contains("geometry")) { - if(restoreGeometry(settings.value("geometry").toByteArray())) + if (settings.contains("geometry")) { + if (restoreGeometry(settings.value("geometry").toByteArray())) m_posInitialized = true; } const QByteArray splitterState = settings.value("vsplitterState").toByteArray(); - if(splitterState.isEmpty()) { + if (splitterState.isEmpty()) { // Default sizes vSplitter->setSizes(QList() << 120 << vSplitter->width()-120); } else { @@ -507,9 +507,9 @@ void MainWindow::readSettings() { } void MainWindow::balloonClicked() { - if(isHidden()) { + if (isHidden()) { show(); - if(isMinimized()) { + if (isMinimized()) { showNormal(); } raise(); @@ -519,13 +519,13 @@ void MainWindow::balloonClicked() { // called when a torrent has finished void MainWindow::finishedTorrent(const QTorrentHandle& h) const { - if(!TorrentPersistentData::isSeed(h.hash())) + if (!TorrentPersistentData::isSeed(h.hash())) showNotificationBaloon(tr("Download completion"), tr("%1 has finished downloading.", "e.g: xxx.avi has finished downloading.").arg(h.name())); } // Notification when disk is full void MainWindow::fullDiskError(const QTorrentHandle& h, QString msg) const { - if(!h.is_valid()) return; + if (!h.is_valid()) return; showNotificationBaloon(tr("I/O Error", "i.e: Input/Output Error"), tr("An I/O error occured for torrent %1.\n Reason: %2", "e.g: An error occured for torrent xxx.avi.\n Reason: disk is full.").arg(h.name()).arg(msg)); } @@ -566,12 +566,12 @@ void MainWindow::displayTransferTab() const { } void MainWindow::displaySearchTab() const { - if(searchEngine) + if (searchEngine) tabs->setCurrentWidget(searchEngine); } void MainWindow::displayRSSTab() const { - if(rssWidget) + if (rssWidget) tabs->setCurrentWidget(rssWidget); } @@ -579,7 +579,7 @@ void MainWindow::displayRSSTab() const { void MainWindow::askRecursiveTorrentDownloadConfirmation(const QTorrentHandle &h) { Preferences pref; - if(pref.recursiveDownloadDisabled()) return; + if (pref.recursiveDownloadDisabled()) return; // Get Torrent name QString torrent_name; try { @@ -592,12 +592,12 @@ void MainWindow::askRecursiveTorrentDownloadConfirmation(const QTorrentHandle &h /*QPushButton *no = */confirmBox.addButton(tr("No"), QMessageBox::NoRole); QPushButton *never = confirmBox.addButton(tr("Never"), QMessageBox::NoRole); confirmBox.exec(); - if(confirmBox.clickedButton() == 0) return; - if(confirmBox.clickedButton() == yes) { + if (confirmBox.clickedButton() == 0) return; + if (confirmBox.clickedButton() == yes) { QBtSession::instance()->recursiveTorrentDownload(h); return; } - if(confirmBox.clickedButton() == never) { + if (confirmBox.clickedButton() == never) { pref.disableRecursiveDownload(); } } @@ -616,10 +616,10 @@ void MainWindow::on_actionSet_global_upload_limit_triggered() { int cur_limit = QBtSession::instance()->getSession()->upload_rate_limit(); #endif const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), cur_limit); - if(ok) { + if (ok) { qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.); QBtSession::instance()->setUploadRateLimit(new_limit); - if(new_limit <= 0) + if (new_limit <= 0) Preferences().setGlobalUploadLimit(-1); else Preferences().setGlobalUploadLimit(new_limit/1024.); @@ -635,10 +635,10 @@ void MainWindow::on_actionSet_global_download_limit_triggered() { int cur_limit = QBtSession::instance()->getSession()->download_rate_limit(); #endif const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), cur_limit); - if(ok) { + if (ok) { qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.); QBtSession::instance()->setDownloadRateLimit(new_limit); - if(new_limit <= 0) + if (new_limit <= 0) Preferences().setGlobalDownloadLimit(-1); else Preferences().setGlobalDownloadLimit(new_limit/1024.); @@ -653,9 +653,9 @@ void MainWindow::on_actionExit_triggered() { } QWidget* MainWindow::getCurrentTabWidget() const { - if(isMinimized() || !isVisible()) + if (isMinimized() || !isVisible()) return 0; - if(tabs->currentIndex() == 0) + if (tabs->currentIndex() == 0) return transferList; return tabs->currentWidget(); } @@ -667,13 +667,13 @@ void MainWindow::setTabText(int index, QString text) const { bool MainWindow::unlockUI() { bool ok = false; QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok); - if(!ok) return false; + if (!ok) return false; Preferences pref; QString real_pass_md5 = pref.getUILockPasswordMD5(); QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(clear_password.toLocal8Bit()); QString password_md5 = md5.result().toHex(); - if(real_pass_md5 == password_md5) { + if (real_pass_md5 == password_md5) { ui_locked = false; pref.setUILocked(false); myTrayIconMenu->setEnabled(true); @@ -693,16 +693,16 @@ void MainWindow::notifyOfUpdate(QString) { // Toggle Main window visibility void MainWindow::toggleVisibility(QSystemTrayIcon::ActivationReason e) { - if(e == QSystemTrayIcon::Trigger || e == QSystemTrayIcon::DoubleClick) { - if(isHidden()) { - if(ui_locked) { + if (e == QSystemTrayIcon::Trigger || e == QSystemTrayIcon::DoubleClick) { + if (isHidden()) { + if (ui_locked) { // Ask for UI lock password - if(!unlockUI()) + if (!unlockUI()) return; } show(); - if(isMinimized()) { - if(isMaximized()) { + if (isMinimized()) { + if (isMaximized()) { showMaximized(); }else{ showNormal(); @@ -720,7 +720,7 @@ void MainWindow::toggleVisibility(QSystemTrayIcon::ActivationReason e) { // Display About Dialog void MainWindow::on_actionAbout_triggered() { //About dialog - if(aboutDlg) { + if (aboutDlg) { aboutDlg->setFocus(); } else { aboutDlg = new about(this); @@ -730,14 +730,14 @@ void MainWindow::on_actionAbout_triggered() { void MainWindow::showEvent(QShowEvent *e) { qDebug("** Show Event **"); - if(getCurrentTabWidget() == transferList) { + if (getCurrentTabWidget() == transferList) { properties->loadDynamicData(); } e->accept(); // Make sure the window is initially centered - if(!m_posInitialized) { + if (!m_posInitialized) { move(misc::screenCenter(this)); m_posInitialized = true; } @@ -747,14 +747,14 @@ void MainWindow::showEvent(QShowEvent *e) { void MainWindow::closeEvent(QCloseEvent *e) { Preferences pref; const bool goToSystrayOnExit = pref.closeToTray(); - if(!force_exit && systrayIcon && goToSystrayOnExit && !this->isHidden()) { + if (!force_exit && systrayIcon && goToSystrayOnExit && !this->isHidden()) { hide(); e->accept(); return; } - if(pref.confirmOnExit() && QBtSession::instance()->hasActiveTorrents()) { - if(e->spontaneous() || force_exit) { - if(!isVisible()) + if (pref.confirmOnExit() && QBtSession::instance()->hasActiveTorrents()) { + if (e->spontaneous() || force_exit) { + if (!isVisible()) show(); QMessageBox confirmBox(QMessageBox::Question, tr("Exiting qBittorrent"), tr("Some files are currently transferring.\nAre you sure you want to quit qBittorrent?"), @@ -764,20 +764,20 @@ void MainWindow::closeEvent(QCloseEvent *e) { QPushButton *alwaysBtn = confirmBox.addButton(tr("Always"), QMessageBox::YesRole); confirmBox.setDefaultButton(yesBtn); confirmBox.exec(); - if(!confirmBox.clickedButton() || confirmBox.clickedButton() == noBtn) { + if (!confirmBox.clickedButton() || confirmBox.clickedButton() == noBtn) { // Cancel exit e->ignore(); force_exit = false; return; } - if(confirmBox.clickedButton() == alwaysBtn) { + if (confirmBox.clickedButton() == alwaysBtn) { // Remember choice Preferences().setConfirmOnExit(false); } } } hide(); - if(systrayIcon) { + if (systrayIcon) { // Hide tray icon systrayIcon->hide(); } @@ -790,7 +790,7 @@ void MainWindow::closeEvent(QCloseEvent *e) { // Display window to create a torrent void MainWindow::on_actionCreate_torrent_triggered() { - if(createTorrentDlg) { + if (createTorrentDlg) { createTorrentDlg->setFocus(); } else { createTorrentDlg = new TorrentCreatorDlg(this); @@ -803,20 +803,20 @@ bool MainWindow::event(QEvent * e) { case QEvent::WindowStateChange: { qDebug("Window change event"); //Now check to see if the window is minimised - if(isMinimized()) { + if (isMinimized()) { qDebug("minimisation"); - if(systrayIcon && Preferences().minimizeToTray()) { + if (systrayIcon && Preferences().minimizeToTray()) { qDebug("Has active window: %d", (int)(qApp->activeWindow() != 0)); // Check if there is a modal window bool has_modal_window = false; foreach (QWidget *widget, QApplication::allWidgets()) { - if(widget->isModal()) { + if (widget->isModal()) { has_modal_window = true; break; } } // Iconify if there is no modal window - if(!has_modal_window) { + if (!has_modal_window) { qDebug("Minimize to Tray enabled, hiding!"); e->accept(); QTimer::singleShot(0, this, SLOT(hide())); @@ -847,11 +847,11 @@ bool MainWindow::event(QEvent * e) { void MainWindow::dropEvent(QDropEvent *event) { event->acceptProposedAction(); QStringList files; - if(event->mimeData()->hasUrls()) { + if (event->mimeData()->hasUrls()) { const QList urls = event->mimeData()->urls(); - foreach(const QUrl &url, urls) { - if(!url.isEmpty()) { - if(url.scheme().compare("file", Qt::CaseInsensitive) == 0) + foreach (const QUrl &url, urls) { + if (!url.isEmpty()) { + if (url.scheme().compare("file", Qt::CaseInsensitive) == 0) files << url.toLocalFile(); else files << url.toString(); @@ -863,19 +863,19 @@ void MainWindow::dropEvent(QDropEvent *event) { // Add file to download list Preferences pref; const bool useTorrentAdditionDialog = pref.useAdditionDialog(); - foreach(QString file, files) { + foreach (QString file, files) { qDebug("Dropped file %s on download list", qPrintable(file)); - if(misc::isUrl(file)) { + if (misc::isUrl(file)) { QBtSession::instance()->downloadFromUrl(file); continue; } // Bitcomet or Magnet link - if(file.startsWith("bc://bt/", Qt::CaseInsensitive)) { + if (file.startsWith("bc://bt/", Qt::CaseInsensitive)) { qDebug("Converting bc link to magnet link"); file = misc::bcLinkToMagnet(file); } - if(file.startsWith("magnet:", Qt::CaseInsensitive)) { - if(useTorrentAdditionDialog) { + if (file.startsWith("magnet:", Qt::CaseInsensitive)) { + if (useTorrentAdditionDialog) { torrentAdditionDialog *dialog = new torrentAdditionDialog(this); dialog->showLoadMagnetURI(file); } else { @@ -884,9 +884,9 @@ void MainWindow::dropEvent(QDropEvent *event) { continue; } // Local file - if(useTorrentAdditionDialog) { + if (useTorrentAdditionDialog) { torrentAdditionDialog *dialog = new torrentAdditionDialog(this); - if(file.startsWith("file:", Qt::CaseInsensitive)) + if (file.startsWith("file:", Qt::CaseInsensitive)) file = QUrl(file).toLocalFile(); dialog->showLoad(file); }else{ @@ -897,7 +897,7 @@ void MainWindow::dropEvent(QDropEvent *event) { // Decode if we accept drag 'n drop or not void MainWindow::dragEnterEvent(QDragEnterEvent *event) { - foreach(const QString &mime, event->mimeData()->formats()){ + foreach (const QString &mime, event->mimeData()->formats()){ qDebug("mimeData: %s", mime.toLocal8Bit().data()); } if (event->mimeData()->hasFormat(QString::fromUtf8("text/plain")) || event->mimeData()->hasFormat(QString::fromUtf8("text/uri-list"))) { @@ -921,11 +921,11 @@ void MainWindow::on_actionOpen_triggered() { const QStringList pathsList = QFileDialog::getOpenFileNames(0, tr("Open Torrent Files"), settings.value(QString::fromUtf8("MainWindowLastDir"), QDir::homePath()).toString(), tr("Torrent Files")+QString::fromUtf8(" (*.torrent)")); - if(!pathsList.empty()) { + if (!pathsList.empty()) { const bool useTorrentAdditionDialog = pref.useAdditionDialog(); const uint listSize = pathsList.size(); - for(uint i=0; ishowLoad(pathsList.at(i)); }else{ @@ -950,24 +950,24 @@ void MainWindow::processParams(const QString& params_str) { void MainWindow::processParams(const QStringList& params) { Preferences pref; const bool useTorrentAdditionDialog = pref.useAdditionDialog(); - foreach(QString param, params) { + foreach (QString param, params) { param = param.trimmed(); - if(misc::isUrl(param)) { + if (misc::isUrl(param)) { QBtSession::instance()->downloadFromUrl(param); }else{ - if(param.startsWith("bc://bt/", Qt::CaseInsensitive)) { + if (param.startsWith("bc://bt/", Qt::CaseInsensitive)) { qDebug("Converting bc link to magnet link"); param = misc::bcLinkToMagnet(param); } - if(param.startsWith("magnet:", Qt::CaseInsensitive)) { - if(useTorrentAdditionDialog) { + if (param.startsWith("magnet:", Qt::CaseInsensitive)) { + if (useTorrentAdditionDialog) { torrentAdditionDialog *dialog = new torrentAdditionDialog(this); dialog->showLoadMagnetURI(param); } else { QBtSession::instance()->addMagnetUri(param); } } else { - if(useTorrentAdditionDialog) { + if (useTorrentAdditionDialog) { torrentAdditionDialog *dialog = new torrentAdditionDialog(this); dialog->showLoad(param); }else{ @@ -985,7 +985,7 @@ void MainWindow::addTorrent(QString path) { void MainWindow::processDownloadedFiles(QString path, QString url) { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool(); - if(useTorrentAdditionDialog) { + if (useTorrentAdditionDialog) { torrentAdditionDialog *dialog = new torrentAdditionDialog(this); dialog->showLoad(path, url); }else{ @@ -1003,11 +1003,11 @@ void MainWindow::loadPreferences(bool configure_session) { const Preferences pref; const bool newSystrayIntegration = pref.systrayIntegration(); actionLock_qBittorrent->setEnabled(newSystrayIntegration); - if(newSystrayIntegration != (systrayIcon!=0)) { - if(newSystrayIntegration) { + if (newSystrayIntegration != (systrayIcon!=0)) { + if (newSystrayIntegration) { // create the trayicon - if(!QSystemTrayIcon::isSystemTrayAvailable()) { - if(!configure_session) { // Program startup + if (!QSystemTrayIcon::isSystemTrayAvailable()) { + if (!configure_session) { // Program startup systrayCreator = new QTimer(this); connect(systrayCreator, SIGNAL(timeout()), this, SLOT(createSystrayDelayed())); systrayCreator->setSingleShot(true); @@ -1026,11 +1026,11 @@ void MainWindow::loadPreferences(bool configure_session) { } } // Reload systray icon - if(newSystrayIntegration && systrayIcon) { + if (newSystrayIntegration && systrayIcon) { systrayIcon->setIcon(getSystrayIcon()); } // General - if(pref.isToolbarDisplayed()) { + if (pref.isToolbarDisplayed()) { toolBar->setVisible(true); } else { // Clear search filter before hiding the top toolbar @@ -1038,7 +1038,7 @@ void MainWindow::loadPreferences(bool configure_session) { toolBar->setVisible(false); } - if(pref.preventFromSuspend()) + if (pref.preventFromSuspend()) { preventTimer->start(PREVENT_SUSPEND_INTERVAL); } @@ -1055,8 +1055,8 @@ void MainWindow::loadPreferences(bool configure_session) { properties->getTrackerList()->setAlternatingRowColors(pref.useAlternatingRowColors()); properties->getPeerList()->setAlternatingRowColors(pref.useAlternatingRowColors()); // Queueing System - if(pref.isQueueingSystemEnabled()) { - if(!actionDecreasePriority->isVisible()) { + if (pref.isQueueingSystemEnabled()) { + if (!actionDecreasePriority->isVisible()) { transferList->hidePriorityColumn(false); actionDecreasePriority->setVisible(true); actionIncreasePriority->setVisible(true); @@ -1064,7 +1064,7 @@ void MainWindow::loadPreferences(bool configure_session) { prioSeparatorMenu->setVisible(true); } } else { - if(actionDecreasePriority->isVisible()) { + if (actionDecreasePriority->isVisible()) { transferList->hidePriorityColumn(true); actionDecreasePriority->setVisible(false); actionIncreasePriority->setVisible(false); @@ -1081,7 +1081,7 @@ void MainWindow::loadPreferences(bool configure_session) { IconProvider::instance()->useSystemIconTheme(pref.useSystemIconTheme()); #endif - if(configure_session) + if (configure_session) QBtSession::instance()->configureSession(); qDebug("GUI settings loaded"); @@ -1089,14 +1089,14 @@ void MainWindow::loadPreferences(bool configure_session) { void MainWindow::addUnauthenticatedTracker(const QPair &tracker) { // Trackers whose authentication was cancelled - if(unauthenticated_trackers.indexOf(tracker) < 0) { + if (unauthenticated_trackers.indexOf(tracker) < 0) { unauthenticated_trackers << tracker; } } // Called when a tracker requires authentication void MainWindow::trackerAuthenticationRequired(const QTorrentHandle& h) { - if(unauthenticated_trackers.indexOf(QPair(h, h.current_tracker())) < 0) { + if (unauthenticated_trackers.indexOf(QPair(h, h.current_tracker())) < 0) { // Tracker login new trackerLogin(this, h); } @@ -1105,7 +1105,7 @@ void MainWindow::trackerAuthenticationRequired(const QTorrentHandle& h) { // Check connection status and display right icon void MainWindow::updateGUI() { // update global informations - if(systrayIcon) { + if (systrayIcon) { #if defined(Q_WS_X11) || defined(Q_WS_MAC) QString html = "
"; html += tr("qBittorrent"); @@ -1124,28 +1124,28 @@ void MainWindow::updateGUI() { #endif systrayIcon->setToolTip(html); // tray icon } - if(displaySpeedInTitle) { + if (displaySpeedInTitle) { setWindowTitle(tr("[D: %1/s, U: %2/s] qBittorrent %3", "D = Download; U = Upload; %3 is qBittorrent version").arg(misc::friendlyUnit(QBtSession::instance()->getSessionStatus().payload_download_rate)).arg(misc::friendlyUnit(QBtSession::instance()->getSessionStatus().payload_upload_rate)).arg(QString::fromUtf8(VERSION))); } } void MainWindow::showNotificationBaloon(QString title, QString msg) const { - if(!Preferences().useProgramNotification()) return; + if (!Preferences().useProgramNotification()) return; #if defined(Q_WS_X11) && defined(QT_DBUS_LIB) org::freedesktop::Notifications notifications("org.freedesktop.Notifications", "/org/freedesktop/Notifications", QDBusConnection::sessionBus()); - if(notifications.isValid()) { + if (notifications.isValid()) { QVariantMap hints; hints["desktop-entry"] = "qBittorrent"; QDBusPendingReply reply = notifications.Notify("qBittorrent", 0, "qbittorrent", title, msg, QStringList(), hints, -1); reply.waitForFinished(); - if(!reply.isError()) + if (!reply.isError()) return; } #endif - if(systrayIcon && QSystemTrayIcon::supportsMessages()) + if (systrayIcon && QSystemTrayIcon::supportsMessages()) systrayIcon->showMessage(title, msg, QSystemTrayIcon::Information, TIME_TRAY_BALLOON); } @@ -1158,13 +1158,13 @@ void MainWindow::showNotificationBaloon(QString title, QString msg) const { void MainWindow::downloadFromURLList(const QStringList& url_list) { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool(); - foreach(QString url, url_list) { - if(url.startsWith("bc://bt/", Qt::CaseInsensitive)) { + foreach (QString url, url_list) { + if (url.startsWith("bc://bt/", Qt::CaseInsensitive)) { qDebug("Converting bc link to magnet link"); url = misc::bcLinkToMagnet(url); } - if(url.startsWith("magnet:", Qt::CaseInsensitive)) { - if(useTorrentAdditionDialog) { + if (url.startsWith("magnet:", Qt::CaseInsensitive)) { + if (useTorrentAdditionDialog) { torrentAdditionDialog *dialog = new torrentAdditionDialog(this); dialog->showLoadMagnetURI(url); } else { @@ -1184,13 +1184,13 @@ void MainWindow::downloadFromURLList(const QStringList& url_list) { void MainWindow::createSystrayDelayed() { static int timeout = 20; - if(QSystemTrayIcon::isSystemTrayAvailable()) { + if (QSystemTrayIcon::isSystemTrayAvailable()) { // Ok, systray integration is now supported // Create systray icon createTrayIcon(); delete systrayCreator; } else { - if(timeout) { + if (timeout) { // Retry a bit later systrayCreator->start(2000); --timeout; @@ -1210,7 +1210,7 @@ void MainWindow::updateAltSpeedsBtn(bool alternative) { } QMenu* MainWindow::getTrayIconMenu() { - if(myTrayIconMenu) + if (myTrayIconMenu) return myTrayIconMenu; // Tray icon Menu myTrayIconMenu = new QMenu(this); @@ -1231,7 +1231,7 @@ QMenu* MainWindow::getTrayIconMenu() { myTrayIconMenu->addAction(actionPause_All); myTrayIconMenu->addSeparator(); myTrayIconMenu->addAction(actionExit); - if(ui_locked) + if (ui_locked) myTrayIconMenu->setEnabled(false); return myTrayIconMenu; } @@ -1249,7 +1249,7 @@ void MainWindow::createTrayIcon() { // Display Program Options void MainWindow::on_actionOptions_triggered() { - if(options) { + if (options) { // Get focus options->setFocus(); } else { @@ -1267,7 +1267,7 @@ void MainWindow::on_actionTop_tool_bar_triggered() { void MainWindow::on_actionSpeed_in_title_bar_triggered() { displaySpeedInTitle = static_cast(sender())->isChecked(); Preferences().showSpeedInTitleBar(displaySpeedInTitle); - if(displaySpeedInTitle) + if (displaySpeedInTitle) updateGUI(); else setWindowTitle(tr("qBittorrent %1", "e.g: qBittorrent v0.x").arg(QString::fromUtf8(VERSION))); @@ -1297,7 +1297,7 @@ void MainWindow::on_action_Import_Torrent_triggered() // Display an input dialog to prompt user for // an url void MainWindow::on_actionDownload_from_URL_triggered() { - if(!downloadFromURLDialog) { + if (!downloadFromURLDialog) { downloadFromURLDialog = new downloadFromURL(this); connect(downloadFromURLDialog, SIGNAL(urlsReadyToBeDownloaded(QStringList)), this, SLOT(downloadFromURLList(QStringList))); } @@ -1307,8 +1307,8 @@ void MainWindow::on_actionDownload_from_URL_triggered() { void MainWindow::handleUpdateCheckFinished(bool update_available, QString new_version) { - if(update_available) { - if(QMessageBox::question(this, tr("A newer version is available"), + if (update_available) { + if (QMessageBox::question(this, tr("A newer version is available"), tr("A newer version of qBittorrent is available on Sourceforge.\nWould you like to update qBittorrent to version %1?").arg(new_version), QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { // The user want to update, let's download the update @@ -1323,7 +1323,7 @@ void MainWindow::handleUpdateCheckFinished(bool update_available, QString new_ve void MainWindow::handleUpdateInstalled(QString error_msg) { - if(!error_msg.isEmpty()) { + if (!error_msg.isEmpty()) { QMessageBox::critical(this, tr("Impossible to update qBittorrent"), tr("qBittorrent failed to update, reason: %1").arg(error_msg)); } } @@ -1348,13 +1348,13 @@ void MainWindow::minimizeWindow() void MainWindow::on_actionExecution_Logs_triggered(bool checked) { - if(checked) { + if (checked) { Q_ASSERT(!m_executionLog); m_executionLog = new ExecutionLog(tabs); int index_tab = tabs->addTab(m_executionLog, tr("Execution Log")); tabs->setTabIcon(index_tab, IconProvider::instance()->getIcon("view-calendar-journal")); } else { - if(m_executionLog) + if (m_executionLog) delete m_executionLog; } Preferences().setExecutionLogEnabled(checked); @@ -1381,7 +1381,7 @@ void MainWindow::on_actionAutoShutdown_system_toggled(bool enabled) void MainWindow::checkForActiveTorrents() { const TorrentStatusReport report = transferList->getSourceModel()->getTorrentStatusReport(); - if(report.nb_active > 0) // Active torrents are present; prevent system from suspend + if (report.nb_active > 0) // Active torrents are present; prevent system from suspend m_pwr->setActivityState(true); else m_pwr->setActivityState(false); diff --git a/src/misc.cpp b/src/misc.cpp index c88724f5f..1e1ef5148 100644 --- a/src/misc.cpp +++ b/src/misc.cpp @@ -107,7 +107,7 @@ QString misc::QDesktopServicesDataLocation() { result = QString::fromWCharArray(path); if (!QCoreApplication::applicationName().isEmpty()) result = result + QLatin1String("\\") + qApp->applicationName(); - if(!result.endsWith("\\")) + if (!result.endsWith("\\")) result += "\\"; return result; #else @@ -208,16 +208,16 @@ QString misc::QDesktopServicesDownloadLocation() { } long long misc::freeDiskSpaceOnPath(QString path) { - if(path.isEmpty()) return -1; + if (path.isEmpty()) return -1; path.replace("\\", "/"); QDir dir_path(path); - if(!dir_path.exists()) { + if (!dir_path.exists()) { QStringList parts = path.split("/"); while (parts.size() > 1 && !QDir(parts.join("/")).exists()) { parts.removeLast(); } dir_path = QDir(parts.join("/")); - if(!dir_path.exists()) return -1; + if (!dir_path.exists()) return -1; } Q_ASSERT(dir_path.exists()); @@ -226,7 +226,7 @@ long long misc::freeDiskSpaceOnPath(QString path) { struct statfs stats; const QString statfs_path = dir_path.path()+"/."; const int ret = statfs (qPrintable(statfs_path), &stats) ; - if(ret == 0) { + if (ret == 0) { available = ((unsigned long long)stats.f_bavail) * ((unsigned long long)stats.f_bsize) ; return available; @@ -264,11 +264,11 @@ long long misc::freeDiskSpaceOnPath(QString path) { void misc::shutdownComputer(bool sleep) { #if defined(Q_WS_X11) && defined(QT_DBUS_LIB) // Use dbus to power off / suspend the system - if(sleep) { + if (sleep) { // Recent systems use UPower QDBusInterface upowerIface("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower", QDBusConnection::systemBus()); - if(upowerIface.isValid()) { + if (upowerIface.isValid()) { upowerIface.call("Suspend"); return; } @@ -281,7 +281,7 @@ void misc::shutdownComputer(bool sleep) { // Recent systems use ConsoleKit QDBusInterface consolekitIface("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Manager", "org.freedesktop.ConsoleKit.Manager", QDBusConnection::systemBus()); - if(consolekitIface.isValid()) { + if (consolekitIface.isValid()) { consolekitIface.call("Stop"); return; } @@ -294,7 +294,7 @@ void misc::shutdownComputer(bool sleep) { #endif #ifdef Q_WS_MAC AEEventID EventToSend; - if(sleep) + if (sleep) EventToSend = kAESleep; else EventToSend = kAEShutDown; @@ -336,7 +336,7 @@ void misc::shutdownComputer(bool sleep) { #ifdef Q_WS_WIN HANDLE hToken; // handle to process token TOKEN_PRIVILEGES tkp; // pointer to token structure - if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return; // Get the LUID for shutdown privilege. LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, @@ -355,7 +355,7 @@ void misc::shutdownComputer(bool sleep) { if (GetLastError() != ERROR_SUCCESS) return; - if(sleep) + if (sleep) SetSuspendState(false, false, false); else InitiateSystemShutdownA(0, tr("qBittorrent will shutdown the computer now because all downloads are complete.").toLocal8Bit().data(), 10, true, false); @@ -372,13 +372,13 @@ QString misc::fixFileNames(QString path) { //qDebug() << Q_FUNC_INFO << path; path.replace("\\", "/"); QStringList parts = path.split("/", QString::SkipEmptyParts); - if(parts.isEmpty()) return path; + if (parts.isEmpty()) return path; QString last_part = parts.takeLast(); QList::iterator it; - for(it = parts.begin(); it != parts.end(); it++) { + for (it = parts.begin(); it != parts.end(); it++) { QByteArray raw_filename = it->toLocal8Bit(); // Make sure the filename is not too long - if(raw_filename.size() > MAX_FILENAME_LENGTH) { + if (raw_filename.size() > MAX_FILENAME_LENGTH) { qDebug() << "Folder" << *it << "was cut because it was too long"; raw_filename.resize(MAX_FILENAME_LENGTH); *it = QString::fromLocal8Bit(raw_filename.constData()); @@ -389,12 +389,12 @@ QString misc::fixFileNames(QString path) { // Fix the last part (file name) QByteArray raw_lastPart = last_part.toLocal8Bit(); qDebug() << "Last part length:" << raw_lastPart.length(); - if(raw_lastPart.length() > MAX_FILENAME_LENGTH) { + if (raw_lastPart.length() > MAX_FILENAME_LENGTH) { qDebug() << "Filename" << last_part << "was cut because it was too long"; // Shorten the name, keep the file extension int point_index = raw_lastPart.lastIndexOf("."); QByteArray extension = ""; - if(point_index >= 0) { + if (point_index >= 0) { extension = raw_lastPart.mid(point_index); raw_lastPart = raw_lastPart.left(point_index); } @@ -408,7 +408,7 @@ QString misc::fixFileNames(QString path) { } QString misc::truncateRootFolder(boost::intrusive_ptr t) { - if(t->num_files() == 1) { + if (t->num_files() == 1) { // Single file torrent #if LIBTORRENT_VERSION_MINOR > 15 QString path = QString::fromUtf8(t->file_at(0).path.c_str()); @@ -421,14 +421,14 @@ QString misc::truncateRootFolder(boost::intrusive_ptr t) { return QString(); } QString root_folder; - for(int i=0; inum_files(); ++i) { + for (int i=0; inum_files(); ++i) { #if LIBTORRENT_VERSION_MINOR > 15 QString path = QString::fromUtf8(t->file_at(i).path.c_str()); #else QString path = QString::fromUtf8(t->file_at(i).path.string().c_str()); #endif QStringList path_parts = path.split("/", QString::SkipEmptyParts); - if(path_parts.size() > 1) { + if (path_parts.size() > 1) { root_folder = path_parts.takeFirst(); } path = fixFileNames(path_parts.join("/")); @@ -439,7 +439,7 @@ QString misc::truncateRootFolder(boost::intrusive_ptr t) { QString misc::truncateRootFolder(libtorrent::torrent_handle h) { torrent_info t = h.get_torrent_info(); - if(t.num_files() == 1) { + if (t.num_files() == 1) { // Single file torrent // Remove possible subfolders #if LIBTORRENT_VERSION_MINOR > 15 @@ -452,14 +452,14 @@ QString misc::truncateRootFolder(libtorrent::torrent_handle h) { return QString(); } QString root_folder; - for(int i=0; i 15 QString path = QString::fromUtf8(t.file_at(i).path.c_str()); #else QString path = QString::fromUtf8(t.file_at(i).path.string().c_str()); #endif QStringList path_parts = path.split("/", QString::SkipEmptyParts); - if(path_parts.size() > 1) { + if (path_parts.size() > 1) { root_folder = path_parts.takeFirst(); } path = fixFileNames(path_parts.join("/")); @@ -470,16 +470,16 @@ QString misc::truncateRootFolder(libtorrent::torrent_handle h) { bool misc::sameFiles(const QString &path1, const QString &path2) { QFile f1(path1), f2(path2); - if(!f1.exists() || !f2.exists()) return false; - if(f1.size() != f2.size()) return false; - if(!f1.open(QIODevice::ReadOnly)) return false; - if(!f2.open(QIODevice::ReadOnly)) { + if (!f1.exists() || !f2.exists()) return false; + if (f1.size() != f2.size()) return false; + if (!f1.open(QIODevice::ReadOnly)) return false; + if (!f2.open(QIODevice::ReadOnly)) { f1.close(); return false; } bool same = true; while(!f1.atEnd() && !f2.atEnd()) { - if(f1.read(5) != f2.read(5)) { + if (f1.read(5) != f2.read(5)) { same = false; break; } @@ -489,34 +489,34 @@ bool misc::sameFiles(const QString &path1, const QString &path2) { } QString misc::updateLabelInSavePath(QString defaultSavePath, QString save_path, const QString &old_label, const QString &new_label) { - if(old_label == new_label) return save_path; + if (old_label == new_label) return save_path; #if defined(Q_WS_WIN) || defined(Q_OS_OS2) defaultSavePath.replace("\\", "/"); save_path.replace("\\", "/"); #endif qDebug("UpdateLabelInSavePath(%s, %s, %s)", qPrintable(save_path), qPrintable(old_label), qPrintable(new_label)); - if(!save_path.startsWith(defaultSavePath)) return save_path; + if (!save_path.startsWith(defaultSavePath)) return save_path; QString new_save_path = save_path; new_save_path.replace(defaultSavePath, ""); QStringList path_parts = new_save_path.split("/", QString::SkipEmptyParts); - if(path_parts.empty()) { - if(!new_label.isEmpty()) + if (path_parts.empty()) { + if (!new_label.isEmpty()) path_parts << new_label; } else { - if(old_label.isEmpty() || path_parts.first() != old_label) { - if(path_parts.first() != new_label) + if (old_label.isEmpty() || path_parts.first() != old_label) { + if (path_parts.first() != new_label) path_parts.prepend(new_label); } else { - if(new_label.isEmpty()) { + if (new_label.isEmpty()) { path_parts.removeAt(0); } else { - if(path_parts.first() != new_label) + if (path_parts.first() != new_label) path_parts.replace(0, new_label); } } } new_save_path = defaultSavePath; - if(!new_save_path.endsWith(QDir::separator())) new_save_path += QDir::separator(); + if (!new_save_path.endsWith(QDir::separator())) new_save_path += QDir::separator(); new_save_path += path_parts.join(QDir::separator()); qDebug("New save path is %s", qPrintable(new_save_path)); return new_save_path; @@ -531,7 +531,7 @@ QString misc::toValidFileSystemName(QString filename) { } bool misc::isValidFileSystemName(const QString& filename) { - if(filename.isEmpty()) return false; + if (filename.isEmpty()) return false; const QRegExp regex("[\\\\/:?\"*<>|]"); return !filename.contains(regex); } @@ -542,9 +542,9 @@ QPoint misc::screenCenter(QWidget *win) { int scrn = 0; const QWidget *w = win->window(); - if(w) + if (w) scrn = QApplication::desktop()->screenNumber(w); - else if(QApplication::desktop()->isVirtualDesktop()) + else if (QApplication::desktop()->isVirtualDesktop()) scrn = QApplication::desktop()->screenNumber(QCursor::pos()); else scrn = QApplication::desktop()->screenNumber(win); @@ -585,7 +585,7 @@ QString misc::searchEngineLocation() { const QString location = QDir::cleanPath(QDesktopServicesDataLocation() + QDir::separator() + folder); QDir locationDir(location); - if(!locationDir.exists()) + if (!locationDir.exists()) locationDir.mkpath(locationDir.absolutePath()); return location; } @@ -594,7 +594,7 @@ QString misc::BTBackupLocation() { const QString location = QDir::cleanPath(QDesktopServicesDataLocation() + QDir::separator() + "BT_backup"); QDir locationDir(location); - if(!locationDir.exists()) + if (!locationDir.exists()) locationDir.mkpath(locationDir.absolutePath()); return location; } @@ -602,7 +602,7 @@ QString misc::BTBackupLocation() { QString misc::cacheLocation() { QString location = QDir::cleanPath(QDesktopServicesCacheLocation()); QDir locationDir(location); - if(!locationDir.exists()) + if (!locationDir.exists()) locationDir.mkpath(locationDir.absolutePath()); return location; } @@ -612,61 +612,61 @@ QString misc::cacheLocation() { // see http://en.wikipedia.org/wiki/Kilobyte // value must be given in bytes QString misc::friendlyUnit(qreal val) { - if(val < 0) + if (val < 0) return tr("Unknown", "Unknown (size)"); int i = 0; while(val >= 1024. && i++<6) val /= 1024.; - if(i == 0) + if (i == 0) return QString::number((long)val) + " " + tr(units[0].source, units[0].comment); return QString::number(val, 'f', 1) + " " + tr(units[i].source, units[i].comment); } bool misc::isPreviewable(QString extension){ - if(extension.isEmpty()) return false; + if (extension.isEmpty()) return false; extension = extension.toUpper(); - if(extension == "AVI") return true; - if(extension == "MP3") return true; - if(extension == "OGG") return true; - if(extension == "OGV") return true; - if(extension == "OGM") return true; - if(extension == "WMV") return true; - if(extension == "WMA") return true; - if(extension == "MPEG") return true; - if(extension == "MPG") return true; - if(extension == "ASF") return true; - if(extension == "QT") return true; - if(extension == "RM") return true; - if(extension == "RMVB") return true; - if(extension == "RMV") return true; - if(extension == "SWF") return true; - if(extension == "FLV") return true; - if(extension == "WAV") return true; - if(extension == "MOV") return true; - if(extension == "VOB") return true; - if(extension == "MID") return true; - if(extension == "AC3") return true; - if(extension == "MP4") return true; - if(extension == "MP2") return true; - if(extension == "AVI") return true; - if(extension == "FLAC") return true; - if(extension == "AU") return true; - if(extension == "MPE") return true; - if(extension == "MOV") return true; - if(extension == "MKV") return true; - if(extension == "AIF") return true; - if(extension == "AIFF") return true; - if(extension == "AIFC") return true; - if(extension == "RA") return true; - if(extension == "RAM") return true; - if(extension == "M4P") return true; - if(extension == "M4A") return true; - if(extension == "3GP") return true; - if(extension == "AAC") return true; - if(extension == "SWA") return true; - if(extension == "MPC") return true; - if(extension == "MPP") return true; - if(extension == "M3U") return true; + if (extension == "AVI") return true; + if (extension == "MP3") return true; + if (extension == "OGG") return true; + if (extension == "OGV") return true; + if (extension == "OGM") return true; + if (extension == "WMV") return true; + if (extension == "WMA") return true; + if (extension == "MPEG") return true; + if (extension == "MPG") return true; + if (extension == "ASF") return true; + if (extension == "QT") return true; + if (extension == "RM") return true; + if (extension == "RMVB") return true; + if (extension == "RMV") return true; + if (extension == "SWF") return true; + if (extension == "FLV") return true; + if (extension == "WAV") return true; + if (extension == "MOV") return true; + if (extension == "VOB") return true; + if (extension == "MID") return true; + if (extension == "AC3") return true; + if (extension == "MP4") return true; + if (extension == "MP2") return true; + if (extension == "AVI") return true; + if (extension == "FLAC") return true; + if (extension == "AU") return true; + if (extension == "MPE") return true; + if (extension == "MOV") return true; + if (extension == "MKV") return true; + if (extension == "AIF") return true; + if (extension == "AIFF") return true; + if (extension == "AIFC") return true; + if (extension == "RA") return true; + if (extension == "RAM") return true; + if (extension == "M4P") return true; + if (extension == "M4A") return true; + if (extension == "3GP") return true; + if (extension == "AAC") return true; + if (extension == "SWA") return true; + if (extension == "MPC") return true; + if (extension == "MPP") return true; + if (extension == "M3U") return true; return false; } @@ -676,7 +676,7 @@ QString misc::bcLinkToMagnet(QString bc_link) { raw_bc = QByteArray::fromBase64(raw_bc); // Decode base64 // Format is now AA/url_encoded_filename/size_bytes/info_hash/ZZ QStringList parts = QString(raw_bc).split("/"); - if(parts.size() != 5) return QString::null; + if (parts.size() != 5) return QString::null; QString filename = parts.at(1); QString hash = parts.at(3); QString magnet = "magnet:?xt=urn:btih:" + hash; @@ -688,7 +688,7 @@ QString misc::magnetUriToName(QString magnet_uri) { QString name = ""; QRegExp regHex("dn=([^&]+)"); const int pos = regHex.indexIn(magnet_uri); - if(pos > -1) { + if (pos > -1) { const QString found = regHex.cap(1); // URL decode name = QUrl::fromPercentEncoding(found.toLocal8Bit()).replace("+", " "); @@ -701,10 +701,10 @@ QString misc::magnetUriToHash(QString magnet_uri) { QRegExp regHex("urn:btih:([0-9A-Za-z]+)"); // Hex int pos = regHex.indexIn(magnet_uri); - if(pos > -1) { + if (pos > -1) { const QString found = regHex.cap(1); qDebug() << Q_FUNC_INFO << "regex found: " << found; - if(found.length() == 40) { + if (found.length() == 40) { const sha1_hash sha1(QByteArray::fromHex(found.toAscii()).constData()); qDebug("magnetUriToHash (Hex): hash: %s", qPrintable(misc::toQString(sha1))); return misc::toQString(sha1); @@ -713,9 +713,9 @@ QString misc::magnetUriToHash(QString magnet_uri) { // Base 32 QRegExp regBase32("urn:btih:([A-Za-z2-7=]+)"); pos = regBase32.indexIn(magnet_uri); - if(pos > -1) { + if (pos > -1) { const QString found = regBase32.cap(1); - if(found.length() > 20 && (found.length()*5)%40 == 0) { + if (found.length() > 20 && (found.length()*5)%40 == 0) { const sha1_hash sha1(base32decode(regBase32.cap(1).toStdString())); hash = misc::toQString(sha1); } @@ -727,14 +727,14 @@ QString misc::magnetUriToHash(QString magnet_uri) { // Replace ~ in path QString misc::expandPath(QString path) { path = path.trimmed(); - if(path.isEmpty()) return path; - if(path.length() == 1) { - if(path[0] == '~' ) return QDir::homePath(); + if (path.isEmpty()) return path; + if (path.length() == 1) { + if (path[0] == '~' ) return QDir::homePath(); } - if(path[0] == '~' && path[1] == QDir::separator()) { + if (path[0] == '~' && path[1] == QDir::separator()) { path.replace(0, 1, QDir::homePath()); } else { - if(QDir::isAbsolutePath(path)) { + if (QDir::isAbsolutePath(path)) { path = QDir(path).absolutePath(); } } @@ -744,27 +744,27 @@ QString misc::expandPath(QString path) { // Take a number of seconds and return an user-friendly // time duration like "1d 2h 10m". QString misc::userFriendlyDuration(qlonglong seconds) { - if(seconds < 0 || seconds >= MAX_ETA) { + if (seconds < 0 || seconds >= MAX_ETA) { return QString::fromUtf8("∞"); } - if(seconds == 0) { + if (seconds == 0) { return "0"; } - if(seconds < 60) { + if (seconds < 60) { return tr("< 1m", "< 1 minute"); } int minutes = seconds / 60; - if(minutes < 60) { + if (minutes < 60) { return tr("%1m","e.g: 10minutes").arg(QString::number(minutes)); } int hours = minutes / 60; minutes = minutes - hours*60; - if(hours < 24) { + if (hours < 24) { return tr("%1h %2m", "e.g: 3hours 5minutes").arg(QString::number(hours)).arg(QString::number(minutes)); } int days = hours / 24; hours = hours - days * 24; - if(days < 100) { + if (days < 100) { return tr("%1d %2h", "e.g: 2days 10hours").arg(QString::number(days)).arg(QString::number(hours)); } return QString::fromUtf8("∞"); @@ -785,7 +785,7 @@ QString misc::getUserIDString() { QStringList misc::toStringList(const QList &l) { QStringList ret; - foreach(const bool &b, l) { + foreach (const bool &b, l) { ret << (b ? "1" : "0"); } return ret; @@ -793,7 +793,7 @@ QStringList misc::toStringList(const QList &l) { QList misc::intListfromStringList(const QStringList &l) { QList ret; - foreach(const QString &s, l) { + foreach (const QString &s, l) { ret << s.toInt(); } return ret; @@ -801,7 +801,7 @@ QList misc::intListfromStringList(const QStringList &l) { QList misc::boolListfromStringList(const QStringList &l) { QList ret; - foreach(const QString &s, l) { + foreach (const QString &s, l) { ret << (s=="1"); } return ret; @@ -811,13 +811,13 @@ quint64 misc::computePathSize(QString path) { // Check if it is a file QFileInfo fi(path); - if(!fi.exists()) return 0; - if(fi.isFile()) return fi.size(); + if (!fi.exists()) return 0; + if (fi.isFile()) return fi.size(); // Compute folder size quint64 size = 0; - foreach(const QFileInfo &subfi, QDir(path).entryInfoList(QDir::Dirs|QDir::Files)) { - if(subfi.fileName().startsWith(".")) continue; - if(subfi.isDir()) + foreach (const QFileInfo &subfi, QDir(path).entryInfoList(QDir::Dirs|QDir::Files)) { + if (subfi.fileName().startsWith(".")) continue; + if (subfi.isDir()) size += misc::computePathSize(subfi.absoluteFilePath()); else size += subfi.size(); @@ -828,7 +828,7 @@ quint64 misc::computePathSize(QString path) bool misc::isValidTorrentFile(const QString &torrent_path) { try { boost::intrusive_ptr t = new torrent_info(torrent_path.toUtf8().constData()); - if(!t->is_valid() || t->num_files() == 0) + if (!t->is_valid() || t->num_files() == 0) throw std::exception(); } catch(std::exception&) { return false; @@ -842,13 +842,13 @@ bool misc::isValidTorrentFile(const QString &torrent_path) { */ QString misc::branchPath(QString file_path, bool uses_slashes) { - if(!uses_slashes) + if (!uses_slashes) file_path.replace("\\", "/"); Q_ASSERT(!file_path.contains("\\")); - if(file_path.endsWith("/")) + if (file_path.endsWith("/")) file_path.chop(1); // Remove trailing slash qDebug() << Q_FUNC_INFO << "before:" << file_path; - if(file_path.contains("/")) + if (file_path.contains("/")) return file_path.left(file_path.lastIndexOf('/')); return ""; } @@ -864,7 +864,7 @@ QString misc::fileName(QString file_path) { file_path.replace("\\", "/"); const int slash_index = file_path.lastIndexOf('/'); - if(slash_index == -1) + if (slash_index == -1) return file_path; return file_path.mid(slash_index+1); } diff --git a/src/misc.h b/src/misc.h index 53fc1f762..59df06fb2 100644 --- a/src/misc.h +++ b/src/misc.h @@ -81,7 +81,7 @@ public: static inline QString file_extension(const QString &filename) { QString extension; int point_index = filename.lastIndexOf("."); - if(point_index >= 0) { + if (point_index >= 0) { extension = filename.mid(point_index+1); } return extension; diff --git a/src/powermanagement/powermanagement.cpp b/src/powermanagement/powermanagement.cpp index dcbd8ad8f..2b882a881 100644 --- a/src/powermanagement/powermanagement.cpp +++ b/src/powermanagement/powermanagement.cpp @@ -56,13 +56,13 @@ PowerManagement::~PowerManagement() void PowerManagement::setActivityState(bool busy) { - if(busy) setBusy(); + if (busy) setBusy(); else setIdle(); } void PowerManagement::setBusy() { - if(m_busy) return; + if (m_busy) return; m_busy = true; #ifdef Q_WS_WIN @@ -71,13 +71,13 @@ void PowerManagement::setBusy() m_inhibitor->RequestBusy(); #elif defined(Q_WS_MAC) IOReturn success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &m_assertionID); - if(success != kIOReturnSuccess) m_busy = false; + if (success != kIOReturnSuccess) m_busy = false; #endif } void PowerManagement::setIdle() { - if(!m_busy) return; + if (!m_busy) return; m_busy = false; #ifdef Q_WS_WIN diff --git a/src/powermanagement/powermanagement_x11.cpp b/src/powermanagement/powermanagement_x11.cpp index 2e90c32ee..b5bd2196c 100644 --- a/src/powermanagement/powermanagement_x11.cpp +++ b/src/powermanagement/powermanagement_x11.cpp @@ -37,7 +37,7 @@ PowerManagementInhibitor::PowerManagementInhibitor(QObject *parent) : QObject(parent) { - if(!QDBusConnection::sessionBus().isConnected()) + if (!QDBusConnection::sessionBus().isConnected()) { qDebug("D-Bus: Could not connect to session bus"); m_state = error; @@ -134,7 +134,7 @@ void PowerManagementInhibitor::OnAsyncReply(QDBusPendingCallWatcher *call) { QDBusPendingReply<> reply = *call; - if(reply.isError()) + if (reply.isError()) { qDebug("D-Bus: Reply: Error: %s", qPrintable(reply.error().message())); m_state = error; @@ -150,7 +150,7 @@ void PowerManagementInhibitor::OnAsyncReply(QDBusPendingCallWatcher *call) { QDBusPendingReply reply = *call; - if(reply.isError()) + if (reply.isError()) { qDebug("D-Bus: Reply: Error: %s", qPrintable(reply.error().message())); diff --git a/src/preferences/advancedsettings.h b/src/preferences/advancedsettings.h index 36d3c3198..1fc54b9d5 100644 --- a/src/preferences/advancedsettings.h +++ b/src/preferences/advancedsettings.h @@ -84,7 +84,7 @@ public slots: // Super seeding pref.enableSuperSeeding(cb_super_seeding.isChecked()); // Network interface - if(combo_iface.currentIndex() == 0) { + if (combo_iface.currentIndex() == 0) { // All interfaces (default) pref.setNetworkInterface(QString::null); } else { @@ -92,7 +92,7 @@ public slots: } // Network address QHostAddress addr(txt_network_address.text().trimmed()); - if(addr.isNull()) + if (addr.isNull()) pref.setNetworkAddress(""); else pref.setNetworkAddress(addr.toString()); @@ -199,10 +199,10 @@ private slots: combo_iface.addItem(tr("Any interface", "i.e. Any network interface")); const QString current_iface = pref.getNetworkInterface(); int i = 1; - foreach(const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) { - if(iface.flags() & QNetworkInterface::IsLoopBack) continue; + foreach (const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) { + if (iface.flags() & QNetworkInterface::IsLoopBack) continue; combo_iface.addItem(iface.name()); - if(!current_iface.isEmpty() && iface.name() == current_iface) + if (!current_iface.isEmpty() && iface.name() == current_iface) combo_iface.setCurrentIndex(i); ++i; } diff --git a/src/preferences/options_imp.cpp b/src/preferences/options_imp.cpp index 66b160545..6620953b1 100644 --- a/src/preferences/options_imp.cpp +++ b/src/preferences/options_imp.cpp @@ -81,8 +81,8 @@ options_imp::options_imp(QWidget *parent): hsplitter->setCollapsible(1, false); // Get apply button in button box QList buttons = buttonBox->buttons(); - foreach(QAbstractButton *button, buttons){ - if(buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole){ + foreach (QAbstractButton *button, buttons){ + if (buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole){ applyButton = button; break; } @@ -98,7 +98,7 @@ options_imp::options_imp(QWidget *parent): initializeLanguageCombo(); // Load week days (scheduler) - for(uint i=1; i<=7; ++i) { + for (uint i=1; i<=7; ++i) { #if QT_VERSION >= 0x040500 schedule_days->addItem(QDate::longDayName(i, QDate::StandaloneFormat)); #else @@ -109,7 +109,7 @@ options_imp::options_imp(QWidget *parent): // Load options loadOptions(); // Disable systray integration if it is not supported by the system - if(!QSystemTrayIcon::isSystemTrayAvailable()){ + if (!QSystemTrayIcon::isSystemTrayAvailable()){ checkShowSystray->setChecked(false); checkShowSystray->setEnabled(false); } @@ -267,7 +267,7 @@ void options_imp::initializeLanguageCombo() // List language files const QDir lang_dir(":/lang"); const QStringList lang_files = lang_dir.entryList(QStringList() << "qbittorrent_*.qm", QDir::Files); - foreach(QString lang_file, lang_files) { + foreach (QString lang_file, lang_files) { QString localeStr = lang_file.mid(12); // remove "qbittorrent_" localeStr.chop(3); // Remove ".qm" QLocale locale(localeStr); @@ -297,13 +297,13 @@ void options_imp::loadWindowState() { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); resize(settings.value(QString::fromUtf8("Preferences/State/size"), sizeFittingScreen()).toSize()); QPoint p = settings.value(QString::fromUtf8("Preferences/State/pos"), QPoint()).toPoint(); - if(!p.isNull()) + if (!p.isNull()) move(p); // Load slider size const QStringList sizes_str = settings.value("Preferences/State/hSplitterSizes", QStringList()).toStringList(); // Splitter size QList sizes; - if(sizes_str.size() == 2) { + if (sizes_str.size() == 2) { sizes << sizes_str.first().toInt(); sizes << sizes_str.last().toInt(); } else { @@ -328,16 +328,16 @@ QSize options_imp::sizeFittingScreen() const { int scrn = 0; QWidget *w = this->topLevelWidget(); - if(w) + if (w) scrn = QApplication::desktop()->screenNumber(w); - else if(QApplication::desktop()->isVirtualDesktop()) + else if (QApplication::desktop()->isVirtualDesktop()) scrn = QApplication::desktop()->screenNumber(QCursor::pos()); else scrn = QApplication::desktop()->screenNumber(this); QRect desk(QApplication::desktop()->availableGeometry(scrn)); - if(width() > desk.width() || height() > desk.height()) { - if(desk.width() > 0 && desk.height() > 0) + if (width() > desk.width() || height() > desk.height()) { + if (desk.width() > 0 && desk.height() > 0) return QSize(desk.width(), desk.height()); } return size(); @@ -348,9 +348,9 @@ void options_imp::saveOptions(){ Preferences pref; // Load the translation QString locale = getLocale(); - if(pref.getLocale() != locale) { + if (pref.getLocale() != locale) { QTranslator *translator = new QTranslator; - if(translator->load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){ + if (translator->load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){ qDebug("%s locale recognized, using translation.", qPrintable(locale)); }else{ qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale)); @@ -454,7 +454,7 @@ void options_imp::saveOptions(){ // Misc preferences // * IPFilter pref.setFilteringEnabled(isFilteringEnabled()); - if(isFilteringEnabled()){ + if (isFilteringEnabled()){ QString filter_path = textFilterPath->text(); #if defined(Q_WS_WIN) || defined(Q_OS_OS2) filter_path.replace("\\", "/"); @@ -471,12 +471,12 @@ void options_imp::saveOptions(){ // End Queueing system preferences // Web UI pref.setWebUiEnabled(isWebUiEnabled()); - if(isWebUiEnabled()) + if (isWebUiEnabled()) { pref.setWebUiPort(webUiPort()); pref.setUPnPForWebUIPort(checkWebUIUPnP->isChecked()); pref.setWebUiHttpsEnabled(checkWebUiHttps->isChecked()); - if(checkWebUiHttps->isChecked()) + if (checkWebUiHttps->isChecked()) { pref.setWebUiHttpsCertificate(m_sslCert); pref.setWebUiHttpsKey(m_sslKey); @@ -508,12 +508,12 @@ int options_imp::getProxyType() const{ return Proxy::SOCKS4; break; case 2: - if(isProxyAuthEnabled()){ + if (isProxyAuthEnabled()){ return Proxy::SOCKS5_PW; } return Proxy::SOCKS5; case 3: - if(isProxyAuthEnabled()){ + if (isProxyAuthEnabled()){ return Proxy::HTTP_PW; } return Proxy::HTTP; @@ -532,7 +532,7 @@ void options_imp::loadOptions(){ checkAltRowColors->setChecked(pref.useAlternatingRowColors()); checkShowSystray->setChecked(pref.systrayIntegration()); checkShowSplash->setChecked(!pref.isSlashScreenDisabled()); - if(checkShowSystray->isChecked()) { + if (checkShowSystray->isChecked()) { checkCloseToSystray->setChecked(pref.closeToTray()); checkMinimizeToSysTray->setChecked(pref.minimizeToTray()); checkStartMinimized->setChecked(pref.startMinimized()); @@ -552,7 +552,7 @@ void options_imp::loadOptions(){ save_path.replace("/", "\\"); #endif textSavePath->setText(save_path); - if(pref.isTempPathEnabled()) { + if (pref.isTempPathEnabled()) { // enable checkTempFolder->setChecked(true); } else { @@ -570,7 +570,7 @@ void options_imp::loadOptions(){ checkStartPaused->setChecked(pref.addTorrentsInPause()); strValue = pref.getExportDir(); - if(strValue.isEmpty()) { + if (strValue.isEmpty()) { // Disable checkExportDir->setChecked(false); } else { @@ -591,11 +591,11 @@ void options_imp::loadOptions(){ autoRunBox->setChecked(pref.isAutoRunEnabled()); autoRun_txt->setText(pref.getAutoRunProgram()); intValue = pref.getActionOnDblClOnTorrentDl(); - if(intValue >= actionTorrentDlOnDblClBox->count()) + if (intValue >= actionTorrentDlOnDblClBox->count()) intValue = 0; actionTorrentDlOnDblClBox->setCurrentIndex(intValue); intValue = pref.getActionOnDblClOnTorrentFn(); - if(intValue >= actionTorrentFnOnDblClBox->count()) + if (intValue >= actionTorrentFnOnDblClBox->count()) intValue = 1; actionTorrentFnOnDblClBox->setCurrentIndex(intValue); // End Downloads preferences @@ -603,7 +603,7 @@ void options_imp::loadOptions(){ spinPort->setValue(pref.getSessionPort()); checkUPnP->setChecked(pref.isUPnPEnabled()); intValue = pref.getGlobalDownloadLimit(); - if(intValue > 0) { + if (intValue > 0) { // Enabled checkDownloadLimit->setChecked(true); spinDownloadLimit->setEnabled(true); @@ -614,7 +614,7 @@ void options_imp::loadOptions(){ spinDownloadLimit->setEnabled(false); } intValue = pref.getGlobalUploadLimit(); - if(intValue != -1) { + if (intValue != -1) { // Enabled checkUploadLimit->setChecked(true); spinUploadLimit->setEnabled(true); @@ -653,7 +653,7 @@ void options_imp::loadOptions(){ comboProxyType->setCurrentIndex(0); } enableProxy(comboProxyType->currentIndex()); - //if(isProxyEnabled()) { + //if (isProxyEnabled()) { // Proxy is enabled, save settings textProxyIP->setText(pref.getProxyIp()); spinProxyPort->setValue(pref.getProxyPort()); @@ -665,7 +665,7 @@ void options_imp::loadOptions(){ // End Connection preferences // Bittorrent preferences intValue = pref.getMaxConnecs(); - if(intValue > 0) { + if (intValue > 0) { // enable checkMaxConnecs->setChecked(true); spinMaxConnec->setEnabled(true); @@ -676,7 +676,7 @@ void options_imp::loadOptions(){ spinMaxConnec->setEnabled(false); } intValue = pref.getMaxConnecsPerTorrent(); - if(intValue > 0) { + if (intValue > 0) { // enable checkMaxConnecsPerTorrent->setChecked(true); spinMaxConnecPerTorrent->setEnabled(true); @@ -687,7 +687,7 @@ void options_imp::loadOptions(){ spinMaxConnecPerTorrent->setEnabled(false); } intValue = pref.getMaxUploadsPerTorrent(); - if(intValue > 0) { + if (intValue > 0) { // enable checkMaxUploadsPerTorrent->setChecked(true); spinMaxUploadsPerTorrent->setEnabled(true); @@ -708,7 +708,7 @@ void options_imp::loadOptions(){ #endif // Ratio limit floatValue = pref.getGlobalMaxRatio(); - if(floatValue >= 0.) { + if (floatValue >= 0.) { // Enable checkMaxRatio->setChecked(true); spinMaxRatio->setEnabled(true); @@ -783,12 +783,12 @@ int options_imp::getMaxActiveTorrents() const { } bool options_imp::minimizeToTray() const{ - if(!checkShowSystray->isChecked()) return false; + if (!checkShowSystray->isChecked()) return false; return checkMinimizeToSysTray->isChecked(); } bool options_imp::closeToTray() const{ - if(!checkShowSystray->isChecked()) return false; + if (!checkShowSystray->isChecked()) return false; return checkCloseToSystray->isChecked(); } @@ -812,17 +812,17 @@ bool options_imp::isUPnPEnabled() const{ // [download,upload] QPair options_imp::getGlobalBandwidthLimits() const{ int DL = -1, UP = -1; - if(checkDownloadLimit->isChecked()){ + if (checkDownloadLimit->isChecked()){ DL = spinDownloadLimit->value(); } - if(checkUploadLimit->isChecked()){ + if (checkUploadLimit->isChecked()){ UP = spinUploadLimit->value(); } return qMakePair(DL, UP); } bool options_imp::startMinimized() const { - if(checkStartMinimized->isChecked()) return true; + if (checkStartMinimized->isChecked()) return true; return checkStartMinimized->isChecked(); } @@ -837,7 +837,7 @@ int options_imp::getDHTPort() const { // Return Share ratio qreal options_imp::getMaxRatio() const{ - if(checkMaxRatio->isChecked()){ + if (checkMaxRatio->isChecked()){ return spinMaxRatio->value(); } return -1; @@ -845,7 +845,7 @@ qreal options_imp::getMaxRatio() const{ // Return Save Path QString options_imp::getSavePath() const{ - if(textSavePath->text().trimmed().isEmpty()){ + if (textSavePath->text().trimmed().isEmpty()){ QString save_path = Preferences().getSavePath(); #if defined(Q_WS_WIN) || defined(Q_OS_OS2) save_path.replace("/", "\\"); @@ -865,7 +865,7 @@ bool options_imp::isTempPathEnabled() const { // Return max connections number int options_imp::getMaxConnecs() const{ - if(!checkMaxConnecs->isChecked()){ + if (!checkMaxConnecs->isChecked()){ return -1; }else{ return spinMaxConnec->value(); @@ -873,7 +873,7 @@ int options_imp::getMaxConnecs() const{ } int options_imp::getMaxConnecsPerTorrent() const{ - if(!checkMaxConnecsPerTorrent->isChecked()){ + if (!checkMaxConnecsPerTorrent->isChecked()){ return -1; }else{ return spinMaxConnecPerTorrent->value(); @@ -881,7 +881,7 @@ int options_imp::getMaxConnecsPerTorrent() const{ } int options_imp::getMaxUploadsPerTorrent() const{ - if(!checkMaxUploadsPerTorrent->isChecked()){ + if (!checkMaxUploadsPerTorrent->isChecked()){ return -1; }else{ return spinMaxUploadsPerTorrent->value(); @@ -889,7 +889,7 @@ int options_imp::getMaxUploadsPerTorrent() const{ } void options_imp::on_buttonBox_accepted(){ - if(applyButton->isEnabled()){ + if (applyButton->isEnabled()){ saveOptions(); applyButton->setEnabled(false); this->hide(); @@ -900,7 +900,7 @@ void options_imp::on_buttonBox_accepted(){ } void options_imp::applySettings(QAbstractButton* button) { - if(button == applyButton){ + if (button == applyButton){ saveOptions(); emit status_changed(); } @@ -925,14 +925,14 @@ void options_imp::enableApplyButton(){ } void options_imp::enableProxy(int index){ - if(index){ + if (index){ //enable lblProxyIP->setEnabled(true); textProxyIP->setEnabled(true); lblProxyPort->setEnabled(true); spinProxyPort->setEnabled(true); checkProxyPeerConnecs->setEnabled(true); - if(index > 1) { + if (index > 1) { checkProxyAuth->setEnabled(true); } else { checkProxyAuth->setEnabled(false); @@ -1008,7 +1008,7 @@ void options_imp::setLocale(const QString &localeStr) { QLocale locale(localeStr); // Attempt to find exact match int index = comboI18n->findData(locale.name(), Qt::UserRole); - if(index < 0) { + if (index < 0) { // Unreconized, use US English index = comboI18n->findData(QLocale("en").name(), Qt::UserRole); Q_ASSERT(index >= 0); @@ -1017,21 +1017,21 @@ void options_imp::setLocale(const QString &localeStr) { } QString options_imp::getExportDir() const { - if(checkExportDir->isChecked()) + if (checkExportDir->isChecked()) return misc::expandPath(textExportDir->text()); return QString(); } // Return action on double-click on a downloading torrent set in options int options_imp::getActionOnDblClOnTorrentDl() const { - if(actionTorrentDlOnDblClBox->currentIndex() < 1) + if (actionTorrentDlOnDblClBox->currentIndex() < 1) return 0; return actionTorrentDlOnDblClBox->currentIndex(); } // Return action on double-click on a finished torrent set in options int options_imp::getActionOnDblClOnTorrentFn() const { - if(actionTorrentFnOnDblClBox->currentIndex() < 1) + if (actionTorrentFnOnDblClBox->currentIndex() < 1) return 0; return actionTorrentFnOnDblClBox->currentIndex(); } @@ -1079,12 +1079,12 @@ void options_imp::on_browseExportDirButton_clicked() { const QString export_path = misc::expandPath(textExportDir->text()); QDir exportDir(export_path); QString dir; - if(!export_path.isEmpty() && exportDir.exists()) { + if (!export_path.isEmpty() && exportDir.exists()) { dir = QFileDialog::getExistingDirectory(this, tr("Choose export directory"), exportDir.absolutePath()); } else { dir = QFileDialog::getExistingDirectory(this, tr("Choose export directory"), QDir::homePath()); } - if(!dir.isNull()){ + if (!dir.isNull()){ #if defined(Q_WS_WIN) || defined(Q_OS_OS2) dir.replace("/", "\\"); #endif @@ -1096,12 +1096,12 @@ void options_imp::on_browseFilterButton_clicked() { const QString filter_path = misc::expandPath(textFilterPath->text()); QDir filterDir(filter_path); QString ipfilter; - if(!filter_path.isEmpty() && filterDir.exists()) { + if (!filter_path.isEmpty() && filterDir.exists()) { ipfilter = QFileDialog::getOpenFileName(this, tr("Choose an ip filter file"), filterDir.absolutePath(), tr("Filters")+QString(" (*.dat *.p2p *.p2b)")); } else { ipfilter = QFileDialog::getOpenFileName(this, tr("Choose an ip filter file"), QDir::homePath(), tr("Filters")+QString(" (*.dat *.p2p *.p2b)")); } - if(!ipfilter.isNull()){ + if (!ipfilter.isNull()){ #if defined(Q_WS_WIN) || defined(Q_OS_OS2) ipfilter.replace("/", "\\"); #endif @@ -1114,12 +1114,12 @@ void options_imp::on_browseSaveDirButton_clicked(){ const QString save_path = misc::expandPath(textSavePath->text()); QDir saveDir(save_path); QString dir; - if(!save_path.isEmpty() && saveDir.exists()) { + if (!save_path.isEmpty() && saveDir.exists()) { dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), saveDir.absolutePath()); } else { dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), QDir::homePath()); } - if(!dir.isNull()){ + if (!dir.isNull()){ #if defined(Q_WS_WIN) || defined(Q_OS_OS2) dir.replace("/", "\\"); #endif @@ -1131,12 +1131,12 @@ void options_imp::on_browseTempDirButton_clicked(){ const QString temp_path = misc::expandPath(textTempPath->text()); QDir tempDir(temp_path); QString dir; - if(!temp_path.isEmpty() && tempDir.exists()) { + if (!temp_path.isEmpty() && tempDir.exists()) { dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), tempDir.absolutePath()); } else { dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), QDir::homePath()); } - if(!dir.isNull()){ + if (!dir.isNull()){ #if defined(Q_WS_WIN) || defined(Q_OS_OS2) dir.replace("/", "\\"); #endif @@ -1178,7 +1178,7 @@ void options_imp::showConnectionTab() void options_imp::on_btnWebUiCrt_clicked() { QString filename = QFileDialog::getOpenFileName(this, QString(), QString(), tr("SSL Certificate (*.crt *.pem)")); - if(filename.isNull()) + if (filename.isNull()) return; QFile file(filename); if (file.open(QIODevice::ReadOnly)) { @@ -1189,7 +1189,7 @@ void options_imp::on_btnWebUiCrt_clicked() { void options_imp::on_btnWebUiKey_clicked() { QString filename = QFileDialog::getOpenFileName(this, QString(), QString(), tr("SSL Key (*.key *.pem)")); - if(filename.isNull()) + if (filename.isNull()) return; QFile file(filename); if (file.open(QIODevice::ReadOnly)) { @@ -1203,7 +1203,7 @@ void options_imp::on_registerDNSBtn_clicked() { } void options_imp::on_IpFilterRefreshBtn_clicked() { - if(m_refreshingIpFilter) return; + if (m_refreshingIpFilter) return; m_refreshingIpFilter = true; // Updating program preferences Preferences pref; @@ -1218,7 +1218,7 @@ void options_imp::on_IpFilterRefreshBtn_clicked() { void options_imp::handleIPFilterParsed(bool error, int ruleCount) { setCursor(QCursor(Qt::ArrowCursor)); - if(error) { + if (error) { QMessageBox::warning(this, tr("Parsing error"), tr("Failed to parse the provided IP filter")); } else { QMessageBox::information(this, tr("Successfully refreshed"), tr("Successfuly parsed the provided IP filter: %1 rules were applied.", "%1 is a number").arg(ruleCount)); @@ -1240,7 +1240,7 @@ QString options_imp::languageToLocalizedString(QLocale::Language language, const case QLocale::Catalan: return QString::fromUtf8("Català"); case QLocale::Galician: return QString::fromUtf8("Galego"); case QLocale::Portuguese: { - if(country == "br") + if (country == "br") return QString::fromUtf8("Português brasileiro"); return QString::fromUtf8("Português"); } @@ -1266,7 +1266,7 @@ QString options_imp::languageToLocalizedString(QLocale::Language language, const case QLocale::Georgian: return QString::fromUtf8("ქართული"); case QLocale::Byelorussian: return QString::fromUtf8("Беларуская"); case QLocale::Chinese: { - if(country == "cn") + if (country == "cn") return QString::fromUtf8("中文 (简体)"); return QString::fromUtf8("中文 (繁體)"); } diff --git a/src/preferences/preferences.h b/src/preferences/preferences.h index c6acb3bbd..4c2c45a5c 100644 --- a/src/preferences/preferences.h +++ b/src/preferences/preferences.h @@ -280,7 +280,7 @@ public: void setExportDir(QString path) { path = path.trimmed(); - if(path.isEmpty()) + if (path.isEmpty()) path = QString(); setValue(QString::fromUtf8("Preferences/Downloads/TorrentExport"), path); } @@ -379,7 +379,7 @@ public: } void setGlobalDownloadLimit(int limit) { - if(limit <= 0) limit = -1; + if (limit <= 0) limit = -1; setValue("Preferences/Connection/GlobalDLLimit", limit); } @@ -388,31 +388,31 @@ public: } void setGlobalUploadLimit(int limit) { - if(limit <= 0) limit = -1; + if (limit <= 0) limit = -1; setValue("Preferences/Connection/GlobalUPLimit", limit); } int getAltGlobalDownloadLimit() const { int ret = value(QString::fromUtf8("Preferences/Connection/GlobalDLLimitAlt"), 10).toInt(); - if(ret <= 0) + if (ret <= 0) ret = 10; return ret; } void setAltGlobalDownloadLimit(int limit) { - if(limit <= 0) limit = -1; + if (limit <= 0) limit = -1; setValue("Preferences/Connection/GlobalDLLimitAlt", limit); } int getAltGlobalUploadLimit() const { int ret = value(QString::fromUtf8("Preferences/Connection/GlobalUPLimitAlt"), 10).toInt(); - if(ret <= 0) + if (ret <= 0) ret = 10; return ret; } void setAltGlobalUploadLimit(int limit) { - if(limit <= 0) limit = -1; + if (limit <= 0) limit = -1; setValue("Preferences/Connection/GlobalUPLimitAlt", limit); } @@ -523,7 +523,7 @@ public: } void setMaxConnecs(int val) { - if(val <= 0) val = -1; + if (val <= 0) val = -1; setValue(QString::fromUtf8("Preferences/Bittorrent/MaxConnecs"), val); } @@ -532,7 +532,7 @@ public: } void setMaxConnecsPerTorrent(int val) { - if(val <= 0) val = -1; + if (val <= 0) val = -1; setValue(QString::fromUtf8("Preferences/Bittorrent/MaxConnecsPerTorrent"), val); } @@ -541,7 +541,7 @@ public: } void setMaxUploadsPerTorrent(int val) { - if(val <= 0) val = -1; + if (val <= 0) val = -1; setValue(QString::fromUtf8("Preferences/Bittorrent/MaxUploadsPerTorrent"), val); } @@ -644,7 +644,7 @@ public: void banIP(const QString &ip) { QStringList banned_ips = value(QString::fromUtf8("Preferences/IPFilter/BannedIPs"), QStringList()).toStringList(); - if(!banned_ips.contains(ip)) { + if (!banned_ips.contains(ip)) { banned_ips << ip; setValue("Preferences/IPFilter/BannedIPs", banned_ips); } @@ -687,7 +687,7 @@ public: } void setMaxActiveDownloads(int val) { - if(val < 0) val = -1; + if (val < 0) val = -1; setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveDownloads"), val); } @@ -696,7 +696,7 @@ public: } void setMaxActiveUploads(int val) { - if(val < 0) val = -1; + if (val < 0) val = -1; setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveUploads"), val); } @@ -705,7 +705,7 @@ public: } void setMaxActiveTorrents(int val) { - if(val < 0) val = -1; + if (val < 0) val = -1; setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveTorrents"), val); } @@ -761,7 +761,7 @@ public: // Get current password md5 QString current_pass_md5 = getWebUiPassword(); // Check if password did not change - if(current_pass_md5 == new_password) return; + if (current_pass_md5 == new_password) return; // Encode to md5 and save QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(getWebUiUsername().toLocal8Bit()+":"+QBT_REALM+":"); @@ -772,7 +772,7 @@ public: QString getWebUiPassword() const { QString pass_ha1 = value("Preferences/WebUI/Password_ha1", "").toString(); - if(pass_ha1.isEmpty()) { + if (pass_ha1.isEmpty()) { QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(getWebUiUsername().toLocal8Bit()+":"+QBT_REALM+":"); md5.addData("adminadmin"); @@ -988,12 +988,12 @@ public: int getMaxHalfOpenConnections() const { const int val = value(QString::fromUtf8("Preferences/Connection/MaxHalfOpenConnec"), 50).toInt(); - if(val <= 0) return -1; + if (val <= 0) return -1; return val; } void setMaxHalfOpenConnections(int value) { - if(value <= 0) value = -1; + if (value <= 0) value = -1; setValue(QString::fromUtf8("Preferences/Connection/MaxHalfOpenConnec"), value); } @@ -1055,14 +1055,14 @@ public: void addTorrentLabel(const QString& label) { QStringList labels = value("TransferListFilters/customLabels").toStringList(); - if(!labels.contains(label)) + if (!labels.contains(label)) labels << label; setValue("TransferListFilters/customLabels", labels); } void removeTorrentLabel(const QString& label) { QStringList labels = value("TransferListFilters/customLabels").toStringList(); - if(labels.contains(label)) + if (labels.contains(label)) labels.removeOne(label); setValue("TransferListFilters/customLabels", labels); } @@ -1086,7 +1086,7 @@ public: const QString version = versions.takeLast(); qDebug("Detected possible Python v%s location", qPrintable(version)); QString path = reg_python.value(version+"/InstallPath/Default", "").toString().replace("/", "\\"); - if(!path.isEmpty() && QDir(path).exists("python.exe")) { + if (!path.isEmpty() && QDir(path).exists("python.exe")) { qDebug("Found python.exe at %s", qPrintable(path)); return path; } @@ -1094,8 +1094,8 @@ public: // Fallback: Detect python from default locations QStringList supported_versions; supported_versions << "32" << "31" << "30" << "27" << "26" << "25"; - foreach(const QString &v, supported_versions) { - if(QFile::exists("C:/Python"+v+"/python.exe")) { + foreach (const QString &v, supported_versions) { + if (QFile::exists("C:/Python"+v+"/python.exe")) { reg_python.setValue(v[0]+"."+v[1]+"/InstallPath/Default", QString("C:\\Python"+v)); return "C:\\Python"+v; } @@ -1113,7 +1113,7 @@ public: static bool isTorrentFileAssocSet() { QSettings settings("HKEY_CLASSES_ROOT", QIniSettings::NativeFormat); - if(settings.value(".torrent/Default").toString() != "qBittorrent") { + if (settings.value(".torrent/Default").toString() != "qBittorrent") { qDebug(".torrent != qBittorrent"); return false; } @@ -1121,15 +1121,15 @@ public: QString shell_command = settings.value("qBittorrent/shell/open/command/Default", "").toString(); qDebug("Shell command is: %s", qPrintable(shell_command)); QRegExp exe_reg("\"([^\"]+)\".*"); - if(exe_reg.indexIn(shell_command) < 0) + if (exe_reg.indexIn(shell_command) < 0) return false; QString assoc_exe = exe_reg.cap(1); qDebug("exe: %s", qPrintable(assoc_exe)); - if(assoc_exe.compare(qApp->applicationFilePath().replace("/", "\\"), Qt::CaseInsensitive) != 0) + if (assoc_exe.compare(qApp->applicationFilePath().replace("/", "\\"), Qt::CaseInsensitive) != 0) return false; // Icon const QString icon_str = "\""+qApp->applicationFilePath().replace("/", "\\")+"\",1"; - if(settings.value("qBittorrent/DefaultIcon/Default", icon_str).toString().compare(icon_str, Qt::CaseInsensitive) != 0) + if (settings.value("qBittorrent/DefaultIcon/Default", icon_str).toString().compare(icon_str, Qt::CaseInsensitive) != 0) return false; return true; @@ -1141,11 +1141,11 @@ public: // Check magnet link assoc QRegExp exe_reg("\"([^\"]+)\".*"); QString shell_command = settings.value("Magnet/shell/open/command/Default", "").toString(); - if(exe_reg.indexIn(shell_command) < 0) + if (exe_reg.indexIn(shell_command) < 0) return false; QString assoc_exe = exe_reg.cap(1); qDebug("exe: %s", qPrintable(assoc_exe)); - if(assoc_exe.compare(qApp->applicationFilePath().replace("/", "\\"), Qt::CaseInsensitive) != 0) + if (assoc_exe.compare(qApp->applicationFilePath().replace("/", "\\"), Qt::CaseInsensitive) != 0) return false; return true; } diff --git a/src/previewselect.cpp b/src/previewselect.cpp index c249712c6..e14cc4473 100644 --- a/src/previewselect.cpp +++ b/src/previewselect.cpp @@ -56,10 +56,10 @@ PreviewSelect::PreviewSelect(QWidget* parent, QTorrentHandle h): QDialog(parent) std::vector fp; h.file_progress(fp); unsigned int nbFiles = h.num_files(); - for(unsigned int i=0; irowCount(); previewListModel->insertRow(row); previewListModel->setData(previewListModel->index(row, NAME), QVariant(fileName)); @@ -71,12 +71,12 @@ PreviewSelect::PreviewSelect(QWidget* parent, QTorrentHandle h): QDialog(parent) previewList->selectionModel()->select(previewListModel->index(0, NAME), QItemSelectionModel::Select); previewList->selectionModel()->select(previewListModel->index(0, SIZE), QItemSelectionModel::Select); previewList->selectionModel()->select(previewListModel->index(0, PROGRESS), QItemSelectionModel::Select); - if(!previewListModel->rowCount()){ + if (!previewListModel->rowCount()){ QMessageBox::critical(0, tr("Preview impossible"), tr("Sorry, we can't preview this file")); close(); } connect(this, SIGNAL(readyToPreviewFile(QString)), parent, SLOT(previewFile(QString))); - if(previewListModel->rowCount() == 1){ + if (previewListModel->rowCount() == 1){ qDebug("Torrent file only contains one file, no need to display selection dialog before preview"); // Only one file : no choice on_previewButton_clicked(); @@ -95,15 +95,15 @@ PreviewSelect::~PreviewSelect(){ void PreviewSelect::on_previewButton_clicked(){ QModelIndex index; QModelIndexList selectedIndexes = previewList->selectionModel()->selectedRows(NAME); - if(selectedIndexes.size() == 0) return; + if (selectedIndexes.size() == 0) return; // Flush data h.flush_cache(); QString path; - foreach(index, selectedIndexes){ + foreach (index, selectedIndexes){ path = h.absolute_files_path().at(indexes.at(index.row())); // File - if(QFile::exists(path)){ + if (QFile::exists(path)){ emit readyToPreviewFile(path); } else { QMessageBox::critical(0, tr("Preview impossible"), tr("Sorry, we can't preview this file")); diff --git a/src/programupdater.cpp b/src/programupdater.cpp index 787551911..5023a26bd 100644 --- a/src/programupdater.cpp +++ b/src/programupdater.cpp @@ -55,7 +55,7 @@ ProgramUpdater::ProgramUpdater(QObject *parent) : mp_manager = new QNetworkAccessManager(this); Preferences pref; // Proxy support - if(pref.isProxyEnabled()) { + if (pref.isProxyEnabled()) { QNetworkProxy proxy; switch(pref.getProxyType()) { case Proxy::SOCKS4: @@ -69,7 +69,7 @@ ProgramUpdater::ProgramUpdater(QObject *parent) : proxy.setHostName(pref.getProxyIp()); proxy.setPort(pref.getProxyPort()); // Proxy authentication - if(pref.isProxyAuthEnabled()) { + if (pref.isProxyAuthEnabled()) { proxy.setUser(pref.getProxyUsername()); proxy.setPassword(pref.getProxyPassword()); } @@ -101,7 +101,7 @@ void ProgramUpdater::rssDownloadFinished(QNetworkReply *reply) disconnect(mp_manager, 0, this, 0); qDebug("Finished downloading the new qBittorrent updates RSS"); QString new_version; - if(!reply->error()) { + if (!reply->error()) { qDebug("No download error, good."); QXmlStreamReader xml(reply); QString item_title; @@ -117,16 +117,16 @@ void ProgramUpdater::rssDownloadFinished(QNetworkReply *reply) in_item = true; } } else if (xml.isEndElement()) { - if(in_item && xml.name() == "title") { + if (in_item && xml.name() == "title") { in_title = false; const QString ext = misc::file_extension(item_title).toUpper(); qDebug("Found an update with file extension: %s", qPrintable(ext)); - if(ext == FILE_EXT) { + if (ext == FILE_EXT) { qDebug("The last update available is %s", qPrintable(item_title)); new_version = extractVersionNumber(item_title); - if(!new_version.isEmpty()) { + if (!new_version.isEmpty()) { qDebug("Detected version is %s", qPrintable(new_version)); - if(isVersionMoreRecent(new_version)) + if (isVersionMoreRecent(new_version)) setUpdateUrl(item_title); } break; @@ -135,7 +135,7 @@ void ProgramUpdater::rssDownloadFinished(QNetworkReply *reply) in_item = false; } } else if (xml.isCharacters() && !xml.isWhitespace()) { - if(in_item && in_title) + if (in_item && in_title) item_title += xml.text().toString(); } } @@ -161,14 +161,14 @@ void ProgramUpdater::updateProgram() // Disconnect SIGNAL/SLOT disconnect(mp_manager, 0, this, 0); // Process the download - if(!reply->error()) { + if (!reply->error()) { // Save the file const QString installer_path = QDir::temp().absoluteFilePath("qbittorrent_update."+FILE_EXT.toLower()); QFile update_installer(installer_path); - if(update_installer.exists()) { + if (update_installer.exists()) { update_installer.remove(); } - if(update_installer.open(QIODevice::WriteOnly)) { + if (update_installer.open(QIODevice::WriteOnly)) { update_installer.write(reply->readAll()); reply->close(); update_installer.close(); diff --git a/src/properties/peeraddition.h b/src/properties/peeraddition.h index 6f0b1f0f8..8232f9d6e 100644 --- a/src/properties/peeraddition.h +++ b/src/properties/peeraddition.h @@ -59,7 +59,7 @@ public: QString getIP() const { QHostAddress ip(lineIP->text()); - if(!ip.isNull()) { + if (!ip.isNull()) { // QHostAddress::toString() cleans up the IP for libtorrent return ip.toString(); } @@ -73,11 +73,11 @@ public: static libtorrent::asio::ip::tcp::endpoint askForPeerEndpoint() { libtorrent::asio::ip::tcp::endpoint ep; PeerAdditionDlg dlg; - if(dlg.exec() == QDialog::Accepted) { + if (dlg.exec() == QDialog::Accepted) { QString ip = dlg.getIP(); boost::system::error_code ec; libtorrent::address addr = libtorrent::address::from_string(qPrintable(ip), ec); - if(ec) { + if (ec) { qDebug("Unable to parse the provided IP: %s", qPrintable(ip)); return ep; } @@ -90,7 +90,7 @@ public: protected slots: void validateInput() { - if(getIP().isEmpty()) { + if (getIP().isEmpty()) { QMessageBox::warning(this, tr("Invalid IP"), tr("The IP you provided is invalid."), QMessageBox::Ok); diff --git a/src/properties/peerlistwidget.cpp b/src/properties/peerlistwidget.cpp index 570bf5f24..866569722 100644 --- a/src/properties/peerlistwidget.cpp +++ b/src/properties/peerlistwidget.cpp @@ -92,30 +92,30 @@ PeerListWidget::~PeerListWidget() { delete proxyModel; delete listModel; delete listDelegate; - if(resolver) + if (resolver) delete resolver; } void PeerListWidget::updatePeerHostNameResolutionState() { - if(Preferences().resolvePeerHostNames()) { - if(!resolver) { + if (Preferences().resolvePeerHostNames()) { + if (!resolver) { resolver = new ReverseResolution(this); connect(resolver, SIGNAL(ip_resolved(QString,QString)), this, SLOT(handleResolved(QString,QString))); loadPeers(properties->getCurrentTorrent(), true); } } else { - if(resolver) { + if (resolver) { delete resolver; } } } void PeerListWidget::updatePeerCountryResolutionState() { - if(Preferences().resolvePeerCountries() != display_flags) { + if (Preferences().resolvePeerCountries() != display_flags) { display_flags = !display_flags; - if(display_flags) { + if (display_flags) { const QTorrentHandle h = properties->getCurrentTorrent(); - if(!h.is_valid()) return; + if (!h.is_valid()) return; loadPeers(h); } } @@ -125,17 +125,17 @@ void PeerListWidget::showPeerListMenu(QPoint) { QMenu menu; bool empty_menu = true; QTorrentHandle h = properties->getCurrentTorrent(); - if(!h.is_valid()) return; + if (!h.is_valid()) return; QModelIndexList selectedIndexes = selectionModel()->selectedRows(); QStringList selectedPeerIPs; - foreach(const QModelIndex &index, selectedIndexes) { + foreach (const QModelIndex &index, selectedIndexes) { int row = proxyModel->mapToSource(index).row(); QString myip = listModel->data(listModel->index(row, PeerListDelegate::IP_HIDDEN)).toString(); selectedPeerIPs << myip; } // Add Peer Action QAction *addPeerAct = 0; - if(!h.is_queued() && !h.is_checking()) { + if (!h.is_queued() && !h.is_checking()) { addPeerAct = menu.addAction(IconProvider::instance()->getIcon("user-group-new"), tr("Add a new peer...")); empty_menu = false; } @@ -144,7 +144,7 @@ void PeerListWidget::showPeerListMenu(QPoint) { QAction *dlLimitAct = 0; QAction *banAct = 0; QAction *copyIPAct = 0; - if(!selectedPeerIPs.isEmpty()) { + if (!selectedPeerIPs.isEmpty()) { copyIPAct = menu.addAction(IconProvider::instance()->getIcon("edit-copy"), tr("Copy IP")); menu.addSeparator(); dlLimitAct = menu.addAction(QIcon(":/Icons/skin/download.png"), tr("Limit download rate...")); @@ -153,12 +153,12 @@ void PeerListWidget::showPeerListMenu(QPoint) { banAct = menu.addAction(IconProvider::instance()->getIcon("user-group-delete"), tr("Ban peer permanently")); empty_menu = false; } - if(empty_menu) return; + if (empty_menu) return; QAction *act = menu.exec(QCursor::pos()); - if(act == 0) return; - if(act == addPeerAct) { + if (act == 0) return; + if (act == addPeerAct) { libtorrent::asio::ip::tcp::endpoint ep = PeerAdditionDlg::askForPeerEndpoint(); - if(ep != libtorrent::asio::ip::tcp::endpoint()) { + if (ep != libtorrent::asio::ip::tcp::endpoint()) { try { h.connect_peer(ep); QMessageBox::information(0, tr("Peer addition"), tr("The peer was added to this torrent.")); @@ -170,19 +170,19 @@ void PeerListWidget::showPeerListMenu(QPoint) { } return; } - if(act == upLimitAct) { + if (act == upLimitAct) { limitUpRateSelectedPeers(selectedPeerIPs); return; } - if(act == dlLimitAct) { + if (act == dlLimitAct) { limitDlRateSelectedPeers(selectedPeerIPs); return; } - if(act == banAct) { + if (act == banAct) { banSelectedPeers(selectedPeerIPs); return; } - if(act == copyIPAct) { + if (act == copyIPAct) { #if defined(Q_WS_WIN) || defined(Q_OS_OS2) QApplication::clipboard()->setText(selectedPeerIPs.join("\r\n")); #else @@ -196,8 +196,8 @@ void PeerListWidget::banSelectedPeers(QStringList peer_ips) { int ret = QMessageBox::question(this, tr("Are you sure? -- qBittorrent"), tr("Are you sure you want to ban permanently the selected peers?"), tr("&Yes"), tr("&No"), QString(), 0, 1); - if(ret) return; - foreach(const QString &ip, peer_ips) { + if (ret) return; + foreach (const QString &ip, peer_ips) { qDebug("Banning peer %s...", ip.toLocal8Bit().data()); QBtSession::instance()->addConsoleMessage(tr("Manually banning peer %1...").arg(ip)); QBtSession::instance()->banIP(ip); @@ -207,22 +207,22 @@ void PeerListWidget::banSelectedPeers(QStringList peer_ips) { } void PeerListWidget::limitUpRateSelectedPeers(QStringList peer_ips) { - if(peer_ips.empty()) return; + if (peer_ips.empty()) return; QTorrentHandle h = properties->getCurrentTorrent(); - if(!h.is_valid()) return; + if (!h.is_valid()) return; bool ok=false; int cur_limit = -1; #if LIBTORRENT_VERSION_MINOR > 15 libtorrent::asio::ip::tcp::endpoint first_ep = peerEndpoints.value(peer_ips.first(), libtorrent::asio::ip::tcp::endpoint()); - if(first_ep != libtorrent::asio::ip::tcp::endpoint()) + if (first_ep != libtorrent::asio::ip::tcp::endpoint()) cur_limit = h.get_peer_upload_limit(first_ep); #endif long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Upload rate limiting"), cur_limit, Preferences().getGlobalUploadLimit()*1024.); - if(!ok) return; - foreach(const QString &ip, peer_ips) { + if (!ok) return; + foreach (const QString &ip, peer_ips) { libtorrent::asio::ip::tcp::endpoint ep = peerEndpoints.value(ip, libtorrent::asio::ip::tcp::endpoint()); - if(ep != libtorrent::asio::ip::tcp::endpoint()) { + if (ep != libtorrent::asio::ip::tcp::endpoint()) { qDebug("Settings Upload limit of %.1f Kb/s to peer %s", limit/1024., ip.toLocal8Bit().data()); try { h.set_peer_upload_limit(ep, limit); @@ -237,20 +237,20 @@ void PeerListWidget::limitUpRateSelectedPeers(QStringList peer_ips) { void PeerListWidget::limitDlRateSelectedPeers(QStringList peer_ips) { QTorrentHandle h = properties->getCurrentTorrent(); - if(!h.is_valid()) return; + if (!h.is_valid()) return; bool ok=false; int cur_limit = -1; #if LIBTORRENT_VERSION_MINOR > 15 libtorrent::asio::ip::tcp::endpoint first_ep = peerEndpoints.value(peer_ips.first(), libtorrent::asio::ip::tcp::endpoint()); - if(first_ep != libtorrent::asio::ip::tcp::endpoint()) + if (first_ep != libtorrent::asio::ip::tcp::endpoint()) cur_limit = h.get_peer_download_limit(first_ep); #endif long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Download rate limiting"), cur_limit, Preferences().getGlobalDownloadLimit()*1024.); - if(!ok) return; - foreach(const QString &ip, peer_ips) { + if (!ok) return; + foreach (const QString &ip, peer_ips) { libtorrent::asio::ip::tcp::endpoint ep = peerEndpoints.value(ip, libtorrent::asio::ip::tcp::endpoint()); - if(ep != libtorrent::asio::ip::tcp::endpoint()) { + if (ep != libtorrent::asio::ip::tcp::endpoint()) { qDebug("Settings Download limit of %.1f Kb/s to peer %s", limit/1024., ip.toLocal8Bit().data()); try { h.set_peer_download_limit(ep, limit); @@ -270,7 +270,7 @@ void PeerListWidget::clear() { peerEndpoints.clear(); missingFlags.clear(); int nbrows = listModel->rowCount(); - if(nbrows > 0) { + if (nbrows > 0) { qDebug("Cleared %d peers", nbrows); listModel->removeRows(0, nbrows); } @@ -287,24 +287,24 @@ void PeerListWidget::saveSettings() const { } void PeerListWidget::loadPeers(const QTorrentHandle &h, bool force_hostname_resolution) { - if(!h.is_valid()) return; + if (!h.is_valid()) return; boost::system::error_code ec; std::vector peers; h.get_peer_info(peers); std::vector::iterator itr; QSet old_peers_set = peerItems.keys().toSet(); - for(itr = peers.begin(); itr != peers.end(); itr++) { + for (itr = peers.begin(); itr != peers.end(); itr++) { peer_info peer = *itr; QString peer_ip = misc::toQString(peer.ip.address().to_string(ec)); - if(ec) continue; - if(peerItems.contains(peer_ip)) { + if (ec) continue; + if (peerItems.contains(peer_ip)) { // Update existing peer updatePeer(peer_ip, peer); old_peers_set.remove(peer_ip); - if(force_hostname_resolution) { - if(resolver) { + if (force_hostname_resolution) { + if (resolver) { const QString host = resolver->getHostFromCache(peer.ip); - if(host.isNull()) { + if (host.isNull()) { resolver->resolve(peer.ip); } else { qDebug("Got peer IP from cache"); @@ -334,20 +334,20 @@ QStandardItem* PeerListWidget::addPeer(QString ip, peer_info peer) { // Adding Peer to peer list listModel->insertRow(row); QString host; - if(resolver) { + if (resolver) { host = resolver->getHostFromCache(peer.ip); } - if(host.isNull()) + if (host.isNull()) listModel->setData(listModel->index(row, PeerListDelegate::IP), ip); else listModel->setData(listModel->index(row, PeerListDelegate::IP), host); listModel->setData(listModel->index(row, PeerListDelegate::IP_HIDDEN), ip); // Resolve peer host name is asked - if(resolver && host.isNull()) + if (resolver && host.isNull()) resolver->resolve(peer.ip); - if(display_flags) { + if (display_flags) { const QIcon ico = GeoIPManager::CountryISOCodeToIcon(peer.country); - if(!ico.isNull()) { + if (!ico.isNull()) { listModel->setData(listModel->index(row, PeerListDelegate::IP), ico, Qt::DecorationRole); const QString country_name = GeoIPManager::CountryISOCodeToName(peer.country); listModel->setData(listModel->index(row, PeerListDelegate::IP), country_name, Qt::ToolTipRole); @@ -368,9 +368,9 @@ QStandardItem* PeerListWidget::addPeer(QString ip, peer_info peer) { void PeerListWidget::updatePeer(QString ip, peer_info peer) { QStandardItem *item = peerItems.value(ip); int row = item->row(); - if(display_flags) { + if (display_flags) { const QIcon ico = GeoIPManager::CountryISOCodeToIcon(peer.country); - if(!ico.isNull()) { + if (!ico.isNull()) { listModel->setData(listModel->index(row, PeerListDelegate::IP), ico, Qt::DecorationRole); const QString country_name = GeoIPManager::CountryISOCodeToName(peer.country); listModel->setData(listModel->index(row, PeerListDelegate::IP), country_name, Qt::ToolTipRole); @@ -388,7 +388,7 @@ void PeerListWidget::updatePeer(QString ip, peer_info peer) { void PeerListWidget::handleResolved(const QString &ip, const QString &hostname) { QStandardItem *item = peerItems.value(ip, 0); - if(item) { + if (item) { qDebug("Resolved %s -> %s", qPrintable(ip), qPrintable(hostname)); item->setData(hostname, Qt::DisplayRole); //listModel->setData(listModel->index(item->row(), IP), hostname, Qt::DisplayRole); @@ -397,7 +397,7 @@ void PeerListWidget::handleResolved(const QString &ip, const QString &hostname) void PeerListWidget::handleSortColumnChanged(int col) { - if(col == 0) { + if (col == 0) { qDebug("Sorting by decoration"); proxyModel->setSortRole(Qt::ToolTipRole); } else { diff --git a/src/properties/propertieswidget.cpp b/src/properties/propertieswidget.cpp index 09468cc03..9be0fc8e3 100644 --- a/src/properties/propertieswidget.cpp +++ b/src/properties/propertieswidget.cpp @@ -140,7 +140,7 @@ void PropertiesWidget::showPiecesAvailability(bool show) { avail_pieces_lbl->setVisible(show); pieces_availability->setVisible(show); avail_average_lbl->setVisible(show); - if(show || (!show && !downloaded_pieces->isVisible())) + if (show || (!show && !downloaded_pieces->isVisible())) line_2->setVisible(show); } @@ -148,12 +148,12 @@ void PropertiesWidget::showPiecesDownloaded(bool show) { downloaded_pieces_lbl->setVisible(show); downloaded_pieces->setVisible(show); progress_lbl->setVisible(show); - if(show || (!show && !pieces_availability->isVisible())) + if (show || (!show && !pieces_availability->isVisible())) line_2->setVisible(show); } void PropertiesWidget::setVisibility(bool visible) { - if(!visible && state == VISIBLE) { + if (!visible && state == VISIBLE) { QSplitter *hSplitter = static_cast(parentWidget()); stackedProperties->setVisible(false); slideSizes = hSplitter->sizes(); @@ -165,7 +165,7 @@ void PropertiesWidget::setVisibility(bool visible) { return; } - if(visible && state == REDUCED) { + if (visible && state == REDUCED) { stackedProperties->setVisible(true); QSplitter *hSplitter = static_cast(parentWidget()); hSplitter->handle(1)->setDisabled(false); @@ -212,13 +212,13 @@ QTorrentHandle PropertiesWidget::getCurrentTorrent() const { } void PropertiesWidget::updateSavePath(const QTorrentHandle& _h) { - if(h.is_valid() && h == _h) { + if (h.is_valid() && h == _h) { QString p; - if(h.has_metadata() && h.num_files() == 1) { + if (h.has_metadata() && h.num_files() == 1) { p = h.firstFileSavePath(); } else { p = TorrentPersistentData::getSavePath(h.hash()); - if(p.isEmpty()) + if (p.isEmpty()) p = h.save_path(); } #if defined(Q_WS_WIN) || defined(Q_OS_OS2) @@ -229,7 +229,7 @@ void PropertiesWidget::updateSavePath(const QTorrentHandle& _h) { } void PropertiesWidget::updateTorrentInfos(const QTorrentHandle& _h) { - if(h.is_valid() && h == _h) { + if (h.is_valid() && h == _h) { loadTorrentInfos(h); } } @@ -237,7 +237,7 @@ void PropertiesWidget::updateTorrentInfos(const QTorrentHandle& _h) { void PropertiesWidget::loadTorrentInfos(const QTorrentHandle &_h) { clear(); h = _h; - if(!h.is_valid()) { + if (!h.is_valid()) { clear(); return; } @@ -250,7 +250,7 @@ void PropertiesWidget::loadTorrentInfos(const QTorrentHandle &_h) { // Hash hash_lbl->setText(h.hash()); PropListModel->model()->clear(); - if(h.has_metadata()) { + if (h.has_metadata()) { // Creation date lbl_creationDate->setText(h.creation_date()); // Pieces size @@ -273,7 +273,7 @@ void PropertiesWidget::readSettings() { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); // Restore splitter sizes QStringList sizes_str = settings.value(QString::fromUtf8("TorrentProperties/SplitterSizes"), QString()).toString().split(","); - if(sizes_str.size() == 2) { + if (sizes_str.size() == 2) { slideSizes << sizes_str.first().toInt(); slideSizes << sizes_str.last().toInt(); QSplitter *hSplitter = static_cast(parentWidget()); @@ -284,7 +284,7 @@ void PropertiesWidget::readSettings() { } const int current_tab = settings.value("TorrentProperties/CurrentTab", -1).toInt(); m_tabBar->setCurrentIndex(current_tab); - if(!settings.value("TorrentProperties/Visible", false).toBool()) { + if (!settings.value("TorrentProperties/Visible", false).toBool()) { setVisibility(false); } } @@ -295,12 +295,12 @@ void PropertiesWidget::saveSettings() { // Splitter sizes QSplitter *hSplitter = static_cast(parentWidget()); QList sizes; - if(state == VISIBLE) + if (state == VISIBLE) sizes = hSplitter->sizes(); else sizes = slideSizes; qDebug("Sizes: %d", sizes.size()); - if(sizes.size() == 2) { + if (sizes.size() == 2) { settings.setValue(QString::fromUtf8("TorrentProperties/SplitterSizes"), QVariant(QString::number(sizes.first())+','+QString::number(sizes.last()))); } settings.setValue("TorrentProperties/FilesListState", filesList->header()->saveState()); @@ -316,27 +316,27 @@ void PropertiesWidget::reloadPreferences() { void PropertiesWidget::loadDynamicData() { // Refresh only if the torrent handle is valid and if visible - if(!h.is_valid() || main_window->getCurrentTabWidget() != transferList || state != VISIBLE) return; + if (!h.is_valid() || main_window->getCurrentTabWidget() != transferList || state != VISIBLE) return; try { // Transfer infos - if(stackedProperties->currentIndex() == PropTabBar::MAIN_TAB) { + if (stackedProperties->currentIndex() == PropTabBar::MAIN_TAB) { wasted->setText(misc::friendlyUnit(h.total_failed_bytes()+h.total_redundant_bytes())); upTotal->setText(misc::friendlyUnit(h.all_time_upload()) + " ("+misc::friendlyUnit(h.total_payload_upload())+" "+tr("this session")+")"); dlTotal->setText(misc::friendlyUnit(h.all_time_download()) + " ("+misc::friendlyUnit(h.total_payload_download())+" "+tr("this session")+")"); - if(h.upload_limit() <= 0) + if (h.upload_limit() <= 0) lbl_uplimit->setText(QString::fromUtf8("∞")); else lbl_uplimit->setText(misc::friendlyUnit(h.upload_limit())+tr("/s", "/second (i.e. per second)")); - if(h.download_limit() <= 0) + if (h.download_limit() <= 0) lbl_dllimit->setText(QString::fromUtf8("∞")); else lbl_dllimit->setText(misc::friendlyUnit(h.download_limit())+tr("/s", "/second (i.e. per second)")); QString elapsed_txt = misc::userFriendlyDuration(h.active_time()); - if(h.is_seed()) { + if (h.is_seed()) { elapsed_txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(misc::userFriendlyDuration(h.seeding_time()))+")"; } lbl_elapsed->setText(elapsed_txt); - if(h.connections_limit() > 0) + if (h.connections_limit() > 0) lbl_connections->setText(QString::number(h.num_connections())+" ("+tr("%1 max", "e.g. 10 max").arg(QString::number(h.connections_limit()))+")"); else lbl_connections->setText(QString::number(h.num_connections())); @@ -344,18 +344,18 @@ void PropertiesWidget::loadDynamicData() { reannounce_lbl->setText(h.next_announce()); // Update ratio info const qreal ratio = QBtSession::instance()->getRealRatio(h.hash()); - if(ratio > QBtSession::MAX_RATIO) + if (ratio > QBtSession::MAX_RATIO) shareRatio->setText(QString::fromUtf8("∞")); else shareRatio->setText(QString(QByteArray::number(ratio, 'f', 2))); - if(!h.is_seed()) { + if (!h.is_seed()) { showPiecesDownloaded(true); // Downloaded pieces bitfield bf(h.get_torrent_info().num_pieces(), 0); h.downloading_pieces(bf); downloaded_pieces->setProgress(h.pieces(), bf); // Pieces availability - if(h.has_metadata() && !h.is_paused() && !h.is_queued() && !h.is_checking()) { + if (h.has_metadata() && !h.is_paused() && !h.is_queued() && !h.is_checking()) { showPiecesAvailability(true); std::vector avail; h.piece_availability(avail); @@ -366,7 +366,7 @@ void PropertiesWidget::loadDynamicData() { } // Progress qreal progress = h.progress()*100.; - if(progress > 99.94 && progress < 100.) + if (progress > 99.94 && progress < 100.) progress = 99.9; progress_lbl->setText(QString::number(progress, 'f', 1)+"%"); } else { @@ -375,19 +375,19 @@ void PropertiesWidget::loadDynamicData() { } return; } - if(stackedProperties->currentIndex() == PropTabBar::TRACKERS_TAB) { + if (stackedProperties->currentIndex() == PropTabBar::TRACKERS_TAB) { // Trackers trackerList->loadTrackers(); return; } - if(stackedProperties->currentIndex() == PropTabBar::PEERS_TAB) { + if (stackedProperties->currentIndex() == PropTabBar::PEERS_TAB) { // Load peers peersList->loadPeers(h); return; } - if(stackedProperties->currentIndex() == PropTabBar::FILES_TAB) { + if (stackedProperties->currentIndex() == PropTabBar::FILES_TAB) { // Files progress - if(h.is_valid() && h.has_metadata()) { + if (h.is_valid() && h.has_metadata()) { qDebug("Updating priorities in files tab"); filesList->setUpdatesEnabled(false); std::vector fp; @@ -405,16 +405,16 @@ void PropertiesWidget::loadUrlSeeds(){ qDebug("Loading URL seeds"); const QStringList hc_seeds = h.url_seeds(); // Add url seeds - foreach(const QString &hc_seed, hc_seeds){ + foreach (const QString &hc_seed, hc_seeds){ qDebug("Loading URL seed: %s", qPrintable(hc_seed)); new QListWidgetItem(hc_seed, listWebSeeds); } } void PropertiesWidget::openDoubleClickedFile(QModelIndex index) { - if(!index.isValid()) return; - if(!h.is_valid() || !h.has_metadata()) return; - if(PropListModel->getType(index) == TorrentFileItem::TFILE) { + if (!index.isValid()) return; + if (!h.is_valid() || !h.has_metadata()) return; + if (PropListModel->getType(index) == TorrentFileItem::TFILE) { int i = PropListModel->getFileIndex(index); const QDir saveDir(h.save_path()); const QString filename = h.filepath_at(i); @@ -422,7 +422,7 @@ void PropertiesWidget::openDoubleClickedFile(QModelIndex index) { qDebug("Trying to open file at %s", qPrintable(file_path)); // Flush data h.flush_cache(); - if(QFile::exists(file_path)) { + if (QFile::exists(file_path)) { QDesktopServices::openUrl(QUrl::fromLocalFile(file_path)); } else { QMessageBox::warning(this, tr("I/O Error"), tr("This file does not exist yet.")); @@ -442,7 +442,7 @@ void PropertiesWidget::openDoubleClickedFile(QModelIndex index) { qDebug("Trying to open folder at %s", qPrintable(file_path)); // Flush data h.flush_cache(); - if(QFile::exists(file_path)) { + if (QFile::exists(file_path)) { QDesktopServices::openUrl(QUrl::fromLocalFile(file_path)); } else { QMessageBox::warning(this, tr("I/O Error"), tr("This folder does not exist yet.")); @@ -454,15 +454,15 @@ void PropertiesWidget::displayFilesListMenu(const QPoint&){ QMenu myFilesLlistMenu; QModelIndexList selectedRows = filesList->selectionModel()->selectedRows(0); QAction *actRename = 0; - if(selectedRows.size() == 1) { + if (selectedRows.size() == 1) { actRename = myFilesLlistMenu.addAction(IconProvider::instance()->getIcon("edit-rename"), tr("Rename...")); myFilesLlistMenu.addSeparator(); } QMenu subMenu; #if LIBTORRENT_VERSION_MINOR > 15 - if(!h.status(0x0).is_seeding) { + if (!h.status(0x0).is_seeding) { #else - if(!static_cast(h).is_seed()) { + if (!static_cast(h).is_seed()) { #endif subMenu.setTitle(tr("Priority")); subMenu.addAction(actionNot_downloaded); @@ -473,24 +473,24 @@ void PropertiesWidget::displayFilesListMenu(const QPoint&){ } // Call menu const QAction *act = myFilesLlistMenu.exec(QCursor::pos()); - if(act) { - if(act == actRename) { + if (act) { + if (act == actRename) { renameSelectedFile(); } else { int prio = 1; - if(act == actionHigh) { + if (act == actionHigh) { prio = prio::HIGH; } else { - if(act == actionMaximum) { + if (act == actionMaximum) { prio = prio::MAXIMUM; } else { - if(act == actionNot_downloaded) { + if (act == actionNot_downloaded) { prio = prio::IGNORED; } } } qDebug("Setting files priority"); - foreach(QModelIndex index, selectedRows) { + foreach (QModelIndex index, selectedRows) { qDebug("Setting priority(%d) for file at row %d", prio, index.row()); PropListModel->setData(PropListModel->index(index.row(), PRIORITY, index.parent()), prio); } @@ -510,36 +510,36 @@ void PropertiesWidget::renameSelectedFile() { tr("New name:"), QLineEdit::Normal, index.data().toString(), &ok); if (ok && !new_name_last.isEmpty()) { - if(!misc::isValidFileSystemName(new_name_last)) { + if (!misc::isValidFileSystemName(new_name_last)) { QMessageBox::warning(this, tr("The file could not be renamed"), tr("This file name contains forbidden characters, please choose a different one."), QMessageBox::Ok); return; } - if(PropListModel->getType(index) == TorrentFileItem::TFILE) { + if (PropListModel->getType(index) == TorrentFileItem::TFILE) { // File renaming const int file_index = PropListModel->getFileIndex(index); - if(!h.is_valid() || !h.has_metadata()) return; + if (!h.is_valid() || !h.has_metadata()) return; QString old_name = h.filepath_at(file_index).replace("\\", "/"); - if(old_name.endsWith(".!qB") && !new_name_last.endsWith(".!qB")) { + if (old_name.endsWith(".!qB") && !new_name_last.endsWith(".!qB")) { new_name_last += ".!qB"; } QStringList path_items = old_name.split("/"); path_items.removeLast(); path_items << new_name_last; QString new_name = path_items.join("/"); - if(old_name == new_name) { + if (old_name == new_name) { qDebug("Name did not change"); return; } new_name = QDir::cleanPath(new_name); // Check if that name is already used - for(int i=0; isetData(index, new_name_last); } else { @@ -570,15 +570,15 @@ void PropertiesWidget::renameSelectedFile() { path_items.removeLast(); path_items << new_name_last; QString new_path = path_items.join("/"); - if(!new_path.endsWith("/")) new_path += "/"; + if (!new_path.endsWith("/")) new_path += "/"; // Check for overwriting const int num_files = h.num_files(); - for(int i=0; isetData(index, new_name_last); // Remove old folder @@ -622,9 +622,9 @@ void PropertiesWidget::askWebSeed(){ const QString url_seed = QInputDialog::getText(this, tr("New url seed", "New HTTP source"), tr("New url seed:"), QLineEdit::Normal, QString::fromUtf8("http://www."), &ok); - if(!ok) return; + if (!ok) return; qDebug("Adding %s web seed", qPrintable(url_seed)); - if(!listWebSeeds->findItems(url_seed, Qt::MatchFixedString).empty()) { + if (!listWebSeeds->findItems(url_seed, Qt::MatchFixedString).empty()) { QMessageBox::warning(this, tr("qBittorrent"), tr("This url seed is already in the list."), QMessageBox::Ok); @@ -638,12 +638,12 @@ void PropertiesWidget::askWebSeed(){ void PropertiesWidget::deleteSelectedUrlSeeds(){ const QList selectedItems = listWebSeeds->selectedItems(); bool change = false; - foreach(const QListWidgetItem *item, selectedItems){ + foreach (const QListWidgetItem *item, selectedItems){ QString url_seed = item->text(); h.remove_url_seed(url_seed); change = true; } - if(change){ + if (change){ // Refresh list loadUrlSeeds(); } @@ -658,45 +658,45 @@ bool PropertiesWidget::applyPriorities() { qDebug("prioritize files: %d", priorities[0]); h.prioritize_files(priorities); // Restore first/last piece first option if necessary - if(first_last_piece_first) + if (first_last_piece_first) h.prioritize_first_last_piece(true); return true; } void PropertiesWidget::on_changeSavePathButton_clicked() { - if(!h.is_valid()) return; + if (!h.is_valid()) return; QString new_path; - if(h.has_metadata() && h.num_files() == 1) { + if (h.has_metadata() && h.num_files() == 1) { new_path = QFileDialog::getSaveFileName(this, tr("Choose save path"), h.firstFileSavePath()); } else { const QDir saveDir(TorrentPersistentData::getSavePath(h.hash())); new_path = QFileDialog::getExistingDirectory(this, tr("Choose save path"), saveDir.absolutePath(), QFileDialog::DontConfirmOverwrite|QFileDialog::ShowDirsOnly|QFileDialog::HideNameFilterDetails); } - if(!new_path.isEmpty()){ + if (!new_path.isEmpty()){ // Check if savePath exists QString save_path_dir = new_path.replace("\\", "/"); QString new_file_name; - if(h.has_metadata() && h.num_files() == 1) { + if (h.has_metadata() && h.num_files() == 1) { new_file_name = misc::fileName(save_path_dir); // New file name save_path_dir = misc::branchPath(save_path_dir, true); // Skip file name } QDir savePath(misc::expandPath(save_path_dir)); // Actually move storage - if(!QBtSession::instance()->useTemporaryFolder() || h.is_seed()) { - if(!savePath.exists()) savePath.mkpath(savePath.absolutePath()); + if (!QBtSession::instance()->useTemporaryFolder() || h.is_seed()) { + if (!savePath.exists()) savePath.mkpath(savePath.absolutePath()); h.move_storage(savePath.absolutePath()); } // Update save_path in dialog QString display_path; - if(h.has_metadata() && h.num_files() == 1) { + if (h.has_metadata() && h.num_files() == 1) { // Rename the file Q_ASSERT(!new_file_name.isEmpty()); #if defined(Q_WS_WIN) || defined(Q_OS_OS2) - if(h.filename_at(0).compare(new_file_name, Qt::CaseInsensitive) != 0) { + if (h.filename_at(0).compare(new_file_name, Qt::CaseInsensitive) != 0) { #else - if(h.filename_at(0).compare(new_file_name, Qt::CaseSensitive) != 0) { + if (h.filename_at(0).compare(new_file_name, Qt::CaseSensitive) != 0) { #endif qDebug("Renaming single file to %s", qPrintable(new_file_name)); h.rename_file(0, new_file_name); @@ -715,7 +715,7 @@ void PropertiesWidget::on_changeSavePathButton_clicked() { } void PropertiesWidget::filteredFilesChanged() { - if(h.is_valid()) { + if (h.is_valid()) { applyPriorities(); } } diff --git a/src/properties/proplistdelegate.h b/src/properties/proplistdelegate.h index 8ad63f050..b33e1eff5 100644 --- a/src/properties/proplistdelegate.h +++ b/src/properties/proplistdelegate.h @@ -80,7 +80,7 @@ public: newopt.rect = opt.rect; // We don't want to display 100% unless // the torrent is really complete - if(progress > 99.94 && progress < 100.) + if (progress > 99.94 && progress < 100.) progress = 99.9; newopt.text = QString(QByteArray::number(progress, 'f', 1))+QString::fromUtf8("%"); newopt.progress = (int)progress; @@ -158,16 +158,16 @@ public: } QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &index) const { - if(index.column() != PRIORITY) return 0; - if(properties) { + if (index.column() != PRIORITY) return 0; + if (properties) { QTorrentHandle h = properties->getCurrentTorrent(); #if LIBTORRENT_VERSION_MINOR > 15 - if(!h.is_valid() || !h.has_metadata() || h.status(0x0).is_seeding) return 0; + if (!h.is_valid() || !h.has_metadata() || h.status(0x0).is_seeding) return 0; #else - if(!h.is_valid() || !h.has_metadata() || static_cast(h).is_seed()) return 0; + if (!h.is_valid() || !h.has_metadata() || static_cast(h).is_seed()) return 0; #endif } - if(index.data().toInt() <= 0) { + if (index.data().toInt() <= 0) { // IGNORED or MIXED return 0; } diff --git a/src/properties/proptabbar.cpp b/src/properties/proptabbar.cpp index 128d0a8cc..189cab852 100644 --- a/src/properties/proptabbar.cpp +++ b/src/properties/proptabbar.cpp @@ -87,7 +87,7 @@ PropTabBar::PropTabBar(QWidget *parent) : // SIGNAL/SLOT connect(m_btnGroup, SIGNAL(buttonClicked(int)), SLOT(setCurrentIndex(int))); // Disable buttons focus - foreach(QAbstractButton *btn, m_btnGroup->buttons()) { + foreach (QAbstractButton *btn, m_btnGroup->buttons()) { btn->setFocusPolicy(Qt::NoFocus); } } @@ -103,11 +103,11 @@ int PropTabBar::currentIndex() const void PropTabBar::setCurrentIndex(int index) { - if(index >= m_btnGroup->buttons().size()) + if (index >= m_btnGroup->buttons().size()) index = 0; // If asked to hide or if the currently selected tab is clicked - if(index < 0 || m_currentIndex == index) { - if(m_currentIndex >= 0) { + if (index < 0 || m_currentIndex == index) { + if (m_currentIndex >= 0) { m_btnGroup->button(m_currentIndex)->setStyleSheet(DEFAULT_BUTTON_CSS); m_currentIndex = -1; emit visibilityToggled(false); @@ -115,7 +115,7 @@ void PropTabBar::setCurrentIndex(int index) return; } // Unselect previous tab - if(m_currentIndex >= 0) { + if (m_currentIndex >= 0) { m_btnGroup->button(m_currentIndex)->setStyleSheet(DEFAULT_BUTTON_CSS); } else { // Nothing was selected, show! diff --git a/src/properties/trackerlist.cpp b/src/properties/trackerlist.cpp index 07032d32f..20e1d77e8 100644 --- a/src/properties/trackerlist.cpp +++ b/src/properties/trackerlist.cpp @@ -83,8 +83,8 @@ TrackerList::~TrackerList() { QList TrackerList::getSelectedTrackerItems() const { QList selected_items = selectedItems(); QList selected_trackers; - foreach(QTreeWidgetItem *item, selectedItems()) { - if(indexOfTopLevelItem(item) >= NB_STICKY_ITEM) { // Ignore STICKY ITEMS + foreach (QTreeWidgetItem *item, selectedItems()) { + if (indexOfTopLevelItem(item) >= NB_STICKY_ITEM) { // Ignore STICKY ITEMS selected_trackers << item; } } @@ -94,37 +94,37 @@ QList TrackerList::getSelectedTrackerItems() const { void TrackerList::setRowColor(int row, QColor color) { unsigned int nbColumns = columnCount(); QTreeWidgetItem *item = topLevelItem(row); - for(unsigned int i=0; isetData(i, Qt::ForegroundRole, color); } } void TrackerList::moveSelectionUp() { QTorrentHandle h = properties->getCurrentTorrent(); - if(!h.is_valid()) { + if (!h.is_valid()) { clear(); return; } QList selected_items = getSelectedTrackerItems(); - if(selected_items.isEmpty()) return; + if (selected_items.isEmpty()) return; bool change = false; - foreach(QTreeWidgetItem *item, selected_items){ + foreach (QTreeWidgetItem *item, selected_items){ int index = indexOfTopLevelItem(item); - if(index > NB_STICKY_ITEM) { + if (index > NB_STICKY_ITEM) { insertTopLevelItem(index-1, takeTopLevelItem(index)); change = true; } } - if(!change) return; + if (!change) return; // Restore selection QItemSelectionModel *selection = selectionModel(); - foreach(QTreeWidgetItem *item, selected_items) { + foreach (QTreeWidgetItem *item, selected_items) { selection->select(indexFromItem(item), QItemSelectionModel::Rows|QItemSelectionModel::Select); } setSelectionModel(selection); // Update torrent trackers std::vector trackers; - for(int i=NB_STICKY_ITEM; idata(COL_URL, Qt::DisplayRole).toString(); announce_entry e(tracker_url.toStdString()); e.tier = i-NB_STICKY_ITEM; @@ -137,30 +137,30 @@ void TrackerList::moveSelectionUp() { void TrackerList::moveSelectionDown() { QTorrentHandle h = properties->getCurrentTorrent(); - if(!h.is_valid()) { + if (!h.is_valid()) { clear(); return; } QList selected_items = getSelectedTrackerItems(); - if(selected_items.isEmpty()) return; + if (selected_items.isEmpty()) return; bool change = false; - for(int i=selectedItems().size()-1; i>= 0; --i) { + for (int i=selectedItems().size()-1; i>= 0; --i) { int index = indexOfTopLevelItem(selected_items.at(i)); - if(index < topLevelItemCount()-1) { + if (index < topLevelItemCount()-1) { insertTopLevelItem(index+1, takeTopLevelItem(index)); change = true; } } - if(!change) return; + if (!change) return; // Restore selection QItemSelectionModel *selection = selectionModel(); - foreach(QTreeWidgetItem *item, selected_items) { + foreach (QTreeWidgetItem *item, selected_items) { selection->select(indexFromItem(item), QItemSelectionModel::Rows|QItemSelectionModel::Select); } setSelectionModel(selection); // Update torrent trackers std::vector trackers; - for(int i=NB_STICKY_ITEM; idata(COL_URL, Qt::DisplayRole).toString(); announce_entry e(tracker_url.toStdString()); e.tier = i-NB_STICKY_ITEM; @@ -192,32 +192,32 @@ void TrackerList::loadStickyItems(const QTorrentHandle &h) { std::vector peers; h.get_peer_info(peers); std::vector::iterator it; - for(it=peers.begin(); it!=peers.end(); it++) { - if(it->source & peer_info::dht) + for (it=peers.begin(); it!=peers.end(); it++) { + if (it->source & peer_info::dht) ++nb_dht; - if(it->source & peer_info::lsd) + if (it->source & peer_info::lsd) ++nb_lsd; - if(it->source & peer_info::pex) + if (it->source & peer_info::pex) ++nb_pex; } // load DHT information - if(QBtSession::instance()->isDHTEnabled() && h.has_metadata() && !h.priv()) { + if (QBtSession::instance()->isDHTEnabled() && h.has_metadata() && !h.priv()) { dht_item->setText(COL_STATUS, tr("Working")); } else { dht_item->setText(COL_STATUS, tr("Disabled")); } dht_item->setText(COL_PEERS, QString::number(nb_dht)); - if(h.has_metadata() && h.priv()) { + if (h.has_metadata() && h.priv()) { dht_item->setText(COL_MSG, tr("This torrent is private")); } // Load PeX Information - if(QBtSession::instance()->isPexEnabled()) + if (QBtSession::instance()->isPexEnabled()) pex_item->setText(COL_STATUS, tr("Working")); else pex_item->setText(COL_STATUS, tr("Disabled")); pex_item->setText(COL_PEERS, QString::number(nb_pex)); // Load LSD Information - if(QBtSession::instance()->isLSDEnabled()) + if (QBtSession::instance()->isLSDEnabled()) lsd_item->setText(COL_STATUS, tr("Working")); else lsd_item->setText(COL_STATUS, tr("Disabled")); @@ -227,16 +227,16 @@ void TrackerList::loadStickyItems(const QTorrentHandle &h) { void TrackerList::loadTrackers() { // Load trackers from torrent handle QTorrentHandle h = properties->getCurrentTorrent(); - if(!h.is_valid()) return; + if (!h.is_valid()) return; loadStickyItems(h); // Load actual trackers information QHash trackers_data = QBtSession::instance()->getTrackersInfo(h.hash()); QStringList old_trackers_urls = tracker_items.keys(); const std::vector trackers = h.trackers(); - for(std::vector::const_iterator it = trackers.begin(); it != trackers.end(); it++) { + for (std::vector::const_iterator it = trackers.begin(); it != trackers.end(); it++) { QString tracker_url = misc::toQString(it->url); QTreeWidgetItem *item = tracker_items.value(tracker_url, 0); - if(!item) { + if (!item) { item = new QTreeWidgetItem(); item->setText(COL_TIER, QString::number(it->tier)); item->setText(COL_URL, tracker_url); @@ -247,15 +247,15 @@ void TrackerList::loadTrackers() { } TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url)); QString error_message = data.last_message.trimmed(); - if(it->verified) { + if (it->verified) { item->setText(COL_STATUS, tr("Working")); item->setText(COL_MSG, ""); } else { - if(it->updating && it->fails == 0) { + if (it->updating && it->fails == 0) { item->setText(COL_STATUS, tr("Updating...")); item->setText(COL_MSG, ""); } else { - if(it->fails > 0) { + if (it->fails > 0) { item->setText(COL_STATUS, tr("Not working")); item->setText(COL_MSG, error_message); } else { @@ -267,7 +267,7 @@ void TrackerList::loadTrackers() { item->setText(COL_PEERS, QString::number(trackers_data.value(tracker_url, TrackerInfos(tracker_url)).num_peers)); } // Remove old trackers - foreach(const QString &tracker, old_trackers_urls) { + foreach (const QString &tracker, old_trackers_urls) { delete tracker_items.take(tracker); } } @@ -275,11 +275,11 @@ void TrackerList::loadTrackers() { // Ask the user for new trackers and add them to the torrent void TrackerList::askForTrackers(){ QTorrentHandle h = properties->getCurrentTorrent(); - if(!h.is_valid()) return; + if (!h.is_valid()) return; QStringList trackers = TrackersAdditionDlg::askForTrackers(h); - if(!trackers.empty()) { - foreach(const QString& tracker, trackers) { - if(tracker.trimmed().isEmpty()) continue; + if (!trackers.empty()) { + foreach (const QString& tracker, trackers) { + if (tracker.trimmed().isEmpty()) continue; announce_entry url(tracker.toStdString()); url.tier = 0; h.add_tracker(url); @@ -293,14 +293,14 @@ void TrackerList::askForTrackers(){ void TrackerList::deleteSelectedTrackers(){ QTorrentHandle h = properties->getCurrentTorrent(); - if(!h.is_valid()) { + if (!h.is_valid()) { clear(); return; } QList selected_items = getSelectedTrackerItems(); - if(selected_items.isEmpty()) return; + if (selected_items.isEmpty()) return; QStringList urls_to_remove; - foreach(QTreeWidgetItem *item, selected_items){ + foreach (QTreeWidgetItem *item, selected_items){ QString tracker_url = item->data(COL_URL, Qt::DisplayRole).toString(); urls_to_remove << tracker_url; tracker_items.remove(tracker_url); @@ -310,8 +310,8 @@ void TrackerList::deleteSelectedTrackers(){ std::vector remaining_trackers; std::vector trackers = h.trackers(); std::vector::iterator it; - for(it = trackers.begin(); it != trackers.end(); it++) { - if(!urls_to_remove.contains(misc::toQString((*it).url))) { + for (it = trackers.begin(); it != trackers.end(); it++) { + if (!urls_to_remove.contains(misc::toQString((*it).url))) { remaining_trackers.push_back(*it); } } @@ -323,28 +323,28 @@ void TrackerList::deleteSelectedTrackers(){ void TrackerList::showTrackerListMenu(QPoint) { QTorrentHandle h = properties->getCurrentTorrent(); - if(!h.is_valid()) return; + if (!h.is_valid()) return; //QList selected_items = getSelectedTrackerItems(); QMenu menu; // Add actions QAction *addAct = menu.addAction(IconProvider::instance()->getIcon("list-add"), tr("Add a new tracker...")); QAction *delAct = 0; - if(!getSelectedTrackerItems().isEmpty()) { + if (!getSelectedTrackerItems().isEmpty()) { delAct = menu.addAction(IconProvider::instance()->getIcon("list-remove"), tr("Remove tracker")); } menu.addSeparator(); QAction *reannounceAct = menu.addAction(IconProvider::instance()->getIcon("view-refresh"), tr("Force reannounce")); QAction *act = menu.exec(QCursor::pos()); - if(act == 0) return; - if(act == addAct) { + if (act == 0) return; + if (act == addAct) { askForTrackers(); return; } - if(act == delAct) { + if (act == delAct) { deleteSelectedTrackers(); return; } - if(act == reannounceAct) { + if (act == reannounceAct) { properties->getCurrentTorrent().force_reannounce(); return; } @@ -352,7 +352,7 @@ void TrackerList::showTrackerListMenu(QPoint) { void TrackerList::loadSettings() { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); - if(!header()->restoreState(settings.value("TorrentProperties/Trackers/TrackerListState").toByteArray())) { + if (!header()->restoreState(settings.value("TorrentProperties/Trackers/TrackerListState").toByteArray())) { setColumnWidth(0, 30); setColumnWidth(1, 300); } diff --git a/src/properties/trackersadditiondlg.h b/src/properties/trackersadditiondlg.h index 536f64b16..624551a58 100644 --- a/src/properties/trackersadditiondlg.h +++ b/src/properties/trackersadditiondlg.h @@ -94,18 +94,18 @@ public slots: } // Load from current user list QStringList tmp = trackers_list->toPlainText().split("\n"); - foreach(const QString &user_url_str, tmp) { + foreach (const QString &user_url_str, tmp) { QUrl user_url(user_url_str); - if(!existingTrackers.contains(user_url)) + if (!existingTrackers.contains(user_url)) existingTrackers << user_url; } // Add new trackers to the list - if(!trackers_list->toPlainText().isEmpty() && !trackers_list->toPlainText().endsWith("\n")) + if (!trackers_list->toPlainText().isEmpty() && !trackers_list->toPlainText().endsWith("\n")) trackers_list->insertPlainText("\n"); int nb = 0; while (!list_file.atEnd()) { const QByteArray line = list_file.readLine().trimmed(); - if(line.isEmpty()) continue; + if (line.isEmpty()) continue; QUrl url(line); if (!existingTrackers.contains(url)) { trackers_list->insertPlainText(line + "\n"); @@ -119,7 +119,7 @@ public slots: setCursor(Qt::ArrowCursor); uTorrentListButton->setEnabled(true); // Display information message if necessary - if(nb == 0) { + if (nb == 0) { QMessageBox::information(this, tr("No change"), tr("No additional trackers were found."), QMessageBox::Ok); } sender()->deleteLater(); @@ -138,7 +138,7 @@ public: static QStringList askForTrackers(QTorrentHandle h) { QStringList trackers; TrackersAdditionDlg dlg(h); - if(dlg.exec() == QDialog::Accepted) { + if (dlg.exec() == QDialog::Accepted) { return dlg.newTrackers(); } return trackers; diff --git a/src/qinisettings.h b/src/qinisettings.h index ed34591b4..6d4031c01 100644 --- a/src/qinisettings.h +++ b/src/qinisettings.h @@ -56,14 +56,14 @@ public: QVariant value(const QString & key, const QVariant &defaultValue = QVariant()) const { QString key_tmp(key); QVariant ret = QSettings::value(key_tmp); - if(ret.isNull()) + if (ret.isNull()) return defaultValue; return ret; } void setValue(const QString &key, const QVariant &val) { QString key_tmp(key); - if(format() == QSettings::NativeFormat) + if (format() == QSettings::NativeFormat) key_tmp.replace("\\", "/"); QSettings::setValue(key_tmp, val); } diff --git a/src/qmacapplication.cpp b/src/qmacapplication.cpp index 5187df2aa..e8680255e 100644 --- a/src/qmacapplication.cpp +++ b/src/qmacapplication.cpp @@ -44,7 +44,7 @@ bool QMacApplication::event(QEvent * ev) { case QEvent::FileOpen: { QString path = static_cast(ev)->file(); - if(path.isEmpty()) { + if (path.isEmpty()) { // Get the url instead path = static_cast(ev)->url().toString(); } diff --git a/src/qtlibtorrent/bandwidthscheduler.h b/src/qtlibtorrent/bandwidthscheduler.h index a7baabfab..5513f8aef 100644 --- a/src/qtlibtorrent/bandwidthscheduler.h +++ b/src/qtlibtorrent/bandwidthscheduler.h @@ -29,7 +29,7 @@ public slots: QTime startAltSpeeds = pref.getSchedulerStartTime(); QTime endAltSpeeds = pref.getSchedulerEndTime(); - if(startAltSpeeds == endAltSpeeds) { + if (startAltSpeeds == endAltSpeeds) { std::cerr << "Error: bandwidth scheduler have the same start time and end time." << std::endl; std::cerr << "The bandwidth scheduler will be disabled" << std::endl; stop(); @@ -41,7 +41,7 @@ public slots: QTime now = QTime::currentTime(); uint time_to_start = secsTo(now, startAltSpeeds); uint time_to_end = secsTo(now, endAltSpeeds); - if(time_to_end < time_to_start) { + if (time_to_end < time_to_start) { // We should be in alternative mode in_alternative_mode = true; // Start counting @@ -61,9 +61,9 @@ public slots: // Get the day this mode was started (either today or yesterday) QDate current_date = QDateTime::currentDateTime().toLocalTime().date(); int day = current_date.dayOfWeek(); - if(in_alternative_mode) { + if (in_alternative_mode) { // It is possible that starttime was yesterday - if(QTime::currentTime().secsTo(pref.getSchedulerStartTime()) > 0) { + if (QTime::currentTime().secsTo(pref.getSchedulerStartTime()) > 0) { current_date.addDays(-1); // Go to yesterday day = current_date.day(); } @@ -75,17 +75,17 @@ public slots: emit switchToAlternativeMode(!in_alternative_mode); break; case WEEK_ENDS: - if(day == Qt::Saturday || day == Qt::Sunday) + if (day == Qt::Saturday || day == Qt::Sunday) emit switchToAlternativeMode(!in_alternative_mode); break; case WEEK_DAYS: - if(day != Qt::Saturday && day != Qt::Sunday) + if (day != Qt::Saturday && day != Qt::Sunday) emit switchToAlternativeMode(!in_alternative_mode); break; default: // Convert our enum index to Qt enum index int scheduler_day = ((int)pref.getSchedulerDays()) - 2; - if(day == scheduler_day) + if (day == scheduler_day) emit switchToAlternativeMode(!in_alternative_mode); break; } @@ -101,7 +101,7 @@ private: // don't want that uint secsTo(QTime now, QTime t) { int diff = now.secsTo(t); - if(diff < 0) { + if (diff < 0) { // 86400 seconds in a day diff += 86400; } diff --git a/src/qtlibtorrent/filterparserthread.h b/src/qtlibtorrent/filterparserthread.h index 90853e2e3..2bd04dddd 100644 --- a/src/qtlibtorrent/filterparserthread.h +++ b/src/qtlibtorrent/filterparserthread.h @@ -69,7 +69,7 @@ public: int ruleCount = 0; QFile file(filePath); if (file.exists()){ - if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){ + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){ std::cerr << "I/O Error: Could not open ip filer file in read mode." << std::endl; return ruleCount; } @@ -79,9 +79,9 @@ public: QByteArray line = file.readLine(); // Ignoring empty lines line = line.trimmed(); - if(line.isEmpty()) continue; + if (line.isEmpty()) continue; // Ignoring commented lines - if(line.startsWith('#') || line.startsWith("//")) continue; + if (line.startsWith('#') || line.startsWith("//")) continue; // Line should be splitted by commas QList partsList = line.split(','); @@ -89,7 +89,7 @@ public: // IP Range should be splitted by a dash QList IPs = partsList.first().split('-'); - if(IPs.size() != 2) { + if (IPs.size() != 2) { qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("Line was %s", line.constData()); continue; @@ -97,30 +97,30 @@ public: boost::system::error_code ec; const QString strStartIP = cleanupIPAddress(IPs.at(0)); - if(strStartIP.isEmpty()) { + if (strStartIP.isEmpty()) { qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("Start IP of the range is malformated: %s", qPrintable(strStartIP)); continue; } libtorrent::address startAddr = libtorrent::address::from_string(qPrintable(strStartIP), ec); - if(ec) { + if (ec) { qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("Start IP of the range is malformated: %s", qPrintable(strStartIP)); continue; } const QString strEndIP = cleanupIPAddress(IPs.at(1)); - if(strEndIP.isEmpty()) { + if (strEndIP.isEmpty()) { qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("End IP of the range is malformated: %s", qPrintable(strEndIP)); continue; } libtorrent::address endAddr = libtorrent::address::from_string(qPrintable(strEndIP), ec); - if(ec) { + if (ec) { qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("End IP of the range is malformated: %s", qPrintable(strEndIP)); continue; } - if(startAddr.is_v4() != endAddr.is_v4()) { + if (startAddr.is_v4() != endAddr.is_v4()) { qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("One IP is IPv4 and the other is IPv6!"); continue; @@ -128,12 +128,12 @@ public: // Check if there is an access value (apparently not mandatory) int nbAccess = 0; - if(nbElem > 1) { + if (nbElem > 1) { // There is possibly one nbAccess = partsList.at(1).trimmed().toInt(); } - if(nbAccess > 127) { + if (nbAccess > 127) { // Ignoring this rule because access value is too high continue; } @@ -155,7 +155,7 @@ public: int ruleCount = 0; QFile file(filePath); if (file.exists()){ - if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){ + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){ std::cerr << "I/O Error: Could not open ip filer file in read mode." << std::endl; return ruleCount; } @@ -163,48 +163,48 @@ public: while (!file.atEnd() && !abort) { ++nbLine; QByteArray line = file.readLine().trimmed(); - if(line.isEmpty()) continue; + if (line.isEmpty()) continue; // Ignoring commented lines - if(line.startsWith('#') || line.startsWith("//")) continue; + if (line.startsWith('#') || line.startsWith("//")) continue; // Line is splitted by : QList partsList = line.split(':'); - if(partsList.size() < 2){ + if (partsList.size() < 2){ qDebug("p2p file: line %d is malformed.", nbLine); continue; } // Get IP range QList IPs = partsList.last().split('-'); - if(IPs.size() != 2) { + if (IPs.size() != 2) { qDebug("p2p file: line %d is malformed.", nbLine); qDebug("line was: %s", line.constData()); continue; } boost::system::error_code ec; QString strStartIP = cleanupIPAddress(IPs.at(0)); - if(strStartIP.isEmpty()) { + if (strStartIP.isEmpty()) { qDebug("p2p file: line %d is malformed.", nbLine); qDebug("Start IP is invalid: %s", qPrintable(strStartIP)); continue; } libtorrent::address startAddr = libtorrent::address::from_string(qPrintable(strStartIP), ec); - if(ec) { + if (ec) { qDebug("p2p file: line %d is malformed.", nbLine); qDebug("Start IP is invalid: %s", qPrintable(strStartIP)); continue; } QString strEndIP = cleanupIPAddress(IPs.at(1)); - if(strEndIP.isEmpty()) { + if (strEndIP.isEmpty()) { qDebug("p2p file: line %d is malformed.", nbLine); qDebug("End IP is invalid: %s", qPrintable(strStartIP)); continue; } libtorrent::address endAddr = libtorrent::address::from_string(qPrintable(strEndIP), ec); - if(ec) { + if (ec) { qDebug("p2p file: line %d is malformed.", nbLine); qDebug("End IP is invalid: %s", qPrintable(strStartIP)); continue; } - if(startAddr.is_v4() != endAddr.is_v4()) { + if (startAddr.is_v4() != endAddr.is_v4()) { qDebug("p2p file: line %d is malformed.", nbLine); qDebug("Line was: %s", line.constData()); continue; @@ -230,8 +230,8 @@ public: do { read = stream.readRawData(&c, 1); total_read += read; - if(read > 0) { - if(c != delim) { + if (read > 0) { + if (c != delim) { name += c; } else { // Delim found @@ -247,7 +247,7 @@ public: int ruleCount = 0; QFile file(filePath); if (file.exists()){ - if(!file.open(QIODevice::ReadOnly)){ + if (!file.open(QIODevice::ReadOnly)){ std::cerr << "I/O Error: Could not open ip filer file in read mode." << std::endl; return ruleCount; } @@ -255,7 +255,7 @@ public: // Read header char buf[7]; unsigned char version; - if( + if ( !stream.readRawData(buf, sizeof(buf)) || memcmp(buf, "\xFF\xFF\xFF\xFFP2B", 7) || !stream.readRawData((char*)&version, sizeof(version)) @@ -264,13 +264,13 @@ public: return ruleCount; } - if(version==1 || version==2) { + if (version==1 || version==2) { qDebug ("p2b version 1 or 2"); unsigned int start, end; string name; while(getlineInStream(stream, name, '\0') && !abort) { - if( + if ( !stream.readRawData((char*)&start, sizeof(start)) || !stream.readRawData((char*)&end, sizeof(end)) ) { @@ -289,26 +289,26 @@ public: } catch(std::exception&) {} } } - else if(version==3) { + else if (version==3) { qDebug ("p2b version 3"); unsigned int namecount; - if(!stream.readRawData((char*)&namecount, sizeof(namecount))) { + if (!stream.readRawData((char*)&namecount, sizeof(namecount))) { std::cerr << "Parsing Error: The filter file is not a valid PeerGuardian P2B file." << std::endl; return ruleCount; } namecount=ntohl(namecount); // Reading names although, we don't really care about them - for(unsigned int i=0; iget_ip_filter(); - if(isRunning()) { + if (isRunning()) { // Already parsing a filter, abort first abort = true; wait(); @@ -368,12 +368,12 @@ public: static void processFilterList(libtorrent::session *s, const QStringList& IPs) { // First, import current filter libtorrent::ip_filter filter = s->get_ip_filter(); - foreach(const QString &ip, IPs) { + foreach (const QString &ip, IPs) { qDebug("Manual ban of peer %s", ip.toLocal8Bit().constData()); boost::system::error_code ec; libtorrent::address addr = libtorrent::address::from_string(ip.toLocal8Bit().constData(), ec); Q_ASSERT(!ec); - if(!ec) + if (!ec) filter.add_rule(addr, addr, libtorrent::ip_filter::blocked); } s->set_ip_filter(filter); @@ -386,7 +386,7 @@ signals: protected: QString cleanupIPAddress(QString _ip) { QHostAddress ip(_ip.trimmed()); - if(ip.isNull()) { + if (ip.isNull()) { return QString(); } return ip.toString(); @@ -395,11 +395,11 @@ protected: void run(){ qDebug("Processing filter file"); int ruleCount = 0; - if(filePath.endsWith(".p2p", Qt::CaseInsensitive)) { + if (filePath.endsWith(".p2p", Qt::CaseInsensitive)) { // PeerGuardian p2p file ruleCount = parseP2PFilterFile(filePath); } else { - if(filePath.endsWith(".p2b", Qt::CaseInsensitive)) { + if (filePath.endsWith(".p2b", Qt::CaseInsensitive)) { // PeerGuardian p2b file ruleCount = parseP2BFilterFile(filePath); } else { @@ -407,7 +407,7 @@ protected: ruleCount = parseDATFilterFile(filePath); } } - if(abort) + if (abort) return; try { s->set_ip_filter(filter); diff --git a/src/qtlibtorrent/qbtsession.cpp b/src/qtlibtorrent/qbtsession.cpp index 07140081e..0781ed69f 100644 --- a/src/qtlibtorrent/qbtsession.cpp +++ b/src/qtlibtorrent/qbtsession.cpp @@ -137,9 +137,9 @@ QBtSession::QBtSession() // Enabling plugins //s->add_extension(&create_metadata_plugin); s->add_extension(&create_ut_metadata_plugin); - if(pref.trackerExchangeEnabled()) + if (pref.trackerExchangeEnabled()) s->add_extension(&create_lt_trackers_plugin); - if(pref.isPeXEnabled()) { + if (pref.isPeXEnabled()) { PeXEnabled = true; s->add_extension(&create_ut_pex_plugin); } else { @@ -176,24 +176,24 @@ QBtSession::~QBtSession() { saveSessionState(); saveFastResumeData(); // Delete our objects - if(m_tracker) + if (m_tracker) delete m_tracker; delete timerAlerts; - if(BigRatioTimer) + if (BigRatioTimer) delete BigRatioTimer; - if(filterParser) + if (filterParser) delete filterParser; delete downloader; - if(bd_scheduler) + if (bd_scheduler) delete bd_scheduler; // HTTP Server - if(httpServer) + if (httpServer) delete httpServer; qDebug("Deleting the session"); delete s; qDebug("BTSession destructor OUT"); #ifndef DISABLE_GUI - if(m_shutdownAct != NO_SHUTDOWN) { + if (m_shutdownAct != NO_SHUTDOWN) { qDebug() << "Sending computer shutdown/suspend signal..."; misc::shutdownComputer(m_shutdownAct == SUSPEND_COMPUTER); } @@ -202,7 +202,7 @@ QBtSession::~QBtSession() { void QBtSession::preAllocateAllFiles(bool b) { const bool change = (preAllocateAll != b); - if(change) { + if (change) { qDebug("PreAllocateAll changed, reloading all torrents!"); preAllocateAll = b; } @@ -212,27 +212,27 @@ void QBtSession::processBigRatios() { qDebug("Process big ratios..."); std::vector torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { const QTorrentHandle h(*torrentIT); - if(!h.is_valid()) continue; - if(h.is_seed()) { + if (!h.is_valid()) continue; + if (h.is_seed()) { const QString hash = h.hash(); const qreal ratio = getRealRatio(hash); qreal ratio_limit = TorrentPersistentData::getRatioLimit(hash); - if(ratio_limit == TorrentPersistentData::NO_RATIO_LIMIT) + if (ratio_limit == TorrentPersistentData::NO_RATIO_LIMIT) continue; - if(ratio_limit == TorrentPersistentData::USE_GLOBAL_RATIO) + if (ratio_limit == TorrentPersistentData::USE_GLOBAL_RATIO) ratio_limit = global_ratio_limit; qDebug("Ratio: %f (limit: %f)", ratio, ratio_limit); Q_ASSERT(ratio_limit >= 0.f); - if(ratio <= MAX_RATIO && ratio >= ratio_limit) { - if(high_ratio_action == REMOVE_ACTION) { + if (ratio <= MAX_RATIO && ratio >= ratio_limit) { + if (high_ratio_action == REMOVE_ACTION) { addConsoleMessage(tr("%1 reached the maximum ratio you set.").arg(h.name())); addConsoleMessage(tr("Removing torrent %1...").arg(h.name())); deleteTorrent(hash); } else { // Pause it - if(!h.is_paused()) { + if (!h.is_paused()) { addConsoleMessage(tr("%1 reached the maximum ratio you set.").arg(h.name())); addConsoleMessage(tr("Pausing torrent %1...").arg(h.name())); pauseTorrent(hash); @@ -246,7 +246,7 @@ void QBtSession::processBigRatios() { void QBtSession::setDownloadLimit(QString hash, long val) { QTorrentHandle h = getTorrentHandle(hash); - if(h.is_valid()) { + if (h.is_valid()) { h.set_download_limit(val); } } @@ -254,7 +254,7 @@ void QBtSession::setDownloadLimit(QString hash, long val) { void QBtSession::setUploadLimit(QString hash, long val) { qDebug("Set upload limit rate to %ld", val); QTorrentHandle h = getTorrentHandle(hash); - if(h.is_valid()) { + if (h.is_valid()) { h.set_upload_limit(val); } } @@ -272,7 +272,7 @@ void QBtSession::startTorrentsInPause(bool b) { } void QBtSession::setQueueingEnabled(bool enable) { - if(queueingEnabled != enable) { + if (queueingEnabled != enable) { qDebug("Queueing system is changing state..."); queueingEnabled = enable; } @@ -285,7 +285,7 @@ void QBtSession::configureSession() { // * Ports binding const unsigned short old_listenPort = getListenPort(); const unsigned short new_listenPort = pref.getSessionPort(); - if(old_listenPort != new_listenPort) { + if (old_listenPort != new_listenPort) { qDebug("Session port changes in program preferences: %d -> %d", old_listenPort, new_listenPort); setListeningPort(new_listenPort); addConsoleMessage(tr("qBittorrent is bound to port: TCP/%1", "e.g: qBittorrent is bound to port: 6881").arg(QString::number(getListenPort()))); @@ -294,7 +294,7 @@ void QBtSession::configureSession() { // Downloads // * Save path defaultSavePath = pref.getSavePath(); - if(pref.isTempPathEnabled()) { + if (pref.isTempPathEnabled()) { setDefaultTempPath(pref.getTempPath()); } else { setDefaultTempPath(QString::null); @@ -305,9 +305,9 @@ void QBtSession::configureSession() { startTorrentsInPause(pref.addTorrentsInPause()); // * Export Dir const bool newTorrentExport = pref.isTorrentExportEnabled(); - if(torrentExport != newTorrentExport) { + if (torrentExport != newTorrentExport) { torrentExport = newTorrentExport; - if(torrentExport) { + if (torrentExport) { qDebug("Torrent export is enabled, exporting the current torrents"); exportTorrentFiles(pref.getExportDir()); } @@ -316,11 +316,11 @@ void QBtSession::configureSession() { // * Global download limit const bool alternative_speeds = pref.isAltBandwidthEnabled(); int down_limit; - if(alternative_speeds) + if (alternative_speeds) down_limit = pref.getAltGlobalDownloadLimit(); else down_limit = pref.getGlobalDownloadLimit(); - if(down_limit <= 0) { + if (down_limit <= 0) { // Download limit disabled setDownloadRateLimit(-1); } else { @@ -328,35 +328,35 @@ void QBtSession::configureSession() { setDownloadRateLimit(down_limit*1024); } int up_limit; - if(alternative_speeds) + if (alternative_speeds) up_limit = pref.getAltGlobalUploadLimit(); else up_limit = pref.getGlobalUploadLimit(); // * Global Upload limit - if(up_limit <= 0) { + if (up_limit <= 0) { // Upload limit disabled setUploadRateLimit(-1); } else { // Enabled setUploadRateLimit(up_limit*1024); } - if(pref.isSchedulerEnabled()) { - if(!bd_scheduler) { + if (pref.isSchedulerEnabled()) { + if (!bd_scheduler) { bd_scheduler = new BandwidthScheduler(this); connect(bd_scheduler, SIGNAL(switchToAlternativeMode(bool)), this, SLOT(useAlternativeSpeedsLimit(bool))); } bd_scheduler->start(); } else { - if(bd_scheduler) delete bd_scheduler; + if (bd_scheduler) delete bd_scheduler; } #ifndef DISABLE_GUI // Resolve countries qDebug("Loading country resolution settings"); const bool new_resolv_countries = pref.resolvePeerCountries(); - if(resolve_countries != new_resolv_countries) { + if (resolve_countries != new_resolv_countries) { qDebug("in country reoslution settings"); resolve_countries = new_resolv_countries; - if(resolve_countries && !geoipDBLoaded) { + if (resolve_countries && !geoipDBLoaded) { qDebug("Loading geoip database"); GeoIPManager::loadDatabase(s); geoipDBLoaded = true; @@ -364,15 +364,15 @@ void QBtSession::configureSession() { // Update torrent handles std::vector torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { QTorrentHandle h = QTorrentHandle(*torrentIT); - if(h.is_valid()) + if (h.is_valid()) h.resolve_countries(resolve_countries); } } #endif // * UPnP / NAT-PMP - if(pref.isUPnPEnabled()) { + if (pref.isUPnPEnabled()) { enableUPnP(true); addConsoleMessage(tr("UPnP / NAT-PMP support [ON]"), QString::fromUtf8("blue")); } else { @@ -412,7 +412,7 @@ void QBtSession::configureSession() { } #endif // Queueing System - if(pref.isQueueingSystemEnabled()) { + if (pref.isQueueingSystemEnabled()) { sessionSettings.active_downloads = pref.getMaxActiveDownloads(); sessionSettings.active_seeds = pref.getMaxActiveUploads(); sessionSettings.active_limit = pref.getMaxActiveTorrents(); @@ -433,13 +433,13 @@ void QBtSession::configureSession() { sessionSettings.rate_limit_ip_overhead = pref.includeOverheadInLimits(); // IP address to announce to trackers QString announce_ip = pref.getNetworkAddress(); - if(!announce_ip.isEmpty()) { + if (!announce_ip.isEmpty()) { #if LIBTORRENT_VERSION_MINOR > 15 sessionSettings.announce_ip = announce_ip.toStdString(); #else boost::system::error_code ec; boost::asio::ip::address addr = boost::asio::ip::address::from_string(announce_ip.toStdString(), ec); - if(!ec) { + if (!ec) { addConsoleMessage(tr("Reporting IP address %1 to trackers...").arg(announce_ip)); sessionSettings.announce_ip = addr; } @@ -460,7 +460,7 @@ void QBtSession::configureSession() { #endif #if LIBTORRENT_VERSION_MINOR > 15 // uTP - if(pref.isuTPEnabled()) { + if (pref.isuTPEnabled()) { sessionSettings.enable_incoming_utp = true; sessionSettings.enable_outgoing_utp = true; } else { @@ -469,7 +469,7 @@ void QBtSession::configureSession() { } // uTP rate limiting sessionSettings.rate_limit_utp = pref.isuTPRateLimited(); - if(sessionSettings.rate_limit_utp) + if (sessionSettings.rate_limit_utp) sessionSettings.mixed_mode_algorithm = session_settings::prefer_tcp; else sessionSettings.mixed_mode_algorithm = session_settings::peer_proportional; @@ -482,16 +482,16 @@ void QBtSession::configureSession() { // * Max uploads per torrent limit setMaxUploadsPerTorrent(pref.getMaxUploadsPerTorrent()); // * DHT - if(pref.isDHTEnabled()) { + if (pref.isDHTEnabled()) { // Set DHT Port - if(enableDHT(true)) { + if (enableDHT(true)) { int dht_port; - if(pref.isDHTPortSameAsBT()) + if (pref.isDHTPortSameAsBT()) dht_port = 0; else dht_port = pref.getDHTPort(); setDHTPort(dht_port); - if(dht_port == 0) dht_port = new_listenPort; + if (dht_port == 0) dht_port = new_listenPort; addConsoleMessage(tr("DHT support [ON], port: UDP/%1").arg(dht_port), QString::fromUtf8("blue")); } else { addConsoleMessage(tr("DHT support [OFF]"), QString::fromUtf8("red")); @@ -501,16 +501,16 @@ void QBtSession::configureSession() { addConsoleMessage(tr("DHT support [OFF]"), QString::fromUtf8("blue")); } // * PeX - if(PeXEnabled) { + if (PeXEnabled) { addConsoleMessage(tr("PeX support [ON]"), QString::fromUtf8("blue")); } else { addConsoleMessage(tr("PeX support [OFF]"), QString::fromUtf8("red")); } - if(PeXEnabled != pref.isPeXEnabled()) { + if (PeXEnabled != pref.isPeXEnabled()) { addConsoleMessage(tr("Restart is required to toggle PeX support"), QString::fromUtf8("red")); } // * LSD - if(pref.isLSDEnabled()) { + if (pref.isLSDEnabled()) { enableLSD(true); addConsoleMessage(tr("Local Peer Discovery support [ON]"), QString::fromUtf8("blue")); } else { @@ -546,7 +546,7 @@ void QBtSession::configureSession() { updateRatioTimer(); // Ip Filter FilterParserThread::processFilterList(s, pref.bannedIPs()); - if(pref.isFilteringEnabled()) { + if (pref.isFilteringEnabled()) { enableIPFilter(pref.getFilter()); }else{ disableIPFilter(); @@ -556,13 +556,13 @@ void QBtSession::configureSession() { QTimer::singleShot(0, this, SLOT(initWebUi())); // * Proxy settings proxy_settings proxySettings; - if(pref.isProxyEnabled()) { + if (pref.isProxyEnabled()) { qDebug("Enabling P2P proxy"); proxySettings.hostname = pref.getProxyIp().toStdString(); qDebug("hostname is %s", proxySettings.hostname.c_str()); proxySettings.port = pref.getProxyPort(); qDebug("port is %d", proxySettings.port); - if(pref.isProxyAuthEnabled()) { + if (pref.isProxyAuthEnabled()) { proxySettings.username = pref.getProxyUsername().toStdString(); proxySettings.password = pref.getProxyPassword().toStdString(); qDebug("username is %s", proxySettings.username.c_str()); @@ -593,18 +593,18 @@ void QBtSession::configureSession() { } setProxySettings(proxySettings); // Tracker - if(pref.isTrackerEnabled()) { - if(!m_tracker) { + if (pref.isTrackerEnabled()) { + if (!m_tracker) { m_tracker = new QTracker(this); } - if(m_tracker->start()) { + if (m_tracker->start()) { addConsoleMessage(tr("Embedded Tracker [ON]"), QString::fromUtf8("blue")); } else { addConsoleMessage(tr("Failed to start the embedded tracker!"), QString::fromUtf8("red")); } } else { addConsoleMessage(tr("Embedded Tracker [OFF]")); - if(m_tracker) + if (m_tracker) delete m_tracker; } // * Scan dirs @@ -629,8 +629,8 @@ void QBtSession::initWebUi() { const QString username = pref.getWebUiUsername(); const QString password = pref.getWebUiPassword(); - if(httpServer) { - if(httpServer->serverPort() != port) { + if (httpServer) { + if (httpServer->serverPort() != port) { httpServer->close(); } } else { @@ -654,7 +654,7 @@ void QBtSession::initWebUi() { httpServer->setAuthorization(username, password); httpServer->setlocalAuthEnabled(pref.isWebUiLocalAuthEnabled()); - if(!httpServer->isListening()) { + if (!httpServer->isListening()) { bool success = httpServer->listen(QHostAddress::Any, port); if (success) addConsoleMessage(tr("The Web UI is listening on port %1").arg(port)); @@ -662,21 +662,21 @@ void QBtSession::initWebUi() { addConsoleMessage(tr("Web User Interface Error - Unable to bind Web UI to port %1").arg(port), "red"); } // DynDNS - if(pref.isDynDNSEnabled()) { - if(!m_dynDNSUpdater) + if (pref.isDynDNSEnabled()) { + if (!m_dynDNSUpdater) m_dynDNSUpdater = new DNSUpdater(this); else m_dynDNSUpdater->updateCredentials(); } else { - if(m_dynDNSUpdater) { + if (m_dynDNSUpdater) { delete m_dynDNSUpdater; m_dynDNSUpdater = 0; } } } else { - if(httpServer) + if (httpServer) delete httpServer; - if(m_dynDNSUpdater) { + if (m_dynDNSUpdater) { delete m_dynDNSUpdater; m_dynDNSUpdater = 0; } @@ -690,7 +690,7 @@ void QBtSession::useAlternativeSpeedsLimit(bool alternative) { pref.setAltBandwidthEnabled(alternative); // Apply settings to the bittorrent session int down_limit = alternative ? pref.getAltGlobalDownloadLimit() : pref.getGlobalDownloadLimit(); - if(down_limit <= 0) { + if (down_limit <= 0) { down_limit = -1; } else { down_limit *= 1024; @@ -698,7 +698,7 @@ void QBtSession::useAlternativeSpeedsLimit(bool alternative) { setDownloadRateLimit(down_limit); // Upload rate int up_limit = alternative ? pref.getAltGlobalUploadLimit() : pref.getGlobalUploadLimit(); - if(up_limit <= 0) { + if (up_limit <= 0) { up_limit = -1; } else { up_limit *= 1024; @@ -716,9 +716,9 @@ QTorrentHandle QBtSession::getTorrentHandle(const QString &hash) const{ bool QBtSession::hasActiveTorrents() const { std::vector torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { const QTorrentHandle h(*torrentIT); - if(h.is_valid() && !h.is_paused() && !h.is_queued()) + if (h.is_valid() && !h.is_paused() && !h.is_queued()) return true; } return false; @@ -727,11 +727,11 @@ bool QBtSession::hasActiveTorrents() const { bool QBtSession::hasDownloadingTorrents() const { std::vector torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { - if(torrentIT->is_valid()) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + if (torrentIT->is_valid()) { try { const torrent_status::state_t state = torrentIT->status().state; - if(state != torrent_status::finished && state != torrent_status::seeding) + if (state != torrent_status::finished && state != torrent_status::seeding) return true; } catch(std::exception) {} } @@ -749,32 +749,32 @@ void QBtSession::banIP(QString ip) { void QBtSession::deleteTorrent(const QString &hash, bool delete_local_files) { qDebug("Deleting torrent with hash: %s", qPrintable(hash)); const QTorrentHandle h = getTorrentHandle(hash); - if(!h.is_valid()) { + if (!h.is_valid()) { qDebug("/!\\ Error: Invalid handle"); return; } emit torrentAboutToBeRemoved(h); qDebug("h is valid, getting name or hash..."); QString fileName; - if(h.has_metadata()) + if (h.has_metadata()) fileName = h.name(); else fileName = h.hash(); // Remove it from session - if(delete_local_files) { - if(h.has_metadata()) { + if (delete_local_files) { + if (h.has_metadata()) { QDir save_dir(h.save_path()); - if(save_dir != QDir(defaultSavePath) && (defaultTempPath.isEmpty() || save_dir != QDir(defaultTempPath))) + if (save_dir != QDir(defaultSavePath) && (defaultTempPath.isEmpty() || save_dir != QDir(defaultTempPath))) savePathsToRemove[hash] = save_dir.absolutePath(); } s->remove_torrent(h, session::delete_files); } else { QStringList uneeded_files; - if(h.has_metadata()) + if (h.has_metadata()) uneeded_files = h.absolute_files_path_uneeded(); s->remove_torrent(h); // Remove unneeded and incomplete files - foreach(const QString &uneeded_file, uneeded_files) { + foreach (const QString &uneeded_file, uneeded_files) { qDebug("Removing uneeded file: %s", qPrintable(uneeded_file)); QFile::remove(uneeded_file); const QString parent_folder = misc::branchPath(uneeded_file); @@ -787,13 +787,13 @@ void QBtSession::deleteTorrent(const QString &hash, bool delete_local_files) { QStringList filters; filters << hash+".*"; const QStringList files = torrentBackup.entryList(filters, QDir::Files, QDir::Unsorted); - foreach(const QString &file, files) { + foreach (const QString &file, files) { QFile::remove(torrentBackup.absoluteFilePath(file)); } TorrentPersistentData::deletePersistentData(hash); // Remove tracker errors trackersInfos.remove(hash); - if(delete_local_files) + if (delete_local_files) addConsoleMessage(tr("'%1' was removed from transfer list and hard disk.", "'xxx.avi' was removed...").arg(fileName)); else addConsoleMessage(tr("'%1' was removed from transfer list.", "'xxx.avi' was removed...").arg(fileName)); @@ -805,10 +805,10 @@ void QBtSession::deleteTorrent(const QString &hash, bool delete_local_files) { void QBtSession::pauseAllTorrents() { std::vector torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { try { QTorrentHandle h = QTorrentHandle(*torrentIT); - if(!h.is_paused()) { + if (!h.is_paused()) { h.pause(); emit pausedTorrent(h); } @@ -823,10 +823,10 @@ std::vector QBtSession::getTorrents() const { void QBtSession::resumeAllTorrents() { std::vector torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { try { QTorrentHandle h = QTorrentHandle(*torrentIT); - if(h.is_paused()) { + if (h.is_paused()) { h.resume(); emit resumedTorrent(h); } @@ -836,7 +836,7 @@ void QBtSession::resumeAllTorrents() { void QBtSession::pauseTorrent(const QString &hash) { QTorrentHandle h = getTorrentHandle(hash); - if(!h.is_paused()) { + if (!h.is_paused()) { h.pause(); emit pausedTorrent(h); } @@ -844,7 +844,7 @@ void QBtSession::pauseTorrent(const QString &hash) { void QBtSession::resumeTorrent(const QString &hash) { QTorrentHandle h = getTorrentHandle(hash); - if(h.is_paused()) { + if (h.is_paused()) { h.resume(); emit resumedTorrent(h); } @@ -854,7 +854,7 @@ bool QBtSession::loadFastResumeData(const QString &hash, std::vector &buf) const QString fastresume_path = QDir(misc::BTBackupLocation()).absoluteFilePath(hash+QString(".fastresume")); qDebug("Trying to load fastresume data: %s", qPrintable(fastresume_path)); QFile fastresume_file(fastresume_path); - if(!fastresume_file.open(QIODevice::ReadOnly)) return false; + if (!fastresume_file.open(QIODevice::ReadOnly)) return false; const QByteArray content = fastresume_file.readAll(); const int content_size = content.size(); buf.resize(content_size); @@ -877,22 +877,22 @@ void QBtSession::loadTorrentSettings(QTorrentHandle& h) { QTorrentHandle QBtSession::addMagnetUri(QString magnet_uri, bool resumed) { QTorrentHandle h; const QString hash(misc::magnetUriToHash(magnet_uri)); - if(hash.isEmpty()) { + if (hash.isEmpty()) { addConsoleMessage(tr("'%1' is not a valid magnet URI.").arg(magnet_uri)); return h; } const QDir torrentBackup(misc::BTBackupLocation()); - if(resumed) { + if (resumed) { // Load metadata const QString torrent_path = torrentBackup.absoluteFilePath(hash+".torrent"); - if(QFile::exists(torrent_path)) + if (QFile::exists(torrent_path)) return addTorrent(torrent_path, false, QString::null, true); } qDebug("Adding a magnet URI: %s", qPrintable(hash)); Q_ASSERT(magnet_uri.startsWith("magnet:", Qt::CaseInsensitive)); // Check for duplicate torrent - if(s->find_torrent(QStringToSha1(hash)).is_valid()) { + if (s->find_torrent(QStringToSha1(hash)).is_valid()) { qDebug("/!\\ Torrent is already in download list"); addConsoleMessage(tr("'%1' is already in download list.", "e.g: 'xxx.avi' is already in download list.").arg(magnet_uri)); return h; @@ -902,18 +902,18 @@ QTorrentHandle QBtSession::addMagnetUri(QString magnet_uri, bool resumed) { // Get save path const QString savePath(getSavePath(hash, false)); - if(!defaultTempPath.isEmpty() && !TorrentPersistentData::isSeed(hash) && resumed) { + if (!defaultTempPath.isEmpty() && !TorrentPersistentData::isSeed(hash) && resumed) { qDebug("addMagnetURI: Temp folder is enabled."); QString torrent_tmp_path = defaultTempPath.replace("\\", "/"); p.save_path = torrent_tmp_path.toUtf8().constData(); // Check if save path exists, creating it otherwise - if(!QDir(torrent_tmp_path).exists()) + if (!QDir(torrent_tmp_path).exists()) QDir().mkpath(torrent_tmp_path); qDebug("addMagnetURI: using save_path: %s", qPrintable(torrent_tmp_path)); } else { p.save_path = savePath.toUtf8().constData(); // Check if save path exists, creating it otherwise - if(!QDir(savePath).exists()) QDir().mkpath(savePath); + if (!QDir(savePath).exists()) QDir().mkpath(savePath); qDebug("addMagnetURI: using save_path: %s", qPrintable(savePath)); } @@ -926,7 +926,7 @@ QTorrentHandle QBtSession::addMagnetUri(QString magnet_uri, bool resumed) { qDebug("Error: %s", e.what()); } // Check if it worked - if(!h.is_valid()) { + if (!h.is_valid()) { // No need to keep on, it failed. qDebug("/!\\ Error: Invalid handle"); return h; @@ -934,7 +934,7 @@ QTorrentHandle QBtSession::addMagnetUri(QString magnet_uri, bool resumed) { Q_ASSERT(h.hash() == hash); // If temp path is enabled, move torrent - if(!defaultTempPath.isEmpty() && !resumed) { + if (!defaultTempPath.isEmpty() && !resumed) { qDebug("Temp folder is enabled, moving new torrent to temp folder"); h.move_storage(defaultTempPath); } @@ -942,10 +942,10 @@ QTorrentHandle QBtSession::addMagnetUri(QString magnet_uri, bool resumed) { loadTorrentSettings(h); // Load filtered files - if(!resumed) { + if (!resumed) { loadTorrentTempData(h, savePath, true); } - if(!addInPause || (Preferences().useAdditionDialog())) { + if (!addInPause || (Preferences().useAdditionDialog())) { // Start torrent because it was added in paused state h.resume(); } @@ -961,17 +961,17 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr // Check if BT_backup directory exists const QDir torrentBackup(misc::BTBackupLocation()); - if(!torrentBackup.exists()) return h; + if (!torrentBackup.exists()) return h; // Fix the input path if necessary #ifdef Q_WS_WIN // Windows hack - if(!path.endsWith(".torrent")) - if(QFile::rename(path, path+".torrent")) path += ".torrent"; + if (!path.endsWith(".torrent")) + if (QFile::rename(path, path+".torrent")) path += ".torrent"; #endif - if(path.startsWith("file:", Qt::CaseInsensitive)) + if (path.startsWith("file:", Qt::CaseInsensitive)) path = QUrl::fromEncoded(path.toLocal8Bit()).toLocalFile(); - if(path.isEmpty()) return h; + if (path.isEmpty()) return h; Q_ASSERT(!misc::isUrl(path)); @@ -981,10 +981,10 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr qDebug() << "Loading torrent at" << path; // Getting torrent file informations t = new torrent_info(path.toUtf8().constData()); - if(!t->is_valid()) + if (!t->is_valid()) throw std::exception(); } catch(std::exception& e) { - if(!from_url.isNull()) { + if (!from_url.isNull()) { addConsoleMessage(tr("Unable to decode torrent file: '%1'", "e.g: Unable to decode torrent file: '/home/y/xxx.torrent'").arg(from_url), QString::fromUtf8("red")); addConsoleMessage(QString::fromLocal8Bit(e.what()), "red"); //emit invalidTorrent(from_url); @@ -1000,7 +1000,7 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr //emit invalidTorrent(path); } addConsoleMessage(tr("This file is either corrupted or this isn't a torrent."),QString::fromUtf8("red")); - if(fromScanDir) { + if (fromScanDir) { // Remove file QFile::remove(path); } @@ -1013,10 +1013,10 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr qDebug(" -> Name: %s", t->name().c_str()); // Check for duplicate - if(s->find_torrent(t->info_hash()).is_valid()) { + if (s->find_torrent(t->info_hash()).is_valid()) { qDebug("/!\\ Torrent is already in download list"); // Update info Bar - if(!from_url.isNull()) { + if (!from_url.isNull()) { addConsoleMessage(tr("'%1' is already in download list.", "e.g: 'xxx.avi' is already in download list.").arg(from_url)); }else{ #if defined(Q_WS_WIN) || defined(Q_OS_OS2) @@ -1033,16 +1033,16 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr mergeTorrents(h_ex, t); // Delete file if temporary - if(!from_url.isNull() || fromScanDir) + if (!from_url.isNull() || fromScanDir) QFile::remove(path); return h; } // Check number of files - if(t->num_files() < 1) { + if (t->num_files() < 1) { addConsoleMessage(tr("Error: The torrent %1 does not contain any file.").arg(misc::toQStringU(t->name()))); // Delete file if temporary - if(!from_url.isNull() || fromScanDir) + if (!from_url.isNull() || fromScanDir) QFile::remove(path); return h; } @@ -1057,8 +1057,8 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr // Get fast resume data if existing bool fastResume = false; std::vector buf; // Needs to stay in the function scope - if(resumed) { - if(loadFastResumeData(hash, buf)) { + if (resumed) { + if (loadFastResumeData(hash, buf)) { fastResume = true; p.resume_data = &buf; qDebug("Successfully loaded fast resume data"); @@ -1068,10 +1068,10 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr else { // Generate fake resume data to make sure unwanted files // are not allocated - if(preAllocateAll) { + if (preAllocateAll) { vector fp; TorrentTempData::getFilesPriority(hash, fp); - if((int)fp.size() == t->num_files()) { + if ((int)fp.size() == t->num_files()) { entry rd = generateFilePriorityResumeData(t, fp); bencode(std::back_inserter(buf), rd); p.resume_data = &buf; @@ -1081,10 +1081,10 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr #endif QString savePath; - if(!from_url.isEmpty() && savepathLabel_fromurl.contains(QUrl::fromEncoded(from_url.toUtf8()))) { + if (!from_url.isEmpty() && savepathLabel_fromurl.contains(QUrl::fromEncoded(from_url.toUtf8()))) { // Enforcing the save path defined before URL download (from RSS for example) QPair savePath_label = savepathLabel_fromurl.take(QUrl::fromEncoded(from_url.toUtf8())); - if(savePath_label.first.isEmpty()) + if (savePath_label.first.isEmpty()) savePath = getSavePath(hash, fromScanDir, path, root_folder); else savePath = savePath_label.first; @@ -1093,21 +1093,21 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr } else { savePath = getSavePath(hash, fromScanDir, path, root_folder); } - if(!defaultTempPath.isEmpty() && !TorrentPersistentData::isSeed(hash) && resumed) { + if (!defaultTempPath.isEmpty() && !TorrentPersistentData::isSeed(hash) && resumed) { qDebug("addTorrent::Temp folder is enabled."); QString torrent_tmp_path = defaultTempPath.replace("\\", "/"); - if(!root_folder.isEmpty()) { - if(!torrent_tmp_path.endsWith("/")) torrent_tmp_path += "/"; + if (!root_folder.isEmpty()) { + if (!torrent_tmp_path.endsWith("/")) torrent_tmp_path += "/"; torrent_tmp_path += root_folder; } p.save_path = torrent_tmp_path.toUtf8().constData(); // Check if save path exists, creating it otherwise - if(!QDir(torrent_tmp_path).exists()) QDir().mkpath(torrent_tmp_path); + if (!QDir(torrent_tmp_path).exists()) QDir().mkpath(torrent_tmp_path); qDebug("addTorrent: using save_path: %s", qPrintable(torrent_tmp_path)); } else { p.save_path = savePath.toUtf8().constData(); // Check if save path exists, creating it otherwise - if(!QDir(savePath).exists()) QDir().mkpath(savePath); + if (!QDir(savePath).exists()) QDir().mkpath(savePath); qDebug("addTorrent: using save_path: %s", qPrintable(savePath)); } @@ -1118,9 +1118,9 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr qDebug("Error: %s", e.what()); } // Check if it worked - if(!h.is_valid()) { + if (!h.is_valid()) { qDebug("/!\\ Error: Invalid handle"); - if(!from_url.isNull()) + if (!from_url.isNull()) QFile::remove(path); return h; } @@ -1130,11 +1130,11 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr // If temp path is enabled, move torrent // XXX: The torrent is moved after the torrent_checked_alert // is received to make sure we don't move a completed torrent (#602938) - /*if(!defaultTempPath.isEmpty() && !resumed) { + /*if (!defaultTempPath.isEmpty() && !resumed) { qDebug("Temp folder is enabled, moving new torrent to temp folder"); QString torrent_tmp_path = defaultTempPath.replace("\\", "/"); - if(!root_folder.isEmpty()) { - if(!torrent_tmp_path.endsWith("/")) torrent_tmp_path += "/"; + if (!root_folder.isEmpty()) { + if (!torrent_tmp_path.endsWith("/")) torrent_tmp_path += "/"; torrent_tmp_path += root_folder; } h.move_storage(torrent_tmp_path); @@ -1142,35 +1142,35 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr loadTorrentSettings(h); - if(!resumed) { + if (!resumed) { qDebug("This is a NEW torrent (first time)..."); loadTorrentTempData(h, savePath, false); // Append .!qB to incomplete files - if(appendqBExtension) + if (appendqBExtension) appendqBextensionToTorrent(h, true); // Backup torrent file const QString newFile = torrentBackup.absoluteFilePath(hash + ".torrent"); - if(path != newFile) + if (path != newFile) QFile::copy(path, newFile); // Copy the torrent file to the export folder - if(torrentExport) + if (torrentExport) exportTorrentFile(h); } - if(!fastResume && (!addInPause || (Preferences().useAdditionDialog() && !fromScanDir))) { + if (!fastResume && (!addInPause || (Preferences().useAdditionDialog() && !fromScanDir))) { // Start torrent because it was added in paused state h.resume(); } // If temporary file, remove it - if(!from_url.isNull() || fromScanDir) + if (!from_url.isNull() || fromScanDir) QFile::remove(path); // Display console message - if(!from_url.isNull()) { - if(fastResume) + if (!from_url.isNull()) { + if (fastResume) addConsoleMessage(tr("'%1' resumed. (fast resume)", "'/home/y/xxx.torrent' was resumed. (fast resume)").arg(from_url)); else addConsoleMessage(tr("'%1' added to download list.", "'/home/y/xxx.torrent' was added to download list.").arg(from_url)); @@ -1178,12 +1178,12 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr #if defined(Q_WS_WIN) || defined(Q_OS_OS2) QString displayed_path = path; displayed_path.replace("/", "\\"); - if(fastResume) + if (fastResume) addConsoleMessage(tr("'%1' resumed. (fast resume)", "'/home/y/xxx.torrent' was resumed. (fast resume)").arg(displayed_path)); else addConsoleMessage(tr("'%1' added to download list.", "'/home/y/xxx.torrent' was added to download list.").arg(displayed_path)); #else - if(fastResume) + if (fastResume) addConsoleMessage(tr("'%1' resumed. (fast resume)", "'/home/y/xxx.torrent' was resumed. (fast resume)").arg(path)); else addConsoleMessage(tr("'%1' added to download list.", "'/home/y/xxx.torrent' was added to download list.").arg(path)); @@ -1199,9 +1199,9 @@ void QBtSession::exportTorrentFile(const QTorrentHandle &h) { Q_ASSERT(torrentExport); QString torrent_path = QDir(misc::BTBackupLocation()).absoluteFilePath(h.hash()+".torrent"); QDir exportPath(Preferences().getExportDir()); - if(exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) { + if (exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) { QString new_torrent_path = exportPath.absoluteFilePath(h.name()+".torrent"); - if(QFile::exists(new_torrent_path) && misc::sameFiles(torrent_path, new_torrent_path)) { + if (QFile::exists(new_torrent_path) && misc::sameFiles(torrent_path, new_torrent_path)) { // Append hash to torrent name to make it unique new_torrent_path = exportPath.absoluteFilePath(h.name()+"-"+h.hash()+".torrent"); } @@ -1215,25 +1215,25 @@ add_torrent_params QBtSession::initializeAddTorrentParams(const QString &hash) { // Seeding mode // Skip checking and directly start seeding (new in libtorrent v0.15) - if(TorrentTempData::isSeedingMode(hash)) + if (TorrentTempData::isSeedingMode(hash)) p.seed_mode=true; else p.seed_mode=false; // Preallocation mode - if(preAllocateAll) + if (preAllocateAll) p.storage_mode = storage_mode_allocate; else p.storage_mode = storage_mode_sparse; // Priorities #if LIBTORRENT_VERSION_MINOR > 15 - if(TorrentTempData::hasTempData(hash)) { + if (TorrentTempData::hasTempData(hash)) { std::vector fp; TorrentTempData::getFilesPriority(hash, fp); - if(!fp.empty()) { + if (!fp.empty()) { std::vector *fp_conv = new std::vector(); - for(uint i=0; ipush_back(fp[i]); } p.file_priorities = fp_conv; @@ -1253,12 +1253,12 @@ void QBtSession::loadTorrentTempData(QTorrentHandle &h, QString savePath, bool m qDebug("loadTorrentTempdata() - ENTER"); const QString hash = h.hash(); // Sequential download - if(TorrentTempData::hasTempData(hash)) { + if (TorrentTempData::hasTempData(hash)) { // sequential download h.set_sequential_download(TorrentTempData::isSequential(hash)); // The following is useless for newly added magnet - if(!magnet) { + if (!magnet) { #if LIBTORRENT_VERSION_MINOR < 16 // Files priorities vector fp; @@ -1272,32 +1272,32 @@ void QBtSession::loadTorrentTempData(QTorrentHandle &h, QString savePath, bool m // Update file names const QStringList files_path = TorrentTempData::getFilesPath(hash); bool force_recheck = false; - if(files_path.size() == h.num_files()) { - for(int i=0; i t) { // Check if the torrent contains trackers or url seeds we don't know about // and add them - if(!h_ex.is_valid()) return; + if (!h_ex.is_valid()) return; std::vector existing_trackers = h_ex.trackers(); std::vector new_trackers = t->trackers(); bool trackers_added = false; @@ -1315,7 +1315,7 @@ void QBtSession::mergeTorrents(QTorrentHandle &h_ex, boost::intrusive_ptr handles = s->get_torrents(); std::vector::iterator itr; - for(itr=handles.begin(); itr != handles.end(); itr++) { + for (itr=handles.begin(); itr != handles.end(); itr++) { const QTorrentHandle h(*itr); - if(!h.is_valid()) { + if (!h.is_valid()) { std::cerr << "Torrent Export: torrent is invalid, skipping..." << std::endl; continue; } const QString src_path(torrentBackup.absoluteFilePath(h.hash()+".torrent")); - if(QFile::exists(src_path)) { + if (QFile::exists(src_path)) { QString dst_path = exportDir.absoluteFilePath(h.name()+".torrent"); - if(QFile::exists(dst_path)) { - if(!misc::sameFiles(src_path, dst_path)) { + if (QFile::exists(dst_path)) { + if (!misc::sameFiles(src_path, dst_path)) { dst_path = exportDir.absoluteFilePath(h.name()+"-"+h.hash()+".torrent"); } else { qDebug("Torrent Export: Destination file exists, skipping..."); @@ -1410,8 +1410,8 @@ void QBtSession::setMaxConnectionsPerTorrent(int max) { // Apply this to all session torrents std::vector handles = s->get_torrents(); std::vector::const_iterator it; - for(it = handles.begin(); it != handles.end(); it++) { - if(!it->is_valid()) + for (it = handles.begin(); it != handles.end(); it++) { + if (!it->is_valid()) continue; try { it->set_max_connections(max); @@ -1424,8 +1424,8 @@ void QBtSession::setMaxUploadsPerTorrent(int max) { // Apply this to all session torrents std::vector handles = s->get_torrents(); std::vector::const_iterator it; - for(it = handles.begin(); it != handles.end(); it++) { - if(!it->is_valid()) + for (it = handles.begin(); it != handles.end(); it++) { + if (!it->is_valid()) continue; try { it->set_max_uploads(max); @@ -1435,20 +1435,20 @@ void QBtSession::setMaxUploadsPerTorrent(int max) { void QBtSession::enableUPnP(bool b) { Preferences pref; - if(b) { - if(!m_upnp) { + if (b) { + if (!m_upnp) { qDebug("Enabling UPnP / NAT-PMP"); m_upnp = s->start_upnp(); m_natpmp = s->start_natpmp(); } // Use UPnP/NAT-PMP for Web UI too - if(pref.isWebUiEnabled() && pref.useUPnPForWebUIPort()) { + if (pref.isWebUiEnabled() && pref.useUPnPForWebUIPort()) { const qint16 port = pref.getWebUiPort(); m_upnp->add_mapping(upnp::tcp, port, port); m_natpmp->add_mapping(natpmp::tcp, port, port); } } else { - if(m_upnp) { + if (m_upnp) { qDebug("Disabling UPnP / NAT-PMP"); s->stop_upnp(); s->stop_natpmp(); @@ -1459,14 +1459,14 @@ void QBtSession::enableUPnP(bool b) { } void QBtSession::enableLSD(bool b) { - if(b) { - if(!LSDEnabled) { + if (b) { + if (!LSDEnabled) { qDebug("Enabling Local Peer Discovery"); s->start_lsd(); LSDEnabled = true; } } else { - if(LSDEnabled) { + if (LSDEnabled) { qDebug("Disabling Local Peer Discovery"); s->stop_lsd(); LSDEnabled = false; @@ -1476,17 +1476,17 @@ void QBtSession::enableLSD(bool b) { void QBtSession::loadSessionState() { const QString state_path = misc::cacheLocation()+QDir::separator()+QString::fromUtf8("ses_state"); - if(!QFile::exists(state_path)) return; - if(QFile(state_path).size() == 0) { + if (!QFile::exists(state_path)) return; + if (QFile(state_path).size() == 0) { // Remove empty invalid state file QFile::remove(state_path); return; } QFile state_file(state_path); - if(!state_file.open(QIODevice::ReadOnly)) return; + if (!state_file.open(QIODevice::ReadOnly)) return; std::vector in; const qint64 content_size = state_file.bytesAvailable(); - if(content_size <= 0) return; + if (content_size <= 0) return; in.resize(content_size); state_file.read(&in[0], content_size); // bdecode @@ -1494,7 +1494,7 @@ void QBtSession::loadSessionState() { #if LIBTORRENT_VERSION_MINOR > 15 error_code ec; lazy_bdecode(&in[0], &in[0] + in.size(), e, ec); - if(!ec) { + if (!ec) { #else if (lazy_bdecode(&in[0], &in[0] + in.size(), e) == 0) { #endif @@ -1518,8 +1518,8 @@ void QBtSession::saveSessionState() { // Enable DHT bool QBtSession::enableDHT(bool b) { - if(b) { - if(!DHTEnabled) { + if (b) { + if (!DHTEnabled) { try { qDebug() << "Starting DHT..."; Q_ASSERT(!s->is_dht_running()); @@ -1536,7 +1536,7 @@ bool QBtSession::enableDHT(bool b) { } } } else { - if(DHTEnabled) { + if (DHTEnabled) { DHTEnabled = false; s->stop_dht(); qDebug("DHT disabled"); @@ -1547,7 +1547,7 @@ bool QBtSession::enableDHT(bool b) { qreal QBtSession::getRealRatio(const QString &hash) const{ QTorrentHandle h = getTorrentHandle(hash); - if(!h.is_valid()) { + if (!h.is_valid()) { return 0.; } @@ -1558,15 +1558,15 @@ qreal QBtSession::getRealRatio(const QString &hash) const{ all_time_download = h.total_done(); } - if(all_time_download == 0) { - if(all_time_upload == 0) + if (all_time_download == 0) { + if (all_time_upload == 0) return 0; return MAX_RATIO+1; } qreal ratio = all_time_upload / (float) all_time_download; Q_ASSERT(ratio >= 0.); - if(ratio > MAX_RATIO) + if (ratio > MAX_RATIO) ratio = MAX_RATIO; return ratio; } @@ -1575,14 +1575,14 @@ qreal QBtSession::getRealRatio(const QString &hash) const{ void QBtSession::saveTempFastResumeData() { std::vector torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { QTorrentHandle h = QTorrentHandle(*torrentIT); try { - if(!h.is_valid() || !h.has_metadata() /*|| h.is_seed() || h.is_paused()*/) continue; + if (!h.is_valid() || !h.has_metadata() /*|| h.is_seed() || h.is_paused()*/) continue; #if LIBTORRENT_VERSION_MINOR > 15 - if(!h.need_save_resume_data()) continue; + if (!h.need_save_resume_data()) continue; #endif - if(h.state() == torrent_status::checking_files || h.state() == torrent_status::queued_for_checking) continue; + if (h.state() == torrent_status::checking_files || h.state() == torrent_status::queued_for_checking) continue; qDebug("Saving fastresume data for %s", qPrintable(h.name())); h.save_resume_data(); }catch(std::exception e){} @@ -1601,15 +1601,15 @@ void QBtSession::saveFastResumeData() { s->pause(); std::vector torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { QTorrentHandle h = QTorrentHandle(*torrentIT); - if(!h.is_valid() || !h.has_metadata()) continue; + if (!h.is_valid() || !h.has_metadata()) continue; try { - if(isQueueingEnabled()) + if (isQueueingEnabled()) TorrentPersistentData::savePriority(h); // Actually with should save fast resume data for paused files too - //if(h.is_paused()) continue; - if(h.state() == torrent_status::checking_files || h.state() == torrent_status::queued_for_checking) continue; + //if (h.is_paused()) continue; + if (h.state() == torrent_status::checking_files || h.state() == torrent_status::queued_for_checking) continue; h.save_resume_data(); ++num_resume_data; } catch(libtorrent::invalid_handle&) {} @@ -1628,7 +1628,7 @@ void QBtSession::saveFastResumeData() { s->pop_alert(); try { // Remove torrent from session - if(rda->handle.is_valid()) + if (rda->handle.is_valid()) s->remove_torrent(rda->handle); }catch(libtorrent::libtorrent_exception){} continue; @@ -1643,16 +1643,16 @@ void QBtSession::saveFastResumeData() { if (!rd->resume_data) continue; QDir torrentBackup(misc::BTBackupLocation()); const QTorrentHandle h(rd->handle); - if(!h.is_valid()) continue; + if (!h.is_valid()) continue; try { // Remove old fastresume file if it exists vector out; bencode(back_inserter(out), *rd->resume_data); const QString filepath = torrentBackup.absoluteFilePath(h.hash()+".fastresume"); QFile resume_file(filepath); - if(resume_file.exists()) + if (resume_file.exists()) QFile::remove(filepath); - if(!out.empty() && resume_file.open(QIODevice::WriteOnly)) { + if (!out.empty() && resume_file.open(QIODevice::WriteOnly)) { resume_file.write(&out[0], out.size()); resume_file.close(); } @@ -1668,7 +1668,7 @@ void QBtSession::addConsoleMessage(QString msg, QString) { emit newConsoleMessage(QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss") + " - " + msg); #else void QBtSession::addConsoleMessage(QString msg, QColor color) { - if(consoleMessages.size() > MAX_LOG_MESSAGES) { + if (consoleMessages.size() > MAX_LOG_MESSAGES) { consoleMessages.removeFirst(); } msg = ""+ QDateTime::currentDateTime().toString(QString::fromUtf8("dd/MM/yyyy hh:mm:ss")) + " - " + msg + ""; @@ -1678,11 +1678,11 @@ void QBtSession::addConsoleMessage(QString msg, QColor color) { } void QBtSession::addPeerBanMessage(QString ip, bool from_ipfilter) { - if(peerBanMessages.size() > MAX_LOG_MESSAGES) { + if (peerBanMessages.size() > MAX_LOG_MESSAGES) { peerBanMessages.removeFirst(); } QString msg; - if(from_ipfilter) + if (from_ipfilter) msg = "" + QDateTime::currentDateTime().toString(QString::fromUtf8("dd/MM/yyyy hh:mm:ss")) + " - " + tr("%1 was blocked due to your IP filter", "x.y.z.w was blocked").arg(ip); else msg = "" + QDateTime::currentDateTime().toString(QString::fromUtf8("dd/MM/yyyy hh:mm:ss")) + " - " + tr("%1 was banned due to corrupt pieces", "x.y.z.w was banned").arg(ip); @@ -1693,24 +1693,24 @@ void QBtSession::addPeerBanMessage(QString ip, bool from_ipfilter) { bool QBtSession::isFilePreviewPossible(const QString &hash) const{ // See if there are supported files in the torrent const QTorrentHandle h = getTorrentHandle(hash); - if(!h.is_valid() || !h.has_metadata()) { + if (!h.is_valid() || !h.has_metadata()) { return false; } const unsigned int nbFiles = h.num_files(); - for(unsigned int i=0; i torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { QTorrentHandle h = QTorrentHandle(*torrentIT); - if(!h.is_valid()) continue; + if (!h.is_valid()) continue; h.move_storage(getSavePath(h.hash())); } } else { @@ -1736,14 +1736,14 @@ void QBtSession::setDefaultTempPath(QString temppath) { // Moving all downloading torrents to temporary save path std::vector torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { QTorrentHandle h = QTorrentHandle(*torrentIT); - if(!h.is_valid()) continue; - if(!h.is_seed()) { + if (!h.is_valid()) continue; + if (!h.is_seed()) { QString root_folder = TorrentPersistentData::getRootFolder(h.hash()); QString torrent_tmp_path = temppath.replace("\\", "/"); - if(!root_folder.isEmpty()) { - if(!torrent_tmp_path.endsWith("/")) torrent_tmp_path += "/"; + if (!root_folder.isEmpty()) { + if (!torrent_tmp_path.endsWith("/")) torrent_tmp_path += "/"; torrent_tmp_path += root_folder; } qDebug("Moving torrent to its temp save path: %s", qPrintable(torrent_tmp_path)); @@ -1755,15 +1755,15 @@ void QBtSession::setDefaultTempPath(QString temppath) { } void QBtSession::appendqBextensionToTorrent(const QTorrentHandle &h, bool append) { - if(!h.is_valid() || !h.has_metadata()) return; + if (!h.is_valid() || !h.has_metadata()) return; std::vector fp; h.file_progress(fp); - for(int i=0; i 0 && (fp[i]/(double)file_size) < 1.) { + if (file_size > 0 && (fp[i]/(double)file_size) < 1.) { const QString name = h.filepath_at(i); - if(!name.endsWith(".!qB")) { + if (!name.endsWith(".!qB")) { const QString new_name = name+".!qB"; qDebug("Renaming %s to %s", qPrintable(name), qPrintable(new_name)); h.rename_file(i, new_name); @@ -1771,7 +1771,7 @@ void QBtSession::appendqBextensionToTorrent(const QTorrentHandle &h, bool append } } else { QString name = h.filepath_at(i); - if(name.endsWith(".!qB")) { + if (name.endsWith(".!qB")) { const QString old_name = name; name.chop(4); qDebug("Renaming %s to %s", qPrintable(old_name), qPrintable(name)); @@ -1782,12 +1782,12 @@ void QBtSession::appendqBextensionToTorrent(const QTorrentHandle &h, bool append } void QBtSession::changeLabelInTorrentSavePath(const QTorrentHandle &h, QString old_label, QString new_label) { - if(!h.is_valid()) return; - if(!appendLabelToSavePath) return; + if (!h.is_valid()) return; + if (!appendLabelToSavePath) return; QString old_save_path = TorrentPersistentData::getSavePath(h.hash()); - if(!old_save_path.startsWith(defaultSavePath)) return; + if (!old_save_path.startsWith(defaultSavePath)) return; QString new_save_path = misc::updateLabelInSavePath(defaultSavePath, old_save_path, old_label, new_label); - if(new_save_path != old_save_path) { + if (new_save_path != old_save_path) { // Move storage qDebug("Moving storage to %s", qPrintable(new_save_path)); QDir().mkpath(new_save_path); @@ -1796,13 +1796,13 @@ void QBtSession::changeLabelInTorrentSavePath(const QTorrentHandle &h, QString o } void QBtSession::appendLabelToTorrentSavePath(const QTorrentHandle& h) { - if(!h.is_valid()) return; + if (!h.is_valid()) return; const QString label = TorrentPersistentData::getLabel(h.hash()); - if(label.isEmpty()) return; + if (label.isEmpty()) return; // Current save path QString old_save_path = TorrentPersistentData::getSavePath(h.hash()); QString new_save_path = misc::updateLabelInSavePath(defaultSavePath, old_save_path, "", label); - if(old_save_path != new_save_path) { + if (old_save_path != new_save_path) { // Move storage QDir().mkpath(new_save_path); h.move_storage(new_save_path); @@ -1810,13 +1810,13 @@ void QBtSession::appendLabelToTorrentSavePath(const QTorrentHandle& h) { } void QBtSession::setAppendLabelToSavePath(bool append) { - if(appendLabelToSavePath != append) { + if (appendLabelToSavePath != append) { appendLabelToSavePath = !appendLabelToSavePath; - if(appendLabelToSavePath) { + if (appendLabelToSavePath) { // Move torrents storage to sub folder with label name std::vector torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { QTorrentHandle h = QTorrentHandle(*torrentIT); appendLabelToTorrentSavePath(h); } @@ -1825,12 +1825,12 @@ void QBtSession::setAppendLabelToSavePath(bool append) { } void QBtSession::setAppendqBExtension(bool append) { - if(appendqBExtension != append) { + if (appendqBExtension != append) { appendqBExtension = !appendqBExtension; // append or remove .!qB extension for incomplete files std::vector torrents = s->get_torrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { QTorrentHandle h = QTorrentHandle(*torrentIT); appendqBextensionToTorrent(h, appendqBExtension); } @@ -1847,7 +1847,7 @@ void QBtSession::setListeningPort(int port) { error_code ec; #endif const QString iface_name = pref.getNetworkInterface(); - if(iface_name.isEmpty()) { + if (iface_name.isEmpty()) { #if LIBTORRENT_VERSION_MINOR > 15 s->listen_on(ports, ec); #else @@ -1857,7 +1857,7 @@ void QBtSession::setListeningPort(int port) { } // Attempt to listen on provided interface const QNetworkInterface network_iface = QNetworkInterface::interfaceFromName(iface_name); - if(!network_iface.isValid()) { + if (!network_iface.isValid()) { qDebug("Invalid network interface: %s", qPrintable(iface_name)); addConsoleMessage(tr("The network interface defined is invalid: %1").arg(iface_name), "red"); addConsoleMessage(tr("Trying any other network interface available instead.")); @@ -1870,19 +1870,19 @@ void QBtSession::setListeningPort(int port) { } QString ip; qDebug("This network interface has %d IP addresses", network_iface.addressEntries().size()); - foreach(const QNetworkAddressEntry &entry, network_iface.addressEntries()) { + foreach (const QNetworkAddressEntry &entry, network_iface.addressEntries()) { qDebug("Trying to listen on IP %s (%s)", qPrintable(entry.ip().toString()), qPrintable(iface_name)); #if LIBTORRENT_VERSION_MINOR > 15 s->listen_on(ports, ec, entry.ip().toString().toAscii().constData()); - if(!ec) { + if (!ec) { #else - if(s->listen_on(ports, entry.ip().toString().toAscii().constData())) { + if (s->listen_on(ports, entry.ip().toString().toAscii().constData())) { #endif ip = entry.ip().toString(); break; } } - if(s->is_listening()) { + if (s->is_listening()) { addConsoleMessage(tr("Listening on IP address %1 on network interface %2...").arg(ip).arg(iface_name)); } else { qDebug("Failed to listen on any of the IP addresses"); @@ -1921,8 +1921,8 @@ void QBtSession::setUploadRateLimit(long rate) { // Torrents will a ratio superior to the given value will // be automatically deleted void QBtSession::setGlobalMaxRatio(qreal ratio) { - if(ratio < 0) ratio = -1.; - if(global_ratio_limit != ratio) { + if (ratio < 0) ratio = -1.; + if (global_ratio_limit != ratio) { global_ratio_limit = ratio; qDebug("* Set global deleteRatio to %.1f", global_ratio_limit); updateRatioTimer(); @@ -1951,7 +1951,7 @@ void QBtSession::removeRatioPerTorrent(const QString &hash) qreal QBtSession::getMaxRatioPerTorrent(const QString &hash, bool *usesGlobalRatio) const { qreal ratio_limit = TorrentPersistentData::getRatioLimit(hash); - if(ratio_limit == TorrentPersistentData::USE_GLOBAL_RATIO) { + if (ratio_limit == TorrentPersistentData::USE_GLOBAL_RATIO) { ratio_limit = global_ratio_limit; *usesGlobalRatio = true; } else { @@ -1972,8 +1972,8 @@ void QBtSession::updateRatioTimer() // Set DHT port (>= 1 or 0 if same as BT) void QBtSession::setDHTPort(int dht_port) { - if(dht_port >= 0) { - if(dht_port == current_dht_port) return; + if (dht_port >= 0) { + if (dht_port == current_dht_port) return; struct dht_settings DHTSettings; DHTSettings.service_port = dht_port; s->set_dht_settings(DHTSettings); @@ -1985,12 +1985,12 @@ void QBtSession::setDHTPort(int dht_port) { // Enable IP Filtering void QBtSession::enableIPFilter(const QString &filter_path, bool force) { qDebug("Enabling IPFiler"); - if(!filterParser) { + if (!filterParser) { filterParser = new FilterParserThread(this, s); connect(filterParser.data(), SIGNAL(IPFilterParsed(int)), SLOT(handleIPFilterParsed(int))); connect(filterParser.data(), SIGNAL(IPFilterError()), SLOT(handleIPFilterError())); } - if(filterPath.isEmpty() || filterPath != filter_path || force) { + if (filterPath.isEmpty() || filterPath != filter_path || force) { filterPath = filter_path; filterParser->processFilterFile(filter_path); } @@ -2000,7 +2000,7 @@ void QBtSession::enableIPFilter(const QString &filter_path, bool force) { void QBtSession::disableIPFilter() { qDebug("Disabling IPFilter"); s->set_ip_filter(ip_filter()); - if(filterParser) { + if (filterParser) { disconnect(filterParser.data(), 0, this, 0); delete filterParser; } @@ -2053,7 +2053,7 @@ void QBtSession::setProxySettings(proxy_settings proxySettings) { } // We need this for urllib in search engine plugins qDebug("HTTP communications proxy string: %s", qPrintable(proxy_str)); - if(proxySettings.type == proxy_settings::socks5 || proxySettings.type == proxy_settings::socks5_pw) + if (proxySettings.type == proxy_settings::socks5 || proxySettings.type == proxy_settings::socks5_pw) qputenv("sock_proxy", proxy_str.toLocal8Bit()); else qputenv("http_proxy", proxy_str.toLocal8Bit()); @@ -2061,9 +2061,9 @@ void QBtSession::setProxySettings(proxy_settings proxySettings) { void QBtSession::recursiveTorrentDownload(const QTorrentHandle &h) { try { - for(int i=0; istart(program); } else { @@ -2131,29 +2131,29 @@ void QBtSession::readAlerts() { while (a.get()) { if (torrent_finished_alert* p = dynamic_cast(a.get())) { QTorrentHandle h(p->handle); - if(h.is_valid()) { + if (h.is_valid()) { const QString hash = h.hash(); qDebug("Got a torrent finished alert for %s", qPrintable(h.name())); // Remove .!qB extension if necessary - if(appendqBExtension) + if (appendqBExtension) appendqBextensionToTorrent(h, false); const bool was_already_seeded = TorrentPersistentData::isSeed(hash); qDebug("Was already seeded: %d", was_already_seeded); - if(!was_already_seeded) { + if (!was_already_seeded) { h.save_resume_data(); qDebug("Checking if the torrent contains torrent files to download"); // Check if there are torrent files inside - for(int i=0; i t = new torrent_info(torrent_fullpath.toUtf8().constData()); - if(t->is_valid()) { + if (t->is_valid()) { qDebug("emitting recursiveTorrentDownloadPossible()"); emit recursiveTorrentDownloadPossible(h); break; @@ -2171,11 +2171,11 @@ void QBtSession::readAlerts() { } } // Move to download directory if necessary - if(!defaultTempPath.isEmpty()) { + if (!defaultTempPath.isEmpty()) { // Check if directory is different const QDir current_dir(h.save_path()); const QDir save_dir(getSavePath(hash)); - if(current_dir != save_dir) { + if (current_dir != save_dir) { qDebug("Moving torrent from the temp folder"); h.move_storage(save_dir.absolutePath()); } @@ -2185,7 +2185,7 @@ void QBtSession::readAlerts() { TorrentPersistentData::saveSeedStatus(h); // Recheck if the user asked to Preferences pref; - if(pref.recheckTorrentsOnCompletion()) { + if (pref.recheckTorrentsOnCompletion()) { h.force_recheck(); } qDebug("Emitting finishedTorrent() signal"); @@ -2200,35 +2200,35 @@ void QBtSession::readAlerts() { bool will_shutdown = false; #endif // AutoRun program - if(pref.isAutoRunEnabled()) + if (pref.isAutoRunEnabled()) autoRunExternalProgram(h, will_shutdown); // Mail notification - if(pref.isMailNotificationEnabled()) + if (pref.isMailNotificationEnabled()) sendNotificationEmail(h); #ifndef DISABLE_GUI // Auto-Shutdown - if(will_shutdown) { + if (will_shutdown) { bool suspend = pref.suspendWhenDownloadsComplete(); bool shutdown = pref.shutdownWhenDownloadsComplete(); // Confirm shutdown QString confirm_msg; - if(suspend) { + if (suspend) { confirm_msg = tr("The computer will now go to sleep mode unless you cancel within the next 15 seconds..."); - } else if(shutdown) { + } else if (shutdown) { confirm_msg = tr("The computer will now be switched off unless you cancel within the next 15 seconds..."); } else { confirm_msg = tr("qBittorrent will now exit unless you cancel within the next 15 seconds..."); } - if(!ShutdownConfirmDlg::askForConfirmation(confirm_msg)) + if (!ShutdownConfirmDlg::askForConfirmation(confirm_msg)) return; // Actually shut down - if(suspend || shutdown) { + if (suspend || shutdown) { qDebug("Preparing for auto-shutdown because all downloads are complete!"); // Disabling it for next time pref.setShutdownWhenDownloadsComplete(false); pref.setSuspendWhenDownloadsComplete(false); // Make sure preferences are synced before exiting - if(suspend) + if (suspend) m_shutdownAct = SUSPEND_COMPUTER; else m_shutdownAct = SHUTDOWN_COMPUTER; @@ -2244,15 +2244,15 @@ void QBtSession::readAlerts() { else if (save_resume_data_alert* p = dynamic_cast(a.get())) { const QDir torrentBackup(misc::BTBackupLocation()); const QTorrentHandle h(p->handle); - if(h.is_valid() && p->resume_data) { + if (h.is_valid() && p->resume_data) { const QString filepath = torrentBackup.absoluteFilePath(h.hash()+".fastresume"); QFile resume_file(filepath); - if(resume_file.exists()) + if (resume_file.exists()) QFile::remove(filepath); qDebug("Saving fastresume data in %s", qPrintable(filepath)); vector out; bencode(back_inserter(out), *p->resume_data); - if(!out.empty() && resume_file.open(QIODevice::WriteOnly)) { + if (!out.empty() && resume_file.open(QIODevice::WriteOnly)) { resume_file.write(&out[0], out.size()); resume_file.close(); } @@ -2260,15 +2260,15 @@ void QBtSession::readAlerts() { } else if (file_renamed_alert* p = dynamic_cast(a.get())) { QTorrentHandle h(p->handle); - if(h.is_valid()) { - if(h.num_files() > 1) { + if (h.is_valid()) { + if (h.num_files() > 1) { // Check if folders were renamed QStringList old_path_parts = h.orig_filepath_at(p->index).split("/"); old_path_parts.removeLast(); QString old_path = old_path_parts.join("/"); QStringList new_path_parts = misc::toQStringU(p->name).split("/"); new_path_parts.removeLast(); - if(!new_path_parts.isEmpty() && old_path != new_path_parts.join("/")) { + if (!new_path_parts.isEmpty() && old_path != new_path_parts.join("/")) { qDebug("Old_path(%s) != new_path(%s)", qPrintable(old_path), qPrintable(new_path_parts.join("/"))); old_path = h.save_path()+"/"+old_path; qDebug("Detected folder renaming, attempt to delete old folder: %s", qPrintable(old_path)); @@ -2284,8 +2284,8 @@ void QBtSession::readAlerts() { else if (torrent_deleted_alert* p = dynamic_cast(a.get())) { qDebug("A torrent was deleted from the hard disk, attempting to remove the root folder too..."); QString hash = misc::toQString(p->info_hash); - if(!hash.isEmpty()) { - if(savePathsToRemove.contains(hash)) { + if (!hash.isEmpty()) { + if (savePathsToRemove.contains(hash)) { const QString dirpath = savePathsToRemove.take(hash); qDebug() << "Removing save path: " << dirpath << "..."; bool ok = QDir().rmdir(dirpath); @@ -2295,9 +2295,9 @@ void QBtSession::readAlerts() { } else { // Fallback qDebug() << "hash is empty, use fallback to remove save path"; - foreach(const QString& key, savePathsToRemove.keys()) { + foreach (const QString& key, savePathsToRemove.keys()) { // Attempt to delete - if(QDir().rmdir(savePathsToRemove[key])) { + if (QDir().rmdir(savePathsToRemove[key])) { savePathsToRemove.remove(key); } } @@ -2305,17 +2305,17 @@ void QBtSession::readAlerts() { } else if (storage_moved_alert* p = dynamic_cast(a.get())) { QTorrentHandle h(p->handle); - if(h.is_valid()) { + if (h.is_valid()) { // Attempt to remove old folder if empty const QString old_save_path = TorrentPersistentData::getPreviousPath(h.hash()); const QString new_save_path = misc::toQStringU(p->path.c_str()); qDebug("Torrent moved from %s to %s", qPrintable(old_save_path), qPrintable(new_save_path)); QDir old_save_dir(old_save_path); - if(old_save_dir != QDir(defaultSavePath) && old_save_dir != QDir(defaultTempPath)) { + if (old_save_dir != QDir(defaultSavePath) && old_save_dir != QDir(defaultTempPath)) { qDebug("Attempting to remove %s", qPrintable(old_save_path)); QDir().rmpath(old_save_path); } - if(defaultTempPath.isEmpty() || !new_save_path.startsWith(defaultTempPath)) { + if (defaultTempPath.isEmpty() || !new_save_path.startsWith(defaultTempPath)) { qDebug("Storage has been moved, updating save path to %s", qPrintable(new_save_path)); TorrentPersistentData::saveSavePath(h.hash(), new_save_path); } @@ -2325,17 +2325,17 @@ void QBtSession::readAlerts() { } else if (metadata_received_alert* p = dynamic_cast(a.get())) { QTorrentHandle h(p->handle); - if(h.is_valid()) { + if (h.is_valid()) { qDebug("Received metadata for %s", qPrintable(h.hash())); // Save metadata const QDir torrentBackup(misc::BTBackupLocation()); - if(!QFile::exists(torrentBackup.absoluteFilePath(h.hash()+QString(".torrent")))) + if (!QFile::exists(torrentBackup.absoluteFilePath(h.hash()+QString(".torrent")))) h.save_torrent_file(torrentBackup.absoluteFilePath(h.hash()+QString(".torrent"))); // Copy the torrent file to the export folder - if(torrentExport) + if (torrentExport) exportTorrentFile(h); // Append .!qB to incomplete files - if(appendqBExtension) + if (appendqBExtension) appendqBextensionToTorrent(h, true); // Truncate root folder const QString root_folder = misc::truncateRootFolder(p->handle); @@ -2343,11 +2343,11 @@ void QBtSession::readAlerts() { qDebug() << "magnet root folder is:" << root_folder; // Move to a subfolder corresponding to the torrent root folder if necessary - if(!root_folder.isEmpty()) { - if(!h.is_seed() && !defaultTempPath.isEmpty()) { + if (!root_folder.isEmpty()) { + if (!h.is_seed() && !defaultTempPath.isEmpty()) { qDebug("Incomplete torrent in temporary folder case"); QString torrent_tmp_path = defaultTempPath.replace("\\", "/"); - if(!torrent_tmp_path.endsWith("/")) torrent_tmp_path += "/"; + if (!torrent_tmp_path.endsWith("/")) torrent_tmp_path += "/"; torrent_tmp_path += root_folder; qDebug() << "Moving torrent to" << torrent_tmp_path; h.move_storage(torrent_tmp_path); @@ -2358,7 +2358,7 @@ void QBtSession::readAlerts() { } } emit metadataReceived(h); - if(h.is_paused()) { + if (h.is_paused()) { // XXX: Unfortunately libtorrent-rasterbar does not send a torrent_paused_alert // and the torrent can be paused when metadata is received emit pausedTorrent(h); @@ -2368,12 +2368,12 @@ void QBtSession::readAlerts() { } else if (file_error_alert* p = dynamic_cast(a.get())) { QTorrentHandle h(p->handle); - if(h.is_valid()) { + if (h.is_valid()) { h.pause(); std::cerr << "File Error: " << p->message().c_str() << std::endl; addConsoleMessage(tr("An I/O error occured, '%1' paused.").arg(h.name())); addConsoleMessage(tr("Reason: %1").arg(misc::toQString(p->message()))); - if(h.is_valid()) { + if (h.is_valid()) { emit fullDiskError(h, misc::toQString(p->message())); //h.pause(); emit pausedTorrent(h); @@ -2383,10 +2383,10 @@ void QBtSession::readAlerts() { else if (file_completed_alert* p = dynamic_cast(a.get())) { QTorrentHandle h(p->handle); qDebug("A file completed download in torrent %s", qPrintable(h.name())); - if(appendqBExtension) { + if (appendqBExtension) { qDebug("appendqBTExtension is true"); QString name = h.filepath_at(p->index); - if(name.endsWith(".!qB")) { + if (name.endsWith(".!qB")) { const QString old_name = name; name.chop(4); qDebug("Renaming %s to %s", qPrintable(old_name), qPrintable(name)); @@ -2395,9 +2395,9 @@ void QBtSession::readAlerts() { } } else if (torrent_paused_alert* p = dynamic_cast(a.get())) { - if(p->handle.is_valid()) { + if (p->handle.is_valid()) { QTorrentHandle h(p->handle); - if(!h.has_error()) + if (!h.has_error()) h.save_resume_data(); emit pausedTorrent(h); } @@ -2405,9 +2405,9 @@ void QBtSession::readAlerts() { else if (tracker_error_alert* p = dynamic_cast(a.get())) { // Level: fatal QTorrentHandle h(p->handle); - if(h.is_valid()){ + if (h.is_valid()){ // Authentication - if(p->status_code != 401) { + if (p->status_code != 401) { qDebug("Received a tracker error for %s: %s", p->url.c_str(), p->msg.c_str()); const QString tracker_url = misc::toQString(p->url); QHash trackers_data = trackersInfos.value(h.hash(), QHash()); @@ -2422,7 +2422,7 @@ void QBtSession::readAlerts() { } else if (tracker_reply_alert* p = dynamic_cast(a.get())) { const QTorrentHandle h(p->handle); - if(h.is_valid()){ + if (h.is_valid()){ qDebug("Received a tracker reply from %s (Num_peers=%d)", p->url.c_str(), p->num_peers); // Connection was successful now. Remove possible old errors QHash trackers_data = trackersInfos.value(h.hash(), QHash()); @@ -2435,7 +2435,7 @@ void QBtSession::readAlerts() { } } else if (tracker_warning_alert* p = dynamic_cast(a.get())) { const QTorrentHandle h(p->handle); - if(h.is_valid()){ + if (h.is_valid()){ // Connection was successful now but there is a warning message QHash trackers_data = trackersInfos.value(h.hash(), QHash()); const QString tracker_url = misc::toQString(p->url); @@ -2473,9 +2473,9 @@ void QBtSession::readAlerts() { } else if (fastresume_rejected_alert* p = dynamic_cast(a.get())) { QTorrentHandle h(p->handle); - if(h.is_valid()) { + if (h.is_valid()) { qDebug("/!\\ Fast resume failed for %s, reason: %s", qPrintable(h.name()), p->message().c_str()); - if(p->error.value() == 134 && TorrentPersistentData::isSeed(h.hash()) && h.has_missing_files()) { + if (p->error.value() == 134 && TorrentPersistentData::isSeed(h.hash()) && h.has_missing_files()) { const QString hash = h.hash(); // Mismatching file size (files were probably moved addConsoleMessage(tr("File sizes mismatch for torrent %1, pausing it.").arg(h.name())); @@ -2497,36 +2497,36 @@ void QBtSession::readAlerts() { // Force reannounce on all torrents because some trackers blacklist some ports std::vector torrents = s->get_torrents(); std::vector::iterator it; - for(it = torrents.begin(); it != torrents.end(); it++) { + for (it = torrents.begin(); it != torrents.end(); it++) { it->force_reannounce(); } emit listenSucceeded(); } else if (torrent_checked_alert* p = dynamic_cast(a.get())) { QTorrentHandle h(p->handle); - if(h.is_valid()){ + if (h.is_valid()){ const QString hash = h.hash(); qDebug("%s have just finished checking", qPrintable(hash)); // Save seed status TorrentPersistentData::saveSeedStatus(h); // Move to temp directory if necessary - if(!h.is_seed() && !defaultTempPath.isEmpty()) { + if (!h.is_seed() && !defaultTempPath.isEmpty()) { // Check if directory is different const QDir current_dir(h.save_path()); const QDir save_dir(getSavePath(h.hash())); - if(current_dir == save_dir) { + if (current_dir == save_dir) { qDebug("Moving the torrent to the temp directory..."); QString root_folder = TorrentPersistentData::getRootFolder(hash); QString torrent_tmp_path = defaultTempPath.replace("\\", "/"); - if(!root_folder.isEmpty()) { - if(!torrent_tmp_path.endsWith("/")) torrent_tmp_path += "/"; + if (!root_folder.isEmpty()) { + if (!torrent_tmp_path.endsWith("/")) torrent_tmp_path += "/"; torrent_tmp_path += root_folder; } h.move_storage(torrent_tmp_path); } } emit torrentFinishedChecking(h); - if(torrentsToPausedAfterChecking.contains(hash)) { + if (torrentsToPausedAfterChecking.contains(hash)) { torrentsToPausedAfterChecking.removeOne(hash); h.pause(); emit pausedTorrent(h); @@ -2539,9 +2539,9 @@ void QBtSession::readAlerts() { void QBtSession::recheckTorrent(const QString &hash) { QTorrentHandle h = getTorrentHandle(hash); - if(h.is_valid() && h.has_metadata()) { - if(h.is_paused()) { - if(!torrentsToPausedAfterChecking.contains(h.hash())) { + if (h.is_valid() && h.has_metadata()) { + if (h.is_paused()) { + if (!torrentsToPausedAfterChecking.contains(h.hash())) { torrentsToPausedAfterChecking << h.hash(); h.resume(); } @@ -2565,15 +2565,15 @@ session_status QBtSession::getSessionStatus() const{ QString QBtSession::getSavePath(const QString &hash, bool fromScanDir, QString filePath, QString root_folder) { QString savePath; - if(TorrentTempData::hasTempData(hash)) { + if (TorrentTempData::hasTempData(hash)) { savePath = TorrentTempData::getSavePath(hash); - if(savePath.isEmpty()) { + if (savePath.isEmpty()) { savePath = defaultSavePath; } - if(appendLabelToSavePath) { + if (appendLabelToSavePath) { qDebug("appendLabelToSavePath is true"); const QString label = TorrentTempData::getLabel(hash); - if(!label.isEmpty()) { + if (!label.isEmpty()) { savePath = misc::updateLabelInSavePath(defaultSavePath, savePath, "", label); } } @@ -2582,22 +2582,22 @@ QString QBtSession::getSavePath(const QString &hash, bool fromScanDir, QString f savePath = TorrentPersistentData::getSavePath(hash); qDebug("SavePath got from persistant data is %s", qPrintable(savePath)); bool append_root_folder = false; - if(savePath.isEmpty()) { - if(fromScanDir && m_scanFolders->downloadInTorrentFolder(filePath)) { + if (savePath.isEmpty()) { + if (fromScanDir && m_scanFolders->downloadInTorrentFolder(filePath)) { savePath = QFileInfo(filePath).dir().path(); } else { savePath = defaultSavePath; } append_root_folder = true; } - if(!fromScanDir && appendLabelToSavePath) { + if (!fromScanDir && appendLabelToSavePath) { const QString label = TorrentPersistentData::getLabel(hash); - if(!label.isEmpty()) { + if (!label.isEmpty()) { qDebug("Torrent label is %s", qPrintable(label)); savePath = misc::updateLabelInSavePath(defaultSavePath, savePath, "", label); } } - if(append_root_folder && !root_folder.isEmpty()) { + if (append_root_folder && !root_folder.isEmpty()) { // Append torrent root folder to the save path savePath = QDir(savePath).absoluteFilePath(root_folder); qDebug("Torrent root folder is %s", qPrintable(root_folder)); @@ -2608,7 +2608,7 @@ QString QBtSession::getSavePath(const QString &hash, bool fromScanDir, QString f // Clean path savePath.replace("\\", "/"); savePath = misc::expandPath(savePath); - if(!savePath.endsWith("/")) + if (!savePath.endsWith("/")) savePath += "/"; return savePath; } @@ -2628,7 +2628,7 @@ void QBtSession::downloadFromUrl(const QString &url) { } void QBtSession::downloadFromURLList(const QStringList& urls) { - foreach(const QString &url, urls) { + foreach (const QString &url, urls) { downloadFromUrl(url); } } @@ -2649,14 +2649,14 @@ void QBtSession::downloadUrlAndSkipDialog(QString url, QString save_path, QStrin // Add to Bittorrent session the downloaded torrent file void QBtSession::processDownloadedFile(QString url, QString file_path) { const int index = url_skippingDlg.indexOf(QUrl::fromEncoded(url.toUtf8())); - if(index < 0) { + if (index < 0) { // Add file to torrent download list #ifdef Q_WS_WIN // Windows hack - if(!file_path.endsWith(".torrent", Qt::CaseInsensitive)) { + if (!file_path.endsWith(".torrent", Qt::CaseInsensitive)) { Q_ASSERT(QFile::exists(file_path)); qDebug("Torrent name does not end with .torrent, from %s", qPrintable(file_path)); - if(QFile::rename(file_path, file_path+".torrent")) { + if (QFile::rename(file_path, file_path+".torrent")) { file_path += ".torrent"; } else { qDebug("Failed to rename torrent file!"); @@ -2702,9 +2702,9 @@ void QBtSession::startUpTorrents() { QStringList filters; filters << "*.torrent"; const QStringList torrents_on_hd = torrentBackup.entryList(filters, QDir::Files, QDir::Unsorted); - foreach(QString hash, torrents_on_hd) { + foreach (QString hash, torrents_on_hd) { hash.chop(8); // remove trailing .torrent - if(!known_torrents.contains(hash)) { + if (!known_torrents.contains(hash)) { qDebug("found torrent with hash: %s on hard disk", qPrintable(hash)); std::cerr << "ERROR Detected!!! Adding back torrent " << qPrintable(hash) << " which got lost for some reason." << std::endl; addTorrent(torrentBackup.path()+QDir::separator()+hash+".torrent", false, QString(), true); @@ -2713,11 +2713,11 @@ void QBtSession::startUpTorrents() { // End of safety measure qDebug("Starting up torrents"); - if(isQueueingEnabled()) { + if (isQueueingEnabled()) { priority_queue, vector >, std::greater > > torrent_queue; - foreach(const QString &hash, known_torrents) { + foreach (const QString &hash, known_torrents) { QString filePath; - if(TorrentPersistentData::isMagnet(hash)) { + if (TorrentPersistentData::isMagnet(hash)) { filePath = TorrentPersistentData::getMagnetUri(hash); } else { filePath = torrentBackup.path()+QDir::separator()+hash+".torrent"; @@ -2731,7 +2731,7 @@ void QBtSession::startUpTorrents() { const QString hash = torrent_queue.top().second; torrent_queue.pop(); qDebug("Starting up torrent %s", qPrintable(hash)); - if(TorrentPersistentData::isMagnet(hash)) { + if (TorrentPersistentData::isMagnet(hash)) { addMagnetUri(TorrentPersistentData::getMagnetUri(hash), true); } else { addTorrent(torrentBackup.path()+QDir::separator()+hash+".torrent", false, QString(), true); @@ -2739,9 +2739,9 @@ void QBtSession::startUpTorrents() { } } else { // Resume downloads - foreach(const QString &hash, known_torrents) { + foreach (const QString &hash, known_torrents) { qDebug("Starting up torrent %s", qPrintable(hash)); - if(TorrentPersistentData::isMagnet(hash)) + if (TorrentPersistentData::isMagnet(hash)) addMagnetUri(TorrentPersistentData::getMagnetUri(hash), true); else addTorrent(torrentBackup.path()+QDir::separator()+hash+".torrent", false, QString(), true); @@ -2754,7 +2754,7 @@ void QBtSession::startUpTorrents() { QBtSession * QBtSession::instance() { - if(!m_instance) { + if (!m_instance) { m_instance = new QBtSession; } return m_instance; @@ -2762,7 +2762,7 @@ QBtSession * QBtSession::instance() void QBtSession::drop() { - if(m_instance) { + if (m_instance) { delete m_instance; m_instance = 0; } @@ -2796,13 +2796,13 @@ entry QBtSession::generateFilePriorityResumeData(boost::intrusive_ptrnum_files(); ++i) { + for (int i=0; inum_files(); ++i) { entry::list_type p; p.push_back(entry(0)); p.push_back(entry(0)); @@ -2811,7 +2811,7 @@ entry QBtSession::generateFilePriorityResumeData(boost::intrusive_ptrnum_pieces(); ++i) { + for (int i=0; inum_pieces(); ++i) { tslots.push_back(-1); } rd["slots"] = entry(tslots); diff --git a/src/qtlibtorrent/qtorrenthandle.cpp b/src/qtlibtorrent/qtorrenthandle.cpp index f5343b5ad..6619d2161 100644 --- a/src/qtlibtorrent/qtorrenthandle.cpp +++ b/src/qtlibtorrent/qtorrenthandle.cpp @@ -56,7 +56,7 @@ using namespace std; #if LIBTORRENT_VERSION_MINOR < 16 static QString boostTimeToQString(const boost::posix_time::ptime &boostDate) { - if(boostDate.is_not_a_date_time()) return ""; + if (boostDate.is_not_a_date_time()) return ""; struct std::tm tm; try { tm = boost::posix_time::to_tm(boostDate); @@ -81,7 +81,7 @@ QString QTorrentHandle::hash() const { QString QTorrentHandle::name() const { QString name = TorrentPersistentData::getName(hash()); - if(name.isEmpty()) { + if (name.isEmpty()) { name = misc::toQStringU(torrent_handle::name()); } return name; @@ -124,7 +124,7 @@ qreal QTorrentHandle::progress() const { #else torrent_status st = torrent_handle::status(); #endif - if(!st.total_wanted) + if (!st.total_wanted) return 0.; if (st.total_wanted_done == st.total_wanted) return 1.; @@ -182,19 +182,19 @@ int QTorrentHandle::num_pieces() const { bool QTorrentHandle::first_last_piece_first() const { // Detect first media file int index = 0; - for(index = 0; index < num_files(); ++index) { + for (index = 0; index < num_files(); ++index) { #if LIBTORRENT_VERSION_MINOR > 15 QString path = misc::toQStringU(get_torrent_info().file_at(index).path); #else QString path = misc::toQStringU(get_torrent_info().file_at(index).path.string()); #endif const QString ext = misc::file_extension(path); - if(misc::isPreviewable(ext) && torrent_handle::file_priority(index) > 0) { + if (misc::isPreviewable(ext) && torrent_handle::file_priority(index) > 0) { break; } ++index; } - if(index >= torrent_handle::get_torrent_info().num_files()) return false; + if (index >= torrent_handle::get_torrent_info().num_files()) return false; file_entry media_file = torrent_handle::get_torrent_info().file_at(index); int piece_size = torrent_handle::get_torrent_info().piece_length(); Q_ASSERT(piece_size>0); @@ -285,7 +285,7 @@ QStringList QTorrentHandle::url_seeds() const { try { const std::set existing_seeds = torrent_handle::url_seeds(); std::set::const_iterator it; - for(it = existing_seeds.begin(); it != existing_seeds.end(); it++) { + for (it = existing_seeds.begin(); it != existing_seeds.end(); it++) { qDebug("URL Seed: %s", it->c_str()); res << misc::toQString(*it); } @@ -306,8 +306,8 @@ size_type QTorrentHandle::actual_size() const { bool QTorrentHandle::has_filtered_pieces() const { std::vector piece_priorities = torrent_handle::piece_priorities(); - for(unsigned int i = 0; i fp = torrent_handle::file_priorities(); - for(uint i = 0; i < fp.size(); ++i) { - if(fp[i] == 0) { + for (uint i = 0; i < fp.size(); ++i) { + if (fp[i] == 0) { const QString file_path = QDir::cleanPath(saveDir.absoluteFilePath(filepath_at(i))); - if(file_path.contains(".unwanted")) + if (file_path.contains(".unwanted")) res << file_path; } } @@ -454,14 +454,14 @@ QStringList QTorrentHandle::absolute_files_path_uneeded() const { bool QTorrentHandle::has_missing_files() const { const QStringList paths = absolute_files_path(); - foreach(const QString &path, paths) { - if(!QFile::exists(path)) return true; + foreach (const QString &path, paths) { + if (!QFile::exists(path)) return true; } return false; } int QTorrentHandle::queue_position() const { - if(torrent_handle::queue_position() < 0) + if (torrent_handle::queue_position() < 0) return -1; return torrent_handle::queue_position()+1; } @@ -540,14 +540,14 @@ bool QTorrentHandle::priv() const { QString QTorrentHandle::firstFileSavePath() const { Q_ASSERT(has_metadata()); QString fsave_path = TorrentPersistentData::getSavePath(hash()); - if(fsave_path.isEmpty()) + if (fsave_path.isEmpty()) fsave_path = save_path(); fsave_path.replace("\\", "/"); - if(!fsave_path.endsWith("/")) + if (!fsave_path.endsWith("/")) fsave_path += "/"; fsave_path += filepath_at(0); // Remove .!qB extension - if(fsave_path.endsWith(".!qB", Qt::CaseInsensitive)) + if (fsave_path.endsWith(".!qB", Qt::CaseInsensitive)) fsave_path.chop(4); return fsave_path; } @@ -572,7 +572,7 @@ QString QTorrentHandle::error() const { void QTorrentHandle::downloading_pieces(bitfield &bf) const { std::vector queue; torrent_handle::get_download_queue(queue); - for(std::vector::iterator it=queue.begin(); it!= queue.end(); it++) { + for (std::vector::iterator it=queue.begin(); it!= queue.end(); it++) { bf.set_bit(it->piece_index); } return; @@ -609,22 +609,22 @@ void QTorrentHandle::pause() const { } void QTorrentHandle::resume() const { - if(has_error()) torrent_handle::clear_error(); + if (has_error()) torrent_handle::clear_error(); const QString torrent_hash = hash(); bool has_persistant_error = TorrentPersistentData::hasError(torrent_hash); TorrentPersistentData::setErrorState(torrent_hash, false); bool temp_path_enabled = Preferences().isTempPathEnabled(); - if(has_persistant_error && temp_path_enabled) { + if (has_persistant_error && temp_path_enabled) { // Torrent was supposed to be seeding, checking again in final destination qDebug("Resuming a torrent with error..."); const QString final_save_path = TorrentPersistentData::getSavePath(torrent_hash); qDebug("Torrent final path is: %s", qPrintable(final_save_path)); - if(!final_save_path.isEmpty()) + if (!final_save_path.isEmpty()) move_storage(final_save_path); } torrent_handle::auto_managed(true); torrent_handle::resume(); - if(has_persistant_error && temp_path_enabled) { + if (has_persistant_error && temp_path_enabled) { // Force recheck torrent_handle::force_recheck(); } @@ -645,7 +645,7 @@ void QTorrentHandle::set_tracker_login(QString username, QString password) const } void QTorrentHandle::move_storage(QString new_path) const { - if(QDir(save_path()) == QDir(new_path)) return; + if (QDir(save_path()) == QDir(new_path)) return; TorrentPersistentData::setPreviousSavePath(hash(), save_path()); // Create destination directory if necessary // or move_storage() will fail... @@ -655,12 +655,12 @@ void QTorrentHandle::move_storage(QString new_path) const { } bool QTorrentHandle::save_torrent_file(QString path) const { - if(!has_metadata()) return false; + if (!has_metadata()) return false; entry meta = bdecode(torrent_handle::get_torrent_info().metadata().get(), torrent_handle::get_torrent_info().metadata().get()+torrent_handle::get_torrent_info().metadata_size()); entry torrent_entry(entry::dictionary_t); torrent_entry["info"] = meta; - if(!torrent_handle::trackers().empty()) + if (!torrent_handle::trackers().empty()) torrent_entry["announce"] = torrent_handle::trackers().front().url; vector out; @@ -677,14 +677,14 @@ bool QTorrentHandle::save_torrent_file(QString path) const { void QTorrentHandle::file_priority(int index, int priority) const { vector priorities = torrent_handle::file_priorities(); - if(priorities[index] != priority) { + if (priorities[index] != priority) { priorities[index] = priority; prioritize_files(priorities); } } void QTorrentHandle::prioritize_files(const vector &files) const { - if((int)files.size() != torrent_handle::get_torrent_info().num_files()) return; + if ((int)files.size() != torrent_handle::get_torrent_info().num_files()) return; qDebug() << Q_FUNC_INFO; bool was_seed = is_seed(); vector progress; @@ -692,25 +692,25 @@ void QTorrentHandle::prioritize_files(const vector &files) const { qDebug() << Q_FUNC_INFO << "Changing files priorities..."; torrent_handle::prioritize_files(files); qDebug() << Q_FUNC_INFO << "Moving unwanted files to .unwanted folder..."; - for(uint i=0; i &files) const { #else Q_UNUSED(created); #endif - if(!parent_path.isEmpty() && !parent_path.endsWith("/")) + if (!parent_path.isEmpty() && !parent_path.endsWith("/")) parent_path += "/"; rename_file(i, parent_path+".unwanted/"+old_name); } } // Move wanted files back to their original folder qDebug() << Q_FUNC_INFO << "Moving wanted files back from .unwanted folder"; - if(files[i] > 0) { + if (files[i] > 0) { QString parent_relpath = misc::branchPath(filepath_at(i)); - if(QDir(parent_relpath).dirName() == ".unwanted") { + if (QDir(parent_relpath).dirName() == ".unwanted") { QString old_name = filename_at(i); QString new_relpath = misc::branchPath(parent_relpath); if (new_relpath.isEmpty()) @@ -744,16 +744,16 @@ void QTorrentHandle::prioritize_files(const vector &files) const { } } - if(was_seed && !is_seed()) { + if (was_seed && !is_seed()) { qDebug() << "Torrent is no longer SEEDING"; // Save seed status TorrentPersistentData::saveSeedStatus(*this); // Move to temp folder if necessary const Preferences pref; - if(pref.isTempPathEnabled()) { + if (pref.isTempPathEnabled()) { QString tmp_path = pref.getTempPath(); QString root_folder = TorrentPersistentData::getRootFolder(hash()); - if(!root_folder.isEmpty()) + if (!root_folder.isEmpty()) tmp_path = QDir(tmp_path).absoluteFilePath(root_folder); qDebug() << "tmp folder is enabled, move torrent to " << tmp_path << " from " << save_path(); move_storage(tmp_path); @@ -768,7 +768,7 @@ void QTorrentHandle::add_tracker(const announce_entry& url) const { void QTorrentHandle::prioritize_first_last_piece(int file_index, bool b) const { // Determine the priority to set int prio = 7; // MAX - if(!b) prio = torrent_handle::file_priority(file_index); + if (!b) prio = torrent_handle::file_priority(file_index); file_entry file = get_torrent_info().file_at(file_index); // Determine the first and last piece of the file int piece_size = torrent_handle::get_torrent_info().piece_length(); @@ -785,13 +785,13 @@ void QTorrentHandle::prioritize_first_last_piece(int file_index, bool b) const { } void QTorrentHandle::prioritize_first_last_piece(bool b) const { - if(!has_metadata()) return; + if (!has_metadata()) return; // Download first and last pieces first for all media files in the torrent int index = 0; - for(index = 0; index < num_files(); ++index) { + for (index = 0; index < num_files(); ++index) { const QString path = filepath_at(index); const QString ext = misc::file_extension(path); - if(misc::isPreviewable(ext) && torrent_handle::file_priority(index) > 0) { + if (misc::isPreviewable(ext) && torrent_handle::file_priority(index) > 0) { qDebug() << "File" << path << "is previewable, toggle downloading of first/last pieces first"; prioritize_first_last_piece(index, b); } diff --git a/src/qtlibtorrent/torrentmodel.cpp b/src/qtlibtorrent/torrentmodel.cpp index cddb28c99..139aee9bc 100644 --- a/src/qtlibtorrent/torrentmodel.cpp +++ b/src/qtlibtorrent/torrentmodel.cpp @@ -41,7 +41,7 @@ TorrentModelItem::TorrentModelItem(const QTorrentHandle &h) m_torrent = h; m_hash = h.hash(); m_name = TorrentPersistentData::getName(h.hash()); - if(m_name.isEmpty()) m_name = h.name(); + if (m_name.isEmpty()) m_name = h.name(); m_addedTime = TorrentPersistentData::getAddedDate(h.hash()); m_seedTime = TorrentPersistentData::getSeedDate(h.hash()); m_label = TorrentPersistentData::getLabel(h.hash()); @@ -51,13 +51,13 @@ TorrentModelItem::State TorrentModelItem::state() const { try { // Pause or Queued - if(m_torrent.is_paused()) { + if (m_torrent.is_paused()) { m_icon = QIcon(":/Icons/skin/paused.png"); m_fgColor = QColor("red"); return m_torrent.is_seed() ? STATE_PAUSED_UP : STATE_PAUSED_DL; } - if(m_torrent.is_queued()) { - if(m_torrent.state() != torrent_status::queued_for_checking + if (m_torrent.is_queued()) { + if (m_torrent.state() != torrent_status::queued_for_checking && m_torrent.state() != torrent_status::checking_resume_data && m_torrent.state() != torrent_status::checking_files) { m_icon = QIcon(":/Icons/skin/queued.png"); @@ -70,7 +70,7 @@ TorrentModelItem::State TorrentModelItem::state() const case torrent_status::allocating: case torrent_status::downloading_metadata: case torrent_status::downloading: { - if(m_torrent.download_payload_rate() > 0) { + if (m_torrent.download_payload_rate() > 0) { m_icon = QIcon(":/Icons/skin/downloading.png"); m_fgColor = QColor("green"); return STATE_DOWNLOADING; @@ -82,7 +82,7 @@ TorrentModelItem::State TorrentModelItem::state() const } case torrent_status::finished: case torrent_status::seeding: - if(m_torrent.upload_payload_rate() > 0) { + if (m_torrent.upload_payload_rate() > 0) { m_icon = QIcon(":/Icons/skin/uploading.png"); m_fgColor = QColor("orange"); return STATE_SEEDING; @@ -112,7 +112,7 @@ TorrentModelItem::State TorrentModelItem::state() const bool TorrentModelItem::setData(int column, const QVariant &value, int role) { qDebug() << Q_FUNC_INFO << column << value; - if(role != Qt::DisplayRole) return false; + if (role != Qt::DisplayRole) return false; // Label and Name columns can be edited switch(column) { case TR_NAME: @@ -121,7 +121,7 @@ bool TorrentModelItem::setData(int column, const QVariant &value, int role) return true; case TR_LABEL: { QString new_label = value.toString(); - if(m_label != new_label) { + if (m_label != new_label) { QString old_label = m_label; m_label = new_label; TorrentPersistentData::saveLabel(m_torrent.hash(), new_label); @@ -137,13 +137,13 @@ bool TorrentModelItem::setData(int column, const QVariant &value, int role) QVariant TorrentModelItem::data(int column, int role) const { - if(role == Qt::DecorationRole && column == TR_NAME) { + if (role == Qt::DecorationRole && column == TR_NAME) { return m_icon; } - if(role == Qt::ForegroundRole) { + if (role == Qt::ForegroundRole) { return m_fgColor; } - if(role != Qt::DisplayRole && role != Qt::UserRole) return QVariant(); + if (role != Qt::DisplayRole && role != Qt::UserRole) return QVariant(); switch(column) { case TR_NAME: return m_name.isEmpty()? m_torrent.name() : m_name; @@ -167,7 +167,7 @@ QVariant TorrentModelItem::data(int column, int role) const return m_torrent.upload_payload_rate(); case TR_ETA: { // XXX: Is this correct? - if(m_torrent.is_seed() || m_torrent.is_paused() || m_torrent.is_queued()) return MAX_ETA; + if (m_torrent.is_seed() || m_torrent.is_paused() || m_torrent.is_queued()) return MAX_ETA; return QBtSession::instance()->getETA(m_torrent.hash()); } case TR_RATIO: @@ -206,7 +206,7 @@ void TorrentModel::populate() { // Load the torrents std::vector torrents = QBtSession::instance()->getSession()->get_torrents(); std::vector::const_iterator it; - for(it = torrents.begin(); it != torrents.end(); it++) { + for (it = torrents.begin(); it != torrents.end(); it++) { addTorrent(QTorrentHandle(*it)); } // Refresh timer @@ -234,7 +234,7 @@ QVariant TorrentModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal) { - if(role == Qt::DisplayRole) { + if (role == Qt::DisplayRole) { switch(section) { case TorrentModelItem::TR_NAME: return tr("Name", "i.e: torrent name"); case TorrentModelItem::TR_PRIORITY: return "#"; @@ -260,7 +260,7 @@ QVariant TorrentModel::headerData(int section, Qt::Orientation orientation, return QVariant(); } } - if(role == Qt::TextAlignmentRole) { + if (role == Qt::TextAlignmentRole) { switch(section) { case TorrentModelItem::TR_PRIORITY: case TorrentModelItem::TR_SIZE: @@ -287,9 +287,9 @@ QVariant TorrentModel::headerData(int section, Qt::Orientation orientation, QVariant TorrentModel::data(const QModelIndex &index, int role) const { - if(!index.isValid()) return QVariant(); + if (!index.isValid()) return QVariant(); try { - if(index.row() >= 0 && index.row() < rowCount() && index.column() >= 0 && index.column() < columnCount()) + if (index.row() >= 0 && index.row() < rowCount() && index.column() >= 0 && index.column() < columnCount()) return m_torrents[index.row()]->data(index.column(), role); } catch(invalid_handle&) {} return QVariant(); @@ -298,12 +298,12 @@ QVariant TorrentModel::data(const QModelIndex &index, int role) const bool TorrentModel::setData(const QModelIndex &index, const QVariant &value, int role) { qDebug() << Q_FUNC_INFO << value; - if(!index.isValid() || role != Qt::DisplayRole) return false; + if (!index.isValid() || role != Qt::DisplayRole) return false; qDebug("Index is valid and role is DisplayRole"); try { - if(index.row() >= 0 && index.row() < rowCount() && index.column() >= 0 && index.column() < columnCount()) { + if (index.row() >= 0 && index.row() < rowCount() && index.column() >= 0 && index.column() < columnCount()) { bool change = m_torrents[index.row()]->setData(index.column(), value, role); - if(change) + if (change) notifyTorrentChanged(index.row()); return change; } @@ -315,8 +315,8 @@ int TorrentModel::torrentRow(const QString &hash) const { QList::const_iterator it; int row = 0; - for(it = m_torrents.constBegin(); it != m_torrents.constEnd(); it++) { - if((*it)->hash() == hash) return row; + for (it = m_torrents.constBegin(); it != m_torrents.constEnd(); it++) { + if ((*it)->hash() == hash) return row; ++row; } return -1; @@ -324,7 +324,7 @@ int TorrentModel::torrentRow(const QString &hash) const void TorrentModel::addTorrent(const QTorrentHandle &h) { - if(torrentRow(h.hash()) < 0) { + if (torrentRow(h.hash()) < 0) { beginInsertTorrent(m_torrents.size()); TorrentModelItem *item = new TorrentModelItem(h); connect(item, SIGNAL(labelChanged(QString,QString)), SLOT(handleTorrentLabelChange(QString,QString))); @@ -338,7 +338,7 @@ void TorrentModel::removeTorrent(const QString &hash) { const int row = torrentRow(hash); qDebug() << Q_FUNC_INFO << hash << row; - if(row >= 0) { + if (row >= 0) { beginRemoveTorrent(row); m_torrents.removeAt(row); endRemoveTorrent(); @@ -368,7 +368,7 @@ void TorrentModel::endRemoveTorrent() void TorrentModel::handleTorrentUpdate(const QTorrentHandle &h) { const int row = torrentRow(h.hash()); - if(row >= 0) { + if (row >= 0) { notifyTorrentChanged(row); } } @@ -380,7 +380,7 @@ void TorrentModel::notifyTorrentChanged(int row) void TorrentModel::setRefreshInterval(int refreshInterval) { - if(m_refreshInterval != refreshInterval) { + if (m_refreshInterval != refreshInterval) { m_refreshInterval = refreshInterval; m_refreshTimer.stop(); m_refreshTimer.start(m_refreshInterval); @@ -396,7 +396,7 @@ TorrentStatusReport TorrentModel::getTorrentStatusReport() const { TorrentStatusReport report; QList::const_iterator it; - for(it = m_torrents.constBegin(); it != m_torrents.constEnd(); it++) { + for (it = m_torrents.constBegin(); it != m_torrents.constEnd(); it++) { switch((*it)->data(TorrentModelItem::TR_STATUS).toInt()) { case TorrentModelItem::STATE_DOWNLOADING: ++report.nb_active; @@ -446,7 +446,7 @@ void TorrentModel::handleTorrentLabelChange(QString previous, QString current) QString TorrentModel::torrentHash(int row) const { - if(row >= 0 && row < rowCount()) + if (row >= 0 && row < rowCount()) return m_torrents.at(row)->hash(); return QString(); } @@ -454,7 +454,7 @@ QString TorrentModel::torrentHash(int row) const void TorrentModel::handleTorrentAboutToBeRemoved(const QTorrentHandle &h) { const int row = torrentRow(h.hash()); - if(row >= 0) { + if (row >= 0) { emit torrentAboutToBeRemoved(m_torrents.at(row)); } } diff --git a/src/qtlibtorrent/torrentspeedmonitor.cpp b/src/qtlibtorrent/torrentspeedmonitor.cpp index eff73d954..f94c621dc 100644 --- a/src/qtlibtorrent/torrentspeedmonitor.cpp +++ b/src/qtlibtorrent/torrentspeedmonitor.cpp @@ -79,13 +79,13 @@ void TorrentSpeedMonitor::run() void SpeedSample::addSample(int s) { m_speedSamples << s; - if(m_speedSamples.size() > max_samples) + if (m_speedSamples.size() > max_samples) m_speedSamples.removeFirst(); } qreal SpeedSample::average() const { - if(m_speedSamples.empty()) return 0; + if (m_speedSamples.empty()) return 0; qlonglong sum = 0; foreach (int s, m_speedSamples) { sum += s; @@ -113,9 +113,9 @@ qlonglong TorrentSpeedMonitor::getETA(const QString &hash) const { QMutexLocker locker(&m_mutex); QTorrentHandle h = m_session->getTorrentHandle(hash); - if(h.is_paused() || !m_samples.contains(hash)) return -1; + if (h.is_paused() || !m_samples.contains(hash)) return -1; const qreal speed_average = m_samples.value(hash).average(); - if(speed_average == 0) return -1; + if (speed_average == 0) return -1; return (h.total_wanted() - h.total_done()) / speed_average; } @@ -123,14 +123,14 @@ void TorrentSpeedMonitor::getSamples() { const std::vector torrents = m_session->getSession()->get_torrents(); std::vector::const_iterator it; - for(it = torrents.begin(); it != torrents.end(); it++) { + for (it = torrents.begin(); it != torrents.end(); it++) { try { #if LIBTORRENT_VERSION_MINOR > 15 torrent_status st = it->status(0x0); - if(!st.paused) + if (!st.paused) m_samples[misc::toQString(it->info_hash())].addSample(st.download_payload_rate); #else - if(!it->is_paused()) + if (!it->is_paused()) m_samples[misc::toQString(it->info_hash())].addSample(it->status().download_payload_rate); #endif } catch(invalid_handle&){} diff --git a/src/qtsingleapp/qtlocalpeer.cpp b/src/qtsingleapp/qtlocalpeer.cpp index b329e9147..e76735a95 100644 --- a/src/qtsingleapp/qtlocalpeer.cpp +++ b/src/qtsingleapp/qtlocalpeer.cpp @@ -148,7 +148,7 @@ bool QtLocalPeer::sendMessage(const QString &message, int timeout) QLocalSocket socket; bool connOk = false; - for(int i = 0; i < 2; i++) { + for (int i = 0; i < 2; i++) { // Try twice, in case the other instance is just starting up socket.connectToServer(socketName); connOk = socket.waitForConnected(timeout/2); diff --git a/src/reverseresolution.h b/src/reverseresolution.h index 8c4377383..f9f96c2df 100644 --- a/src/reverseresolution.h +++ b/src/reverseresolution.h @@ -64,7 +64,7 @@ public: const QString ip_str = misc::toQString(ip.address().to_string(ec)); if (ec) return QString(); QString ret; - if(m_cache.contains(ip_str)) { + if (m_cache.contains(ip_str)) { qDebug("Got host name from cache"); ret = *m_cache.object(ip_str); } else { @@ -77,7 +77,7 @@ public: boost::system::error_code ec; const QString ip_str = misc::toQString(ip.address().to_string(ec)); if (ec) return; - if(m_cache.contains(ip_str)) { + if (m_cache.contains(ip_str)) { qDebug("Resolved host name using cache"); emit ip_resolved(ip_str, *m_cache.object(ip_str)); return; @@ -93,9 +93,9 @@ private slots: void hostResolved(const QHostInfo& host) { if (host.error() == QHostInfo::NoError) { const QString hostname = host.hostName(); - if(host.addresses().isEmpty() || hostname.isEmpty()) return; + if (host.addresses().isEmpty() || hostname.isEmpty()) return; const QString ip = host.addresses().first().toString(); - if(hostname != ip) { + if (hostname != ip) { //qDebug() << Q_FUNC_INFO << ip << QString("->") << hostname; m_cache.insert(ip, new QString(hostname)); emit ip_resolved(ip, hostname); diff --git a/src/rss/automatedrssdownloader.cpp b/src/rss/automatedrssdownloader.cpp index 8707cff7f..c052ca4d5 100644 --- a/src/rss/automatedrssdownloader.cpp +++ b/src/rss/automatedrssdownloader.cpp @@ -122,19 +122,19 @@ void AutomatedRssDownloader::saveSettings() void AutomatedRssDownloader::loadRulesList() { // Make sure we save the current item before clearing - if(m_editedRule) { + if (m_editedRule) { saveEditedRule(); } ui->listRules->clear(); foreach (const QString &rule_name, m_ruleList->ruleNames()) { QListWidgetItem *item = new QListWidgetItem(rule_name, ui->listRules); item->setFlags(item->flags()|Qt::ItemIsUserCheckable); - if(m_ruleList->getRule(rule_name)->isEnabled()) + if (m_ruleList->getRule(rule_name)->isEnabled()) item->setCheckState(Qt::Checked); else item->setCheckState(Qt::Unchecked); } - if(ui->listRules->count() > 0 && !ui->listRules->currentItem()) + if (ui->listRules->count() > 0 && !ui->listRules->currentItem()) ui->listRules->setCurrentRow(0); } @@ -144,11 +144,11 @@ void AutomatedRssDownloader::loadFeedList() const QStringList feed_aliases = settings.getRssFeedsAliases(); const QStringList feed_urls = settings.getRssFeedsUrls(); QStringList existing_urls; - for(int i=0; ilistFeeds); item->setData(Qt::UserRole, feed_url); item->setFlags(item->flags()|Qt::ItemIsUserCheckable); @@ -159,18 +159,18 @@ void AutomatedRssDownloader::loadFeedList() void AutomatedRssDownloader::updateFeedList() { disconnect(ui->listFeeds, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(handleFeedCheckStateChange(QListWidgetItem*))); - for(int i=0; ilistFeeds->count(); ++i) { + for (int i=0; ilistFeeds->count(); ++i) { QListWidgetItem *item = ui->listFeeds->item(i); const QString feed_url = item->data(Qt::UserRole).toString(); bool all_enabled = false; - foreach(const QListWidgetItem *ruleItem, ui->listRules->selectedItems()) { + foreach (const QListWidgetItem *ruleItem, ui->listRules->selectedItems()) { RssDownloadRulePtr rule = m_ruleList->getRule(ruleItem->text()); - if(!rule) continue; + if (!rule) continue; qDebug() << "Rule" << rule->name() << "affects" << rule->rssFeeds().size() << "feeds."; - foreach(QString test, rule->rssFeeds()) { + foreach (QString test, rule->rssFeeds()) { qDebug() << "Feed is " << test; } - if(rule->rssFeeds().contains(feed_url)) { + if (rule->rssFeeds().contains(feed_url)) { qDebug() << "Rule " << rule->name() << " affects feed " << feed_url; all_enabled = true; } else { @@ -179,7 +179,7 @@ void AutomatedRssDownloader::updateFeedList() break; } } - if(all_enabled) + if (all_enabled) item->setCheckState(Qt::Checked); else item->setCheckState(Qt::Unchecked); @@ -201,7 +201,7 @@ void AutomatedRssDownloader::updateRuleDefinitionBox() saveEditedRule(); // Update rule definition box const QList selection = ui->listRules->selectedItems(); - if(selection.count() == 1) { + if (selection.count() == 1) { m_editedRule = selection.first(); RssDownloadRulePtr rule = getCurrentRule(); if (rule) { @@ -250,7 +250,7 @@ void AutomatedRssDownloader::clearRuleDefinitionBox() RssDownloadRulePtr AutomatedRssDownloader::getCurrentRule() const { QListWidgetItem * current_item = ui->listRules->currentItem(); - if(current_item) + if (current_item) return m_ruleList->getRule(current_item->text()); return RssDownloadRulePtr(); } @@ -259,16 +259,16 @@ void AutomatedRssDownloader::initLabelCombobox() { // Load custom labels const QStringList customLabels = Preferences().getTorrentLabels(); - foreach(const QString& label, customLabels) { + foreach (const QString& label, customLabels) { ui->comboLabel->addItem(label); } } void AutomatedRssDownloader::saveEditedRule() { - if(!m_editedRule) return; + if (!m_editedRule) return; qDebug() << Q_FUNC_INFO << m_editedRule; - if(ui->listRules->findItems(m_editedRule->text(), Qt::MatchExactly).isEmpty()) { + if (ui->listRules->findItems(m_editedRule->text(), Qt::MatchExactly).isEmpty()) { qDebug() << "Could not find rule" << m_editedRule->text() << "in the UI list"; qDebug() << "Probably removed the item, no need to save it"; return; @@ -284,13 +284,13 @@ void AutomatedRssDownloader::saveEditedRule() rule->setUseRegex(ui->checkRegex->isChecked()); rule->setMustContain(ui->lineContains->text()); rule->setMustNotContain(ui->lineNotContains->text()); - if(ui->saveDiffDir_check->isChecked()) + if (ui->saveDiffDir_check->isChecked()) rule->setSavePath(ui->lineSavePath->text()); else rule->setSavePath(""); rule->setLabel(ui->comboLabel->currentText()); // Save new label - if(!rule->label().isEmpty()) + if (!rule->label().isEmpty()) Preferences().addTorrentLabel(rule->label()); //rule->setRssFeeds(getSelectedFeeds()); // Save it @@ -302,9 +302,9 @@ void AutomatedRssDownloader::on_addRuleBtn_clicked() { // Ask for a rule name const QString rule_name = QInputDialog::getText(this, tr("New rule name"), tr("Please type the name of the new download rule->")); - if(rule_name.isEmpty()) return; + if (rule_name.isEmpty()) return; // Check if this rule name already exists - if(m_ruleList->getRule(rule_name)) { + if (m_ruleList->getRule(rule_name)) { QMessageBox::warning(this, tr("Rule name conflict"), tr("A rule with this name already exists, please choose another name.")); return; } @@ -319,16 +319,16 @@ void AutomatedRssDownloader::on_addRuleBtn_clicked() void AutomatedRssDownloader::on_removeRuleBtn_clicked() { const QList selection = ui->listRules->selectedItems(); - if(selection.isEmpty()) return; + if (selection.isEmpty()) return; // Ask for confirmation QString confirm_text; - if(selection.count() == 1) + if (selection.count() == 1) confirm_text = tr("Are you sure you want to remove the download rule named %1?").arg(selection.first()->text()); else confirm_text = tr("Are you sure you want to remove the selected download rules?"); - if(QMessageBox::question(this, tr("Rule deletion confirmation"), confirm_text, QMessageBox::Yes, QMessageBox::No) != QMessageBox::Yes) + if (QMessageBox::question(this, tr("Rule deletion confirmation"), confirm_text, QMessageBox::Yes, QMessageBox::No) != QMessageBox::Yes) return; - foreach(QListWidgetItem *item, selection) { + foreach (QListWidgetItem *item, selection) { // Actually remove the item ui->listRules->removeItemWidget(item); const QString rule_name = item->text(); @@ -343,22 +343,22 @@ void AutomatedRssDownloader::on_removeRuleBtn_clicked() void AutomatedRssDownloader::on_browseSP_clicked() { QString save_path = QFileDialog::getExistingDirectory(this, tr("Destination directory"), QDir::homePath()); - if(!save_path.isEmpty()) + if (!save_path.isEmpty()) ui->lineSavePath->setText(save_path); } void AutomatedRssDownloader::on_exportBtn_clicked() { - if(m_ruleList->isEmpty()) { + if (m_ruleList->isEmpty()) { QMessageBox::warning(this, tr("Invalid action"), tr("The list is empty, there is nothing to export.")); return; } // Ask for a save path QString save_path = QFileDialog::getSaveFileName(this, tr("Where would you like to save the list?"), QDir::homePath(), tr("Rules list (*.rssrules)")); - if(save_path.isEmpty()) return; - if(!save_path.endsWith(".rssrules", Qt::CaseInsensitive)) + if (save_path.isEmpty()) return; + if (!save_path.endsWith(".rssrules", Qt::CaseInsensitive)) save_path += ".rssrules"; - if(!m_ruleList->serialize(save_path)) { + if (!m_ruleList->serialize(save_path)) { QMessageBox::warning(this, tr("I/O Error"), tr("Failed to create the destination file")); return; } @@ -368,9 +368,9 @@ void AutomatedRssDownloader::on_importBtn_clicked() { // Ask for filter path QString load_path = QFileDialog::getOpenFileName(this, tr("Please point to the RSS download rules file"), QDir::homePath(), tr("Rules list (*.rssrules *.filters)")); - if(load_path.isEmpty() || !QFile::exists(load_path)) return; + if (load_path.isEmpty() || !QFile::exists(load_path)) return; // Load it - if(!m_ruleList->unserialize(load_path)) { + if (!m_ruleList->unserialize(load_path)) { QMessageBox::warning(this, tr("Import Error"), tr("Failed to import the selected rules file")); return; } @@ -386,8 +386,8 @@ void AutomatedRssDownloader::displayRulesListMenu(const QPoint &pos) QAction *delAct = 0; QAction *renameAct = 0; const QList selection = ui->listRules->selectedItems(); - if(!selection.isEmpty()) { - if(selection.count() == 1) { + if (!selection.isEmpty()) { + if (selection.count() == 1) { delAct = menu.addAction(IconProvider::instance()->getIcon("list-remove"), tr("Delete rule")); menu.addSeparator(); renameAct = menu.addAction(IconProvider::instance()->getIcon("edit-rename"), tr("Rename rule->..")); @@ -396,16 +396,16 @@ void AutomatedRssDownloader::displayRulesListMenu(const QPoint &pos) } } QAction *act = menu.exec(QCursor::pos()); - if(!act) return; - if(act == addAct) { + if (!act) return; + if (act == addAct) { on_addRuleBtn_clicked(); return; } - if(act == delAct) { + if (act == delAct) { on_removeRuleBtn_clicked(); return; } - if(act == renameAct) { + if (act == renameAct) { renameSelectedRule(); return; } @@ -414,12 +414,12 @@ void AutomatedRssDownloader::displayRulesListMenu(const QPoint &pos) void AutomatedRssDownloader::renameSelectedRule() { QListWidgetItem *item = ui->listRules->currentItem(); - if(!item) return; + if (!item) return; forever { QString new_name = QInputDialog::getText(this, tr("Rule renaming"), tr("Please type the new rule name"), QLineEdit::Normal, item->text()); new_name = new_name.trimmed(); - if(new_name.isEmpty()) return; - if(m_ruleList->ruleNames().contains(new_name, Qt::CaseInsensitive)) { + if (new_name.isEmpty()) return; + if (m_ruleList->ruleNames().contains(new_name, Qt::CaseInsensitive)) { QMessageBox::warning(this, tr("Rule name conflict"), tr("A rule with this name already exists, please choose another name.")); } else { // Rename the rule @@ -432,7 +432,7 @@ void AutomatedRssDownloader::renameSelectedRule() void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feed_item) { - if(ui->ruleDefBox->isEnabled()) { + if (ui->ruleDefBox->isEnabled()) { // Make sure the current rule is saved saveEditedRule(); } @@ -441,15 +441,15 @@ void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feed_it RssDownloadRulePtr rule = m_ruleList->getRule(rule_item->text()); Q_ASSERT(rule); QStringList affected_feeds = rule->rssFeeds(); - if(feed_item->checkState() == Qt::Checked) { - if(!affected_feeds.contains(feed_url)) + if (feed_item->checkState() == Qt::Checked) { + if (!affected_feeds.contains(feed_url)) affected_feeds << feed_url; } else { - if(affected_feeds.contains(feed_url)) + if (affected_feeds.contains(feed_url)) affected_feeds.removeOne(feed_url); } // Save the updated rule - if(affected_feeds.size() != rule->rssFeeds().size()) { + if (affected_feeds.size() != rule->rssFeeds().size()) { rule->setRssFeeds(affected_feeds); m_ruleList->saveRule(rule); } @@ -461,7 +461,7 @@ void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feed_it void AutomatedRssDownloader::updateMatchingArticles() { ui->treeMatchingArticles->clear(); - if(ui->ruleDefBox->isEnabled()) { + if (ui->ruleDefBox->isEnabled()) { saveEditedRule(); } RssManagerPtr manager = m_manager.toStrongRef(); @@ -469,17 +469,17 @@ void AutomatedRssDownloader::updateMatchingArticles() return; const QHash all_feeds = manager->getAllFeedsAsHash(); - foreach(const QListWidgetItem *rule_item, ui->listRules->selectedItems()) { + foreach (const QListWidgetItem *rule_item, ui->listRules->selectedItems()) { RssDownloadRulePtr rule = m_ruleList->getRule(rule_item->text()); - if(!rule) continue; - foreach(const QString &feed_url, rule->rssFeeds()) { + if (!rule) continue; + foreach (const QString &feed_url, rule->rssFeeds()) { qDebug() << Q_FUNC_INFO << feed_url; - if(!all_feeds.contains(feed_url)) continue; // Feed was removed + if (!all_feeds.contains(feed_url)) continue; // Feed was removed RssFeedPtr feed = all_feeds.value(feed_url); Q_ASSERT(feed); - if(!feed) continue; + if (!feed) continue; const QStringList matching_articles = rule->findMatchingArticles(feed); - if(!matching_articles.isEmpty()) + if (!matching_articles.isEmpty()) addFeedArticlesToTree(feed, matching_articles); } } @@ -489,15 +489,15 @@ void AutomatedRssDownloader::addFeedArticlesToTree(const RssFeedPtr& feed, const { // Check if this feed is already in the tree QTreeWidgetItem *treeFeedItem = 0; - for(int i=0; itreeMatchingArticles->topLevelItemCount(); ++i) { + for (int i=0; itreeMatchingArticles->topLevelItemCount(); ++i) { QTreeWidgetItem *item = ui->treeMatchingArticles->topLevelItem(i); - if(item->data(0, Qt::UserRole).toString() == feed->url()) { + if (item->data(0, Qt::UserRole).toString() == feed->url()) { treeFeedItem = item; break; } } // If there is none, create it - if(!treeFeedItem) { + if (!treeFeedItem) { treeFeedItem = new QTreeWidgetItem(QStringList() << feed->displayName()); treeFeedItem->setToolTip(0, feed->displayName()); QFont f = treeFeedItem->font(0); @@ -508,7 +508,7 @@ void AutomatedRssDownloader::addFeedArticlesToTree(const RssFeedPtr& feed, const ui->treeMatchingArticles->addTopLevelItem(treeFeedItem); } // Insert the articles - foreach(const QString &art, articles) { + foreach (const QString &art, articles) { QTreeWidgetItem *item = new QTreeWidgetItem(QStringList() << art); item->setToolTip(0, art); treeFeedItem->addChild(item); @@ -519,7 +519,7 @@ void AutomatedRssDownloader::addFeedArticlesToTree(const RssFeedPtr& feed, const void AutomatedRssDownloader::updateFieldsToolTips(bool regex) { QString tip; - if(regex) { + if (regex) { tip = tr("Regex mode: use Perl-like regular expressions"); ui->lineContains->setToolTip(tip); ui->lineNotContains->setToolTip(tip); @@ -536,18 +536,18 @@ void AutomatedRssDownloader::updateMustLineValidity() const QString text = ui->lineContains->text(); bool valid = true; QStringList tokens; - if(ui->checkRegex->isChecked()) + if (ui->checkRegex->isChecked()) tokens << text; else tokens << text.split(" "); - foreach(const QString &token, tokens) { + foreach (const QString &token, tokens) { QRegExp reg(token, Qt::CaseInsensitive, ui->checkRegex->isChecked() ? QRegExp::RegExp : QRegExp::Wildcard); - if(!reg.isValid()) { + if (!reg.isValid()) { valid = false; break; } } - if(valid) { + if (valid) { ui->lineContains->setStyleSheet(""); ui->lbl_must_stat->setPixmap(QPixmap()); } else { @@ -561,18 +561,18 @@ void AutomatedRssDownloader::updateMustNotLineValidity() const QString text = ui->lineNotContains->text(); bool valid = true; QStringList tokens; - if(ui->checkRegex->isChecked()) + if (ui->checkRegex->isChecked()) tokens << text; else tokens << text.split(QRegExp("[\\s|]")); - foreach(const QString &token, tokens) { + foreach (const QString &token, tokens) { QRegExp reg(token, Qt::CaseInsensitive, ui->checkRegex->isChecked() ? QRegExp::RegExp : QRegExp::Wildcard); - if(!reg.isValid()) { + if (!reg.isValid()) { valid = false; break; } } - if(valid) { + if (valid) { ui->lineNotContains->setStyleSheet(""); ui->lbl_mustnot_stat->setPixmap(QPixmap()); } else { diff --git a/src/rss/cookiesdlg.cpp b/src/rss/cookiesdlg.cpp index b1a092e69..7890550d9 100644 --- a/src/rss/cookiesdlg.cpp +++ b/src/rss/cookiesdlg.cpp @@ -46,9 +46,9 @@ CookiesDlg::CookiesDlg(QWidget *parent, const QList &raw_cookies) : ui->del_btn->setIcon(IconProvider::instance()->getIcon("list-remove")); ui->infos_lbl->setText(tr("Common keys for cookies are : '%1', '%2'.\nYou should get this information from your Web browser preferences.").arg("uid").arg("pass")); - foreach(const QByteArray &raw_cookie, raw_cookies) { + foreach (const QByteArray &raw_cookie, raw_cookies) { QList cookie_parts = raw_cookie.split('='); - if(cookie_parts.size() != 2) continue; + if (cookie_parts.size() != 2) continue; const int i = ui->cookiesTable->rowCount(); ui->cookiesTable->setRowCount(i+1); ui->cookiesTable->setItem(i, COOKIE_KEY, new QTableWidgetItem(cookie_parts.first().data())); @@ -70,21 +70,21 @@ void CookiesDlg::on_add_btn_clicked() { void CookiesDlg::on_del_btn_clicked() { // Get selected cookie QList selection = ui->cookiesTable->selectedItems(); - if(!selection.isEmpty()) { + if (!selection.isEmpty()) { ui->cookiesTable->removeRow(selection.first()->row()); } } QList CookiesDlg::getCookies() const { QList ret; - for(int i=0; icookiesTable->rowCount(); ++i) { + for (int i=0; icookiesTable->rowCount(); ++i) { QString key; - if(ui->cookiesTable->item(i, COOKIE_KEY)) + if (ui->cookiesTable->item(i, COOKIE_KEY)) key = ui->cookiesTable->item(i, COOKIE_KEY)->text().trimmed(); QString value; - if(ui->cookiesTable->item(i, COOKIE_VALUE)) + if (ui->cookiesTable->item(i, COOKIE_VALUE)) value = ui->cookiesTable->item(i, COOKIE_VALUE)->text().trimmed(); - if(!key.isEmpty() && !value.isEmpty()) { + if (!key.isEmpty() && !value.isEmpty()) { const QString raw_cookie = key+"="+value; qDebug("Cookie: %s", qPrintable(raw_cookie)); ret << raw_cookie.toLocal8Bit(); @@ -95,7 +95,7 @@ QList CookiesDlg::getCookies() const { QList CookiesDlg::askForCookies(QWidget *parent, const QList &raw_cookies, bool *ok) { CookiesDlg dlg(parent, raw_cookies); - if(dlg.exec()) { + if (dlg.exec()) { *ok = true; return dlg.getCookies(); } diff --git a/src/rss/feedlistwidget.cpp b/src/rss/feedlistwidget.cpp index 112ac92e7..8dc641c6c 100644 --- a/src/rss/feedlistwidget.cpp +++ b/src/rss/feedlistwidget.cpp @@ -64,7 +64,7 @@ void FeedListWidget::itemAboutToBeRemoved(QTreeWidgetItem *item) { m_feedsItems.remove(feed->id()); } if (RssFolderPtr folder = qSharedPointerDynamicCast(file)) { RssFeedList feeds = folder->getAllFeeds(); - foreach(const RssFeedPtr& feed, feeds) { + foreach (const RssFeedPtr& feed, feeds) { m_feedsItems.remove(feed->id()); } } @@ -84,8 +84,8 @@ QTreeWidgetItem* FeedListWidget::stickyUnreadItem() const { QStringList FeedListWidget::getItemPath(QTreeWidgetItem* item) const { QStringList path; - if(item) { - if(item->parent()) + if (item) { + if (item->parent()) path << getItemPath(item->parent()); path.append(getRSSItem(item)->id()); } @@ -95,19 +95,19 @@ QStringList FeedListWidget::getItemPath(QTreeWidgetItem* item) const { QList FeedListWidget::getAllOpenFolders(QTreeWidgetItem *parent) const { QList open_folders; int nbChildren; - if(parent) + if (parent) nbChildren = parent->childCount(); else nbChildren = topLevelItemCount(); - for(int i=0; ichild(i); else item = topLevelItem(i); - if(isFolder(item) && item->isExpanded()) { + if (isFolder(item) && item->isExpanded()) { QList open_subfolders = getAllOpenFolders(item); - if(!open_subfolders.empty()) { + if (!open_subfolders.empty()) { open_folders << open_subfolders; } else { open_folders << item; @@ -120,9 +120,9 @@ QList FeedListWidget::getAllOpenFolders(QTreeWidgetItem *paren QList FeedListWidget::getAllFeedItems(QTreeWidgetItem* folder) { QList feeds; const int nbChildren = folder->childCount(); - for(int i=0; ichild(i); - if(isFeed(item)) { + if (isFeed(item)) { feeds << item; } else { feeds << getAllFeedItems(item); @@ -166,21 +166,21 @@ QTreeWidgetItem* FeedListWidget::currentFeed() const { } void FeedListWidget::updateCurrentFeed(QTreeWidgetItem* new_item) { - if(!new_item) return; - if(!m_rssMapping.contains(new_item)) return; - if(isFeed(new_item) || new_item == m_unreadStickyItem) + if (!new_item) return; + if (!m_rssMapping.contains(new_item)) return; + if (isFeed(new_item) || new_item == m_unreadStickyItem) m_currentFeed = new_item; } void FeedListWidget::dragMoveEvent(QDragMoveEvent * event) { QTreeWidgetItem *item = itemAt(event->pos()); - if(item == m_unreadStickyItem) { + if (item == m_unreadStickyItem) { event->ignore(); } else { - if(item && isFolder(item)) + if (item && isFolder(item)) event->ignore(); else { - if(selectedItems().contains(m_unreadStickyItem)) { + if (selectedItems().contains(m_unreadStickyItem)) { event->ignore(); } else { QTreeWidget::dragMoveEvent(event); @@ -194,7 +194,7 @@ void FeedListWidget::dropEvent(QDropEvent *event) { QList folders_altered; QTreeWidgetItem *dest_folder_item = itemAt(event->pos()); RssFolderPtr dest_folder; - if(dest_folder_item) { + if (dest_folder_item) { dest_folder = qSharedPointerCast(getRSSItem(dest_folder_item)); folders_altered << dest_folder_item; } else { @@ -202,26 +202,26 @@ void FeedListWidget::dropEvent(QDropEvent *event) { } QList src_items = selectedItems(); // Check if there is not going to overwrite another file - foreach(QTreeWidgetItem *src_item, src_items) { + foreach (QTreeWidgetItem *src_item, src_items) { RssFilePtr file = getRSSItem(src_item); - if(dest_folder->hasChild(file->id())) { + if (dest_folder->hasChild(file->id())) { emit overwriteAttempt(file->id()); return; } } // Proceed with the move - foreach(QTreeWidgetItem *src_item, src_items) { + foreach (QTreeWidgetItem *src_item, src_items) { QTreeWidgetItem *parent_folder = src_item->parent(); - if(parent_folder && !folders_altered.contains(parent_folder)) + if (parent_folder && !folders_altered.contains(parent_folder)) folders_altered << parent_folder; // Actually move the file RssFilePtr file = getRSSItem(src_item); m_rssManager->moveFile(file, dest_folder); } QTreeWidget::dropEvent(event); - if(dest_folder_item) + if (dest_folder_item) dest_folder_item->setExpanded(true); // Emit signal for update - if(!folders_altered.empty()) + if (!folders_altered.empty()) emit foldersAltered(folders_altered); } diff --git a/src/rss/rss_imp.cpp b/src/rss/rss_imp.cpp index f85d24da7..8db1c8d50 100644 --- a/src/rss/rss_imp.cpp +++ b/src/rss/rss_imp.cpp @@ -63,22 +63,22 @@ enum ArticleRoles { // display a right-click menu void RSSImp::displayRSSListMenu(const QPoint& pos){ - if(!m_feedList->indexAt(pos).isValid()) { + if (!m_feedList->indexAt(pos).isValid()) { // No item under the mouse, clear selection m_feedList->clearSelection(); } QMenu myRSSListMenu(this); QList selectedItems = m_feedList->selectedItems(); - if(selectedItems.size() > 0) { + if (selectedItems.size() > 0) { myRSSListMenu.addAction(actionUpdate); myRSSListMenu.addAction(actionMark_items_read); myRSSListMenu.addSeparator(); - if(selectedItems.size() == 1) { - if(m_feedList->getRSSItem(selectedItems.first()) != m_rssManager) { + if (selectedItems.size() == 1) { + if (m_feedList->getRSSItem(selectedItems.first()) != m_rssManager) { myRSSListMenu.addAction(actionRename); myRSSListMenu.addAction(actionDelete); myRSSListMenu.addSeparator(); - if(m_feedList->isFolder(selectedItems.first())) { + if (m_feedList->isFolder(selectedItems.first())) { myRSSListMenu.addAction(actionNew_folder); } else { myRSSListMenu.addAction(actionManage_cookies); @@ -86,7 +86,7 @@ void RSSImp::displayRSSListMenu(const QPoint& pos){ } } myRSSListMenu.addAction(actionNew_subscription); - if(m_feedList->isFeed(selectedItems.first())) { + if (m_feedList->isFeed(selectedItems.first())) { myRSSListMenu.addSeparator(); myRSSListMenu.addAction(actionCopy_feed_URL); } @@ -102,18 +102,18 @@ void RSSImp::displayRSSListMenu(const QPoint& pos){ void RSSImp::displayItemsListMenu(const QPoint&){ QMenu myItemListMenu(this); QList selectedItems = listArticles->selectedItems(); - if(selectedItems.size() > 0) { + if (selectedItems.size() > 0) { bool has_attachment = false; - foreach(const QListWidgetItem *item, selectedItems) { + foreach (const QListWidgetItem *item, selectedItems) { qDebug("text(3) URL: %s", qPrintable(item->data(Article::FeedUrlRole).toString())); qDebug("text(2) TITLE: %s", qPrintable(item->data(Article::TitleRole).toString())); - if(m_feedList->getRSSItemFromUrl(item->data(Article::FeedUrlRole).toString()) + if (m_feedList->getRSSItemFromUrl(item->data(Article::FeedUrlRole).toString()) ->getItem(item->data(Article::IdRole).toString())->hasAttachment()) { has_attachment = true; break; } } - if(has_attachment) + if (has_attachment) myItemListMenu.addAction(actionDownload_torrent); myItemListMenu.addAction(actionOpen_news_URL); } @@ -130,7 +130,7 @@ void RSSImp::on_actionManage_cookies_triggered() { bool ok = false; RssSettings settings; QList raw_cookies = CookiesDlg::askForCookies(this, settings.getHostNameCookies(feed_hostname), &ok); - if(ok) { + if (ok) { settings.setHostNameCookies(feed_hostname, raw_cookies); } } @@ -138,7 +138,7 @@ void RSSImp::on_actionManage_cookies_triggered() { void RSSImp::askNewFolder() { QTreeWidgetItem *parent_item = 0; RssFolderPtr rss_parent; - if(m_feedList->selectedItems().size() > 0) { + if (m_feedList->selectedItems().size() > 0) { parent_item = m_feedList->selectedItems().at(0); rss_parent = qSharedPointerDynamicCast(m_feedList->getRSSItem(parent_item)); Q_ASSERT(rss_parent); @@ -147,10 +147,10 @@ void RSSImp::askNewFolder() { } bool ok; QString new_name = QInputDialog::getText(this, tr("Please choose a folder name"), tr("Folder name:"), QLineEdit::Normal, tr("New folder"), &ok); - if(ok) { + if (ok) { RssFolderPtr new_folder = rss_parent->addFolder(new_name); QTreeWidgetItem* folder_item; - if(parent_item) + if (parent_item) folder_item = new QTreeWidgetItem(parent_item); else folder_item = new QTreeWidgetItem(m_feedList); @@ -160,7 +160,7 @@ void RSSImp::askNewFolder() { folder_item->setText(0, new_folder->displayName() + QString::fromUtf8(" (0)")); folder_item->setData(0,Qt::DecorationRole, QVariant(IconProvider::instance()->getIcon("inode-directory"))); // Expand parent folder to display new folder - if(parent_item) + if (parent_item) parent_item->setExpanded(true); m_rssManager->saveStreamList(); } @@ -177,18 +177,18 @@ void RSSImp::on_newFeedButton_clicked() { // Determine parent folder for new feed QTreeWidgetItem *parent_item = 0; QList selected_items = m_feedList->selectedItems(); - if(!selected_items.empty()) { + if (!selected_items.empty()) { parent_item = selected_items.first(); // Consider the case where the user clicked on Unread item - if(parent_item == m_feedList->stickyUnreadItem()) { + if (parent_item == m_feedList->stickyUnreadItem()) { parent_item = 0; } else { - if(m_feedList->isFolder(parent_item)) + if (m_feedList->isFolder(parent_item)) parent_item = parent_item->parent(); } } RssFolderPtr rss_parent; - if(parent_item) { + if (parent_item) { rss_parent = qSharedPointerCast(m_feedList->getRSSItem(parent_item)); } else { rss_parent = m_rssManager; @@ -197,14 +197,14 @@ void RSSImp::on_newFeedButton_clicked() { bool ok; QString clip_txt = qApp->clipboard()->text(); QString default_url = "http://"; - if(clip_txt.startsWith("http://", Qt::CaseInsensitive) || clip_txt.startsWith("https://", Qt::CaseInsensitive) || clip_txt.startsWith("ftp://", Qt::CaseInsensitive)) { + if (clip_txt.startsWith("http://", Qt::CaseInsensitive) || clip_txt.startsWith("https://", Qt::CaseInsensitive) || clip_txt.startsWith("ftp://", Qt::CaseInsensitive)) { default_url = clip_txt; } QString newUrl = QInputDialog::getText(this, tr("Please type a rss stream url"), tr("Stream URL:"), QLineEdit::Normal, default_url, &ok); - if(ok) { + if (ok) { newUrl = newUrl.trimmed(); - if(!newUrl.isEmpty()){ - if(m_feedList->hasFeed(newUrl)) { + if (!newUrl.isEmpty()){ + if (m_feedList->hasFeed(newUrl)) { QMessageBox::warning(this, tr("qBittorrent"), tr("This rss feed is already in the list."), QMessageBox::Ok); @@ -213,7 +213,7 @@ void RSSImp::on_newFeedButton_clicked() { RssFeedPtr stream = rss_parent->addStream(m_rssManager.data(), newUrl); // Create TreeWidget item QTreeWidgetItem* item; - if(parent_item) + if (parent_item) item = new QTreeWidgetItem(parent_item); else item = new QTreeWidgetItem(m_feedList); @@ -231,9 +231,9 @@ void RSSImp::on_newFeedButton_clicked() { // delete a stream by a button void RSSImp::deleteSelectedItems() { QList selectedItems = m_feedList->selectedItems(); - if(selectedItems.size() == 0) return; + if (selectedItems.size() == 0) return; int ret; - if(selectedItems.size() > 1) + if (selectedItems.size() > 1) ret = QMessageBox::question(this, tr("Are you sure? -- qBittorrent"), tr("Are you sure you want to delete these elements from the list?"), tr("&Yes"), tr("&No"), QString(), 0, 1); @@ -241,9 +241,9 @@ void RSSImp::deleteSelectedItems() { ret = QMessageBox::question(this, tr("Are you sure? -- qBittorrent"), tr("Are you sure you want to delete this element from the list?"), tr("&Yes"), tr("&No"), QString(), 0, 1); - if(!ret) { - foreach(QTreeWidgetItem *item, selectedItems){ - if(m_feedList->currentFeed() == item){ + if (!ret) { + foreach (QTreeWidgetItem *item, selectedItems){ + if (m_feedList->currentFeed() == item){ textBrowser->clear(); m_currentArticle = 0; listArticles->clear(); @@ -272,22 +272,22 @@ void RSSImp::loadFoldersOpenState() { settings.beginGroup("Rss"); QStringList open_folders = settings.value("open_folders", QStringList()).toStringList(); settings.endGroup(); - foreach(QString var_path, open_folders) { + foreach (QString var_path, open_folders) { QStringList path = var_path.split("\\"); QTreeWidgetItem *parent = 0; - foreach(QString name, path) { + foreach (QString name, path) { int nbChildren = 0; - if(parent) + if (parent) nbChildren = parent->childCount(); else nbChildren = m_feedList->topLevelItemCount(); - for(int i=0; ichild(i); else child = m_feedList->topLevelItem(i); - if(m_feedList->getRSSItem(child)->id() == name) { + if (m_feedList->getRSSItem(child)->id() == name) { parent = child; parent->setExpanded(true); qDebug("expanding folder %s", qPrintable(name)); @@ -301,7 +301,7 @@ void RSSImp::loadFoldersOpenState() { void RSSImp::saveFoldersOpenState() { QStringList open_folders; QList items = m_feedList->getAllOpenFolders(); - foreach(QTreeWidgetItem* item, items) { + foreach (QTreeWidgetItem* item, items) { QString path = m_feedList->getItemPath(item).join("\\"); qDebug("saving open folder: %s", qPrintable(path)); open_folders << path; @@ -314,7 +314,7 @@ void RSSImp::saveFoldersOpenState() { // refresh all streams by a button void RSSImp::on_updateAllButton_clicked() { - foreach(QTreeWidgetItem *item, m_feedList->getAllFeedItems()) { + foreach (QTreeWidgetItem *item, m_feedList->getAllFeedItems()) { item->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png"))); } m_rssManager->refresh(); @@ -322,10 +322,10 @@ void RSSImp::on_updateAllButton_clicked() { void RSSImp::downloadTorrent() { QList selected_items = listArticles->selectedItems(); - foreach(const QListWidgetItem* item, selected_items) { + foreach (const QListWidgetItem* item, selected_items) { RssArticlePtr article = m_feedList->getRSSItemFromUrl(item->data(Article::FeedUrlRole).toString()) ->getItem(item->data(Article::IdRole).toString()); - if(article->hasAttachment()) { + if (article->hasAttachment()) { QBtSession::instance()->downloadFromUrl(article->torrentUrl()); } else { QBtSession::instance()->downloadFromUrl(article->link()); @@ -336,11 +336,11 @@ void RSSImp::downloadTorrent() { // open the url of the news in a browser void RSSImp::openNewsUrl() { QList selected_items = listArticles->selectedItems(); - foreach(const QListWidgetItem* item, selected_items) { + foreach (const QListWidgetItem* item, selected_items) { RssArticlePtr news = m_feedList->getRSSItemFromUrl(item->data(Article::FeedUrlRole).toString()) ->getItem(item->data(Article::IdRole).toString()); const QString link = news->link(); - if(!link.isEmpty()) + if (!link.isEmpty()) QDesktopServices::openUrl(QUrl(link)); } } @@ -356,8 +356,8 @@ void RSSImp::renameFiles() { do { newName = QInputDialog::getText(this, tr("Please choose a new name for this RSS feed"), tr("New feed name:"), QLineEdit::Normal, m_feedList->getRSSItem(item)->displayName(), &ok); // Check if name is already taken - if(ok) { - if(rss_item->parent()->hasChild(newName)) { + if (ok) { + if (rss_item->parent()->hasChild(newName)) { QMessageBox::warning(0, tr("Name already in use"), tr("This name is already used by another item, please choose another one.")); ok = false; } @@ -374,11 +374,11 @@ void RSSImp::renameFiles() { //right-click on stream : refresh it void RSSImp::refreshSelectedItems() { QList selectedItems = m_feedList->selectedItems(); - foreach(QTreeWidgetItem* item, selectedItems){ + foreach (QTreeWidgetItem* item, selectedItems){ RssFilePtr file = m_feedList->getRSSItem(item); // Update icons - if(item == m_feedList->stickyUnreadItem()) { - foreach(QTreeWidgetItem *feed, m_feedList->getAllFeedItems()) { + if (item == m_feedList->stickyUnreadItem()) { + foreach (QTreeWidgetItem *feed, m_feedList->getAllFeedItems()) { feed->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png"))); } file->refresh(); @@ -388,7 +388,7 @@ void RSSImp::refreshSelectedItems() { item->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png"))); } else if (qSharedPointerDynamicCast(file)) { // Update feeds in the folder - foreach(QTreeWidgetItem *feed, m_feedList->getAllFeedItems(item)) { + foreach (QTreeWidgetItem *feed, m_feedList->getAllFeedItems(item)) { feed->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png"))); } } @@ -402,8 +402,8 @@ void RSSImp::copySelectedFeedsURL() { QStringList URLs; QList selectedItems = m_feedList->selectedItems(); QTreeWidgetItem* item; - foreach(item, selectedItems){ - if(m_feedList->isFeed(item)) + foreach (item, selectedItems){ + if (m_feedList->isFeed(item)) URLs << m_feedList->getItemID(item); } qApp->clipboard()->setText(URLs.join("\n")); @@ -412,25 +412,25 @@ void RSSImp::copySelectedFeedsURL() { void RSSImp::on_markReadButton_clicked() { QList selectedItems = m_feedList->selectedItems(); QTreeWidgetItem* item; - foreach(item, selectedItems){ + foreach (item, selectedItems){ RssFilePtr rss_item = m_feedList->getRSSItem(item); rss_item->markAsRead(); updateItemInfos(item); } - if(selectedItems.size()) + if (selectedItems.size()) refreshArticleList(m_feedList->currentItem()); } void RSSImp::fillFeedsList(QTreeWidgetItem *parent, const RssFolderPtr& rss_parent) { QList children; - if(parent) { + if (parent) { children = rss_parent->getContent(); } else { children = m_rssManager->getContent(); } foreach (const RssFilePtr& rss_child, children){ QTreeWidgetItem* item; - if(!parent) + if (!parent) item = new QTreeWidgetItem(m_feedList); else item = new QTreeWidgetItem(parent); @@ -438,7 +438,7 @@ void RSSImp::fillFeedsList(QTreeWidgetItem *parent, const RssFolderPtr& rss_pare // Notify TreeWidget of item addition m_feedList->itemAdded(item, rss_child); // Set Icon - if(qSharedPointerDynamicCast(rss_child)) { + if (qSharedPointerDynamicCast(rss_child)) { item->setData(0,Qt::DecorationRole, QVariant(QIcon(QString::fromUtf8(":/Icons/loading.png")))); } else if (RssFolderPtr folder = qSharedPointerDynamicCast(rss_child)) { item->setData(0,Qt::DecorationRole, QVariant(IconProvider::instance()->getIcon("inode-directory"))); @@ -450,19 +450,19 @@ void RSSImp::fillFeedsList(QTreeWidgetItem *parent, const RssFolderPtr& rss_pare // fills the newsList void RSSImp::refreshArticleList(QTreeWidgetItem* item) { - if(!item) { + if (!item) { listArticles->clear(); return; } RssFilePtr rss_item = m_feedList->getRSSItem(item); - if(!rss_item) return; + if (!rss_item) return; qDebug("Getting the list of news"); RssArticleList news; - if(rss_item == m_rssManager) + if (rss_item == m_rssManager) news = rss_item->unreadArticleList(); - else if(rss_item) + else if (rss_item) news = rss_item->articleList(); // Sort RssManager::sortNewsList(news); @@ -471,12 +471,12 @@ void RSSImp::refreshArticleList(QTreeWidgetItem* item) { m_currentArticle = 0; listArticles->clear(); qDebug("Got the list of news"); - foreach(const RssArticlePtr &article, news){ + foreach (const RssArticlePtr &article, news){ QListWidgetItem* it = new QListWidgetItem(listArticles); it->setData(Article::TitleRole, article->title()); it->setData(Article::FeedUrlRole, article->parent()->url()); it->setData(Article::IdRole, article->guid()); - if(article->isRead()){ + if (article->isRead()){ it->setData(Article::ColorRole, QVariant(QColor("grey"))); it->setData(Article::IconRole, QVariant(QIcon(":/Icons/sphere.png"))); }else{ @@ -491,14 +491,14 @@ void RSSImp::refreshArticleList(QTreeWidgetItem* item) { // display a news void RSSImp::refreshTextBrowser() { QList selection = listArticles->selectedItems(); - if(selection.empty()) return; + if (selection.empty()) return; Q_ASSERT(selection.size() == 1); QListWidgetItem *item = selection.first(); Q_ASSERT(item); - if(item == m_currentArticle) return; + if (item == m_currentArticle) return; // Stop displaying previous news if necessary - if(m_feedList->currentFeed() == m_feedList->stickyUnreadItem()) { - if(m_currentArticle) { + if (m_feedList->currentFeed() == m_feedList->stickyUnreadItem()) { + if (m_currentArticle) { disconnect(listArticles, SIGNAL(itemSelectionChanged()), this, SLOT(refreshTextBrowser())); listArticles->removeItemWidget(m_currentArticle); Q_ASSERT(m_currentArticle); @@ -512,10 +512,10 @@ void RSSImp::refreshTextBrowser() { QString html; html += "
"; html += "
"+article->title() + "
"; - if(article->date().isValid()) { + if (article->date().isValid()) { html += "
"+tr("Date: ")+""+article->date().toLocalTime().toString(Qt::SystemLocaleLongDate)+"
"; } - if(!article->author().isEmpty()) { + if (!article->author().isEmpty()) { html += "
"+tr("Author: ")+""+article->author()+"
"; } html += "
"; @@ -540,17 +540,17 @@ void RSSImp::saveSlidersPosition() { void RSSImp::restoreSlidersPosition() { QIniSettings settings("qBittorrent", "qBittorrent"); QByteArray pos_h = settings.value("rss/splitter_h", QByteArray()).toByteArray(); - if(!pos_h.isNull()) { + if (!pos_h.isNull()) { splitter_h->restoreState(pos_h); } QByteArray pos_v = settings.value("rss/splitter_v", QByteArray()).toByteArray(); - if(!pos_v.isNull()) { + if (!pos_v.isNull()) { splitter_v->restoreState(pos_v); } } void RSSImp::updateItemsInfos(const QList &items) { - foreach(QTreeWidgetItem* item, items) { + foreach (QTreeWidgetItem* item, items) { updateItemInfos(item); } } @@ -561,13 +561,13 @@ void RSSImp::updateItemInfos(QTreeWidgetItem *item) { return; QString name; - if(rss_item == m_rssManager) + if (rss_item == m_rssManager) name = tr("Unread"); else name = rss_item->displayName(); item->setText(0, name + QString::fromUtf8(" (") + QString::number(rss_item->unreadCount(), 10)+ QString(")")); // If item has a parent, update it too - if(item->parent()) + if (item->parent()) updateItemInfos(item->parent()); } @@ -581,19 +581,19 @@ void RSSImp::updateFeedInfos(const QString &url, const QString &display_name, ui QTreeWidgetItem *item = m_feedList->getTreeItemFromUrl(url); RssFeedPtr stream = qSharedPointerCast(m_feedList->getRSSItem(item)); item->setText(0, display_name + QString::fromUtf8(" (") + QString::number(nbUnread, 10)+ QString(")")); - if(!stream->isLoading()) + if (!stream->isLoading()) item->setData(0,Qt::DecorationRole, QVariant(QIcon(stream->icon()))); // Update parent - if(item->parent()) + if (item->parent()) updateItemInfos(item->parent()); // Update Unread item updateItemInfos(m_feedList->stickyUnreadItem()); // If the feed is selected, update the displayed news - if(m_feedList->currentItem() == item ){ + if (m_feedList->currentItem() == item ){ refreshArticleList(item); } else { // Update unread items - if(m_feedList->currentItem() == m_feedList->stickyUnreadItem()) { + if (m_feedList->currentItem() == m_feedList->stickyUnreadItem()) { refreshArticleList(m_feedList->stickyUnreadItem()); } } @@ -680,7 +680,7 @@ RSSImp::~RSSImp(){ void RSSImp::on_settingsButton_clicked() { RssSettingsDlg dlg(this); - if(dlg.exec()) + if (dlg.exec()) updateRefreshInterval(RssSettings().getRSSRefreshInterval()); } @@ -688,6 +688,6 @@ void RSSImp::on_rssDownloaderBtn_clicked() { AutomatedRssDownloader dlg(m_rssManager, this); dlg.exec(); - if(dlg.isRssDownloaderEnabled()) + if (dlg.isRssDownloaderEnabled()) on_updateAllButton_clicked(); } diff --git a/src/rss/rssarticle.cpp b/src/rss/rssarticle.cpp index 81291ca41..2ae9538f3 100644 --- a/src/rss/rssarticle.cpp +++ b/src/rss/rssarticle.cpp @@ -223,33 +223,33 @@ RssArticlePtr xmlToRssArticle(RssFeed* parent, QXmlStreamReader& xml) while(!xml.atEnd()) { xml.readNext(); - if(xml.isEndElement() && xml.name() == "item") + if (xml.isEndElement() && xml.name() == "item") break; - if(xml.isStartElement()) { - if(xml.name() == "title") { + if (xml.isStartElement()) { + if (xml.name() == "title") { title = xml.readElementText(); } - else if(xml.name() == "enclosure") { - if(xml.attributes().value("type") == "application/x-bittorrent") { + else if (xml.name() == "enclosure") { + if (xml.attributes().value("type") == "application/x-bittorrent") { torrentUrl = xml.attributes().value("url").toString(); } } - else if(xml.name() == "link") { + else if (xml.name() == "link") { link = xml.readElementText(); - if(guid.isEmpty()) + if (guid.isEmpty()) guid = link; } - else if(xml.name() == "description") { + else if (xml.name() == "description") { description = xml.readElementText(); } - else if(xml.name() == "pubDate") { + else if (xml.name() == "pubDate") { date = RssArticle::parseDate(xml.readElementText()); } - else if(xml.name() == "author") { + else if (xml.name() == "author") { author = xml.readElementText(); } - else if(xml.name() == "guid") { + else if (xml.name() == "guid") { guid = xml.readElementText(); } } @@ -271,7 +271,7 @@ RssArticlePtr xmlToRssArticle(RssFeed* parent, QXmlStreamReader& xml) RssArticlePtr hashToRssArticle(RssFeed* parent, const QVariantHash &h) { const QString guid = h.value("id").toString(); - if(guid.isEmpty()) return RssArticlePtr(); + if (guid.isEmpty()) return RssArticlePtr(); RssArticlePtr art(new RssArticle(parent, guid)); art->m_title = h.value("title", "").toString(); @@ -302,7 +302,7 @@ QString RssArticle::link() const { } QString RssArticle::description() const{ - if(m_description.isNull()) + if (m_description.isNull()) return ""; return m_description; } diff --git a/src/rss/rssdownloadrule.cpp b/src/rss/rssdownloadrule.cpp index 3bc514867..6ae6e8c89 100644 --- a/src/rss/rssdownloadrule.cpp +++ b/src/rss/rssdownloadrule.cpp @@ -43,26 +43,26 @@ RssDownloadRule::RssDownloadRule(): m_enabled(false), m_useRegex(false) bool RssDownloadRule::matches(const QString &article_title) const { - foreach(const QString& token, m_mustContain) { - if(token.isEmpty() || token == "") + foreach (const QString& token, m_mustContain) { + if (token.isEmpty() || token == "") continue; QRegExp reg(token, Qt::CaseInsensitive, m_useRegex ? QRegExp::RegExp : QRegExp::Wildcard); //reg.setMinimal(false); - if(reg.indexIn(article_title) < 0) return false; + if (reg.indexIn(article_title) < 0) return false; } qDebug("Checking not matching tokens"); // Checking not matching - foreach(const QString& token, m_mustNotContain) { - if(token.isEmpty()) continue; + foreach (const QString& token, m_mustNotContain) { + if (token.isEmpty()) continue; QRegExp reg(token, Qt::CaseInsensitive, m_useRegex ? QRegExp::RegExp : QRegExp::Wildcard); - if(reg.indexIn(article_title) > -1) return false; + if (reg.indexIn(article_title) > -1) return false; } return true; } void RssDownloadRule::setMustContain(const QString &tokens) { - if(m_useRegex) + if (m_useRegex) m_mustContain = QStringList() << tokens; else m_mustContain = tokens.split(" "); @@ -70,7 +70,7 @@ void RssDownloadRule::setMustContain(const QString &tokens) void RssDownloadRule::setMustNotContain(const QString &tokens) { - if(m_useRegex) + if (m_useRegex) m_mustNotContain = QStringList() << tokens; else m_mustNotContain = tokens.split(QRegExp("[\\s|]")); @@ -83,7 +83,7 @@ RssDownloadRulePtr RssDownloadRule::fromOldFormat(const QVariantHash &rule_hash, rule->setName(rule_name); rule->setMustContain(rule_hash.value("matches", "").toString()); rule->setMustNotContain(rule_hash.value("not", "").toString()); - if(!feed_url.isEmpty()) + if (!feed_url.isEmpty()) rule->setRssFeeds(QStringList() << feed_url); rule->setSavePath(rule_hash.value("save_path", "").toString()); // Is enabled? @@ -128,7 +128,7 @@ bool RssDownloadRule::operator==(const RssDownloadRule &other) { void RssDownloadRule::setSavePath(const QString &save_path) { - if(!save_path.isEmpty() && QDir(save_path) != QDir(Preferences().getSavePath())) + if (!save_path.isEmpty() && QDir(save_path) != QDir(Preferences().getSavePath())) m_savePath = save_path; else m_savePath = QString(); @@ -138,7 +138,7 @@ QStringList RssDownloadRule::findMatchingArticles(const RssFeedPtr& feed) const { QStringList ret; const RssArticleHash& feed_articles = feed->articleHash(); - for(RssArticleHash::ConstIterator artIt = feed_articles.begin(); artIt != feed_articles.end(); artIt++) { + for (RssArticleHash::ConstIterator artIt = feed_articles.begin(); artIt != feed_articles.end(); artIt++) { const QString title = artIt.value()->title(); if (matches(title)) ret << title; diff --git a/src/rss/rssdownloadrulelist.cpp b/src/rss/rssdownloadrulelist.cpp index 9a41ae902..a92181413 100644 --- a/src/rss/rssdownloadrulelist.cpp +++ b/src/rss/rssdownloadrulelist.cpp @@ -44,7 +44,7 @@ RssDownloadRuleList::RssDownloadRuleList(){ RssDownloadRuleList* RssDownloadRuleList::instance() { - if(!m_instance) + if (!m_instance) m_instance = new RssDownloadRuleList; return m_instance; } @@ -61,9 +61,9 @@ RssDownloadRulePtr RssDownloadRuleList::findMatchingRule(const QString &feed_url { Q_ASSERT(RssSettings().isRssDownloadingEnabled()); QStringList rule_names = m_feedRules.value(feed_url); - foreach(const QString &rule_name, rule_names) { + foreach (const QString &rule_name, rule_names) { RssDownloadRulePtr rule = m_rules[rule_name]; - if(rule->isEnabled() && rule->matches(article_title)) return rule; + if (rule->isEnabled() && rule->matches(article_title)) return rule; } return RssDownloadRulePtr(); } @@ -77,7 +77,7 @@ void RssDownloadRuleList::saveRulesToStorage() void RssDownloadRuleList::loadRulesFromStorage() { QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss"); - if(qBTRSS.contains("feed_filters")) { + if (qBTRSS.contains("feed_filters")) { importFeedsInOldFormat(qBTRSS.value("feed_filters").toHash()); // Remove outdated rules qBTRSS.remove("feed_filters"); @@ -91,16 +91,16 @@ void RssDownloadRuleList::loadRulesFromStorage() void RssDownloadRuleList::importFeedsInOldFormat(const QHash &rules) { - foreach(const QString &feed_url, rules.keys()) { + foreach (const QString &feed_url, rules.keys()) { importFeedRulesInOldFormat(feed_url, rules.value(feed_url).toHash()); } } void RssDownloadRuleList::importFeedRulesInOldFormat(const QString &feed_url, const QHash &rules) { - foreach(const QString &rule_name, rules.keys()) { + foreach (const QString &rule_name, rules.keys()) { RssDownloadRulePtr rule = RssDownloadRule::fromOldFormat(rules.value(rule_name).toHash(), feed_url, rule_name); - if(!rule) continue; + if (!rule) continue; // Check for rule name clash while(m_rules.contains(rule->name())) { rule->setName(rule->name()+"_"); @@ -113,7 +113,7 @@ void RssDownloadRuleList::importFeedRulesInOldFormat(const QString &feed_url, co QVariantHash RssDownloadRuleList::toVariantHash() const { QVariantHash ret; - foreach(const RssDownloadRulePtr &rule, m_rules.values()) { + foreach (const RssDownloadRulePtr &rule, m_rules.values()) { ret.insert(rule->name(), rule->toVariantHash()); } return ret; @@ -121,9 +121,9 @@ QVariantHash RssDownloadRuleList::toVariantHash() const void RssDownloadRuleList::loadRulesFromVariantHash(const QVariantHash &h) { - foreach(const QVariant& v, h.values()) { + foreach (const QVariant& v, h.values()) { RssDownloadRulePtr rule = RssDownloadRule::fromNewFormat(v.toHash()); - if(rule && !rule->name().isEmpty()) { + if (rule && !rule->name().isEmpty()) { saveRule(rule); } } @@ -133,13 +133,13 @@ void RssDownloadRuleList::saveRule(const RssDownloadRulePtr &rule) { qDebug() << Q_FUNC_INFO << rule->name(); Q_ASSERT(rule); - if(m_rules.contains(rule->name())) { + if (m_rules.contains(rule->name())) { qDebug("This is an update, removing old rule first"); removeRule(rule->name()); } m_rules.insert(rule->name(), rule); // Update feedRules hashtable - foreach(const QString &feed_url, rule->rssFeeds()) { + foreach (const QString &feed_url, rule->rssFeeds()) { m_feedRules[feed_url].append(rule->name()); } // Save rules @@ -150,10 +150,10 @@ void RssDownloadRuleList::saveRule(const RssDownloadRulePtr &rule) void RssDownloadRuleList::removeRule(const QString &name) { qDebug() << Q_FUNC_INFO << name; - if(!m_rules.contains(name)) return; + if (!m_rules.contains(name)) return; RssDownloadRulePtr rule = m_rules.take(name); // Update feedRules hashtable - foreach(const QString &feed_url, rule->rssFeeds()) { + foreach (const QString &feed_url, rule->rssFeeds()) { m_feedRules[feed_url].removeOne(rule->name()); } // Save rules @@ -162,12 +162,12 @@ void RssDownloadRuleList::removeRule(const QString &name) void RssDownloadRuleList::renameRule(const QString &old_name, const QString &new_name) { - if(!m_rules.contains(old_name)) return; + if (!m_rules.contains(old_name)) return; RssDownloadRulePtr rule = m_rules.take(old_name); rule->setName(new_name); m_rules.insert(new_name, rule); // Update feedRules hashtable - foreach(const QString &feed_url, rule->rssFeeds()) { + foreach (const QString &feed_url, rule->rssFeeds()) { m_feedRules[feed_url].replace(m_feedRules[feed_url].indexOf(old_name), new_name); } // Save rules @@ -182,7 +182,7 @@ RssDownloadRulePtr RssDownloadRuleList::getRule(const QString &name) const bool RssDownloadRuleList::serialize(const QString& path) { QFile f(path); - if(f.open(QIODevice::WriteOnly)) { + if (f.open(QIODevice::WriteOnly)) { QDataStream out(&f); out.setVersion(QDataStream::Qt_4_5); out << toVariantHash(); @@ -196,16 +196,16 @@ bool RssDownloadRuleList::serialize(const QString& path) bool RssDownloadRuleList::unserialize(const QString &path) { QFile f(path); - if(f.open(QIODevice::ReadOnly)) { + if (f.open(QIODevice::ReadOnly)) { QDataStream in(&f); - if(path.endsWith(".filters", Qt::CaseInsensitive)) { + if (path.endsWith(".filters", Qt::CaseInsensitive)) { // Old format (< 2.5.0) qDebug("Old serialization format detected, processing..."); in.setVersion(QDataStream::Qt_4_3); QVariantHash tmp; in >> tmp; f.close(); - if(tmp.isEmpty()) return false; + if (tmp.isEmpty()) return false; qDebug("Processing was successful!"); // Unfortunately the feed_url is lost importFeedRulesInOldFormat("", tmp); @@ -215,7 +215,7 @@ bool RssDownloadRuleList::unserialize(const QString &path) QVariantHash tmp; in >> tmp; f.close(); - if(tmp.isEmpty()) return false; + if (tmp.isEmpty()) return false; qDebug("Processing was successful!"); loadRulesFromVariantHash(tmp); } diff --git a/src/rss/rssfeed.cpp b/src/rss/rssfeed.cpp index 01c90cce6..f492e47c2 100644 --- a/src/rss/rssfeed.cpp +++ b/src/rss/rssfeed.cpp @@ -56,7 +56,7 @@ RssFeed::RssFeed(RssManager* manager, RssFolder* parent, const QString &url): } RssFeed::~RssFeed(){ - if(!m_icon.startsWith(":/") && QFile::exists(m_icon)) + if (!m_icon.startsWith(":/") && QFile::exists(m_icon)) QFile::remove(m_icon); } @@ -91,7 +91,7 @@ void RssFeed::loadItemsFromDisk() { } void RssFeed::refresh() { - if(m_loading) { + if (m_loading) { qWarning() << Q_FUNC_INFO << "Feed" << this->displayName() << "is already being refreshed, ignoring request"; return; } @@ -143,11 +143,11 @@ void RssFeed::rename(const QString &new_name){ // Return the alias if the stream has one, the url if it has no alias QString RssFeed::displayName() const { - if(!m_alias.isEmpty()) { + if (!m_alias.isEmpty()) { //qDebug("getName() returned alias: %s", (const char*)alias.toLocal8Bit()); return m_alias; } - if(!m_title.isEmpty()) { + if (!m_title.isEmpty()) { //qDebug("getName() returned title: %s", (const char*)title.toLocal8Bit()); return m_title; } @@ -160,7 +160,7 @@ QString RssFeed::url() const{ } QString RssFeed::icon() const{ - if(m_downloadFailure) + if (m_downloadFailure) return ":/Icons/oxygen/unavailable.png"; return m_icon; } @@ -170,7 +170,7 @@ bool RssFeed::hasCustomIcon() const{ } void RssFeed::setIconPath(const QString &path) { - if(path.isEmpty() || !QFile::exists(path)) return; + if (path.isEmpty() || !QFile::exists(path)) return; m_icon = path; } @@ -192,7 +192,7 @@ void RssFeed::markAsRead() { uint RssFeed::unreadCount() const{ uint nbUnread = 0; for (RssArticleHash::ConstIterator it=m_articles.begin(); it != m_articles.end(); it++) { - if(!it.value()->isRead()) + if (!it.value()->isRead()) ++nbUnread; } return nbUnread; @@ -205,7 +205,7 @@ RssArticleList RssFeed::articleList() const{ RssArticleList RssFeed::unreadArticleList() const { RssArticleList unread_news; for (RssArticleHash::ConstIterator it = m_articles.begin(); it != m_articles.end(); it++) { - if(!it.value()->isRead()) + if (!it.value()->isRead()) unread_news << it.value(); } return unread_news; @@ -229,8 +229,8 @@ bool RssFeed::parseRSS(QIODevice* device) { } while (!xml.atEnd()) { xml.readNext(); - if(xml.isStartElement()) { - if(xml.name() != "rss") { + if (xml.isStartElement()) { + if (xml.name() != "rss") { qDebug("ERROR: this is not a rss file, root tag is <%s>", qPrintable(xml.name().toString())); return false; } else { @@ -242,37 +242,37 @@ bool RssFeed::parseRSS(QIODevice* device) { while(!xml.atEnd()) { xml.readNext(); - if(!xml.isStartElement()) + if (!xml.isStartElement()) continue; - if(xml.name() != "channel") + if (xml.name() != "channel") continue; // Parse channel content while(!xml.atEnd()) { xml.readNext(); - if(xml.isEndElement() && xml.name() == "channel") + if (xml.isEndElement() && xml.name() == "channel") break; // End of this channel, parse the next one - if(!xml.isStartElement()) + if (!xml.isStartElement()) continue; - if(xml.name() == "title") { + if (xml.name() == "title") { m_title = xml.readElementText(); - if(m_alias == url()) + if (m_alias == url()) rename(m_title); } - else if(xml.name() == "image") { + else if (xml.name() == "image") { QString icon_path = xml.attributes().value("url").toString(); - if(!icon_path.isEmpty()) { + if (!icon_path.isEmpty()) { m_iconUrl = icon_path; m_manager->rssDownloader()->downloadUrl(m_iconUrl); } } - else if(xml.name() == "item") { + else if (xml.name() == "item") { RssArticlePtr art = xmlToRssArticle(this, xml); - if(art && !itemAlreadyExists(art->guid())) + if (art && !itemAlreadyExists(art->guid())) m_articles.insert(art->guid(), art); } } @@ -282,7 +282,7 @@ bool RssFeed::parseRSS(QIODevice* device) { resizeList(); // RSS Feed Downloader - if(RssSettings().isRssDownloadingEnabled()) + if (RssSettings().isRssDownloadingEnabled()) downloadMatchingArticleTorrents(); // Save items to disk (for safety) @@ -295,15 +295,15 @@ void RssFeed::downloadMatchingArticleTorrents() { Q_ASSERT(RssSettings().isRssDownloadingEnabled()); for (RssArticleHash::ConstIterator it = m_articles.begin(); it != m_articles.end(); it++) { RssArticlePtr item = it.value(); - if(item->isRead()) continue; + if (item->isRead()) continue; QString torrent_url; - if(item->hasAttachment()) + if (item->hasAttachment()) torrent_url = item->torrentUrl(); else torrent_url = item->link(); // Check if the item should be automatically downloaded RssDownloadRulePtr matching_rule = RssDownloadRuleList::instance()->findMatchingRule(m_url, item->title()); - if(matching_rule) { + if (matching_rule) { // Item was downloaded, consider it as Read item->markAsRead(); // Download the torrent @@ -316,11 +316,11 @@ void RssFeed::downloadMatchingArticleTorrents() { void RssFeed::resizeList() { const uint max_articles = RssSettings().getRSSMaxArticlesPerFeed(); const uint nb_articles = m_articles.size(); - if(nb_articles > max_articles) { + if (nb_articles > max_articles) { RssArticleList listItems = m_articles.values(); RssManager::sortNewsList(listItems); const int excess = nb_articles - max_articles; - for(uint i=nb_articles-excess; iguid()); } } @@ -330,9 +330,9 @@ void RssFeed::resizeList() { bool RssFeed::parseXmlFile(const QString &file_path){ qDebug("openRss() called"); QFile fileRss(file_path); - if(!fileRss.open(QIODevice::ReadOnly | QIODevice::Text)) { + if (!fileRss.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug("openRss error: open failed, no file or locked, %s", qPrintable(file_path)); - if(QFile::exists(file_path)) { + if (QFile::exists(file_path)) { fileRss.remove(); } return false; @@ -341,25 +341,25 @@ bool RssFeed::parseXmlFile(const QString &file_path){ // start reading the xml bool ret = parseRSS(&fileRss); fileRss.close(); - if(QFile::exists(file_path)) + if (QFile::exists(file_path)) fileRss.remove(); return ret; } // read and store the downloaded rss' informations void RssFeed::handleFinishedDownload(const QString& url, const QString &file_path) { - if(url == m_url) { + if (url == m_url) { qDebug() << Q_FUNC_INFO << "Successfuly downloaded RSS feed at" << url; m_downloadFailure = false; m_loading = false; // Parse the download RSS - if(parseXmlFile(file_path)) { + if (parseXmlFile(file_path)) { m_refreshed = true; m_manager->forwardFeedInfosChanged(m_url, displayName(), unreadCount()); // XXX: Ugly qDebug() << Q_FUNC_INFO << "Feed parsed successfuly"; } } - else if(url == m_iconUrl) { + else if (url == m_iconUrl) { m_icon = file_path; qDebug() << Q_FUNC_INFO << "icon path:" << m_icon; m_manager->forwardFeedIconChanged(m_url, m_icon); // XXX: Ugly @@ -367,7 +367,7 @@ void RssFeed::handleFinishedDownload(const QString& url, const QString &file_pat } void RssFeed::handleDownloadFailure(const QString &url, const QString& error) { - if(url != m_url) return; + if (url != m_url) return; m_downloadFailure = true; m_loading = false; m_manager->forwardFeedInfosChanged(m_url, displayName(), unreadCount()); // XXX: Ugly diff --git a/src/rss/rssfile.cpp b/src/rss/rssfile.cpp index 71c3c6811..f41912484 100644 --- a/src/rss/rssfile.cpp +++ b/src/rss/rssfile.cpp @@ -33,7 +33,7 @@ QStringList RssFile::pathHierarchy() const { QStringList path; - if(parent()) + if (parent()) path << parent()->pathHierarchy(); path << id(); return path; diff --git a/src/rss/rssfolder.cpp b/src/rss/rssfolder.cpp index 133aa1265..2d7bddf5e 100644 --- a/src/rss/rssfolder.cpp +++ b/src/rss/rssfolder.cpp @@ -186,7 +186,7 @@ void RssFolder::removeAllSettings() { void RssFolder::saveItemsToDisk() { - foreach(const RssFilePtr& child, m_children.values()) { + foreach (const RssFilePtr& child, m_children.values()) { child->saveItemsToDisk(); } } diff --git a/src/rss/rssmanager.cpp b/src/rss/rssmanager.cpp index a95f10a4e..b78c64ebb 100644 --- a/src/rss/rssmanager.cpp +++ b/src/rss/rssmanager.cpp @@ -54,7 +54,7 @@ RssManager::~RssManager(){ } void RssManager::updateRefreshInterval(uint val){ - if(m_refreshInterval != val) { + if (m_refreshInterval != val) { m_refreshInterval = val; m_refreshTimer.start(m_refreshInterval*60000); qDebug("New RSS refresh interval is now every %dmin", m_refreshInterval); @@ -65,20 +65,20 @@ void RssManager::loadStreamList() { RssSettings settings; const QStringList streamsUrl = settings.getRssFeedsUrls(); const QStringList aliases = settings.getRssFeedsAliases(); - if(streamsUrl.size() != aliases.size()){ + if (streamsUrl.size() != aliases.size()){ std::cerr << "Corrupted Rss list, not loading it\n"; return; } uint i = 0; qDebug() << Q_FUNC_INFO << streamsUrl; - foreach(QString s, streamsUrl){ + foreach (QString s, streamsUrl){ QStringList path = s.split("\\", QString::SkipEmptyParts); - if(path.empty()) continue; + if (path.empty()) continue; const QString feed_url = path.takeLast(); qDebug() << "Feed URL:" << feed_url; // Create feed path (if it does not exists) RssFolder* feed_parent = this; - foreach(const QString &folder_name, path) { + foreach (const QString &folder_name, path) { qDebug() << "Adding parent folder:" << folder_name; feed_parent = feed_parent->addFolder(folder_name).data(); } @@ -86,7 +86,7 @@ void RssManager::loadStreamList() { qDebug() << "Adding feed to parent folder"; RssFeedPtr stream = feed_parent->addStream(this, feed_url); const QString alias = aliases.at(i); - if(!alias.isEmpty()) { + if (!alias.isEmpty()) { stream->rename(alias); } ++i; @@ -104,7 +104,7 @@ void RssManager::forwardFeedIconChanged(const QString &url, const QString &icon_ void RssManager::moveFile(const RssFilePtr& file, const RssFolderPtr& dest_folder) { RssFolder* src_folder = file->parent(); - if(dest_folder != src_folder) { + if (dest_folder != src_folder) { // Remove reference in old folder src_folder->takeChild(file->id()); // add to new Folder @@ -118,9 +118,9 @@ void RssManager::saveStreamList() const { QStringList streamsUrl; QStringList aliases; QList streams = getAllFeeds(); - foreach(const RssFeedPtr& stream, streams) { + foreach (const RssFeedPtr& stream, streams) { QString stream_path = stream->pathHierarchy().join("\\"); - if(stream_path.isNull()) { + if (stream_path.isNull()) { stream_path = ""; } qDebug("Saving stream path: %s", qPrintable(stream_path)); diff --git a/src/rss/rsssettings.h b/src/rss/rsssettings.h index 353e39418..feb8775c2 100644 --- a/src/rss/rsssettings.h +++ b/src/rss/rsssettings.h @@ -89,7 +89,7 @@ public: QList getHostNameCookies(const QString &host_name) const { QMap hosts_table = value("Rss/hosts_cookies").toMap(); - if(!hosts_table.contains(host_name)) return QList(); + if (!hosts_table.contains(host_name)) return QList(); QByteArray raw_cookies = hosts_table.value(host_name).toByteArray(); return raw_cookies.split(':'); } @@ -97,10 +97,10 @@ public: void setHostNameCookies(const QString &host_name, const QList &cookies) { QMap hosts_table = value("Rss/hosts_cookies").toMap(); QByteArray raw_cookies = ""; - foreach(const QByteArray& cookie, cookies) { + foreach (const QByteArray& cookie, cookies) { raw_cookies += cookie + ":"; } - if(raw_cookies.endsWith(":")) + if (raw_cookies.endsWith(":")) raw_cookies.chop(1); hosts_table.insert(host_name, raw_cookies); setValue("Rss/hosts_cookies", hosts_table); diff --git a/src/searchengine/engineselectdlg.cpp b/src/searchengine/engineselectdlg.cpp index 3650b9476..bf43628c6 100644 --- a/src/searchengine/engineselectdlg.cpp +++ b/src/searchengine/engineselectdlg.cpp @@ -76,15 +76,15 @@ engineSelectDlg::~engineSelectDlg() { void engineSelectDlg::dropEvent(QDropEvent *event) { event->acceptProposedAction(); QStringList files=event->mimeData()->text().split(QString::fromUtf8("\n")); - foreach(QString file, files) { + foreach (QString file, files) { qDebug("dropped %s", qPrintable(file)); - if(misc::isUrl(file)) { + if (misc::isUrl(file)) { setCursor(QCursor(Qt::WaitCursor)); downloader->downloadUrl(file); continue; } - if(file.endsWith(".py", Qt::CaseInsensitive)) { - if(file.startsWith("file:", Qt::CaseInsensitive)) + if (file.endsWith(".py", Qt::CaseInsensitive)) { + if (file.startsWith("file:", Qt::CaseInsensitive)) file = QUrl(file).toLocalFile(); QString plugin_name = misc::fileName(file); plugin_name.chop(3); // Remove extension @@ -96,7 +96,7 @@ void engineSelectDlg::dropEvent(QDropEvent *event) { // Decode if we accept drag 'n drop or not void engineSelectDlg::dragEnterEvent(QDragEnterEvent *event) { QString mime; - foreach(mime, event->mimeData()->formats()){ + foreach (mime, event->mimeData()->formats()){ qDebug("mimeData: %s", qPrintable(mime)); } if (event->mimeData()->hasFormat(QString::fromUtf8("text/plain")) || event->mimeData()->hasFormat(QString::fromUtf8("text/uri-list"))) { @@ -113,7 +113,7 @@ void engineSelectDlg::on_updateButton_clicked() { void engineSelectDlg::toggleEngineState(QTreeWidgetItem *item, int) { SupportedEngine *engine = supported_engines->value(item->text(ENGINE_ID)); engine->setEnabled(!engine->isEnabled()); - if(engine->isEnabled()) { + if (engine->isEnabled()) { item->setText(ENGINE_STATE, tr("Yes")); setRowColor(pluginsTree->indexOfTopLevelItem(item), "green"); } else { @@ -126,7 +126,7 @@ void engineSelectDlg::displayContextMenu(const QPoint&) { QMenu myContextMenu(this); // Enable/disable pause/start action given the DL state QList items = pluginsTree->selectedItems(); - if(items.isEmpty()) return; + if (items.isEmpty()) return; QString first_id = items.first()->text(ENGINE_ID); actionEnable->setChecked(supported_engines->value(first_id)->isEnabled()); myContextMenu.addAction(actionEnable); @@ -143,11 +143,11 @@ void engineSelectDlg::on_actionUninstall_triggered() { QList items = pluginsTree->selectedItems(); QTreeWidgetItem *item; bool error = false; - foreach(item, items) { + foreach (item, items) { int index = pluginsTree->indexOfTopLevelItem(item); Q_ASSERT(index != -1); QString id = item->text(ENGINE_ID); - if(QFile::exists(":/nova/engines/"+id+".py")) { + if (QFile::exists(":/nova/engines/"+id+".py")) { error = true; // Disable it instead supported_engines->value(id)->setEnabled(false); @@ -162,7 +162,7 @@ void engineSelectDlg::on_actionUninstall_triggered() { filters << id+".*"; QStringList files = enginesFolder.entryList(filters, QDir::Files, QDir::Unsorted); QString file; - foreach(file, files) { + foreach (file, files) { enginesFolder.remove(file); } // Remove it from supported engines @@ -170,7 +170,7 @@ void engineSelectDlg::on_actionUninstall_triggered() { delete item; } } - if(error) + if (error) QMessageBox::warning(0, tr("Uninstall warning"), tr("Some plugins could not be uninstalled because they are included in qBittorrent.\n Only the ones you added yourself can be uninstalled.\nHowever, those plugins were disabled.")); else QMessageBox::information(0, tr("Uninstall success"), tr("All selected plugins were uninstalled successfully")); @@ -179,12 +179,12 @@ void engineSelectDlg::on_actionUninstall_triggered() { void engineSelectDlg::enableSelection(bool enable) { QList items = pluginsTree->selectedItems(); QTreeWidgetItem *item; - foreach(item, items) { + foreach (item, items) { int index = pluginsTree->indexOfTopLevelItem(item); Q_ASSERT(index != -1); QString id = item->text(ENGINE_ID); supported_engines->value(id)->setEnabled(enable); - if(enable) { + if (enable) { item->setText(ENGINE_STATE, tr("Yes")); setRowColor(index, "green"); } else { @@ -197,16 +197,16 @@ void engineSelectDlg::enableSelection(bool enable) { // Set the color of a row in data model void engineSelectDlg::setRowColor(int row, QString color){ QTreeWidgetItem *item = pluginsTree->topLevelItem(row); - for(int i=0; icolumnCount(); ++i){ + for (int i=0; icolumnCount(); ++i){ item->setData(i, Qt::ForegroundRole, QVariant(QColor(color))); } } QList engineSelectDlg::findItemsWithUrl(QString url){ QList res; - for(int i=0; itopLevelItemCount(); ++i) { + for (int i=0; itopLevelItemCount(); ++i) { QTreeWidgetItem *item = pluginsTree->topLevelItem(i); - if(url.startsWith(item->text(ENGINE_URL), Qt::CaseInsensitive)) + if (url.startsWith(item->text(ENGINE_URL), Qt::CaseInsensitive)) res << item; } return res; @@ -214,9 +214,9 @@ QList engineSelectDlg::findItemsWithUrl(QString url){ QTreeWidgetItem* engineSelectDlg::findItemWithID(QString id){ QList res; - for(int i=0; itopLevelItemCount(); ++i) { + for (int i=0; itopLevelItemCount(); ++i) { QTreeWidgetItem *item = pluginsTree->topLevelItem(i); - if(id == item->text(ENGINE_ID)) + if (id == item->text(ENGINE_ID)) return item; } return 0; @@ -232,7 +232,7 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) { qDebug("Asked to install plugin at %s", qPrintable(path)); qreal new_version = SearchEngine::getPluginVersion(path); qDebug("Version to be installed: %.2f", new_version); - if(!isUpdateNeeded(plugin_name, new_version)) { + if (!isUpdateNeeded(plugin_name, new_version)) { qDebug("Apparently update is not needed, we have a more recent version"); QMessageBox::information(this, tr("Search plugin install")+" -- "+tr("qBittorrent"), tr("A more recent version of %1 search engine plugin is already installed.", "%1 is the name of the search engine").arg(plugin_name)); return; @@ -240,7 +240,7 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) { // Process with install QString dest_path = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+plugin_name+".py"; bool update = false; - if(QFile::exists(dest_path)) { + if (QFile::exists(dest_path)) { // Backup in case install fails QFile::copy(dest_path, dest_path+".bak"); QFile::remove(dest_path); @@ -252,8 +252,8 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) { // Update supported plugins supported_engines->update(); // Check if this was correctly installed - if(!supported_engines->contains(plugin_name)) { - if(update) { + if (!supported_engines->contains(plugin_name)) { + if (update) { // Remove broken file QFile::remove(dest_path); // restore backup @@ -269,10 +269,10 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) { } } // Install was successful, remove backup - if(update) { + if (update) { QFile::remove(dest_path+".bak"); } - if(update) { + if (update) { QMessageBox::information(this, tr("Search plugin install")+" -- "+tr("qBittorrent"), tr("%1 search engine plugin was successfully updated.", "%1 is the name of the search engine").arg(plugin_name)); return; } else { @@ -284,7 +284,7 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) { void engineSelectDlg::loadSupportedSearchEngines() { // Some clean up first pluginsTree->clear(); - foreach(QString name, supported_engines->keys()) { + foreach (QString name, supported_engines->keys()) { addNewEngine(name); } } @@ -295,7 +295,7 @@ void engineSelectDlg::addNewEngine(QString engine_name) { item->setText(ENGINE_NAME, engine->getFullName()); item->setText(ENGINE_URL, engine->getUrl()); item->setText(ENGINE_ID, engine->getName()); - if(engine->isEnabled()) { + if (engine->isEnabled()) { item->setText(ENGINE_STATE, tr("Yes")); setRowColor(pluginsTree->indexOfTopLevelItem(item), "green"); } else { @@ -304,12 +304,12 @@ void engineSelectDlg::addNewEngine(QString engine_name) { } // Handle icon QString iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+engine->getName()+".png"; - if(QFile::exists(iconPath)) { + if (QFile::exists(iconPath)) { // Good, we already have the icon item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath))); } else { iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+engine->getName()+".ico"; - if(QFile::exists(iconPath)) { // ICO support + if (QFile::exists(iconPath)) { // ICO support item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath))); } else { // Icon is missing, we must download it @@ -340,8 +340,8 @@ void engineSelectDlg::askForLocalPlugin() { tr("Select search plugins"), QDir::homePath(), tr("qBittorrent search plugins")+QString::fromUtf8(" (*.py)")); QString path; - foreach(path, pathsList) { - if(path.endsWith(".py", Qt::CaseInsensitive)) { + foreach (path, pathsList) { + if (path.endsWith(".py", Qt::CaseInsensitive)) { QString plugin_name = path.split(QDir::separator()).last(); plugin_name.replace(".py", "", Qt::CaseInsensitive); installPlugin(path, plugin_name); @@ -353,7 +353,7 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) { qDebug("Checking if update is needed"); bool file_correct = false; QFile versions(versions_file); - if(!versions.open(QIODevice::ReadOnly | QIODevice::Text)){ + if (!versions.open(QIODevice::ReadOnly | QIODevice::Text)){ qDebug("* Error: Could not read versions.txt file"); return false; } @@ -362,19 +362,19 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) { QByteArray line = versions.readLine(); line.replace("\n", ""); line = line.trimmed(); - if(line.isEmpty()) continue; - if(line.startsWith("#")) continue; + if (line.isEmpty()) continue; + if (line.startsWith("#")) continue; QList list = line.split(' '); - if(list.size() != 2) continue; + if (list.size() != 2) continue; QString plugin_name = QString(list.first()); - if(!plugin_name.endsWith(":")) continue; + if (!plugin_name.endsWith(":")) continue; plugin_name.chop(1); // remove trailing ':' bool ok; qreal version = list.last().toFloat(&ok); qDebug("read line %s: %.2f", qPrintable(plugin_name), version); - if(!ok) continue; + if (!ok) continue; file_correct = true; - if(isUpdateNeeded(plugin_name, version)) { + if (isUpdateNeeded(plugin_name, version)) { qDebug("Plugin: %s is outdated", qPrintable(plugin_name)); // Downloading update setCursor(QCursor(Qt::WaitCursor)); @@ -389,7 +389,7 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) { versions.close(); // Clean up tmp file QFile::remove(versions_file); - if(file_correct && !updated) { + if (file_correct && !updated) { QMessageBox::information(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("All your plugins are already up to date.")); } return file_correct; @@ -398,18 +398,18 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) { void engineSelectDlg::processDownloadedFile(QString url, QString filePath) { setCursor(QCursor(Qt::ArrowCursor)); qDebug("engineSelectDlg received %s", qPrintable(url)); - if(url.endsWith("favicon.ico", Qt::CaseInsensitive)){ + if (url.endsWith("favicon.ico", Qt::CaseInsensitive)){ // Icon downloaded QImage fileIcon; - if(fileIcon.load(filePath)) { + if (fileIcon.load(filePath)) { QList items = findItemsWithUrl(url); QTreeWidgetItem *item; - foreach(item, items){ + foreach (item, items){ QString id = item->text(ENGINE_ID); QString iconPath; QFile icon(filePath); icon.open(QIODevice::ReadOnly); - if(ICOHandler::canRead(&icon)) + if (ICOHandler::canRead(&icon)) iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".ico"; else iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".png"; @@ -421,14 +421,14 @@ void engineSelectDlg::processDownloadedFile(QString url, QString filePath) { QFile::remove(filePath); return; } - if(url.endsWith("versions.txt")) { - if(!parseVersionsFile(filePath)) { + if (url.endsWith("versions.txt")) { + if (!parseVersionsFile(filePath)) { QMessageBox::warning(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("Sorry, update server is temporarily unavailable.")); } QFile::remove(filePath); return; } - if(url.endsWith(".py", Qt::CaseInsensitive)) { + if (url.endsWith(".py", Qt::CaseInsensitive)) { QString plugin_name = misc::fileName(url); plugin_name.chop(3); // Remove extension installPlugin(filePath, plugin_name); @@ -439,15 +439,15 @@ void engineSelectDlg::processDownloadedFile(QString url, QString filePath) { void engineSelectDlg::handleDownloadFailure(QString url, QString reason) { setCursor(QCursor(Qt::ArrowCursor)); - if(url.endsWith("favicon.ico", Qt::CaseInsensitive)){ + if (url.endsWith("favicon.ico", Qt::CaseInsensitive)){ qDebug("Could not download favicon: %s, reason: %s", qPrintable(url), qPrintable(reason)); return; } - if(url.endsWith("versions.txt")) { + if (url.endsWith("versions.txt")) { QMessageBox::warning(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("Sorry, update server is temporarily unavailable.")); return; } - if(url.endsWith(".py", Qt::CaseInsensitive)) { + if (url.endsWith(".py", Qt::CaseInsensitive)) { // a plugin update download has been failed QString plugin_name = url.split('/').last(); plugin_name.replace(".py", "", Qt::CaseInsensitive); diff --git a/src/searchengine/searchengine.cpp b/src/searchengine/searchengine.cpp index 893b91ccb..fc5485275 100644 --- a/src/searchengine/searchengine.cpp +++ b/src/searchengine/searchengine.cpp @@ -114,7 +114,7 @@ void SearchEngine::fillCatCombobox() { comboCategory->clear(); comboCategory->addItem(full_cat_names["all"], QVariant("all")); QStringList supported_cat = supported_engines->supportedCategories(); - foreach(QString cat, supported_cat) { + foreach (QString cat, supported_cat) { qDebug("Supported category: %s", qPrintable(cat)); comboCategory->addItem(full_cat_names[cat], QVariant(cat)); } @@ -123,10 +123,10 @@ void SearchEngine::fillCatCombobox() { #ifdef Q_WS_WIN bool SearchEngine::addPythonPathToEnv() { QString python_path = Preferences::getPythonPath(); - if(!python_path.isEmpty()) { + if (!python_path.isEmpty()) { // Add it to PATH envvar QString path_envar = QString::fromLocal8Bit(qgetenv("PATH").constData()); - if(path_envar.isNull()) { + if (path_envar.isNull()) { path_envar = ""; } path_envar = python_path+";"+path_envar; @@ -162,7 +162,7 @@ void SearchEngine::pythonDownloadSuccess(QString url, QString file_path) { qDebug("Setup should be complete!"); // Reload search engine has_python = addPythonPathToEnv(); - if(has_python) { + if (has_python) { supported_engines->update(); // Launch the search again on_search_button_clicked(); @@ -189,7 +189,7 @@ SearchEngine::~SearchEngine(){ saveSearchHistory(); searchProcess->kill(); searchProcess->waitForFinished(); - foreach(QProcess *downloader, downloaders) { + foreach (QProcess *downloader, downloaders) { // Make sure we disconnect the SIGNAL/SLOT first // To avoid qreal free downloader->disconnect(); @@ -203,7 +203,7 @@ SearchEngine::~SearchEngine(){ delete searchTimeout; delete searchProcess; delete supported_engines; - if(searchCompleter) + if (searchCompleter) delete searchCompleter; } @@ -215,24 +215,24 @@ void SearchEngine::displayPatternContextMenu(QPoint) { QAction clearAct(IconProvider::instance()->getIcon("edit-clear"), tr("Clear field"), &myMenu); QAction clearHistoryAct(IconProvider::instance()->getIcon("edit-clear-history"), tr("Clear completion history"), &myMenu); bool hasCopyAct = false; - if(search_pattern->hasSelectedText()) { + if (search_pattern->hasSelectedText()) { myMenu.addAction(&cutAct); myMenu.addAction(©Act); hasCopyAct = true; } - if(qApp->clipboard()->mimeData()->hasText()) { + if (qApp->clipboard()->mimeData()->hasText()) { myMenu.addAction(&pasteAct); hasCopyAct = true; } - if(hasCopyAct) + if (hasCopyAct) myMenu.addSeparator(); myMenu.addAction(&clearHistoryAct); myMenu.addAction(&clearAct); QAction *act = myMenu.exec(QCursor::pos()); - if(act != 0) { - if(act == &clearHistoryAct) { + if (act != 0) { + if (act == &clearHistoryAct) { // Ask for confirmation - if(QMessageBox::question(this, tr("Confirmation"), tr("Are you sure you want to clear the history?"), QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { + if (QMessageBox::question(this, tr("Confirmation"), tr("Are you sure you want to clear the history?"), QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { // Clear history searchHistory.setStringList(QStringList()); } @@ -255,9 +255,9 @@ void SearchEngine::displayPatternContextMenu(QPoint) { void SearchEngine::tab_changed(int t) {//when we switch from a tab that is not empty to another that is empty the download button //doesn't have to be available - if(t>-1) + if (t>-1) {//-1 = no more tab - if(all_tab.at(tabWidget->currentIndex())->getCurrentSearchListModel()->rowCount()) { + if (all_tab.at(tabWidget->currentIndex())->getCurrentSearchListModel()->rowCount()) { download_button->setEnabled(true); goToDescBtn->setEnabled(true); } else { @@ -296,8 +296,8 @@ void SearchEngine::giveFocusToSearchInput() { // Function called when we click on search button void SearchEngine::on_search_button_clicked(){ #ifdef Q_WS_WIN - if(!has_python) { - if(QMessageBox::question(this, tr("Missing Python Interpreter"), + if (!has_python) { + if (QMessageBox::question(this, tr("Missing Python Interpreter"), tr("Python 2.x is required to use the search engine but it does not seem to be installed.\nDo you want to install it now?"), QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { // Download and Install Python @@ -306,17 +306,17 @@ void SearchEngine::on_search_button_clicked(){ return; } #endif - if(searchProcess->state() != QProcess::NotRunning){ + if (searchProcess->state() != QProcess::NotRunning){ #ifdef Q_WS_WIN searchProcess->kill(); #else searchProcess->terminate(); #endif search_stopped = true; - if(searchTimeout->isActive()) { + if (searchTimeout->isActive()) { searchTimeout->stop(); } - if(search_button->text() != tr("Search")) { + if (search_button->text() != tr("Search")) { search_button->setText(tr("Search")); return; } @@ -327,7 +327,7 @@ void SearchEngine::on_search_button_clicked(){ const QString pattern = search_pattern->text().trimmed(); // No search pattern entered - if(pattern.isEmpty()){ + if (pattern.isEmpty()){ QMessageBox::critical(0, tr("Empty search pattern"), tr("Please type a search pattern first")); return; } @@ -344,11 +344,11 @@ void SearchEngine::on_search_button_clicked(){ #endif // if the pattern is not in the pattern QStringList wordList = searchHistory.stringList(); - if(wordList.indexOf(pattern) == -1){ + if (wordList.indexOf(pattern) == -1){ //update the searchHistory list wordList.append(pattern); // verify the max size of the history - if(wordList.size() > SEARCHHISTORY_MAXSIZE) + if (wordList.size() > SEARCHHISTORY_MAXSIZE) wordList = wordList.mid(wordList.size()/2); searchHistory.setStringList(wordList); } @@ -373,7 +373,7 @@ void SearchEngine::on_search_button_clicked(){ } void SearchEngine::createCompleter() { - if(searchCompleter) + if (searchCompleter) delete searchCompleter; searchCompleter = new QCompleter(&searchHistory); searchCompleter->setCaseSensitivity(Qt::CaseInsensitive); @@ -381,14 +381,14 @@ void SearchEngine::createCompleter() { } void SearchEngine::propagateSectionResized(int index, int , int newsize) { - foreach(SearchTab * tab, all_tab) { + foreach (SearchTab * tab, all_tab) { tab->getCurrentTreeView()->setColumnWidth(index, newsize); } saveResultsColumnsWidth(); } void SearchEngine::saveResultsColumnsWidth() { - if(all_tab.size() > 0) { + if (all_tab.size() > 0) { QTreeView* treeview = all_tab.first()->getCurrentTreeView(); QIniSettings settings("qBittorrent", "qBittorrent"); QStringList width_list; @@ -396,14 +396,14 @@ void SearchEngine::saveResultsColumnsWidth() { short nbColumns = all_tab.first()->getCurrentSearchListModel()->columnCount(); QString line = settings.value("SearchResultsColsWidth", QString()).toString(); - if(!line.isEmpty()) { + if (!line.isEmpty()) { width_list = line.split(' '); } - for(short i=0; icolumnWidth(i)<1 && width_list.size() == nbColumns && width_list.at(i).toInt()>=1) { + for (short i=0; icolumnWidth(i)<1 && width_list.size() == nbColumns && width_list.at(i).toInt()>=1) { // load the former width new_width_list << width_list.at(i); - } else if(treeview->columnWidth(i)>=1) { + } else if (treeview->columnWidth(i)>=1) { // usual case, save the current width new_width_list << QString::number(treeview->columnWidth(i)); } else { @@ -417,11 +417,11 @@ void SearchEngine::saveResultsColumnsWidth() { } void SearchEngine::downloadTorrent(QString engine_url, QString torrent_url) { - if(torrent_url.startsWith("bc://bt/", Qt::CaseInsensitive)) { + if (torrent_url.startsWith("bc://bt/", Qt::CaseInsensitive)) { qDebug("Converting bc link to magnet link"); torrent_url = misc::bcLinkToMagnet(torrent_url); } - if(torrent_url.startsWith("magnet:")) { + if (torrent_url.startsWith("magnet:")) { QStringList urls; urls << torrent_url; mp_mainWindow->downloadFromURLList(urls); @@ -453,24 +453,24 @@ void SearchEngine::readSearchOutput(){ QByteArray output = searchProcess->readAllStandardOutput(); output.replace("\r", ""); QList lines_list = output.split('\n'); - if(!search_result_line_truncated.isEmpty()){ + if (!search_result_line_truncated.isEmpty()){ QByteArray end_of_line = lines_list.takeFirst(); lines_list.prepend(search_result_line_truncated+end_of_line); } search_result_line_truncated = lines_list.takeLast().trimmed(); - foreach(const QByteArray &line, lines_list){ + foreach (const QByteArray &line, lines_list){ appendSearchResult(QString::fromUtf8(line)); } - if(currentSearchTab) + if (currentSearchTab) currentSearchTab->getCurrentLabel()->setText(tr("Results")+QString::fromUtf8(" (")+QString::number(nb_search_results)+QString::fromUtf8("):")); } void SearchEngine::downloadFinished(int exitcode, QProcess::ExitStatus) { QProcess *downloadProcess = (QProcess*)sender(); - if(exitcode == 0) { + if (exitcode == 0) { QString line = QString::fromUtf8(downloadProcess->readAllStandardOutput()).trimmed(); QStringList parts = line.split(' '); - if(parts.size() == 2) { + if (parts.size() == 2) { QString path = parts[0]; QString url = parts[1]; QBtSession::instance()->processDownloadedFile(url, path); @@ -490,7 +490,7 @@ void SearchEngine::updateNova() { QFile package_file(search_dir.absoluteFilePath("__init__.py")); package_file.open(QIODevice::WriteOnly | QIODevice::Text); package_file.close(); - if(!search_dir.exists("engines")){ + if (!search_dir.exists("engines")){ search_dir.mkdir("engines"); } QFile package_file2(search_dir.absolutePath().replace("\\", "/")+"/engines/__init__.py"); @@ -498,8 +498,8 @@ void SearchEngine::updateNova() { package_file2.close(); // Copy search plugin files (if necessary) QString filePath = search_dir.absoluteFilePath("nova2.py"); - if(getPluginVersion(":/"+nova_folder+"/nova2.py") > getPluginVersion(filePath)) { - if(QFile::exists(filePath)) { + if (getPluginVersion(":/"+nova_folder+"/nova2.py") > getPluginVersion(filePath)) { + if (QFile::exists(filePath)) { QFile::remove(filePath); QFile::remove(filePath+"c"); } @@ -507,8 +507,8 @@ void SearchEngine::updateNova() { } filePath = search_dir.absoluteFilePath("nova2dl.py"); - if(getPluginVersion(":/"+nova_folder+"/nova2dl.py") > getPluginVersion(filePath)) { - if(QFile::exists(filePath)){ + if (getPluginVersion(":/"+nova_folder+"/nova2dl.py") > getPluginVersion(filePath)) { + if (QFile::exists(filePath)){ QFile::remove(filePath); QFile::remove(filePath+"c"); } @@ -516,8 +516,8 @@ void SearchEngine::updateNova() { } filePath = search_dir.absoluteFilePath("novaprinter.py"); - if(getPluginVersion(":/"+nova_folder+"/novaprinter.py") > getPluginVersion(filePath)) { - if(QFile::exists(filePath)){ + if (getPluginVersion(":/"+nova_folder+"/novaprinter.py") > getPluginVersion(filePath)) { + if (QFile::exists(filePath)){ QFile::remove(filePath); QFile::remove(filePath+"c"); } @@ -525,8 +525,8 @@ void SearchEngine::updateNova() { } filePath = search_dir.absoluteFilePath("helpers.py"); - if(getPluginVersion(":/"+nova_folder+"/helpers.py") > getPluginVersion(filePath)) { - if(QFile::exists(filePath)){ + if (getPluginVersion(":/"+nova_folder+"/helpers.py") > getPluginVersion(filePath)) { + if (QFile::exists(filePath)){ QFile::remove(filePath); QFile::remove(filePath+"c"); } @@ -534,7 +534,7 @@ void SearchEngine::updateNova() { } filePath = search_dir.absoluteFilePath("socks.py"); - if(QFile::exists(filePath)){ + if (QFile::exists(filePath)){ QFile::remove(filePath); QFile::remove(filePath+"c"); } @@ -542,7 +542,7 @@ void SearchEngine::updateNova() { if (nova_folder == "nova3") { filePath = search_dir.absoluteFilePath("sgmllib3.py"); - if(QFile::exists(filePath)){ + if (QFile::exists(filePath)){ QFile::remove(filePath); QFile::remove(filePath+"c"); } @@ -551,14 +551,14 @@ void SearchEngine::updateNova() { QDir destDir(QDir(misc::searchEngineLocation()).absoluteFilePath("engines")); QDir shipped_subDir(":/"+nova_folder+"/engines/"); QStringList files = shipped_subDir.entryList(); - foreach(const QString &file, files){ + foreach (const QString &file, files){ QString shipped_file = shipped_subDir.absoluteFilePath(file); // Copy python classes - if(file.endsWith(".py")) { + if (file.endsWith(".py")) { const QString dest_file = destDir.absoluteFilePath(file); - if(getPluginVersion(shipped_file) > getPluginVersion(dest_file) ) { + if (getPluginVersion(shipped_file) > getPluginVersion(dest_file) ) { qDebug("shipped %s is more recent then local plugin, updating...", qPrintable(file)); - if(QFile::exists(dest_file)) { + if (QFile::exists(dest_file)) { qDebug("Removing old %s", qPrintable(dest_file)); QFile::remove(dest_file); QFile::remove(dest_file+"c"); @@ -568,8 +568,8 @@ void SearchEngine::updateNova() { } } else { // Copy icons - if(file.endsWith(".png")) { - if(!QFile::exists(destDir.absoluteFilePath(file))) { + if (file.endsWith(".png")) { + if (!QFile::exists(destDir.absoluteFilePath(file))) { QFile::copy(shipped_file, destDir.absoluteFilePath(file)); } } @@ -581,32 +581,32 @@ void SearchEngine::updateNova() { // Search can be finished for 3 reasons : // Error | Stopped by user | Finished normally void SearchEngine::searchFinished(int exitcode,QProcess::ExitStatus){ - if(searchTimeout->isActive()) { + if (searchTimeout->isActive()) { searchTimeout->stop(); } QIniSettings settings("qBittorrent", "qBittorrent"); bool useNotificationBalloons = settings.value("Preferences/General/NotificationBaloons", true).toBool(); - if(useNotificationBalloons && mp_mainWindow->getCurrentTabWidget() != this) { + if (useNotificationBalloons && mp_mainWindow->getCurrentTabWidget() != this) { mp_mainWindow->showNotificationBaloon(tr("Search Engine"), tr("Search has finished")); } - if(exitcode){ + if (exitcode){ #ifdef Q_WS_WIN search_status->setText(tr("Search aborted")); #else search_status->setText(tr("An error occured during search...")); #endif }else{ - if(search_stopped){ + if (search_stopped){ search_status->setText(tr("Search aborted")); }else{ - if(no_search_results){ + if (no_search_results){ search_status->setText(tr("Search returned no results")); }else{ search_status->setText(tr("Search has finished")); } } } - if(currentSearchTab) + if (currentSearchTab) currentSearchTab->getCurrentLabel()->setText(tr("Results", "i.e: Search results")+QString::fromUtf8(" (")+QString::number(nb_search_results)+QString::fromUtf8("):")); search_button->setText("Search"); } @@ -615,11 +615,11 @@ void SearchEngine::searchFinished(int exitcode,QProcess::ExitStatus){ // Line is in the following form : // file url | file name | file size | nb seeds | nb leechers | Search engine url void SearchEngine::appendSearchResult(const QString &line){ - if(!currentSearchTab) { - if(searchProcess->state() != QProcess::NotRunning){ + if (!currentSearchTab) { + if (searchProcess->state() != QProcess::NotRunning){ searchProcess->terminate(); } - if(searchTimeout->isActive()) { + if (searchTimeout->isActive()) { searchTimeout->stop(); } search_stopped = true; @@ -627,7 +627,7 @@ void SearchEngine::appendSearchResult(const QString &line){ } const QStringList parts = line.split("|"); const int nb_fields = parts.size(); - if(nb_fields < NB_PLUGIN_COLUMNS-1){ //-1 because desc_link is optional + if (nb_fields < NB_PLUGIN_COLUMNS-1){ //-1 because desc_link is optional return; } Q_ASSERT(currentSearchTab); @@ -642,20 +642,20 @@ void SearchEngine::appendSearchResult(const QString &line){ cur_model->setData(cur_model->index(row, SIZE), parts.at(PL_SIZE).trimmed().toLongLong()); // Size bool ok = false; qlonglong nb_seeders = parts.at(PL_SEEDS).trimmed().toLongLong(&ok); - if(!ok || nb_seeders < 0) { + if (!ok || nb_seeders < 0) { cur_model->setData(cur_model->index(row, SEEDS), tr("Unknown")); // Seeders } else { cur_model->setData(cur_model->index(row, SEEDS), nb_seeders); // Seeders } qlonglong nb_leechers = parts.at(PL_LEECHS).trimmed().toLongLong(&ok); - if(!ok || nb_leechers < 0) { + if (!ok || nb_leechers < 0) { cur_model->setData(cur_model->index(row, LEECHS), tr("Unknown")); // Leechers } else { cur_model->setData(cur_model->index(row, LEECHS), nb_leechers); // Leechers } cur_model->setData(cur_model->index(row, ENGINE_URL), parts.at(PL_ENGINE_URL).trimmed()); // Engine URL // Description Link - if(nb_fields == NB_PLUGIN_COLUMNS) + if (nb_fields == NB_PLUGIN_COLUMNS) cur_model->setData(cur_model->index(row, DESC_LINK), parts.at(PL_DESC_LINK).trimmed()); no_search_results = false; @@ -667,19 +667,19 @@ void SearchEngine::appendSearchResult(const QString &line){ #if QT_VERSION >= 0x040500 void SearchEngine::closeTab(int index) { - if(index == tabWidget->indexOf(currentSearchTab)) { + if (index == tabWidget->indexOf(currentSearchTab)) { qDebug("Deleted current search Tab"); - if(searchProcess->state() != QProcess::NotRunning){ + if (searchProcess->state() != QProcess::NotRunning){ searchProcess->terminate(); } - if(searchTimeout->isActive()) { + if (searchTimeout->isActive()) { searchTimeout->stop(); } search_stopped = true; currentSearchTab = 0; } delete all_tab.takeAt(index); - if(!all_tab.size()) { + if (!all_tab.size()) { download_button->setEnabled(false); goToDescBtn->setEnabled(false); } @@ -687,22 +687,22 @@ void SearchEngine::closeTab(int index) { #else // Clear search results list void SearchEngine::closeTab_button_clicked(){ - if(all_tab.size()) { + if (all_tab.size()) { qDebug("currentTab rank: %d", tabWidget->currentIndex()); qDebug("currentSearchTab rank: %d", tabWidget->indexOf(currentSearchTab)); - if(tabWidget->currentIndex() == tabWidget->indexOf(currentSearchTab)) { + if (tabWidget->currentIndex() == tabWidget->indexOf(currentSearchTab)) { qDebug("Deleted current search Tab"); - if(searchProcess->state() != QProcess::NotRunning){ + if (searchProcess->state() != QProcess::NotRunning){ searchProcess->terminate(); } - if(searchTimeout->isActive()) { + if (searchTimeout->isActive()) { searchTimeout->stop(); } search_stopped = true; currentSearchTab = 0; } delete all_tab.takeAt(tabWidget->currentIndex()); - if(!all_tab.size()) { + if (!all_tab.size()) { closeTab_button->setEnabled(false); download_button->setEnabled(false); } @@ -714,8 +714,8 @@ void SearchEngine::closeTab_button_clicked(){ void SearchEngine::on_download_button_clicked(){ //QModelIndexList selectedIndexes = currentSearchTab->getCurrentTreeView()->selectionModel()->selectedIndexes(); QModelIndexList selectedIndexes = all_tab.at(tabWidget->currentIndex())->getCurrentTreeView()->selectionModel()->selectedIndexes(); - foreach(const QModelIndex &index, selectedIndexes){ - if(index.column() == NAME){ + foreach (const QModelIndex &index, selectedIndexes){ + if (index.column() == NAME){ // Get Item url QSortFilterProxyModel* model = all_tab.at(tabWidget->currentIndex())->getCurrentSearchListProxy(); QString torrent_url = model->data(model->index(index.row(), URL_COLUMN)).toString(); @@ -729,11 +729,11 @@ void SearchEngine::on_download_button_clicked(){ void SearchEngine::on_goToDescBtn_clicked() { QModelIndexList selectedIndexes = all_tab.at(tabWidget->currentIndex())->getCurrentTreeView()->selectionModel()->selectedIndexes(); - foreach(const QModelIndex &index, selectedIndexes){ - if(index.column() == NAME) { + foreach (const QModelIndex &index, selectedIndexes){ + if (index.column() == NAME) { QSortFilterProxyModel* model = all_tab.at(tabWidget->currentIndex())->getCurrentSearchListProxy(); const QString desc_url = model->data(model->index(index.row(), DESC_LINK)).toString(); - if(!desc_url.isEmpty()) + if (!desc_url.isEmpty()) QDesktopServices::openUrl(QUrl::fromEncoded(desc_url.toUtf8())); } } diff --git a/src/searchengine/searchengine.h b/src/searchengine/searchengine.h index 3b9629e6c..44f86e359 100644 --- a/src/searchengine/searchengine.h +++ b/src/searchengine/searchengine.h @@ -65,17 +65,17 @@ public: static qreal getPluginVersion(QString filePath) { QFile plugin(filePath); - if(!plugin.exists()){ + if (!plugin.exists()){ qDebug("%s plugin does not exist, returning 0.0", qPrintable(filePath)); return 0.0; } - if(!plugin.open(QIODevice::ReadOnly | QIODevice::Text)){ + if (!plugin.open(QIODevice::ReadOnly | QIODevice::Text)){ return 0.0; } qreal version = 0.0; while (!plugin.atEnd()){ QByteArray line = plugin.readLine(); - if(line.startsWith("#VERSION: ")){ + if (line.startsWith("#VERSION: ")){ line = line.split(' ').last().trimmed(); version = line.toFloat(); qDebug("plugin %s version: %.2f", qPrintable(filePath), version); diff --git a/src/searchengine/searchtab.cpp b/src/searchengine/searchtab.cpp index ad056eaf7..2f26780b4 100644 --- a/src/searchengine/searchtab.cpp +++ b/src/searchengine/searchtab.cpp @@ -77,7 +77,7 @@ SearchTab::SearchTab(SearchEngine *parent) : QWidget(), parent(parent) connect(resultsBrowser, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(downloadSelectedItem(const QModelIndex&))); // Load last columns width for search results list - if(!loadColWidthResultsList()){ + if (!loadColWidthResultsList()){ resultsBrowser->header()->resizeSection(0, 275); } @@ -108,13 +108,13 @@ QHeaderView* SearchTab::header() const { bool SearchTab::loadColWidthResultsList() { QIniSettings settings("qBittorrent", "qBittorrent"); QString line = settings.value("SearchResultsColsWidth", QString()).toString(); - if(line.isEmpty()) + if (line.isEmpty()) return false; QStringList width_list = line.split(' '); - if(width_list.size() < SearchListModel->columnCount()) + if (width_list.size() < SearchListModel->columnCount()) return false; unsigned int listSize = width_list.size(); - for(unsigned int i=0; iheader()->resizeSection(i, width_list.at(i).toInt()); } return true; @@ -143,7 +143,7 @@ QStandardItemModel* SearchTab::getCurrentSearchListModel() const // Set the color of a row in data model void SearchTab::setRowColor(int row, QString color){ proxyModel->setDynamicSortFilter(false); - for(int i=0; icolumnCount(); ++i){ + for (int i=0; icolumnCount(); ++i){ proxyModel->setData(proxyModel->index(row, i), QVariant(QColor(color)), Qt::ForegroundRole); } proxyModel->setDynamicSortFilter(true); diff --git a/src/searchengine/supportedengines.h b/src/searchengine/supportedengines.h index a01456290..78f5bf39d 100644 --- a/src/searchengine/supportedengines.h +++ b/src/searchengine/supportedengines.h @@ -89,7 +89,7 @@ public: // Save to Hard disk QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QStringList disabled_engines = settings.value(QString::fromUtf8("SearchEngines/disabledEngines"), QStringList()).toStringList(); - if(enabled) { + if (enabled) { disabled_engines.removeAll(name); } else { disabled_engines.append(name); @@ -106,7 +106,7 @@ signals: public: SupportedEngines(bool has_python = true) { - if(has_python) + if (has_python) update(); } @@ -116,8 +116,8 @@ public: QStringList enginesEnabled() const { QStringList engines; - foreach(const SupportedEngine *engine, values()) { - if(engine->isEnabled()) + foreach (const SupportedEngine *engine, values()) { + if (engine->isEnabled()) engines << engine->getName(); } return engines; @@ -125,12 +125,12 @@ public: QStringList supportedCategories() const { QStringList supported_cat; - foreach(const SupportedEngine *engine, values()) { - if(engine->isEnabled()) { + foreach (const SupportedEngine *engine, values()) { + if (engine->isEnabled()) { const QStringList &s = engine->getSupportedCategories(); - foreach(QString cat, s) { + foreach (QString cat, s) { cat = cat.trimmed(); - if(!cat.isEmpty() && !supported_cat.contains(cat)) + if (!cat.isEmpty() && !supported_cat.contains(cat)) supported_cat << cat; } } @@ -150,21 +150,21 @@ public slots: nova.waitForFinished(); QString capabilities = QString(nova.readAll()); QDomDocument xml_doc; - if(!xml_doc.setContent(capabilities)) { + if (!xml_doc.setContent(capabilities)) { std::cerr << "Could not parse Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data() << std::endl; std::cerr << "Error: " << nova.readAllStandardError().constData() << std::endl; return; } QDomElement root = xml_doc.documentElement(); - if(root.tagName() != "capabilities") { + if (root.tagName() != "capabilities") { std::cout << "Invalid XML file for Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data() << std::endl; return; } - for(QDomNode engine_node = root.firstChild(); !engine_node.isNull(); engine_node = engine_node.nextSibling()) { + for (QDomNode engine_node = root.firstChild(); !engine_node.isNull(); engine_node = engine_node.nextSibling()) { QDomElement engine_elem = engine_node.toElement(); - if(!engine_elem.isNull()) { + if (!engine_elem.isNull()) { SupportedEngine *s = new SupportedEngine(engine_elem); - if(this->contains(s->getName())) { + if (this->contains(s->getName())) { // Already in the list delete s; } else { diff --git a/src/smtp.cpp b/src/smtp.cpp index 616b87458..1b3bd8bca 100644 --- a/src/smtp.cpp +++ b/src/smtp.cpp @@ -122,14 +122,14 @@ void Smtp::sendMail(const QString &from, const QString &to, const QString &subje this->from = from; rcpt = to; // Authentication - if(pref.getMailNotificationSMTPAuth()) { + if (pref.getMailNotificationSMTPAuth()) { username = pref.getMailNotificationSMTPUsername(); password = pref.getMailNotificationSMTPPassword(); } // Connect to SMTP server #ifndef QT_NO_OPENSSL - if(pref.getMailNotificationSMTPSSL()) { + if (pref.getMailNotificationSMTPSSL()) { socket->connectToHostEncrypted(pref.getMailNotificationSMTP(), DEFAULT_PORT_SSL); use_ssl = true; } else { @@ -158,7 +158,7 @@ void Smtp::readyRead() switch(state) { case Init: { - if(code[0] == '2') { + if (code[0] == '2') { // Connection was successful ehlo(); } else { @@ -257,7 +257,7 @@ QByteArray Smtp::encode_mime_header(const QString& key, const QString& value, QT if (!prefix.isEmpty()) line += prefix; if (!value.contains("=?") && latin1->canEncode(value)) { bool firstWord = true; - foreach(const QByteArray& word, value.toAscii().split(' ')) { + foreach (const QByteArray& word, value.toAscii().split(' ')) { if (line.size() > 78) { rv = rv + line + "\r\n"; line.clear(); @@ -292,7 +292,7 @@ QByteArray Smtp::encode_mime_header(const QString& key, const QString& value, QT void Smtp::ehlo() { QByteArray address = "127.0.0.1"; - foreach(const QHostAddress& addr, QNetworkInterface::allAddresses()) + foreach (const QHostAddress& addr, QNetworkInterface::allAddresses()) { if (addr == QHostAddress::LocalHost || addr == QHostAddress::LocalHostIPv6) continue; @@ -309,7 +309,7 @@ void Smtp::parseEhloResponse(const QByteArray& code, bool continued, const QStri { if (code != "250") { // Error - if(state == EhloSent) { + if (state == EhloSent) { // try to send HELO instead of EHLO qDebug() << "EHLO failed, trying HELO instead..."; socket->write("helo\r\n"); diff --git a/src/speedlimitdlg.h b/src/speedlimitdlg.h index ae06906fc..31cf58570 100644 --- a/src/speedlimitdlg.h +++ b/src/speedlimitdlg.h @@ -60,10 +60,10 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg { dlg.setWindowTitle(title); dlg.setMaxValue(max_value/1024.); dlg.setDefaultValue(default_value/1024.); - if(dlg.exec() == QDialog::Accepted) { + if (dlg.exec() == QDialog::Accepted) { *ok = true; int val = dlg.getSpeedLimit(); - if(val <= 0) + if (val <= 0) return -1; return val*1024; } else { @@ -75,7 +75,7 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg { protected slots: void updateSpinValue(int val) const { qDebug("Called updateSpinValue with %d", val); - if(val <= 0){ + if (val <= 0){ spinBandwidth->setValue(0); spinBandwidth->setSpecialValueText(QString::fromUtf8("∞")); spinBandwidth->setSuffix(QString::fromUtf8("")); @@ -86,7 +86,7 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg { } void updateSliderValue(int val) const { - if(val <= 0) { + if (val <= 0) { spinBandwidth->setValue(0); spinBandwidth->setSpecialValueText(QString::fromUtf8("∞")); spinBandwidth->setSuffix(QString::fromUtf8("")); @@ -96,21 +96,21 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg { long getSpeedLimit() const { long val = bandwidthSlider->value(); - if(val > 0) + if (val > 0) return val; return -1; } void setMaxValue(long val) const { - if(val > 0) { + if (val > 0) { bandwidthSlider->setMaximum(val); spinBandwidth->setMaximum(val); } } void setDefaultValue(long val) const { - if(val < 0) val = 0; - if(val > bandwidthSlider->maximum()) val = bandwidthSlider->maximum(); + if (val < 0) val = 0; + if (val > bandwidthSlider->maximum()) val = bandwidthSlider->maximum(); bandwidthSlider->setValue(val); updateSpinValue(val); } diff --git a/src/statusbar.h b/src/statusbar.h index 183110f0e..6d45156b6 100644 --- a/src/statusbar.h +++ b/src/statusbar.h @@ -167,11 +167,11 @@ public slots: void refreshStatusBar() { // Update connection status const libtorrent::session_status sessionStatus = QBtSession::instance()->getSessionStatus(); - if(!QBtSession::instance()->getSession()->is_listening()) { + if (!QBtSession::instance()->getSession()->is_listening()) { connecStatusLblIcon->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/disconnected.png"))); connecStatusLblIcon->setToolTip(QString::fromUtf8("")+tr("Connection Status:")+QString::fromUtf8("
")+tr("Offline. This usually means that qBittorrent failed to listen on the selected port for incoming connections.")); } else { - if(sessionStatus.has_incoming_connections) { + if (sessionStatus.has_incoming_connections) { // Connection OK connecStatusLblIcon->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/connected.png"))); connecStatusLblIcon->setToolTip(QString::fromUtf8("")+tr("Connection Status:")+QString::fromUtf8("
")+tr("Online")); @@ -181,7 +181,7 @@ public slots: } } // Update Number of DHT nodes - if(QBtSession::instance()->isDHTEnabled()) { + if (QBtSession::instance()->isDHTEnabled()) { DHTLbl->setVisible(true); //statusSep1->setVisible(true); DHTLbl->setText(tr("DHT: %1 nodes").arg(QString::number(sessionStatus.dht_nodes))); @@ -195,7 +195,7 @@ public slots: } void updateAltSpeedsBtn(bool alternative) { - if(alternative) { + if (alternative) { altSpeedsBtn->setIcon(QIcon(":/Icons/slow.png")); altSpeedsBtn->setToolTip(tr("Click to switch to regular speed limits")); altSpeedsBtn->setDown(true); @@ -218,18 +218,18 @@ public slots: int cur_limit = QBtSession::instance()->getSession()->download_rate_limit(); #endif long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), cur_limit); - if(ok) { + if (ok) { Preferences pref; bool alt = pref.isAltBandwidthEnabled(); - if(new_limit <= 0) { + if (new_limit <= 0) { qDebug("Setting global download rate limit to Unlimited"); QBtSession::instance()->setDownloadRateLimit(-1); - if(!alt) + if (!alt) pref.setGlobalDownloadLimit(-1); } else { qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.); QBtSession::instance()->setDownloadRateLimit(new_limit); - if(!alt) + if (!alt) pref.setGlobalDownloadLimit(new_limit/1024.); } } @@ -243,18 +243,18 @@ public slots: int cur_limit = QBtSession::instance()->getSession()->upload_rate_limit(); #endif long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), cur_limit); - if(ok) { + if (ok) { Preferences pref; bool alt = pref.isAltBandwidthEnabled(); - if(new_limit <= 0) { + if (new_limit <= 0) { qDebug("Setting global upload rate limit to Unlimited"); QBtSession::instance()->setUploadRateLimit(-1); - if(!alt) + if (!alt) Preferences().setGlobalUploadLimit(-1); } else { qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.); QBtSession::instance()->setUploadRateLimit(new_limit); - if(!alt) + if (!alt) Preferences().setGlobalUploadLimit(new_limit/1024.); } } diff --git a/src/torrentadditiondlg.cpp b/src/torrentadditiondlg.cpp index c0927f9e8..c215e29af 100644 --- a/src/torrentadditiondlg.cpp +++ b/src/torrentadditiondlg.cpp @@ -91,7 +91,7 @@ torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) : appendLabelToSavePath = pref.appendTorrentLabel(); QString display_path = defaultSavePath.replace("\\", "/"); - if(!display_path.endsWith("/")) + if (!display_path.endsWith("/")) display_path += "/"; path_history << display_path; #if defined(Q_WS_WIN) || defined(Q_OS_OS2) @@ -99,7 +99,7 @@ torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) : #endif savePathTxt->addItem(display_path); - if(pref.addTorrentsInPause()) { + if (pref.addTorrentsInPause()) { addInPause->setChecked(true); //addInPause->setEnabled(false); } @@ -108,7 +108,7 @@ torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) : settings.beginGroup(QString::fromUtf8("TransferListFilters")); const QStringList customLabels = settings.value("customLabels", QStringList()).toStringList(); comboLabel->addItem(""); - foreach(const QString& label, customLabels) { + foreach (const QString& label, customLabels) { comboLabel->addItem(label); } @@ -142,7 +142,7 @@ void torrentAdditionDialog::readSettings() { } } if (m_showContentList) { - if(!torrentContentList->header()->restoreState(settings.value("TorrentAdditionDlg/ContentHeaderState").toByteArray())) { + if (!torrentContentList->header()->restoreState(settings.value("TorrentAdditionDlg/ContentHeaderState").toByteArray())) { qDebug() << Q_FUNC_INFO << "First executation, resize first section to 400px..."; torrentContentList->header()->resizeSection(0, 400); // Default } @@ -162,16 +162,16 @@ void torrentAdditionDialog::limitDialogWidth() { int scrn = 0; const QWidget *w = this->window(); - if(w) + if (w) scrn = QApplication::desktop()->screenNumber(w); - else if(QApplication::desktop()->isVirtualDesktop()) + else if (QApplication::desktop()->isVirtualDesktop()) scrn = QApplication::desktop()->screenNumber(QCursor::pos()); else scrn = QApplication::desktop()->screenNumber(this); QRect desk(QApplication::desktop()->availableGeometry(scrn)); int max_width = desk.width(); - if(max_width > 0) + if (max_width > 0) setMaximumWidth(max_width); } @@ -179,12 +179,12 @@ void torrentAdditionDialog::hideTorrentContent() { // Disable useless widgets torrentContentList->setVisible(false); //torrentContentLbl->setVisible(false); - for(int i=0; icount(); ++i) { - if(selectionBtnsLayout->itemAt(i)->widget()) + for (int i=0; icount(); ++i) { + if (selectionBtnsLayout->itemAt(i)->widget()) selectionBtnsLayout->itemAt(i)->widget()->setVisible(false); } - for(int i=0; icount(); ++i) { - if(contentFilterLayout->itemAt(i)->widget()) + for (int i=0; icount(); ++i) { + if (contentFilterLayout->itemAt(i)->widget()) contentFilterLayout->itemAt(i)->widget()->setVisible(false); } contentFilterLayout->update(); @@ -204,13 +204,13 @@ void torrentAdditionDialog::showLoadMagnetURI(QString magnet_uri) { // Get torrent hash hash = misc::magnetUriToHash(magnet_uri); - if(hash.isEmpty()) { + if (hash.isEmpty()) { QBtSession::instance()->addConsoleMessage(tr("Unable to decode magnet link:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red")); return; } // Set torrent name fileName = misc::magnetUriToName(magnet_uri); - if(fileName.isEmpty()) { + if (fileName.isEmpty()) { fileName = tr("Magnet Link"); } fileNameLbl->setText(QString::fromUtf8("
")+fileName+QString::fromUtf8("
")); @@ -234,10 +234,10 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) { is_magnet = false; // This is an URL to a local file, switch to local path - if(filePath.startsWith("file:", Qt::CaseInsensitive)) + if (filePath.startsWith("file:", Qt::CaseInsensitive)) filePath = QUrl::fromEncoded(filePath.toLocal8Bit()).toLocalFile(); - if(!QFile::exists(filePath)) { + if (!QFile::exists(filePath)) { close(); return; } @@ -249,11 +249,11 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) { // Getting torrent file informations try { t = new torrent_info(filePath.toUtf8().data()); - if(!t->is_valid()) + if (!t->is_valid()) throw std::exception(); } catch(std::exception&) { qDebug("Caught error loading torrent"); - if(!from_url.isNull()){ + if (!from_url.isNull()){ QBtSession::instance()->addConsoleMessage(tr("Unable to decode torrent file:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red")); QFile::remove(filePath); }else{ @@ -263,7 +263,7 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) { return; } nbFiles = t->num_files(); - if(nbFiles == 0) { + if (nbFiles == 0) { // Empty torrent file!? close(); return; @@ -278,18 +278,18 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) { hash = misc::toQString(t->info_hash()); // Use left() to remove .old extension QString newFileName; - if(fileName.endsWith(QString::fromUtf8(".old"))){ + if (fileName.endsWith(QString::fromUtf8(".old"))){ newFileName = fileName.left(fileName.size()-4); }else{ newFileName = fileName; } fileNameLbl->setText(QString::fromUtf8("
")+newFileName+QString::fromUtf8("
")); - if(t->num_files() > 1) { + if (t->num_files() > 1) { // List files in torrent PropListModel->model()->setupModelData(*t); connect(PropDelegate, SIGNAL(filteredFilesChanged()), this, SLOT(updateDiskSpaceLabels())); // Loads files path in the torrent - for(uint i=0; i= 16 files_path << misc::toQStringU(fs.file_path(t->file_at(i))); #else @@ -310,13 +310,13 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) { #if defined(Q_WS_WIN) || defined(Q_OS_OS2) save_path.replace("/", "\\"); #endif - if(!save_path.endsWith(QDir::separator())) + if (!save_path.endsWith(QDir::separator())) save_path += QDir::separator(); // If the torrent has a root folder, append it to the save path - if(!root_folder.isEmpty()) { + if (!root_folder.isEmpty()) { save_path += root_folder; } - if(nbFiles == 1) { + if (nbFiles == 1) { // single file torrent #if LIBTORRENT_VERSION_MINOR >= 16 QString single_file_relpath = misc::toQStringU(fs.file_path(t->file_at(0))); @@ -334,7 +334,7 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) { updateDiskSpaceLabels(); // Hide useless widgets - if(t->num_files() <= 1) + if (t->num_files() <= 1) hideTorrentContent(); // Remember dialog geometry @@ -352,7 +352,7 @@ void torrentAdditionDialog::displayContentListMenu(const QPoint&) { QMenu myFilesLlistMenu; const QModelIndexList selectedRows = torrentContentList->selectionModel()->selectedRows(0); QAction *actRename = 0; - if(selectedRows.size() == 1 && t->num_files() > 1) { + if (selectedRows.size() == 1 && t->num_files() > 1) { actRename = myFilesLlistMenu.addAction(IconProvider::instance()->getIcon("edit-rename"), tr("Rename...")); myFilesLlistMenu.addSeparator(); } @@ -365,24 +365,24 @@ void torrentAdditionDialog::displayContentListMenu(const QPoint&) { myFilesLlistMenu.addMenu(&subMenu); // Call menu QAction *act = myFilesLlistMenu.exec(QCursor::pos()); - if(act) { - if(act == actRename) { + if (act) { + if (act == actRename) { renameSelectedFile(); } else { int prio = 1; - if(act == actionHigh) { + if (act == actionHigh) { prio = prio::HIGH; } else { - if(act == actionMaximum) { + if (act == actionMaximum) { prio = prio::MAXIMUM; } else { - if(act == actionNot_downloaded) { + if (act == actionNot_downloaded) { prio = prio::IGNORED; } } } qDebug("Setting files priority"); - foreach(const QModelIndex &index, selectedRows) { + foreach (const QModelIndex &index, selectedRows) { qDebug("Setting priority(%d) for file at row %d", prio, index.row()); PropListModel->setData(PropListModel->index(index.row(), PRIORITY, index.parent()), prio); } @@ -401,13 +401,13 @@ void torrentAdditionDialog::renameSelectedFile() { tr("New name:"), QLineEdit::Normal, index.data().toString(), &ok); if (ok && !new_name_last.isEmpty()) { - if(!misc::isValidFileSystemName(new_name_last)) { + if (!misc::isValidFileSystemName(new_name_last)) { QMessageBox::warning(this, tr("The file could not be renamed"), tr("This file name contains forbidden characters, please choose a different one."), QMessageBox::Ok); return; } - if(PropListModel->getType(index) == TorrentFileItem::TFILE) { + if (PropListModel->getType(index) == TorrentFileItem::TFILE) { // File renaming const uint file_index = PropListModel->getFileIndex(index); QString old_name = files_path.at(file_index); @@ -417,19 +417,19 @@ void torrentAdditionDialog::renameSelectedFile() { path_items.removeLast(); path_items << new_name_last; QString new_name = path_items.join("/"); - if(old_name == new_name) { + if (old_name == new_name) { qDebug("Name did not change"); return; } new_name = QDir::cleanPath(new_name); qDebug("New name: %s", qPrintable(new_name)); // Check if that name is already used - for(uint i=0; icurrentText())); lbl_disk_space->setText(misc::friendlyUnit(available)); - if(!is_magnet) { + if (!is_magnet) { // Determine torrent size qulonglong torrent_size = 0; - if(t->num_files() > 1) { + if (t->num_files() > 1) { const unsigned int nbFiles = t->num_files(); const std::vector priorities = PropListModel->model()->getFilesPriorities(nbFiles); - for(unsigned int i=0; i 0) + for (unsigned int i=0; i 0) torrent_size += t->file_at(i).size; } } else { @@ -511,8 +511,8 @@ void torrentAdditionDialog::updateDiskSpaceLabels() { lbl_torrent_size->setText(misc::friendlyUnit(torrent_size)); // Check if free space is sufficient - if(available > 0) { - if((unsigned long long)available > torrent_size) { + if (available > 0) { + if ((unsigned long long)available > torrent_size) { // Space is sufficient label_space_msg->setText(tr("(%1 left after torrent download)", "e.g. (100MiB left after torrent download)").arg(misc::friendlyUnit(available-torrent_size))); } else { @@ -531,13 +531,13 @@ void torrentAdditionDialog::on_browseButton_clicked(){ QString new_path; QString root_folder; const QString label_name = comboLabel->currentText(); - if(t->num_files() == 1) { + if (t->num_files() == 1) { new_path = QFileDialog::getSaveFileName(this, tr("Choose save path"), savePathTxt->currentText(), QString(), 0, QFileDialog::DontConfirmOverwrite); - if(!new_path.isEmpty()) { + if (!new_path.isEmpty()) { QStringList path_parts = new_path.replace("\\", "/").split("/"); const QString filename = path_parts.takeLast(); // Append label - if(QDir(path_parts.join(QDir::separator())) == QDir(defaultSavePath) && !label_name.isEmpty()) + if (QDir(path_parts.join(QDir::separator())) == QDir(defaultSavePath) && !label_name.isEmpty()) path_parts << label_name; // Append file name path_parts << filename; @@ -546,26 +546,26 @@ void torrentAdditionDialog::on_browseButton_clicked(){ } } else { QString truncated_path = getCurrentTruncatedSavePath(&root_folder); - if(!truncated_path.isEmpty() && QDir(truncated_path).exists()){ + if (!truncated_path.isEmpty() && QDir(truncated_path).exists()){ new_path = QFileDialog::getExistingDirectory(this, tr("Choose save path"), truncated_path); }else{ new_path = QFileDialog::getExistingDirectory(this, tr("Choose save path"), QDir::homePath()); } - if(!new_path.isEmpty()) { + if (!new_path.isEmpty()) { QStringList path_parts = new_path.replace("\\", "/").split("/"); - if(path_parts.last().isEmpty()) + if (path_parts.last().isEmpty()) path_parts.removeLast(); // Append label - if(QDir(new_path) == QDir(defaultSavePath) && !label_name.isEmpty()) + if (QDir(new_path) == QDir(defaultSavePath) && !label_name.isEmpty()) path_parts << label_name; // Append root folder - if(!root_folder.isEmpty()) + if (!root_folder.isEmpty()) path_parts << root_folder; // Construct new_path new_path = path_parts.join(QDir::separator()); } } - if(!new_path.isEmpty()) { + if (!new_path.isEmpty()) { // Check if this new path already exists in the list QString new_truncated_path = getTruncatedSavePath(new_path); #if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) @@ -573,7 +573,7 @@ void torrentAdditionDialog::on_browseButton_clicked(){ #else const int cur_index = path_history.indexOf(QRegExp(new_truncated_path, Qt::CaseSensitive)); #endif - if(cur_index >= 0) { + if (cur_index >= 0) { savePathTxt->setCurrentIndex(cur_index); } #if defined(Q_WS_WIN) || defined(Q_OS_OS2) @@ -602,7 +602,7 @@ void torrentAdditionDialog::savePiecesPriorities(){ void torrentAdditionDialog::on_OkButton_clicked(){ Preferences pref; qDebug() << "void torrentAdditionDialog::on_OkButton_clicked() - ENTER"; - if(savePathTxt->currentText().trimmed().isEmpty()){ + if (savePathTxt->currentText().trimmed().isEmpty()){ QMessageBox::critical(0, tr("Empty save path"), tr("Please enter a save path")); return; } @@ -612,7 +612,7 @@ void torrentAdditionDialog::on_OkButton_clicked(){ #endif save_path = misc::expandPath(save_path); qDebug("Save path is %s", qPrintable(save_path)); - if(!is_magnet && t->num_files() == 1) { + if (!is_magnet && t->num_files() == 1) { // Remove file name QStringList parts = save_path.split("/"); const QString single_file_name = parts.takeLast(); @@ -631,15 +631,15 @@ void torrentAdditionDialog::on_OkButton_clicked(){ qDebug("Saving save path to temp data: %s", qPrintable(savePath.absolutePath())); TorrentTempData::setSavePath(hash, savePath.absolutePath()); qDebug("Torrent label is: %s", qPrintable(comboLabel->currentText().trimmed())); - if(!current_label.isEmpty()) + if (!current_label.isEmpty()) TorrentTempData::setLabel(hash, current_label); // Is download sequential? TorrentTempData::setSequential(hash, checkIncrementalDL->isChecked()); // Save files path // Loads files path in the torrent - if(!is_magnet) { + if (!is_magnet) { bool path_changed = false; - for(uint i=0; i= 16 file_storage fs = t->files(); QString old_path = misc::toQStringU(fs.file_path(t->file_at(i))); @@ -647,23 +647,23 @@ void torrentAdditionDialog::on_OkButton_clicked(){ QString old_path = misc::toQStringU(t->file_at(i).path.string()); #endif #if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) - if(files_path.at(i).compare(old_path, Qt::CaseSensitive) != 0) { + if (files_path.at(i).compare(old_path, Qt::CaseSensitive) != 0) { #else - if(files_path.at(i).compare(old_path, Qt::CaseInsensitive) != 0) { + if (files_path.at(i).compare(old_path, Qt::CaseInsensitive) != 0) { #endif path_changed = true; break; } } - if(path_changed) { + if (path_changed) { qDebug("Changing files paths"); TorrentTempData::setFilesPath(hash, files_path); } } // Skip file checking and directly start seeding - if(addInSeed->isChecked()) { + if (addInSeed->isChecked()) { // Check if local file(s) actually exist - if(is_magnet || QFile::exists(savePathTxt->currentText())) { + if (is_magnet || QFile::exists(savePathTxt->currentText())) { TorrentTempData::setSeedingMode(hash, true); } else { QMessageBox::warning(0, tr("Seeding mode error"), tr("You chose to skip file checking. However, local files do not seem to exist in the current destionation folder. Please disable this feature or update the save path.")); @@ -671,7 +671,7 @@ void torrentAdditionDialog::on_OkButton_clicked(){ } } // Check if there is at least one selected file - if(!is_magnet && t->num_files() > 1 && allFiltered()){ + if (!is_magnet && t->num_files() > 1 && allFiltered()){ QMessageBox::warning(0, tr("Invalid file selection"), tr("You must select at least one file in the torrent")); return; } @@ -683,23 +683,23 @@ void torrentAdditionDialog::on_OkButton_clicked(){ pref.setSavePath(getCurrentTruncatedSavePath()); // Check if savePath exists - if(!savePath.exists()){ - if(!savePath.mkpath(savePath.path())){ + if (!savePath.exists()){ + if (!savePath.mkpath(savePath.path())){ QMessageBox::critical(0, tr("Save path creation error"), tr("Could not create the save path")); return; } } // save filtered files - if(!is_magnet && t->num_files() > 1) + if (!is_magnet && t->num_files() > 1) savePiecesPriorities(); // Add to download list QTorrentHandle h; - if(is_magnet) + if (is_magnet) h = QBtSession::instance()->addMagnetUri(from_url, false); else h = QBtSession::instance()->addTorrent(filePath, false, from_url); - if(addInPause->isChecked() && h.is_valid()) { + if (addInPause->isChecked() && h.is_valid()) { h.pause(); } // Close the dialog @@ -710,14 +710,14 @@ void torrentAdditionDialog::on_OkButton_clicked(){ void torrentAdditionDialog::resetComboLabelIndex(QString text) { // Select first index - if(text != comboLabel->itemText(comboLabel->currentIndex())) { + if (text != comboLabel->itemText(comboLabel->currentIndex())) { comboLabel->setItemText(0, text); comboLabel->setCurrentIndex(0); } } void torrentAdditionDialog::updateLabelInSavePath(QString label) { - if(appendLabelToSavePath) { + if (appendLabelToSavePath) { // Update Label in combobox savePathTxt->setItemText(0, misc::updateLabelInSavePath(defaultSavePath, savePathTxt->itemText(0), old_label, label)); // update edit text @@ -735,15 +735,15 @@ void torrentAdditionDialog::updateSavePathCurrentText() { QString root_folder_or_file_name = ""; getCurrentTruncatedSavePath(&root_folder_or_file_name); // Update other combo items - for(int i=0; icount(); ++i) { - if(i == savePathTxt->currentIndex()) continue; + for (int i=0; icount(); ++i) { + if (i == savePathTxt->currentIndex()) continue; QString item_path = path_history.at(i); - if(item_path.isEmpty()) continue; + if (item_path.isEmpty()) continue; // Append label - if(i == 0 && appendLabelToSavePath && QDir(item_path) == QDir(defaultSavePath) && !comboLabel->currentText().isEmpty()) + if (i == 0 && appendLabelToSavePath && QDir(item_path) == QDir(defaultSavePath) && !comboLabel->currentText().isEmpty()) item_path += comboLabel->currentText() + "/"; // Append root_folder or filename - if(!root_folder_or_file_name.isEmpty()) + if (!root_folder_or_file_name.isEmpty()) item_path += root_folder_or_file_name; #if defined(Q_WS_WIN) || defined(Q_OS_OS2) item_path.replace("/", "\\"); @@ -763,17 +763,17 @@ QString torrentAdditionDialog::getTruncatedSavePath(QString save_path, QString* save_path = misc::expandPath(save_path); QStringList parts = save_path.replace("\\", "/").split("/"); // Remove torrent root folder - if(!QDir(save_path).exists() || (!is_magnet && t->num_files() == 1)) { + if (!QDir(save_path).exists() || (!is_magnet && t->num_files() == 1)) { QString tmp = parts.takeLast(); - if(root_folder_or_file_name) + if (root_folder_or_file_name) *root_folder_or_file_name = tmp; } // Remove label - if(appendLabelToSavePath && savePathTxt->currentIndex() == 0 && parts.last() == comboLabel->currentText()) { + if (appendLabelToSavePath && savePathTxt->currentIndex() == 0 && parts.last() == comboLabel->currentText()) { parts.removeLast(); } QString truncated_path = parts.join("/"); - if(!truncated_path.endsWith("/")) + if (!truncated_path.endsWith("/")) truncated_path += "/"; qDebug("Truncated save path: %s", qPrintable(truncated_path)); return truncated_path; @@ -785,14 +785,14 @@ void torrentAdditionDialog::saveTruncatedPathHistory() { // Get current history QStringList history = settings.value("TorrentAdditionDlg/save_path_history").toStringList(); #if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) - if(!history.contains(current_save_path, Qt::CaseSensitive)) { + if (!history.contains(current_save_path, Qt::CaseSensitive)) { #else - if(!history.contains(current_save_path, Qt::CaseInsensitive)) { + if (!history.contains(current_save_path, Qt::CaseInsensitive)) { #endif // Add save path to history history << current_save_path; // Limit list size - if(history.size() > 8) + if (history.size() > 8) history.removeFirst(); // Save history settings.setValue("TorrentAdditionDlg/save_path_history", history); @@ -803,8 +803,8 @@ void torrentAdditionDialog::loadSavePathHistory() { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); // Load save path history QStringList raw_path_history = settings.value("TorrentAdditionDlg/save_path_history").toStringList(); - foreach(const QString &sp, raw_path_history) { - if(QDir(sp) != QDir(defaultSavePath)) { + foreach (const QString &sp, raw_path_history) { + if (QDir(sp) != QDir(defaultSavePath)) { QString dsp = sp; #if defined(Q_WS_WIN) || defined(Q_OS_OS2) dsp.replace("/", "\\"); diff --git a/src/torrentcreator/torrentcreatordlg.cpp b/src/torrentcreator/torrentcreatordlg.cpp index af0bffee6..8d0bf7960 100644 --- a/src/torrentcreator/torrentcreatordlg.cpp +++ b/src/torrentcreator/torrentcreatordlg.cpp @@ -63,7 +63,7 @@ TorrentCreatorDlg::TorrentCreatorDlg(QWidget *parent): QDialog(parent), creatorT } TorrentCreatorDlg::~TorrentCreatorDlg() { - if(creatorThread) + if (creatorThread) delete creatorThread; } @@ -71,14 +71,14 @@ void TorrentCreatorDlg::on_addFolder_button_clicked(){ QIniSettings settings("qBittorrent", "qBittorrent"); QString last_path = settings.value("CreateTorrent/last_add_path", QDir::homePath()).toString(); QString dir = QFileDialog::getExistingDirectory(this, tr("Select a folder to add to the torrent"), last_path, QFileDialog::ShowDirsOnly); - if(!dir.isEmpty()) { + if (!dir.isEmpty()) { settings.setValue("CreateTorrent/last_add_path", dir); #if defined(Q_WS_WIN) || defined(Q_OS_OS2) dir.replace("/", "\\"); #endif textInputPath->setText(dir); // Update piece size - if(checkAutoPieceSize->isChecked()) + if (checkAutoPieceSize->isChecked()) updateOptimalPieceSize(); } } @@ -87,14 +87,14 @@ void TorrentCreatorDlg::on_addFile_button_clicked(){ QIniSettings settings("qBittorrent", "qBittorrent"); QString last_path = settings.value("CreateTorrent/last_add_path", QDir::homePath()).toString(); QString file = QFileDialog::getOpenFileName(this, tr("Select a file to add to the torrent"), last_path); - if(!file.isEmpty()) { + if (!file.isEmpty()) { settings.setValue("CreateTorrent/last_add_path", misc::branchPath(file)); #if defined(Q_WS_WIN) || defined(Q_OS_OS2) file.replace("/", "\\"); #endif textInputPath->setText(file); // Update piece size - if(checkAutoPieceSize->isChecked()) + if (checkAutoPieceSize->isChecked()) updateOptimalPieceSize(); } } @@ -108,21 +108,21 @@ void TorrentCreatorDlg::on_createButton_clicked(){ QString input = textInputPath->text().trimmed(); if (input.endsWith(QDir::separator())) input.chop(1); - if(input.isEmpty()){ + if (input.isEmpty()){ QMessageBox::critical(0, tr("No input path set"), tr("Please type an input path first")); return; } QStringList trackers = trackers_list->toPlainText().split("\n"); - if(!trackers_list->toPlainText().trimmed().isEmpty()) + if (!trackers_list->toPlainText().trimmed().isEmpty()) saveTrackerList(); QIniSettings settings("qBittorrent", "qBittorrent"); QString last_path = settings.value("CreateTorrent/last_save_path", QDir::homePath()).toString(); QString destination = QFileDialog::getSaveFileName(this, tr("Select destination torrent file"), last_path, tr("Torrent Files")+QString::fromUtf8(" (*.torrent)")); - if(!destination.isEmpty()) { + if (!destination.isEmpty()) { settings.setValue("CreateTorrent/last_save_path", misc::branchPath(destination)); - if(!destination.toUpper().endsWith(".TORRENT")) + if (!destination.toUpper().endsWith(".TORRENT")) destination += QString::fromUtf8(".torrent"); } else { return; @@ -154,7 +154,7 @@ void TorrentCreatorDlg::handleCreationFailure(QString msg) { void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path) { // Remove busy cursor setCursor(QCursor(Qt::ArrowCursor)); - if(checkStartSeeding->isChecked()) { + if (checkStartSeeding->isChecked()) { QString root_folder; // Create save path temp data boost::intrusive_ptr t; @@ -167,7 +167,7 @@ void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path) } QString hash = misc::toQString(t->info_hash()); QString save_path = branch_path; - if(!root_folder.isEmpty()) { + if (!root_folder.isEmpty()) { save_path = QDir(save_path).absoluteFilePath(root_folder); } TorrentTempData::setSavePath(hash, save_path); @@ -181,7 +181,7 @@ void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path) void TorrentCreatorDlg::on_cancelButton_clicked() { // End torrent creation thread - if(creatorThread && creatorThread->isRunning()) { + if (creatorThread && creatorThread->isRunning()) { creatorThread->abortCreation(); creatorThread->terminate(); // Wait for termination @@ -219,7 +219,7 @@ void TorrentCreatorDlg::showProgressBar(bool show) void TorrentCreatorDlg::on_checkAutoPieceSize_clicked(bool checked) { comboPieceSize->setEnabled(!checked); - if(checked) { + if (checked) { updateOptimalPieceSize(); } } @@ -228,18 +228,18 @@ void TorrentCreatorDlg::updateOptimalPieceSize() { quint64 torrent_size = misc::computePathSize(textInputPath->text()); qDebug("Torrent size is %lld", torrent_size); - if(torrent_size == 0) return; + if (torrent_size == 0) return; int i = 0; qulonglong nb_pieces = 0; do { nb_pieces = (double)torrent_size/(m_piece_sizes.at(i)*1024.); qDebug("nb_pieces=%lld with piece_size=%s", nb_pieces, qPrintable(comboPieceSize->itemText(i))); - if(nb_pieces <= NB_PIECES_MIN) { - if(i > 1) + if (nb_pieces <= NB_PIECES_MIN) { + if (i > 1) --i; break; } - if(nb_pieces < NB_PIECES_MAX) { + if (nb_pieces < NB_PIECES_MAX) { qDebug("Good, nb_pieces=%lld < %d", nb_pieces, NB_PIECES_MAX); break; } diff --git a/src/torrentcreator/torrentcreatorthread.cpp b/src/torrentcreator/torrentcreatorthread.cpp index ff00746d7..2d2a5c966 100644 --- a/src/torrentcreator/torrentcreatorthread.cpp +++ b/src/torrentcreator/torrentcreatorthread.cpp @@ -75,7 +75,7 @@ void TorrentCreatorThread::create(QString _input_path, QString _save_path, QStri { input_path = _input_path; save_path = _save_path; - if(QFile(save_path).exists()) + if (QFile(save_path).exists()) QFile::remove(save_path); trackers = _trackers; url_seeds = _url_seeds; @@ -104,17 +104,17 @@ void TorrentCreatorThread::run() { file_storage fs; // Adding files to the torrent libtorrent::add_files(fs, input_path.toUtf8().constData(), file_filter); - if(abort) return; + if (abort) return; create_torrent t(fs, piece_size); // Add url seeds - foreach(const QString &seed, url_seeds){ + foreach (const QString &seed, url_seeds){ t.add_url_seed(seed.trimmed().toStdString()); } - foreach(const QString &tracker, trackers) { + foreach (const QString &tracker, trackers) { t.add_tracker(tracker.trimmed().toStdString()); } - if(abort) return; + if (abort) return; // calculate the hash for all pieces const QString parent_path = misc::branchPath(input_path); set_piece_hashes(t, parent_path.toUtf8().constData(), boost::bind(&sendProgressUpdateSignal, _1, t.num_pieces(), this)); @@ -124,13 +124,13 @@ void TorrentCreatorThread::run() { t.set_comment(comment.toUtf8().constData()); // Is private ? t.set_priv(is_private); - if(abort) return; + if (abort) return; // create the torrent and print it to out qDebug("Saving to %s", qPrintable(save_path)); std::vector torrent; bencode(back_inserter(torrent), t.generate()); QFile outfile(save_path); - if(!torrent.empty() && outfile.open(QIODevice::WriteOnly)) { + if (!torrent.empty() && outfile.open(QIODevice::WriteOnly)) { outfile.write(&torrent[0], torrent.size()); outfile.close(); emit updateProgress(100); diff --git a/src/torrentfilesmodel.h b/src/torrentfilesmodel.h index 75e4cd355..bd889cd07 100644 --- a/src/torrentfilesmodel.h +++ b/src/torrentfilesmodel.h @@ -75,7 +75,7 @@ public: QString name = misc::toQStringU(f.path.filename()); #endif // Do not display incomplete extensions - if(name.endsWith(".!qB")) + if (name.endsWith(".!qB")) name.chop(4); itemData << name; //qDebug("Created a TreeItem file with name %s", qPrintable(getName())); @@ -84,7 +84,7 @@ public: total_done = 0; itemData << 0.; // Progress; itemData << prio::NORMAL; // Priority - if(parent) { + if (parent) { parent->appendChild(this); parent->updateSize(); } @@ -95,14 +95,14 @@ public: parentItem = parent; m_type = FOLDER; // Do not display incomplete extensions - if(name.endsWith(".!qB")) + if (name.endsWith(".!qB")) name.chop(4); itemData << name; itemData << 0.; // Size itemData << 0.; // Progress; total_done = 0; itemData << prio::NORMAL; // Priority - if(parent) { + if (parent) { parent->appendChild(this); } } @@ -155,36 +155,36 @@ public: } void setSize(qulonglong size) { - if(getSize() == size) return; + if (getSize() == size) return; itemData.replace(COL_SIZE, (qulonglong)size); - if(parentItem) + if (parentItem) parentItem->updateSize(); } void updateSize() { - if(m_type == ROOT) return; + if (m_type == ROOT) return; Q_ASSERT(m_type == FOLDER); qulonglong size = 0; - foreach(TorrentFileItem* child, childItems) { - if(child->getPriority() != prio::IGNORED) + foreach (TorrentFileItem* child, childItems) { + if (child->getPriority() != prio::IGNORED) size += child->getSize(); } setSize(size); } void setProgress(qulonglong done) { - if(getPriority() == 0) return; + if (getPriority() == 0) return; total_done = done; qulonglong size = getSize(); Q_ASSERT(total_done <= size); qreal progress; - if(size > 0) + if (size > 0) progress = total_done/(float)size; else progress = 1.; Q_ASSERT(progress >= 0. && progress <= 1.); itemData.replace(COL_PROGRESS, progress); - if(parentItem) + if (parentItem) parentItem->updateProgress(); } @@ -193,20 +193,20 @@ public: } qreal getProgress() const { - if(getPriority() == 0) + if (getPriority() == 0) return -1; qulonglong size = getSize(); - if(size > 0) + if (size > 0) return total_done/(float)getSize(); return 1.; } void updateProgress() { - if(m_type == ROOT) return; + if (m_type == ROOT) return; Q_ASSERT(m_type == FOLDER); total_done = 0; - foreach(TorrentFileItem* child, childItems) { - if(child->getPriority() > 0) + foreach (TorrentFileItem* child, childItems) { + if (child->getPriority() > 0) total_done += child->getTotalDone(); } //qDebug("Folder: total_done: %llu/%llu", total_done, getSize()); @@ -221,17 +221,17 @@ public: void setPriority(int new_prio, bool update_parent=true) { Q_ASSERT(new_prio != prio::PARTIAL || m_type == FOLDER); // PARTIAL only applies to folders const int old_prio = getPriority(); - if(old_prio == new_prio) return; + if (old_prio == new_prio) return; qDebug("setPriority(%s, %d)", qPrintable(getName()), new_prio); // Reset progress if priority is 0 - if(new_prio == 0) { + if (new_prio == 0) { setProgress(0); } itemData.replace(COL_PRIO, new_prio); // Update parent - if(update_parent && parentItem) { + if (update_parent && parentItem) { qDebug("Updating parent item"); parentItem->updateSize(); parentItem->updateProgress(); @@ -239,15 +239,15 @@ public: } // Update children - if(new_prio != prio::PARTIAL && !childItems.empty()) { + if (new_prio != prio::PARTIAL && !childItems.empty()) { qDebug("Updating children items"); - foreach(TorrentFileItem* child, childItems) { + foreach (TorrentFileItem* child, childItems) { // Do not update the parent since // the parent is causing the update child->setPriority(new_prio, false); } } - if(m_type == FOLDER) { + if (m_type == FOLDER) { updateSize(); updateProgress(); } @@ -255,28 +255,28 @@ public: // Only non-root folders use this function void updatePriority() { - if(m_type == ROOT) return; + if (m_type == ROOT) return; Q_ASSERT(m_type == FOLDER); - if(childItems.isEmpty()) return; + if (childItems.isEmpty()) return; // If all children have the same priority // then the folder should have the same // priority const int prio = childItems.first()->getPriority(); - for(int i=1; igetPriority() != prio) { + for (int i=1; igetPriority() != prio) { setPriority(prio::PARTIAL); return; } } // All child items have the same priorrity // Update mine if necessary - if(prio != getPriority()) + if (prio != getPriority()) setPriority(prio); } TorrentFileItem* childWithName(QString name) const { - foreach(TorrentFileItem *child, childItems) { - if(child->getName() == name) return child; + foreach (TorrentFileItem *child, childItems) { + if (child->getName() == name) return child; } return 0; } @@ -290,9 +290,9 @@ public: //Q_ASSERT(!childWithName(item->getName())); Q_ASSERT(m_type != TFILE); int i=0; - for(i=0; igetName(); - if(QString::localeAwareCompare(newchild_name, childItems.at(i)->getName()) < 0) break; + if (QString::localeAwareCompare(newchild_name, childItems.at(i)->getName()) < 0) break; } childItems.insert(i, item); //childItems.append(item); @@ -313,7 +313,7 @@ public: } QVariant data(int column) const { - if(column == COL_PROGRESS) + if (column == COL_PROGRESS) return getProgress(); return itemData.value(column); } @@ -355,7 +355,7 @@ public: void updateFilesProgress(std::vector fp) { emit layoutAboutToBeChanged(); - for(unsigned int i=0; i= 0); files_index[i]->setProgress(fp[i]); } @@ -364,7 +364,7 @@ public: void updateFilesPriorities(const std::vector &fprio) { emit layoutAboutToBeChanged(); - for(unsigned int i=0; isetPriority(fprio[i]); } @@ -373,7 +373,7 @@ public: std::vector getFilesPriorities(unsigned int nbFiles) const { std::vector prio; - for(unsigned int i=0; igetPriority()); prio.push_back(files_index[i]->getPriority()); } @@ -381,8 +381,8 @@ public: } bool allFiltered() const { - for(int i=0; ichildCount(); ++i) { - if(rootItem->child(i)->getPriority() != prio::IGNORED) + for (int i=0; ichildCount(); ++i) { + if (rootItem->child(i)->getPriority() != prio::IGNORED) return false; } return true; @@ -396,12 +396,12 @@ public: } bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) { - if(!index.isValid()) return false; + if (!index.isValid()) return false; if (index.column() == 0 && role == Qt::CheckStateRole) { TorrentFileItem *item = static_cast(index.internalPointer()); qDebug("setData(%s, %d", qPrintable(item->getName()), value.toInt()); - if(item->getPriority() != value.toInt()) { - if(value.toInt() == Qt::PartiallyChecked) + if (item->getPriority() != value.toInt()) { + if (value.toInt() == Qt::PartiallyChecked) item->setPriority(prio::PARTIAL); else if (value.toInt() == Qt::Unchecked) item->setPriority(prio::IGNORED); @@ -450,16 +450,16 @@ public: if (!index.isValid()) return QVariant(); TorrentFileItem *item = static_cast(index.internalPointer()); - if(index.column() == 0 && role == Qt::DecorationRole) { - if(item->isFolder()) + if (index.column() == 0 && role == Qt::DecorationRole) { + if (item->isFolder()) return IconProvider::instance()->getIcon("inode-directory"); else return IconProvider::instance()->getIcon("text-plain"); } - if(index.column() == 0 && role == Qt::CheckStateRole) { - if(item->data(TorrentFileItem::COL_PRIO).toInt() == prio::IGNORED) + if (index.column() == 0 && role == Qt::CheckStateRole) { + if (item->data(TorrentFileItem::COL_PRIO).toInt() == prio::IGNORED) return Qt::Unchecked; - if(item->data(TorrentFileItem::COL_PRIO).toInt() == prio::PARTIAL) + if (item->data(TorrentFileItem::COL_PRIO).toInt() == prio::PARTIAL) return Qt::PartiallyChecked; return Qt::Checked; } @@ -472,7 +472,7 @@ public: Qt::ItemFlags flags(const QModelIndex &index) const { if (!index.isValid()) return 0; - if(getType(index) == TorrentFileItem::FOLDER) + if (getType(index) == TorrentFileItem::FOLDER) return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsTristate; return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable; } @@ -487,7 +487,7 @@ public: QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const { if (parent.isValid() && parent.column() != 0) return QModelIndex(); - if(column >= TorrentFileItem::NB_COL) + if (column >= TorrentFileItem::NB_COL) return QModelIndex(); TorrentFileItem *parentItem; @@ -497,7 +497,7 @@ public: else parentItem = static_cast(parent.internalPointer()); Q_ASSERT(parentItem); - if(row >= parentItem->childCount()) + if (row >= parentItem->childCount()) return QModelIndex(); TorrentFileItem *childItem = parentItem->child(row); @@ -513,7 +513,7 @@ public: return QModelIndex(); TorrentFileItem *childItem = static_cast(index.internalPointer()); - if(!childItem) return QModelIndex(); + if (!childItem) return QModelIndex(); TorrentFileItem *parentItem = childItem->parent(); if (parentItem == rootItem) @@ -539,7 +539,7 @@ public: void clear() { qDebug("clear called"); beginResetModel(); - if(files_index) { + if (files_index) { delete [] files_index; files_index = 0; } @@ -549,7 +549,7 @@ public: void setupModelData(const libtorrent::torrent_info &t) { qDebug("setup model data called"); - if(t.num_files() == 0) return; + if (t.num_files() == 0) return; emit layoutAboutToBeChanged(); // Initialize files_index array qDebug("Torrent contains %d files", t.num_files()); @@ -560,7 +560,7 @@ public: TorrentFileItem *current_parent; // Iterate over files - for(int i=0; i= 16 @@ -572,9 +572,9 @@ public: QStringList pathFolders = path.split("/"); pathFolders.removeAll(".unwanted"); pathFolders.takeLast(); - foreach(const QString &pathPart, pathFolders) { + foreach (const QString &pathPart, pathFolders) { TorrentFileItem *new_parent = current_parent->childWithName(pathPart); - if(!new_parent) { + if (!new_parent) { new_parent = new TorrentFileItem(pathPart, current_parent); } current_parent = new_parent; @@ -588,16 +588,16 @@ public: public slots: void selectAll() { - for(int i=0; ichildCount(); ++i) { + for (int i=0; ichildCount(); ++i) { TorrentFileItem *child = rootItem->child(i); - if(child->getPriority() == prio::IGNORED) + if (child->getPriority() == prio::IGNORED) child->setPriority(prio::NORMAL); } emit dataChanged(index(0,0), index(rowCount(), columnCount())); } void selectNone() { - for(int i=0; ichildCount(); ++i) { + for (int i=0; ichildCount(); ++i) { rootItem->child(i)->setPriority(prio::IGNORED); } emit dataChanged(index(0,0), index(rowCount(), columnCount())); @@ -642,9 +642,9 @@ public: } QModelIndex parent(const QModelIndex & child) const { - if(!child.isValid()) return QModelIndex(); + if (!child.isValid()) return QModelIndex(); QModelIndex sourceParent = m_model->parent(mapToSource(child)); - if(!sourceParent.isValid()) return QModelIndex(); + if (!sourceParent.isValid()) return QModelIndex(); return mapFromSource(sourceParent); } @@ -662,14 +662,14 @@ protected: public slots: void selectAll() { - for(int i=0; ilineTorrent->clear(); @@ -76,7 +76,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked() { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); const QString default_dir = settings.value(QString::fromUtf8("TorrentImport/LastContentDir"), QDir::homePath()).toString(); - if(t->num_files() == 1) { + if (t->num_files() == 1) { // Single file torrent #if LIBTORRENT_VERSION_MINOR > 15 const QString file_name = misc::fileName(misc::toQStringU(t->file_at(0).path)); @@ -87,12 +87,12 @@ void TorrentImportDlg::on_browseContentBtn_clicked() QString extension = misc::file_extension(file_name); qDebug("File extension is : %s", qPrintable(extension)); QString filter; - if(!extension.isEmpty()) { + if (!extension.isEmpty()) { extension = extension.toUpper(); filter = tr("%1 Files", "%1 is a file extension (e.g. PDF)").arg(extension)+" (*."+extension+")"; } m_contentPath = QFileDialog::getOpenFileName(this, tr("Please provide the location of %1", "%1 is a file name").arg(file_name), default_dir, filter); - if(m_contentPath.isEmpty() || !QFile(m_contentPath).exists()) { + if (m_contentPath.isEmpty() || !QFile(m_contentPath).exists()) { m_contentPath = QString::null; ui->importBtn->setEnabled(false); ui->checkSkipCheck->setEnabled(false); @@ -106,7 +106,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked() #endif // Check file size const qint64 file_size = QFile(m_contentPath).size(); - if(t->file_at(0).size == file_size) { + if (t->file_at(0).size == file_size) { qDebug("The file size matches, allowing fast seeding..."); ui->checkSkipCheck->setEnabled(true); } else { @@ -117,7 +117,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked() // Handle file renaming QStringList parts = m_contentPath.replace("\\", "/").split("/"); QString new_file_name = parts.takeLast(); - if(new_file_name != file_name) { + if (new_file_name != file_name) { qDebug("The file has been renamed"); QStringList new_parts = m_filesPath.first().split("/"); new_parts.replace(new_parts.count()-1, new_file_name); @@ -128,7 +128,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked() // multiple files torrent m_contentPath = QFileDialog::getExistingDirectory(this, tr("Please point to the location of the torrent: %1").arg(misc::toQStringU(t->name())), default_dir); - if(m_contentPath.isEmpty() || !QDir(m_contentPath).exists()) { + if (m_contentPath.isEmpty() || !QDir(m_contentPath).exists()) { m_contentPath = QString::null; ui->importBtn->setEnabled(false); ui->checkSkipCheck->setEnabled(false); @@ -143,13 +143,13 @@ void TorrentImportDlg::on_browseContentBtn_clicked() bool size_mismatch = false; QDir content_dir(m_contentPath); // Check file sizes - for(int i=0; inum_files(); ++i) { + for (int i=0; inum_files(); ++i) { #if LIBTORRENT_VERSION_MINOR > 15 const QString rel_path = misc::toQStringU(t->file_at(i).path); #else const QString rel_path = misc::toQStringU(t->file_at(i).path.string()); #endif - if(QFile(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))).size() != t->file_at(i).size) { + if (QFile(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))).size() != t->file_at(i).size) { qDebug("%s is %lld", qPrintable(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))), (long long int) QFile(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))).size()); qDebug("%s is %lld", @@ -158,7 +158,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked() break; } } - if(size_mismatch) { + if (size_mismatch) { qDebug("The file size does not match, forbidding fast seeding..."); ui->checkSkipCheck->setChecked(false); ui->checkSkipCheck->setEnabled(false); @@ -193,14 +193,14 @@ void TorrentImportDlg::importTorrent() { qDebug() << Q_FUNC_INFO << "ENTER"; TorrentImportDlg dlg; - if(dlg.exec()) { + if (dlg.exec()) { qDebug() << "Loading the torrent file..."; boost::intrusive_ptr t = dlg.torrent(); - if(!t->is_valid()) + if (!t->is_valid()) return; QString torrent_path = dlg.getTorrentPath(); QString content_path = dlg.getContentPath(); - if(torrent_path.isEmpty() || content_path.isEmpty() || !QFile(torrent_path).exists()) { + if (torrent_path.isEmpty() || content_path.isEmpty() || !QFile(torrent_path).exists()) { qWarning() << "Incorrect input, aborting." << torrent_path << content_path; return; } @@ -225,7 +225,7 @@ void TorrentImportDlg::loadTorrent(const QString &torrent_path) // Load the torrent file try { t = new torrent_info(torrent_path.toUtf8().constData()); - if(!t->is_valid() || t->num_files() == 0) + if (!t->is_valid() || t->num_files() == 0) throw std::exception(); } catch(std::exception&) { ui->browseContentBtn->setEnabled(false); @@ -251,7 +251,7 @@ void TorrentImportDlg::initializeFilesPath() { m_filesPath.clear(); // Loads files path in the torrent - for(int i=0; inum_files(); ++i) { + for (int i=0; inum_files(); ++i) { #if LIBTORRENT_VERSION_MINOR > 15 m_filesPath << misc::toQStringU(t->file_at(i).path).replace("\\", "/"); #else diff --git a/src/torrentpersistentdata.h b/src/torrentpersistentdata.h index fcb2edd68..6ab919d80 100644 --- a/src/torrentpersistentdata.h +++ b/src/torrentpersistentdata.h @@ -53,7 +53,7 @@ public: static void deleteTempData(QString hash) { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume")); QHash all_data = settings.value("torrents-tmp").toHash(); - if(all_data.contains(hash)) { + if (all_data.contains(hash)) { all_data.remove(hash); settings.setValue("torrents-tmp", all_data); } @@ -161,7 +161,7 @@ public: const QHash all_data = settings.value("torrents-tmp").toHash(); const QHash data = all_data.value(hash).toHash(); const QList list_var = misc::intListfromStringList(data.value("files_priority").toStringList()); - foreach(const int &var, list_var) { + foreach (const int &var, list_var) { fp.push_back(var); } } @@ -207,8 +207,8 @@ public: QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume")); const QHash all_data = settings.value("torrents").toHash(); QHash::ConstIterator it; - for(it = all_data.constBegin(); it != all_data.constEnd(); it++) { - if(it.value().toHash().value("max_ratio", USE_GLOBAL_RATIO).toReal() >= 0) { + for (it = all_data.constBegin(); it != all_data.constEnd(); it++) { + if (it.value().toHash().value("max_ratio", USE_GLOBAL_RATIO).toReal() >= 0) { return true; } } @@ -219,7 +219,7 @@ public: QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume")); QHash all_data = settings.value("torrents").toHash(); QHash data = all_data.value(hash).toHash(); - if(!data.contains("add_date")) { + if (!data.contains("add_date")) { data["add_date"] = QDateTime::currentDateTime(); all_data[hash] = data; settings.setValue("torrents", all_data); @@ -231,7 +231,7 @@ public: const QHash all_data = settings.value("torrents").toHash(); const QHash data = all_data.value(hash).toHash(); QDateTime dt = data.value("add_date").toDateTime(); - if(!dt.isValid()) { + if (!dt.isValid()) { setAddedDate(hash); dt = QDateTime::currentDateTime(); } @@ -290,7 +290,7 @@ public: QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume")); QHash all_data = settings.value("torrents").toHash(); QHash data = all_data[h.hash()].toHash(); - if(h.is_seed()) + if (h.is_seed()) data["seed_date"] = QDateTime::currentDateTime(); else data.remove("seed_date"); @@ -308,7 +308,7 @@ public: static void deletePersistentData(QString hash) { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume")); QHash all_data = settings.value("torrents").toHash(); - if(all_data.contains(hash)) { + if (all_data.contains(hash)) { all_data.remove(hash); settings.setValue("torrents", all_data); } @@ -322,12 +322,12 @@ public: QHash all_data = settings.value("torrents").toHash(); QHash data = all_data.value(h.hash()).toHash(); data["is_magnet"] = is_magnet; - if(is_magnet) { + if (is_magnet) { data["magnet_uri"] = misc::toQString(make_magnet_uri(h)); } data["seed"] = h.is_seed(); data["priority"] = h.queue_position(); - if(save_path.isEmpty()) { + if (save_path.isEmpty()) { qDebug("TorrentPersistantData: save path is %s", qPrintable(h.save_path())); data["save_path"] = h.save_path(); } else { @@ -394,11 +394,11 @@ public: QHash all_data = settings.value("torrents").toHash(); QHash data = all_data[h.hash()].toHash(); bool was_seed = data.value("seed", false).toBool(); - if(was_seed != h.is_seed()) { + if (was_seed != h.is_seed()) { data["seed"] = !was_seed; all_data[h.hash()] = data; settings.setValue("torrents", all_data); - if(!was_seed) { + if (!was_seed) { // Save completion date saveSeedDate(h); } diff --git a/src/tracker/qpeer.h b/src/tracker/qpeer.h index 2f4ddbac7..05073ee0f 100644 --- a/src/tracker/qpeer.h +++ b/src/tracker/qpeer.h @@ -20,7 +20,7 @@ struct QPeer { libtorrent::entry toEntry(bool no_peer_id) const { libtorrent::entry::dictionary_type peer_map; - if(!no_peer_id) + if (!no_peer_id) peer_map["id"] = libtorrent::entry(peer_id.toStdString()); peer_map["ip"] = libtorrent::entry(ip.toStdString()); peer_map["port"] = libtorrent::entry(port); diff --git a/src/tracker/qtracker.cpp b/src/tracker/qtracker.cpp index 9de1abf8f..d7dd88a12 100644 --- a/src/tracker/qtracker.cpp +++ b/src/tracker/qtracker.cpp @@ -48,7 +48,7 @@ QTracker::QTracker(QObject *parent) : } QTracker::~QTracker() { - if(isListening()) { + if (isListening()) { qDebug("Shutting down the embedded tracker..."); close(); } @@ -69,8 +69,8 @@ bool QTracker::start() { const int listen_port = Preferences().getTrackerPort(); // - if(isListening()) { - if(serverPort() == listen_port) { + if (isListening()) { + if (serverPort() == listen_port) { // Already listening on the right port, just return return true; } @@ -88,19 +88,19 @@ void QTracker::readRequest() QByteArray input = socket->readAll(); //qDebug("QTracker: Raw request:\n%s", input.data()); QHttpRequestHeader http_request(input); - if(!http_request.isValid()) { + if (!http_request.isValid()) { qDebug("QTracker: Invalid HTTP Request:\n %s", qPrintable(http_request.toString())); respondInvalidRequest(socket, 100, "Invalid request type"); return; } //qDebug("QTracker received the following request:\n%s", qPrintable(parser.toString())); // Request is correct, is it a GET request? - if(http_request.method() != "GET") { + if (http_request.method() != "GET") { qDebug("QTracker: Unsupported HTTP request: %s", qPrintable(http_request.method())); respondInvalidRequest(socket, 100, "Invalid request type"); return; } - if(!http_request.path().startsWith("/announce", Qt::CaseInsensitive)) { + if (!http_request.path().startsWith("/announce", Qt::CaseInsensitive)) { qDebug("QTracker: Unrecognized path: %s", qPrintable(http_request.path())); respondInvalidRequest(socket, 100, "Invalid request type"); return; @@ -134,82 +134,82 @@ void QTracker::respondToAnnounceRequest(QTcpSocket *socket, // IP annonce_req.peer.ip = socket->peerAddress().toString(); // 1. Get info_hash - if(!get_parameters.contains("info_hash")) { + if (!get_parameters.contains("info_hash")) { qDebug("QTracker: Missing info_hash"); respondInvalidRequest(socket, 101, "Missing info_hash"); return; } annonce_req.info_hash = get_parameters.value("info_hash"); // info_hash cannot be longer than 20 bytes - /*if(annonce_req.info_hash.toAscii().length() > 20) { + /*if (annonce_req.info_hash.toAscii().length() > 20) { qDebug("QTracker: Info_hash is not 20 byte long: %s (%d)", qPrintable(annonce_req.info_hash), annonce_req.info_hash.toAscii().length()); respondInvalidRequest(socket, 150, "Invalid infohash"); return; }*/ // 2. Get peer ID - if(!get_parameters.contains("peer_id")) { + if (!get_parameters.contains("peer_id")) { qDebug("QTracker: Missing peer_id"); respondInvalidRequest(socket, 102, "Missing peer_id"); return; } annonce_req.peer.peer_id = get_parameters.value("peer_id"); // peer_id cannot be longer than 20 bytes - /*if(annonce_req.peer.peer_id.length() > 20) { + /*if (annonce_req.peer.peer_id.length() > 20) { qDebug("QTracker: peer_id is not 20 byte long: %s", qPrintable(annonce_req.peer.peer_id)); respondInvalidRequest(socket, 151, "Invalid peerid"); return; }*/ // 3. Get port - if(!get_parameters.contains("port")) { + if (!get_parameters.contains("port")) { qDebug("QTracker: Missing port"); respondInvalidRequest(socket, 103, "Missing port"); return; } bool ok = false; annonce_req.peer.port = get_parameters.value("port").toInt(&ok); - if(!ok || annonce_req.peer.port < 1 || annonce_req.peer.port > 65535) { + if (!ok || annonce_req.peer.port < 1 || annonce_req.peer.port > 65535) { qDebug("QTracker: Invalid port number (%d)", annonce_req.peer.port); respondInvalidRequest(socket, 103, "Missing port"); return; } // 4. Get event annonce_req.event = ""; - if(get_parameters.contains("event")) { + if (get_parameters.contains("event")) { annonce_req.event = get_parameters.value("event"); qDebug("QTracker: event is %s", qPrintable(annonce_req.event)); } // 5. Get numwant annonce_req.numwant = 50; - if(get_parameters.contains("numwant")) { + if (get_parameters.contains("numwant")) { int tmp = get_parameters.value("numwant").toInt(); - if(tmp > 0) { + if (tmp > 0) { qDebug("QTracker: numwant=%d", tmp); annonce_req.numwant = tmp; } } // 6. no_peer_id (extension) annonce_req.no_peer_id = false; - if(get_parameters.contains("no_peer_id")) { + if (get_parameters.contains("no_peer_id")) { annonce_req.no_peer_id = true; } // 7. TODO: support "compact" extension // Done parsing, now let's reply - if(m_torrents.contains(annonce_req.info_hash)) { - if(annonce_req.event == "stopped") { + if (m_torrents.contains(annonce_req.info_hash)) { + if (annonce_req.event == "stopped") { qDebug("QTracker: Peer stopped downloading, deleting it from the list"); m_torrents[annonce_req.info_hash].remove(annonce_req.peer.qhash()); return; } } else { // Unknown torrent - if(m_torrents.size() == MAX_TORRENTS) { + if (m_torrents.size() == MAX_TORRENTS) { // Reached max size, remove a random torrent m_torrents.erase(m_torrents.begin()); } } // Register the user PeerList peers = m_torrents.value(annonce_req.info_hash); - if(peers.size() == MAX_PEERS_PER_TORRENT) { + if (peers.size() == MAX_PEERS_PER_TORRENT) { // Too many peers, remove a random one peers.erase(peers.begin()); } @@ -226,8 +226,8 @@ void QTracker::ReplyWithPeerList(QTcpSocket *socket, const TrackerAnnounceReques reply_dict["interval"] = entry(ANNOUNCE_INTERVAL); QList peers = m_torrents.value(annonce_req.info_hash).values(); entry::list_type peer_list; - foreach(const QPeer & p, peers) { - //if(p != annonce_req.peer) + foreach (const QPeer & p, peers) { + //if (p != annonce_req.peer) peer_list.push_back(p.toEntry(annonce_req.no_peer_id)); } reply_dict["peers"] = entry(peer_list); diff --git a/src/transferlistdelegate.h b/src/transferlistdelegate.h index 2b9e1fe8d..c2a8d2eb9 100644 --- a/src/transferlistdelegate.h +++ b/src/transferlistdelegate.h @@ -77,7 +77,7 @@ public: case TorrentModelItem::TR_SEEDS: case TorrentModelItem::TR_PEERS: { QString display = QString::number(index.data().toLongLong()); - if(index.data(Qt::UserRole).toLongLong() > 0) { + if (index.data(Qt::UserRole).toLongLong() > 0) { // Scrape was successful, we have total values display += " ("+QString::number(index.data(Qt::UserRole).toLongLong())+")"; } @@ -132,7 +132,7 @@ public: QItemDelegate::drawBackground(painter, opt, index); const qlonglong limit = index.data().toLongLong(); opt.displayAlignment = Qt::AlignRight; - if(limit > 0) + if (limit > 0) QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::number(limit/1024., 'f', 1) + " " + tr("KiB/s", "KiB/second (.i.e per second)")); else QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8("∞")); @@ -142,7 +142,7 @@ public: QItemDelegate::drawBackground(painter, opt, index); QString txt = misc::userFriendlyDuration(index.data().toLongLong()); qlonglong seeding_time = index.data(Qt::UserRole).toLongLong(); - if(seeding_time > 0) + if (seeding_time > 0) txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(misc::userFriendlyDuration(seeding_time))+")"; QItemDelegate::drawDisplay(painter, opt, opt.rect, txt); break; @@ -156,7 +156,7 @@ public: QItemDelegate::drawBackground(painter, opt, index); opt.displayAlignment = Qt::AlignRight; const qreal ratio = index.data().toDouble(); - if(ratio > QBtSession::MAX_RATIO) + if (ratio > QBtSession::MAX_RATIO) QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8("∞")); else QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::number(ratio, 'f', 2)); @@ -164,7 +164,7 @@ public: } case TorrentModelItem::TR_PRIORITY: { const int priority = index.data().toInt(); - if(priority >= 0) { + if (priority >= 0) { opt.displayAlignment = Qt::AlignRight; QItemDelegate::paint(painter, opt, index); } else { @@ -179,7 +179,7 @@ public: qreal progress = index.data().toDouble()*100.; // We don't want to display 100% unless // the torrent is really complete - if(progress > 99.94 && progress < 100.) + if (progress > 99.94 && progress < 100.) progress = 99.9; newopt.rect = opt.rect; newopt.text = QString::number(progress, 'f', 1)+"%"; diff --git a/src/transferlistfilterswidget.h b/src/transferlistfilterswidget.h index 262dca064..79e542959 100644 --- a/src/transferlistfilterswidget.h +++ b/src/transferlistfilterswidget.h @@ -67,8 +67,8 @@ public: // Redefine addItem() to make sure the list stays sorted void addItem(QListWidgetItem *it) { Q_ASSERT(count() >= 2); - for(int i=2; itext().localeAwareCompare(it->text()) >= 0) { + for (int i=2; itext().localeAwareCompare(it->text()) >= 0) { insertItem(i, it); return; } @@ -87,8 +87,8 @@ public: int rowFromLabel(QString label) const { Q_ASSERT(!label.isEmpty()); - for(int i=2; ipos()) && row(itemAt(event->pos())) > 0) { - if(itemHover) { - if(itemHover != itemAt(event->pos())) { + if (itemAt(event->pos()) && row(itemAt(event->pos())) > 0) { + if (itemHover) { + if (itemHover != itemAt(event->pos())) { setItemHover(false); itemHover = itemAt(event->pos()); setItemHover(true); @@ -111,7 +111,7 @@ protected: } event->acceptProposedAction(); } else { - if(itemHover) + if (itemHover) setItemHover(false); event->ignore(); } @@ -119,7 +119,7 @@ protected: void dropEvent(QDropEvent *event) { qDebug("Drop Event in labels list"); - if(itemAt(event->pos())) { + if (itemAt(event->pos())) { emit torrentDropped(row(itemAt(event->pos()))); } event->ignore(); @@ -129,7 +129,7 @@ protected: } void dragLeaveEvent(QDragLeaveEvent*) { - if(itemHover) + if (itemHover) setItemHover(false); // Select current item again currentItem()->setSelected(true); @@ -137,7 +137,7 @@ protected: void setItemHover(bool hover) { Q_ASSERT(itemHover); - if(hover) { + if (hover) { itemHover->setData(Qt::DecorationRole, IconProvider::instance()->getIcon("folder-documents.png")); itemHover->setSelected(true); //setCurrentItem(itemHover); @@ -271,7 +271,7 @@ public: QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); statusFilters->setCurrentRow(settings.value("TransferListFilters/selectedFilterIndex", 0).toInt()); const QStringList label_list = Preferences().getTorrentLabels(); - foreach(const QString &label, label_list) { + foreach (const QString &label, label_list) { customLabels.insert(label, 0); qDebug("Creating label QListWidgetItem: %s", qPrintable(label)); QListWidgetItem *newLabel = new QListWidgetItem(); @@ -294,7 +294,7 @@ protected slots: void torrentDropped(int row) { Q_ASSERT(row > 0); - if(row == 1) { + if (row == 1) { transferList->setSelectionLabel(""); } else { transferList->setSelectionLabel(labelFilters->labelFromRow(row)); @@ -303,7 +303,7 @@ protected slots: void addLabel(QString label) { label = misc::toValidFileSystemName(label.trimmed()); - if(label.isEmpty() || customLabels.contains(label)) return; + if (label.isEmpty() || customLabels.contains(label)) return; QListWidgetItem *newLabel = new QListWidgetItem(); newLabel->setText(label + " (0)"); newLabel->setData(Qt::DecorationRole, IconProvider::instance()->getIcon("inode-directory")); @@ -315,7 +315,7 @@ protected slots: void showLabelMenu(QPoint) { QMenu labelMenu(labelFilters); QAction *removeAct = 0; - if(!labelFilters->selectedItems().empty() && labelFilters->row(labelFilters->selectedItems().first()) > 1) + if (!labelFilters->selectedItems().empty() && labelFilters->row(labelFilters->selectedItems().first()) > 1) removeAct = labelMenu.addAction(IconProvider::instance()->getIcon("list-remove"), tr("Remove label")); QAction *addAct = labelMenu.addAction(IconProvider::instance()->getIcon("list-add"), tr("Add label...")); labelMenu.addSeparator(); @@ -324,24 +324,24 @@ protected slots: QAction *deleteTorrentsAct = labelMenu.addAction(IconProvider::instance()->getIcon("edit-delete"), tr("Delete torrents")); QAction *act = 0; act = labelMenu.exec(QCursor::pos()); - if(act) { - if(act == removeAct) { + if (act) { + if (act == removeAct) { removeSelectedLabel(); return; } - if(act == deleteTorrentsAct) { + if (act == deleteTorrentsAct) { transferList->deleteVisibleTorrents(); return; } - if(act == startAct) { + if (act == startAct) { transferList->startVisibleTorrents(); return; } - if(act == pauseAct) { + if (act == pauseAct) { transferList->pauseVisibleTorrents(); return; } - if(act == addAct) { + if (act == addAct) { bool ok; QString label = ""; bool invalid; @@ -349,7 +349,7 @@ protected slots: invalid = false; label = QInputDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, label, &ok); if (ok && !label.isEmpty()) { - if(misc::isValidFileSystemName(label)) { + if (misc::isValidFileSystemName(label)) { addLabel(label); } else { QMessageBox::warning(this, tr("Invalid label name"), tr("Please don't use any special characters in the label name.")); @@ -395,8 +395,8 @@ protected slots: void torrentChangedLabel(TorrentModelItem *torrentItem, QString old_label, QString new_label) { Q_UNUSED(torrentItem); qDebug("Torrent label changed from %s to %s", qPrintable(old_label), qPrintable(new_label)); - if(!old_label.isEmpty()) { - if(customLabels.contains(old_label)) { + if (!old_label.isEmpty()) { + if (customLabels.contains(old_label)) { const int new_count = customLabels.value(old_label, 0) - 1; Q_ASSERT(new_count >= 0); customLabels.insert(old_label, new_count); @@ -406,8 +406,8 @@ protected slots: } --nb_labeled; } - if(!new_label.isEmpty()) { - if(!customLabels.contains(new_label)) + if (!new_label.isEmpty()) { + if (!customLabels.contains(new_label)) addLabel(new_label); const int new_count = customLabels.value(new_label, 0) + 1; Q_ASSERT(new_count >= 1); @@ -423,8 +423,8 @@ protected slots: void handleNewTorrent(TorrentModelItem* torrentItem) { QString label = torrentItem->data(TorrentModelItem::TR_LABEL).toString(); qDebug("New torrent was added with label: %s", qPrintable(label)); - if(!label.isEmpty()) { - if(!customLabels.contains(label)) { + if (!label.isEmpty()) { + if (!customLabels.contains(label)) { addLabel(label); } // Update label counter @@ -448,7 +448,7 @@ protected slots: void torrentAboutToBeDeleted(TorrentModelItem* torrentItem) { Q_ASSERT(torrentItem); QString label = torrentItem->data(TorrentModelItem::TR_LABEL).toString(); - if(!label.isEmpty()) { + if (!label.isEmpty()) { // Update label counter const int new_count = customLabels.value(label, 0) - 1; customLabels.insert(label, new_count); diff --git a/src/transferlistwidget.cpp b/src/transferlistwidget.cpp index 1e37fec32..232e1066a 100644 --- a/src/transferlistwidget.cpp +++ b/src/transferlistwidget.cpp @@ -108,7 +108,7 @@ TransferListWidget::TransferListWidget(QWidget *parent, MainWindow *main_window, setDragDropMode(QAbstractItemView::DragOnly); // Default hidden columns - if(!column_loaded) { + if (!column_loaded) { setColumnHidden(TorrentModelItem::TR_PRIORITY, true); setColumnHidden(TorrentModelItem::TR_ADD_DATE, true); setColumnHidden(TorrentModelItem::TR_SEED_DATE, true); @@ -165,9 +165,9 @@ inline QString TransferListWidget::getHashFromRow(int row) const { inline QModelIndex TransferListWidget::mapToSource(const QModelIndex &index) const { Q_ASSERT(index.isValid()); - if(index.model() == nameFilterModel) + if (index.model() == nameFilterModel) return labelFilterModel->mapToSource(statusFilterModel->mapToSource(nameFilterModel->mapToSource(index))); - if(index.model() == statusFilterModel) + if (index.model() == statusFilterModel) return labelFilterModel->mapToSource(statusFilterModel->mapToSource(index)); return labelFilterModel->mapToSource(index); } @@ -188,9 +188,9 @@ void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) { const int row = mapToSource(index).row(); const QString hash = getHashFromRow(row); QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(!h.is_valid()) return; + if (!h.is_valid()) return; int action; - if(h.is_seed()) { + if (h.is_seed()) { action = Preferences().getActionOnDblClOnTorrentFn(); } else { action = Preferences().getActionOnDblClOnTorrentDl(); @@ -198,7 +198,7 @@ void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) { switch(action) { case TOGGLE_PAUSE: - if(h.is_paused()) { + if (h.is_paused()) { h.resume(); } else { h.pause(); @@ -213,7 +213,7 @@ void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) { QStringList TransferListWidget::getSelectedTorrentsHashes() const { QStringList hashes; const QModelIndexList selectedIndexes = selectionModel()->selectedRows(); - foreach(const QModelIndex &index, selectedIndexes) { + foreach (const QModelIndex &index, selectedIndexes) { hashes << getHashFromRow(mapToSource(index).row()); } return hashes; @@ -221,22 +221,22 @@ QStringList TransferListWidget::getSelectedTorrentsHashes() const { void TransferListWidget::setSelectedTorrentsLocation() { const QStringList hashes = getSelectedTorrentsHashes(); - if(hashes.isEmpty()) return; + if (hashes.isEmpty()) return; QString dir; const QDir saveDir(TorrentPersistentData::getSavePath(hashes.first())); qDebug("Old save path is %s", qPrintable(saveDir.absolutePath())); dir = QFileDialog::getExistingDirectory(this, tr("Choose save path"), saveDir.absolutePath(), QFileDialog::DontConfirmOverwrite|QFileDialog::ShowDirsOnly|QFileDialog::HideNameFilterDetails); - if(!dir.isNull()) { + if (!dir.isNull()) { qDebug("New path is %s", qPrintable(dir)); // Check if savePath exists QDir savePath(misc::expandPath(dir)); qDebug("New path after clean up is %s", qPrintable(savePath.absolutePath())); - foreach(const QString & hash, hashes) { + foreach (const QString & hash, hashes) { // Actually move storage QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(!BTSession->useTemporaryFolder() || h.is_seed()) { - if(!savePath.exists()) savePath.mkpath(savePath.absolutePath()); + if (!BTSession->useTemporaryFolder() || h.is_seed()) { + if (!savePath.exists()) savePath.mkpath(savePath.absolutePath()); h.move_storage(savePath.absolutePath()); } else { TorrentPersistentData::saveSavePath(h.hash(), savePath.absolutePath()); @@ -248,79 +248,79 @@ void TransferListWidget::setSelectedTorrentsLocation() { void TransferListWidget::startSelectedTorrents() { const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { BTSession->resumeTorrent(hash); } } void TransferListWidget::startVisibleTorrents() { QStringList hashes; - for(int i=0; irowCount(); ++i) { + for (int i=0; irowCount(); ++i) { const int row = mapToSource(nameFilterModel->index(i, 0)).row(); hashes << getHashFromRow(row); } - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { BTSession->resumeTorrent(hash); } } void TransferListWidget::pauseSelectedTorrents() { const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { BTSession->pauseTorrent(hash); } } void TransferListWidget::pauseVisibleTorrents() { QStringList hashes; - for(int i=0; irowCount(); ++i) { + for (int i=0; irowCount(); ++i) { const int row = mapToSource(nameFilterModel->index(i, 0)).row(); hashes << getHashFromRow(row); } - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { BTSession->pauseTorrent(hash); } } void TransferListWidget::deleteSelectedTorrents() { - if(main_window->getCurrentTabWidget() != this) return; + if (main_window->getCurrentTabWidget() != this) return; const QStringList& hashes = getSelectedTorrentsHashes(); - if(hashes.empty()) return; + if (hashes.empty()) return; bool delete_local_files = false; - if(Preferences().confirmTorrentDeletion() && + if (Preferences().confirmTorrentDeletion() && !DeletionConfirmationDlg::askForDeletionConfirmation(&delete_local_files)) return; - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { BTSession->deleteTorrent(hash, delete_local_files); } } void TransferListWidget::deleteVisibleTorrents() { - if(nameFilterModel->rowCount() <= 0) return; + if (nameFilterModel->rowCount() <= 0) return; bool delete_local_files = false; - if(Preferences().confirmTorrentDeletion() && + if (Preferences().confirmTorrentDeletion() && !DeletionConfirmationDlg::askForDeletionConfirmation(&delete_local_files)) return; QStringList hashes; - for(int i=0; irowCount(); ++i) { + for (int i=0; irowCount(); ++i) { const int row = mapToSource(nameFilterModel->index(i, 0)).row(); hashes << getHashFromRow(row); } - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { BTSession->deleteTorrent(hash, delete_local_files); } } void TransferListWidget::increasePrioSelectedTorrents() { qDebug() << Q_FUNC_INFO; - if(main_window->getCurrentTabWidget() != this) return; + if (main_window->getCurrentTabWidget() != this) return; const QStringList hashes = getSelectedTorrentsHashes(); std::priority_queue, std::vector >, std::greater > > torrent_queue; // Sort torrents by priority - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { try { QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(!h.is_seed()) { + if (!h.is_seed()) { torrent_queue.push(qMakePair(h.queue_position(), h)); } }catch(invalid_handle&){} @@ -337,14 +337,14 @@ void TransferListWidget::increasePrioSelectedTorrents() { void TransferListWidget::decreasePrioSelectedTorrents() { qDebug() << Q_FUNC_INFO; - if(main_window->getCurrentTabWidget() != this) return; + if (main_window->getCurrentTabWidget() != this) return; const QStringList hashes = getSelectedTorrentsHashes(); std::priority_queue, std::vector >, std::less > > torrent_queue; // Sort torrents by priority - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { try { QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(!h.is_seed()) { + if (!h.is_seed()) { torrent_queue.push(qMakePair(h.queue_position(), h)); } }catch(invalid_handle&){} @@ -360,22 +360,22 @@ void TransferListWidget::decreasePrioSelectedTorrents() { } void TransferListWidget::topPrioSelectedTorrents() { - if(main_window->getCurrentTabWidget() != this) return; + if (main_window->getCurrentTabWidget() != this) return; const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(h.is_valid() && !h.is_seed()) { + if (h.is_valid() && !h.is_seed()) { h.queue_position_top(); } } } void TransferListWidget::bottomPrioSelectedTorrents() { - if(main_window->getCurrentTabWidget() != this) return; + if (main_window->getCurrentTabWidget() != this) return; const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(h.is_valid() && !h.is_seed()) { + if (h.is_valid() && !h.is_seed()) { h.queue_position_bottom(); } } @@ -384,9 +384,9 @@ void TransferListWidget::bottomPrioSelectedTorrents() { void TransferListWidget::copySelectedMagnetURIs() const { QStringList magnet_uris; const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { const QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(h.is_valid() && h.has_metadata()) + if (h.is_valid() && h.has_metadata()) magnet_uris << misc::toQString(make_magnet_uri(h.get_torrent_info())); } qApp->clipboard()->setText(magnet_uris.join("\n")); @@ -400,12 +400,12 @@ void TransferListWidget::hidePriorityColumn(bool hide) { void TransferListWidget::openSelectedTorrentsFolder() const { QStringList pathsList; const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { const QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(h.is_valid()) { + if (h.is_valid()) { const QString savePath = h.save_path(); qDebug("Opening path at %s", qPrintable(savePath)); - if(!pathsList.contains(savePath)) { + if (!pathsList.contains(savePath)) { pathsList.append(savePath); QDesktopServices::openUrl(QUrl::fromLocalFile(savePath)); } @@ -415,9 +415,9 @@ void TransferListWidget::openSelectedTorrentsFolder() const { void TransferListWidget::previewSelectedTorrents() { const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { const QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(h.is_valid() && h.has_metadata()) { + if (h.is_valid() && h.has_metadata()) { new PreviewSelect(this, h); } } @@ -428,28 +428,28 @@ void TransferListWidget::setDlLimitSelectedTorrents() { bool first = true; bool all_same_limit = true; const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { const QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(h.is_valid() && !h.is_seed()) { + if (h.is_valid() && !h.is_seed()) { selected_torrents << h; // Determine current limit for selected torrents - if(first) { + if (first) { first = false; } else { - if(all_same_limit && h.download_limit() != selected_torrents.first().download_limit()) + if (all_same_limit && h.download_limit() != selected_torrents.first().download_limit()) all_same_limit = false; } } } - if(selected_torrents.empty()) return; + if (selected_torrents.empty()) return; bool ok=false; int default_limit = -1; - if(all_same_limit) + if (all_same_limit) default_limit = selected_torrents.first().download_limit(); const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Download Speed Limiting"), default_limit, Preferences().getGlobalDownloadLimit()*1024.); - if(ok) { - foreach(const QTorrentHandle &h, selected_torrents) { + if (ok) { + foreach (const QTorrentHandle &h, selected_torrents) { qDebug("Applying download speed limit of %ld Kb/s to torrent %s", (long)(new_limit/1024.), qPrintable(h.hash())); BTSession->setDownloadLimit(h.hash(), new_limit); } @@ -461,28 +461,28 @@ void TransferListWidget::setUpLimitSelectedTorrents() { bool first = true; bool all_same_limit = true; const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { const QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(h.is_valid()) { + if (h.is_valid()) { selected_torrents << h; // Determine current limit for selected torrents - if(first) { + if (first) { first = false; } else { - if(all_same_limit && h.upload_limit() != selected_torrents.first().upload_limit()) + if (all_same_limit && h.upload_limit() != selected_torrents.first().upload_limit()) all_same_limit = false; } } } - if(selected_torrents.empty()) return; + if (selected_torrents.empty()) return; bool ok=false; int default_limit = -1; - if(all_same_limit) + if (all_same_limit) default_limit = selected_torrents.first().upload_limit(); const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Upload Speed Limiting"), default_limit, Preferences().getGlobalUploadLimit()*1024.); - if(ok) { - foreach(const QTorrentHandle &h, selected_torrents) { + if (ok) { + foreach (const QTorrentHandle &h, selected_torrents) { qDebug("Applying upload speed limit of %ld Kb/s to torrent %s", (long)(new_limit/1024.), qPrintable(h.hash())); BTSession->setUploadLimit(h.hash(), new_limit); } @@ -514,7 +514,7 @@ void TransferListWidget::setMaxRatioSelectedTorrents() { void TransferListWidget::recheckSelectedTorrents() { const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { BTSession->recheckTorrent(hash); } } @@ -524,8 +524,8 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&){ QMenu hideshowColumn(this); hideshowColumn.setTitle(tr("Column visibility")); QList actions; - for(int i=0; i < listModel->columnCount(); ++i) { - if(!BTSession->isQueueingEnabled() && i == TorrentModelItem::TR_PRIORITY) { + for (int i=0; i < listModel->columnCount(); ++i) { + if (!BTSession->isQueueingEnabled() && i == TorrentModelItem::TR_PRIORITY) { actions.append(0); continue; } @@ -536,21 +536,21 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&){ } // Call menu QAction *act = hideshowColumn.exec(QCursor::pos()); - if(act) { + if (act) { int col = actions.indexOf(act); Q_ASSERT(col >= 0); qDebug("Toggling column %d visibility", col); setColumnHidden(col, !isColumnHidden(col)); - if(!isColumnHidden(col) && columnWidth(col) <= 5) + if (!isColumnHidden(col) && columnWidth(col) <= 5) setColumnWidth(col, 100); } } void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const { const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(h.is_valid() && h.has_metadata()) { + if (h.is_valid() && h.has_metadata()) { h.super_seeding(!h.super_seeding()); } } @@ -558,12 +558,12 @@ void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const { void TransferListWidget::toggleSelectedTorrentsSequentialDownload() const { const QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(h.is_valid() && h.has_metadata()) { + if (h.is_valid() && h.has_metadata()) { bool was_sequential = h.is_sequential_download(); h.set_sequential_download(!was_sequential); - if(!was_sequential) + if (!was_sequential) h.prioritize_first_last_piece(true); } } @@ -571,9 +571,9 @@ void TransferListWidget::toggleSelectedTorrentsSequentialDownload() const { void TransferListWidget::toggleSelectedFirstLastPiecePrio() const { QStringList hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(h.is_valid() && h.has_metadata()) { + if (h.is_valid() && h.has_metadata()) { h.prioritize_first_last_piece(!h.first_last_piece_first()); } } @@ -587,7 +587,7 @@ void TransferListWidget::askNewLabelForSelection() { invalid = false; const QString label = QInputDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, "", &ok); if (ok && !label.isEmpty()) { - if(misc::isValidFileSystemName(label)) { + if (misc::isValidFileSystemName(label)) { setSelectionLabel(label); } else { QMessageBox::warning(this, tr("Invalid label name"), tr("Please don't use any special characters in the label name.")); @@ -599,11 +599,11 @@ void TransferListWidget::askNewLabelForSelection() { void TransferListWidget::renameSelectedTorrent() { const QModelIndexList selectedIndexes = selectionModel()->selectedRows(); - if(selectedIndexes.size() != 1) return; - if(!selectedIndexes.first().isValid()) return; + if (selectedIndexes.size() != 1) return; + if (!selectedIndexes.first().isValid()) return; const QString hash = getHashFromRow(mapToSource(selectedIndexes.first()).row()); const QTorrentHandle h = BTSession->getTorrentHandle(hash); - if(!h.is_valid()) return; + if (!h.is_valid()) return; // Ask for a new Name bool ok; const QString name = QInputDialog::getText(this, tr("Rename"), tr("New name:"), QLineEdit::Normal, h.name(), &ok); @@ -615,7 +615,7 @@ void TransferListWidget::renameSelectedTorrent() { void TransferListWidget::setSelectionLabel(QString label) { const QStringList& hashes = getSelectedTorrentsHashes(); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { Q_ASSERT(!hash.isEmpty()); const int row = getRowFromHash(hash); const QString old_label = listModel->data(listModel->index(row, TorrentModelItem::TR_LABEL)).toString(); @@ -627,8 +627,8 @@ void TransferListWidget::setSelectionLabel(QString label) { } void TransferListWidget::removeLabelFromRows(QString label) { - for(int i=0; irowCount(); ++i) { - if(listModel->data(listModel->index(i, TorrentModelItem::TR_LABEL)) == label) { + for (int i=0; irowCount(); ++i) { + if (listModel->data(listModel->index(i, TorrentModelItem::TR_LABEL)) == label) { const QString hash = getHashFromRow(i); listModel->setData(listModel->index(i, TorrentModelItem::TR_LABEL), "", Qt::DisplayRole); // Update save path if necessary @@ -694,63 +694,63 @@ void TransferListWidget::displayListMenu(const QPoint&) { bool first = true; QTorrentHandle h; qDebug("Displaying menu"); - foreach(const QModelIndex &index, selectedIndexes) { + foreach (const QModelIndex &index, selectedIndexes) { // Get the file name QString hash = getHashFromRow(mapToSource(index).row()); // Get handle and pause the torrent h = BTSession->getTorrentHandle(hash); - if(!h.is_valid()) continue; - if(h.has_metadata()) + if (!h.is_valid()) continue; + if (h.has_metadata()) one_has_metadata = true; - if(!h.is_seed()) { + if (!h.is_seed()) { one_not_seed = true; - if(h.has_metadata()) { - if(first) { + if (h.has_metadata()) { + if (first) { sequential_download_mode = h.is_sequential_download(); prioritize_first_last = h.first_last_piece_first(); } else { - if(sequential_download_mode != h.is_sequential_download()) { + if (sequential_download_mode != h.is_sequential_download()) { all_same_sequential_download_mode = false; } - if(prioritize_first_last != h.first_last_piece_first()) { + if (prioritize_first_last != h.first_last_piece_first()) { all_same_prio_firstlast = false; } } } } else { - if(!one_not_seed && all_same_super_seeding && h.has_metadata()) { - if(first) { + if (!one_not_seed && all_same_super_seeding && h.has_metadata()) { + if (first) { super_seeding_mode = h.super_seeding(); } else { - if(super_seeding_mode != h.super_seeding()) { + if (super_seeding_mode != h.super_seeding()) { all_same_super_seeding = false; } } } } - if(h.is_paused()) { - if(!has_start) { + if (h.is_paused()) { + if (!has_start) { listMenu.addAction(&actionStart); has_start = true; } }else{ - if(!has_pause) { + if (!has_pause) { listMenu.addAction(&actionPause); has_pause = true; } } - if(h.has_metadata() && BTSession->isFilePreviewPossible(hash) && !has_preview) { + if (h.has_metadata() && BTSession->isFilePreviewPossible(hash) && !has_preview) { has_preview = true; } first = false; - if(has_pause && has_start && has_preview && one_not_seed) break; + if (has_pause && has_start && has_preview && one_not_seed) break; } listMenu.addSeparator(); listMenu.addAction(&actionDelete); listMenu.addSeparator(); listMenu.addAction(&actionSetTorrentPath); - if(selectedIndexes.size() == 1) + if (selectedIndexes.size() == 1) listMenu.addAction(&actionRename); // Label Menu QStringList customLabels = getCustomLabels(); @@ -760,44 +760,44 @@ void TransferListWidget::displayListMenu(const QPoint&) { labelActions << labelMenu->addAction(IconProvider::instance()->getIcon("list-add"), tr("New...", "New label...")); labelActions << labelMenu->addAction(IconProvider::instance()->getIcon("edit-clear"), tr("Reset", "Reset label")); labelMenu->addSeparator(); - foreach(const QString &label, customLabels) { + foreach (const QString &label, customLabels) { labelActions << labelMenu->addAction(IconProvider::instance()->getIcon("inode-directory"), label); } listMenu.addSeparator(); - if(one_not_seed) + if (one_not_seed) listMenu.addAction(&actionSet_download_limit); listMenu.addAction(&actionSet_max_ratio); listMenu.addAction(&actionSet_upload_limit); - if(!one_not_seed && all_same_super_seeding && one_has_metadata) { + if (!one_not_seed && all_same_super_seeding && one_has_metadata) { actionSuper_seeding_mode.setChecked(super_seeding_mode); listMenu.addAction(&actionSuper_seeding_mode); } listMenu.addSeparator(); bool added_preview_action = false; - if(has_preview) { + if (has_preview) { listMenu.addAction(&actionPreview_file); added_preview_action = true; } - if(one_not_seed && one_has_metadata) { - if(all_same_sequential_download_mode) { + if (one_not_seed && one_has_metadata) { + if (all_same_sequential_download_mode) { actionSequential_download.setChecked(sequential_download_mode); listMenu.addAction(&actionSequential_download); added_preview_action = true; } - if(all_same_prio_firstlast) { + if (all_same_prio_firstlast) { actionFirstLastPiece_prio.setChecked(prioritize_first_last); listMenu.addAction(&actionFirstLastPiece_prio); added_preview_action = true; } } - if(added_preview_action) + if (added_preview_action) listMenu.addSeparator(); - if(one_has_metadata) { + if (one_has_metadata) { listMenu.addAction(&actionForce_recheck); listMenu.addSeparator(); } listMenu.addAction(&actionOpen_destination_folder); - if(BTSession->isQueueingEnabled() && one_not_seed) { + if (BTSession->isQueueingEnabled() && one_not_seed) { listMenu.addSeparator(); QMenu *prioMenu = listMenu.addMenu(tr("Priority")); prioMenu->addAction(&actionTopPriority); @@ -806,22 +806,22 @@ void TransferListWidget::displayListMenu(const QPoint&) { prioMenu->addAction(&actionBottomPriority); } listMenu.addSeparator(); - if(one_has_metadata) + if (one_has_metadata) listMenu.addAction(&actionCopy_magnet_link); // Call menu QAction *act = 0; act = listMenu.exec(QCursor::pos()); - if(act) { + if (act) { // Parse label actions only (others have slots assigned) int i = labelActions.indexOf(act); - if(i >= 0) { + if (i >= 0) { // Label action - if(i == 0) { + if (i == 0) { // New Label askNewLabelForSelection(); } else { QString label = ""; - if(i > 1) + if (i > 1) label = customLabels.at(i-2); // Update Label setSelectionLabel(label); @@ -833,7 +833,7 @@ void TransferListWidget::displayListMenu(const QPoint&) { void TransferListWidget::currentChanged(const QModelIndex& current, const QModelIndex&) { qDebug("CURRENT CHANGED"); QTorrentHandle h; - if(current.isValid()) { + if (current.isValid()) { const int row = mapToSource(current).row(); h = BTSession->getTorrentHandle(getHashFromRow(row)); // Scroll Fix @@ -843,11 +843,11 @@ void TransferListWidget::currentChanged(const QModelIndex& current, const QModel } void TransferListWidget::applyLabelFilter(QString label) { - if(label == "all") { + if (label == "all") { labelFilterModel->setFilterRegExp(QRegExp()); return; } - if(label == "none") { + if (label == "none") { labelFilterModel->setFilterRegExp(QRegExp("^$")); return; } @@ -884,7 +884,7 @@ void TransferListWidget::applyStatusFilter(int f) { statusFilterModel->setFilterRegExp(QRegExp()); } // Select first item if nothing is selected - if(selectionModel()->selectedRows(0).empty() && nameFilterModel->rowCount() > 0) { + if (selectionModel()->selectedRows(0).empty() && nameFilterModel->rowCount() > 0) { qDebug("Nothing is selected, selecting first row: %s", qPrintable(nameFilterModel->index(0, TorrentModelItem::TR_NAME).data().toString())); selectionModel()->setCurrentIndex(nameFilterModel->index(0, TorrentModelItem::TR_NAME), QItemSelectionModel::SelectCurrent|QItemSelectionModel::Rows); } @@ -900,7 +900,7 @@ bool TransferListWidget::loadSettings() { QIniSettings settings("qBittorrent", "qBittorrent"); bool ok = header()->restoreState(settings.value("TransferList/HeaderState").toByteArray()); - if(!ok) { + if (!ok) { header()->resizeSection(0, 200); // Default } return ok; diff --git a/src/webui/eventmanager.cpp b/src/webui/eventmanager.cpp index cba4636b7..434888854 100644 --- a/src/webui/eventmanager.cpp +++ b/src/webui/eventmanager.cpp @@ -58,23 +58,23 @@ QList EventManager::getEventList() const { QList EventManager::getPropTrackersInfo(QString hash) const { QList trackersInfo; QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(h.is_valid()) { + if (h.is_valid()) { QHash trackers_data = QBtSession::instance()->getTrackersInfo(hash); std::vector vect_trackers = h.trackers(); std::vector::iterator it; - for(it = vect_trackers.begin(); it != vect_trackers.end(); it++) { + for (it = vect_trackers.begin(); it != vect_trackers.end(); it++) { QVariantMap tracker; QString tracker_url = misc::toQString(it->url); tracker["url"] = tracker_url; TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url)); QString error_message = data.last_message.trimmed(); - if(it->verified) { + if (it->verified) { tracker["status"] = tr("Working"); } else { - if(it->updating && it->fails == 0) { + if (it->updating && it->fails == 0) { tracker["status"] = tr("Updating..."); } else { - if(it->fails > 0) { + if (it->fails > 0) { tracker["status"] = tr("Not working"); } else { tracker["status"] = tr("Not contacted yet"); @@ -92,21 +92,21 @@ QList EventManager::getPropTrackersInfo(QString hash) const { QList EventManager::getPropFilesInfo(QString hash) const { QList files; QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(!h.is_valid() || !h.has_metadata()) return files; + if (!h.is_valid() || !h.has_metadata()) return files; std::vector priorities = h.file_priorities(); std::vector fp; h.file_progress(fp); - for(int i=0; i 0) + if (size > 0) file["progress"] = fp[i]/(double)size; else file["progress"] = 1.; // Empty file... file["priority"] = priorities[i]; - if(i == 0) + if (i == 0) file["is_seed"] = h.is_seed(); files << file; } @@ -116,11 +116,11 @@ QList EventManager::getPropFilesInfo(QString hash) const { void EventManager::setGlobalPreferences(QVariantMap m) { // UI Preferences pref; - if(m.contains("locale")) { + if (m.contains("locale")) { QString locale = m["locale"].toString(); - if(pref.getLocale() != locale) { + if (pref.getLocale() != locale) { QTranslator *translator = new QTranslator; - if(translator->load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){ + if (translator->load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){ qDebug("%s locale recognized, using translation.", qPrintable(locale)); }else{ qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale)); @@ -132,184 +132,184 @@ void EventManager::setGlobalPreferences(QVariantMap m) { } } // Downloads - if(m.contains("save_path")) + if (m.contains("save_path")) pref.setSavePath(m["save_path"].toString()); - if(m.contains("temp_path_enabled")) + if (m.contains("temp_path_enabled")) pref.setTempPathEnabled(m["temp_path_enabled"].toBool()); - if(m.contains("temp_path")) + if (m.contains("temp_path")) pref.setTempPath(m["temp_path"].toString()); - if(m.contains("scan_dirs") && m.contains("download_in_scan_dirs")) { + if (m.contains("scan_dirs") && m.contains("download_in_scan_dirs")) { QVariantList download_at_path_tmp = m["download_in_scan_dirs"].toList(); QList download_at_path; - foreach(QVariant var, download_at_path_tmp) { + foreach (QVariant var, download_at_path_tmp) { download_at_path << var.toBool(); } QStringList old_folders = pref.getScanDirs(); QStringList new_folders = m["scan_dirs"].toStringList(); - if(download_at_path.size() == new_folders.size()) { + if (download_at_path.size() == new_folders.size()) { pref.setScanDirs(new_folders); pref.setDownloadInScanDirs(download_at_path); - foreach(const QString &old_folder, old_folders) { + foreach (const QString &old_folder, old_folders) { // Update deleted folders - if(!new_folders.contains(old_folder)) { + if (!new_folders.contains(old_folder)) { QBtSession::instance()->getScanFoldersModel()->removePath(old_folder); } } int i = 0; - foreach(const QString &new_folder, new_folders) { + foreach (const QString &new_folder, new_folders) { qDebug("New watched folder: %s", qPrintable(new_folder)); // Update new folders - if(!old_folders.contains(new_folder)) { + if (!old_folders.contains(new_folder)) { QBtSession::instance()->getScanFoldersModel()->addPath(new_folder, download_at_path.at(i)); } ++i; } } } - if(m.contains("export_dir")) + if (m.contains("export_dir")) pref.setExportDir(m["export_dir"].toString()); - if(m.contains("mail_notification_enabled")) + if (m.contains("mail_notification_enabled")) pref.setMailNotificationEnabled(m["mail_notification_enabled"].toBool()); - if(m.contains("mail_notification_email")) + if (m.contains("mail_notification_email")) pref.setMailNotificationEmail(m["mail_notification_email"].toString()); - if(m.contains("mail_notification_smtp")) + if (m.contains("mail_notification_smtp")) pref.setMailNotificationSMTP(m["mail_notification_smtp"].toString()); - if(m.contains("mail_notification_ssl_enabled")) + if (m.contains("mail_notification_ssl_enabled")) pref.setMailNotificationSMTPSSL(m["mail_notification_ssl_enabled"].toBool()); - if(m.contains("mail_notification_auth_enabled")) + if (m.contains("mail_notification_auth_enabled")) pref.setMailNotificationSMTPAuth(m["mail_notification_auth_enabled"].toBool()); - if(m.contains("mail_notification_username")) + if (m.contains("mail_notification_username")) pref.setMailNotificationSMTPUsername(m["mail_notification_username"].toString()); - if(m.contains("mail_notification_password")) + if (m.contains("mail_notification_password")) pref.setMailNotificationSMTPPassword(m["mail_notification_password"].toString()); - if(m.contains("autorun_enabled")) + if (m.contains("autorun_enabled")) pref.setAutoRunEnabled(m["autorun_enabled"].toBool()); - if(m.contains("autorun_program")) + if (m.contains("autorun_program")) pref.setAutoRunProgram(m["autorun_program"].toString()); - if(m.contains("preallocate_all")) + if (m.contains("preallocate_all")) pref.preAllocateAllFiles(m["preallocate_all"].toBool()); - if(m.contains("queueing_enabled")) + if (m.contains("queueing_enabled")) pref.setQueueingSystemEnabled(m["queueing_enabled"].toBool()); - if(m.contains("max_active_downloads")) + if (m.contains("max_active_downloads")) pref.setMaxActiveDownloads(m["max_active_downloads"].toInt()); - if(m.contains("max_active_torrents")) + if (m.contains("max_active_torrents")) pref.setMaxActiveTorrents(m["max_active_torrents"].toInt()); - if(m.contains("max_active_uploads")) + if (m.contains("max_active_uploads")) pref.setMaxActiveUploads(m["max_active_uploads"].toInt()); - if(m.contains("dont_count_slow_torrents")) + if (m.contains("dont_count_slow_torrents")) pref.setIgnoreSlowTorrentsForQueueing(m["dont_count_slow_torrents"].toBool()); - if(m.contains("incomplete_files_ext")) + if (m.contains("incomplete_files_ext")) pref.useIncompleteFilesExtension(m["incomplete_files_ext"].toBool()); // Connection - if(m.contains("listen_port")) + if (m.contains("listen_port")) pref.setSessionPort(m["listen_port"].toInt()); - if(m.contains("upnp")) + if (m.contains("upnp")) pref.setUPnPEnabled(m["upnp"].toBool()); - if(m.contains("dl_limit")) + if (m.contains("dl_limit")) pref.setGlobalDownloadLimit(m["dl_limit"].toInt()); - if(m.contains("up_limit")) + if (m.contains("up_limit")) pref.setGlobalUploadLimit(m["up_limit"].toInt()); - if(m.contains("max_connec")) + if (m.contains("max_connec")) pref.setMaxConnecs(m["max_connec"].toInt()); - if(m.contains("max_connec_per_torrent")) + if (m.contains("max_connec_per_torrent")) pref.setMaxConnecsPerTorrent(m["max_connec_per_torrent"].toInt()); - if(m.contains("max_uploads_per_torrent")) + if (m.contains("max_uploads_per_torrent")) pref.setMaxUploadsPerTorrent(m["max_uploads_per_torrent"].toInt()); #if LIBTORRENT_VERSION_MINOR >= 16 - if(m.contains("enable_utp")) + if (m.contains("enable_utp")) pref.setuTPEnabled(m["enable_utp"].toBool()); - if(m.contains("limit_utp_rate")) + if (m.contains("limit_utp_rate")) pref.setuTPRateLimited(m["limit_utp_rate"].toBool()); #endif - if(m.contains("limit_tcp_overhead")) + if (m.contains("limit_tcp_overhead")) pref.includeOverheadInLimits(m["limit_tcp_overhead"].toBool()); - if(m.contains("alt_dl_limit")) + if (m.contains("alt_dl_limit")) pref.setAltGlobalDownloadLimit(m["alt_dl_limit"].toInt()); - if(m.contains("alt_up_limit")) + if (m.contains("alt_up_limit")) pref.setAltGlobalUploadLimit(m["alt_up_limit"].toInt()); - if(m.contains("scheduler_enabled")) + if (m.contains("scheduler_enabled")) pref.setSchedulerEnabled(m["scheduler_enabled"].toBool()); - if(m.contains("schedule_from_hour") && m.contains("schedule_from_min")) { + if (m.contains("schedule_from_hour") && m.contains("schedule_from_min")) { pref.setSchedulerStartTime(QTime(m["schedule_from_hour"].toInt(), m["schedule_from_min"].toInt())); } - if(m.contains("schedule_to_hour") && m.contains("schedule_to_min")) { + if (m.contains("schedule_to_hour") && m.contains("schedule_to_min")) { pref.setSchedulerEndTime(QTime(m["schedule_to_hour"].toInt(), m["schedule_to_min"].toInt())); } - if(m.contains("scheduler_days")) + if (m.contains("scheduler_days")) pref.setSchedulerDays(scheduler_days(m["scheduler_days"].toInt())); // Bittorrent - if(m.contains("dht")) + if (m.contains("dht")) pref.setDHTEnabled(m["dht"].toBool()); - if(m.contains("dhtSameAsBT")) + if (m.contains("dhtSameAsBT")) pref.setDHTPortSameAsBT(m["dhtSameAsBT"].toBool()); - if(m.contains("dht_port")) + if (m.contains("dht_port")) pref.setDHTPort(m["dht_port"].toInt()); - if(m.contains("pex")) + if (m.contains("pex")) pref.setPeXEnabled(m["pex"].toBool()); qDebug("Pex support: %d", (int)m["pex"].toBool()); - if(m.contains("lsd")) + if (m.contains("lsd")) pref.setLSDEnabled(m["lsd"].toBool()); - if(m.contains("encryption")) + if (m.contains("encryption")) pref.setEncryptionSetting(m["encryption"].toInt()); #if LIBTORRENT_VERSION_MINOR >= 16 - if(m.contains("anonymous_mode")) + if (m.contains("anonymous_mode")) pref.enableAnonymousMode(m["anonymous_mode"].toBool()); #endif // Proxy - if(m.contains("proxy_type")) + if (m.contains("proxy_type")) pref.setProxyType(m["proxy_type"].toInt()); - if(m.contains("proxy_ip")) + if (m.contains("proxy_ip")) pref.setProxyIp(m["proxy_ip"].toString()); - if(m.contains("proxy_port")) + if (m.contains("proxy_port")) pref.setProxyPort(m["proxy_port"].toUInt()); - if(m.contains("proxy_peer_connections")) + if (m.contains("proxy_peer_connections")) pref.setProxyPeerConnections(m["proxy_peer_connections"].toBool()); - if(m.contains("proxy_auth_enabled")) + if (m.contains("proxy_auth_enabled")) pref.setProxyAuthEnabled(m["proxy_auth_enabled"].toBool()); - if(m.contains("proxy_username")) + if (m.contains("proxy_username")) pref.setProxyUsername(m["proxy_username"].toString()); - if(m.contains("proxy_password")) + if (m.contains("proxy_password")) pref.setProxyPassword(m["proxy_password"].toString()); // IP Filter - if(m.contains("ip_filter_enabled")) + if (m.contains("ip_filter_enabled")) pref.setFilteringEnabled(m["ip_filter_enabled"].toBool()); - if(m.contains("ip_filter_path")) + if (m.contains("ip_filter_path")) pref.setFilter(m["ip_filter_path"].toString()); // Web UI - if(m.contains("web_ui_port")) + if (m.contains("web_ui_port")) pref.setWebUiPort(m["web_ui_port"].toUInt()); - if(m.contains("web_ui_username")) + if (m.contains("web_ui_username")) pref.setWebUiUsername(m["web_ui_username"].toString()); - if(m.contains("web_ui_password")) + if (m.contains("web_ui_password")) pref.setWebUiPassword(m["web_ui_password"].toString()); - if(m.contains("bypass_local_auth")) + if (m.contains("bypass_local_auth")) pref.setWebUiLocalAuthEnabled(!m["bypass_local_auth"].toBool()); - if(m.contains("use_https")) + if (m.contains("use_https")) pref.setWebUiHttpsEnabled(m["use_https"].toBool()); #ifndef QT_NO_OPENSSL - if(m.contains("ssl_key")) { + if (m.contains("ssl_key")) { QByteArray raw_key = m["ssl_key"].toString().toAscii(); if (!QSslKey(raw_key, QSsl::Rsa).isNull()) pref.setWebUiHttpsKey(raw_key); } - if(m.contains("ssl_cert")) { + if (m.contains("ssl_cert")) { QByteArray raw_cert = m["ssl_cert"].toString().toAscii(); if (!QSslCertificate(raw_cert).isNull()) pref.setWebUiHttpsCertificate(raw_cert); } #endif // Dyndns - if(m.contains("dyndns_enabled")) + if (m.contains("dyndns_enabled")) pref.setDynDNSEnabled(m["dyndns_enabled"].toBool()); - if(m.contains("dyndns_service")) + if (m.contains("dyndns_service")) pref.setDynDNSService(m["dyndns_service"].toInt()); - if(m.contains("dyndns_username")) + if (m.contains("dyndns_username")) pref.setDynDNSUsername(m["dyndns_username"].toString()); - if(m.contains("dyndns_password")) + if (m.contains("dyndns_password")) pref.setDynDNSPassword(m["dyndns_password"].toString()); - if(m.contains("dyndns_domain")) + if (m.contains("dyndns_domain")) pref.setDynDomainName(m["dyndns_domain"].toString()); // Reload preferences QBtSession::instance()->configureSession(); @@ -326,7 +326,7 @@ QVariantMap EventManager::getGlobalPreferences() const { data["temp_path"] = pref.getTempPath(); data["scan_dirs"] = pref.getScanDirs(); QVariantList var_list; - foreach(bool b, pref.getDownloadInScanDirs()) { + foreach (bool b, pref.getDownloadInScanDirs()) { var_list << b; } data["download_in_scan_dirs"] = var_list; @@ -412,10 +412,10 @@ QVariantMap EventManager::getGlobalPreferences() const { QVariantMap EventManager::getPropGeneralInfo(QString hash) const { QVariantMap data; QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(h.is_valid() && h.has_metadata()) { + if (h.is_valid() && h.has_metadata()) { // Save path QString p = TorrentPersistentData::getSavePath(hash); - if(p.isEmpty()) p = h.save_path(); + if (p.isEmpty()) p = h.save_path(); data["save_path"] = p; // Creation date data["creation_date"] = h.creation_date(); @@ -426,23 +426,23 @@ QVariantMap EventManager::getPropGeneralInfo(QString hash) const { data["total_wasted"] = QVariant(misc::friendlyUnit(h.total_failed_bytes()+h.total_redundant_bytes())); data["total_uploaded"] = QVariant(misc::friendlyUnit(h.all_time_upload()) + " ("+misc::friendlyUnit(h.total_payload_upload())+" "+tr("this session")+")"); data["total_downloaded"] = QVariant(misc::friendlyUnit(h.all_time_download()) + " ("+misc::friendlyUnit(h.total_payload_download())+" "+tr("this session")+")"); - if(h.upload_limit() <= 0) + if (h.upload_limit() <= 0) data["up_limit"] = QString::fromUtf8("∞"); else data["up_limit"] = QVariant(misc::friendlyUnit(h.upload_limit())+tr("/s", "/second (i.e. per second)")); - if(h.download_limit() <= 0) + if (h.download_limit() <= 0) data["dl_limit"] = QString::fromUtf8("∞"); else data["dl_limit"] = QVariant(misc::friendlyUnit(h.download_limit())+tr("/s", "/second (i.e. per second)")); QString elapsed_txt = misc::userFriendlyDuration(h.active_time()); - if(h.is_seed()) { + if (h.is_seed()) { elapsed_txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(misc::userFriendlyDuration(h.seeding_time()))+")"; } data["time_elapsed"] = elapsed_txt; data["nb_connections"] = QVariant(QString::number(h.num_connections())+" ("+tr("%1 max", "e.g. 10 max").arg(QString::number(h.connections_limit()))+")"); // Update ratio info qreal ratio = QBtSession::instance()->getRealRatio(h.hash()); - if(ratio > 100.) + if (ratio > 100.) data["share_ratio"] = QString::fromUtf8("∞"); else data["share_ratio"] = QString(QByteArray::number(ratio, 'f', 1)); @@ -465,18 +465,18 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h) QString hash = h.hash(); QVariantMap event; event["eta"] = QVariant(QString::fromUtf8("∞")); - if(h.is_paused()) { - if(h.has_error()) { + if (h.is_paused()) { + if (h.has_error()) { event["state"] = QVariant("error"); } else { - if(h.is_seed()) + if (h.is_seed()) event["state"] = QVariant("pausedUP"); else event["state"] = QVariant("pausedDL"); } } else { - if(QBtSession::instance()->isQueueingEnabled() && h.is_queued()) { - if(h.is_seed()) + if (QBtSession::instance()->isQueueingEnabled() && h.is_queued()) { + if (h.is_seed()) event["state"] = QVariant("queuedUP"); else event["state"] = QVariant("queuedDL"); @@ -485,7 +485,7 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h) { case torrent_status::finished: case torrent_status::seeding: - if(h.upload_payload_rate() > 0) { + if (h.upload_payload_rate() > 0) { event["state"] = QVariant("uploading"); } else { event["state"] = QVariant("stalledUP"); @@ -495,7 +495,7 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h) case torrent_status::checking_files: case torrent_status::queued_for_checking: case torrent_status::checking_resume_data: - if(h.is_seed()) { + if (h.is_seed()) { event["state"] = QVariant("checkingUP"); } else { event["state"] = QVariant("checkingDL"); @@ -503,7 +503,7 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h) break; case torrent_status::downloading: case torrent_status::downloading_metadata: - if(h.download_payload_rate() > 0) + if (h.download_payload_rate() > 0) event["state"] = QVariant("downloading"); else event["state"] = QVariant("stalledDL"); @@ -519,8 +519,8 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h) event["size"] = QVariant(misc::friendlyUnit(h.actual_size())); event["progress"] = QVariant((double)h.progress()); event["dlspeed"] = QVariant(tr("%1/s", "e.g. 120 KiB/s").arg(misc::friendlyUnit(h.download_payload_rate()))); - if(QBtSession::instance()->isQueueingEnabled()) { - if(h.queue_position() >= 0) + if (QBtSession::instance()->isQueueingEnabled()) { + if (h.queue_position() >= 0) event["priority"] = QVariant(QString::number(h.queue_position())); else event["priority"] = "*"; @@ -529,16 +529,16 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h) } event["upspeed"] = QVariant(tr("%1/s", "e.g. 120 KiB/s").arg(misc::friendlyUnit(h.upload_payload_rate()))); QString seeds = QString::number(h.num_seeds()); - if(h.num_complete() > 0) + if (h.num_complete() > 0) seeds += " ("+QString::number(h.num_complete())+")"; event["num_seeds"] = QVariant(seeds); QString leechs = QString::number(h.num_peers()-h.num_seeds()); - if(h.num_incomplete() > 0) + if (h.num_incomplete() > 0) leechs += " ("+QString::number(h.num_incomplete())+")"; event["num_leechs"] = QVariant(leechs); event["seed"] = QVariant(h.is_seed()); qreal ratio = QBtSession::instance()->getRealRatio(hash); - if(ratio > 100.) + if (ratio > 100.) event["ratio"] = QString::fromUtf8("∞"); else event["ratio"] = QVariant(QString::number(ratio, 'f', 1)); diff --git a/src/webui/httpconnection.cpp b/src/webui/httpconnection.cpp index 0eeb1363d..9a78a6516 100644 --- a/src/webui/httpconnection.cpp +++ b/src/webui/httpconnection.cpp @@ -120,7 +120,7 @@ void HttpConnection::read() { m_parser.writeMessage(message); } - if(m_parser.isError()) { + if (m_parser.isError()) { qDebug() << Q_FUNC_INFO << "message parsing error"; m_generator.setStatusLine(400, "Bad Request"); write(); @@ -150,7 +150,7 @@ void HttpConnection::translateDocument(QString& data) { found = false; i = regex.indexIn(data, i); - if(i >= 0) { + if (i >= 0) { //qDebug("Found translatable string: %s", regex.cap(1).toUtf8().data()); QByteArray word = regex.cap(1).toLocal8Bit(); @@ -173,20 +173,20 @@ void HttpConnection::translateDocument(QString& data) { } void HttpConnection::respond() { - if((m_socket->peerAddress() != QHostAddress::LocalHost + if ((m_socket->peerAddress() != QHostAddress::LocalHost && m_socket->peerAddress() != QHostAddress::LocalHostIPv6) || m_httpserver->isLocalAuthEnabled()) { // Authentication const QString peer_ip = m_socket->peerAddress().toString(); const int nb_fail = m_httpserver->NbFailedAttemptsForIp(peer_ip); - if(nb_fail >= MAX_AUTH_FAILED_ATTEMPTS) { + if (nb_fail >= MAX_AUTH_FAILED_ATTEMPTS) { m_generator.setStatusLine(403, "Forbidden"); m_generator.setMessage(tr("Your IP address has been banned after too many failed authentication attempts.")); write(); return; } QString auth = m_parser.header().value("Authorization"); - if(auth.isEmpty()) { + if (auth.isEmpty()) { // Return unauthorized header qDebug("Auth is Empty..."); m_generator.setStatusLine(401, "Unauthorized"); @@ -211,10 +211,10 @@ void HttpConnection::respond() { } QString url = m_parser.url(); // Favicon - if(url.endsWith("favicon.ico")) { + if (url.endsWith("favicon.ico")) { qDebug("Returning favicon"); QFile favicon(":/Icons/skin/qbittorrent16.png"); - if(favicon.open(QIODevice::ReadOnly)) { + if (favicon.open(QIODevice::ReadOnly)) { QByteArray data = favicon.readAll(); favicon.close(); m_generator.setStatusLine(200, "OK"); @@ -242,28 +242,28 @@ void HttpConnection::respond() { respondJson(); return; } - if(list.size() > 2) { - if(list[1] == "propertiesGeneral") { + if (list.size() > 2) { + if (list[1] == "propertiesGeneral") { const QString& hash = list[2]; respondGenPropertiesJson(hash); return; } - if(list[1] == "propertiesTrackers") { + if (list[1] == "propertiesTrackers") { const QString& hash = list[2]; respondTrackersPropertiesJson(hash); return; } - if(list[1] == "propertiesFiles") { + if (list[1] == "propertiesFiles") { const QString& hash = list[2]; respondFilesPropertiesJson(hash); return; } } else { - if(list[1] == "preferences") { + if (list[1] == "preferences") { respondPreferencesJson(); return; } else { - if(list[1] == "transferInfo") { + if (list[1] == "transferInfo") { respondGlobalTransferInfoJson(); return; } @@ -281,7 +281,7 @@ void HttpConnection::respond() { // Icons from theme qDebug() << "list[0]" << list[0]; - if(list[0] == "theme" && list.size() == 2) { + if (list[0] == "theme" && list.size() == 2) { #ifdef DISABLE_GUI url = ":/Icons/oxygen/"+list[1]+".png"; #else @@ -292,14 +292,14 @@ void HttpConnection::respond() { if (list[0] == "images") { list[0] = "Icons"; } else { - if(list.last().endsWith(".html")) + if (list.last().endsWith(".html")) list.prepend("html"); list.prepend("webui"); } url = ":/" + list.join("/"); } QFile file(url); - if(!file.open(QIODevice::ReadOnly)) { + if (!file.open(QIODevice::ReadOnly)) { qDebug("File %s was not found!", qPrintable(url)); respondNotFound(); return; @@ -314,7 +314,7 @@ void HttpConnection::respond() { file.close(); // Translate the page - if(ext == "html" || (ext == "js" && !list.last().startsWith("excanvas"))) { + if (ext == "html" || (ext == "js" && !list.last().startsWith("excanvas"))) { QString dataStr = QString::fromUtf8(data.constData()); translateDocument(dataStr); if (url.endsWith("about.html")) { @@ -391,17 +391,17 @@ void HttpConnection::respondGlobalTransferInfoJson() { } void HttpConnection::respondCommand(const QString& command) { - if(command == "download") { + if (command == "download") { QString urls = m_parser.post("urls"); QStringList list = urls.split('\n'); - foreach(QString url, list){ + foreach (QString url, list){ url = url.trimmed(); - if(!url.isEmpty()){ - if(url.startsWith("bc://bt/", Qt::CaseInsensitive)) { + if (!url.isEmpty()){ + if (url.startsWith("bc://bt/", Qt::CaseInsensitive)) { qDebug("Converting bc link to magnet link"); url = misc::bcLinkToMagnet(url); } - if(url.startsWith("magnet:", Qt::CaseInsensitive)) { + if (url.startsWith("magnet:", Qt::CaseInsensitive)) { emit MagnetReadyToBeDownloaded(url); } else { qDebug("Downloading url: %s", (const char*)url.toLocal8Bit()); @@ -412,14 +412,14 @@ void HttpConnection::respondCommand(const QString& command) { return; } - if(command == "addTrackers") { + if (command == "addTrackers") { QString hash = m_parser.post("hash"); - if(!hash.isEmpty()) { + if (!hash.isEmpty()) { QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(h.is_valid() && h.has_metadata()) { + if (h.is_valid() && h.has_metadata()) { QString urls = m_parser.post("urls"); QStringList list = urls.split('\n'); - foreach(const QString& url, list) { + foreach (const QString& url, list) { announce_entry e(url.toStdString()); h.add_tracker(e); } @@ -427,7 +427,7 @@ void HttpConnection::respondCommand(const QString& command) { } return; } - if(command == "upload") { + if (command == "upload") { qDebug() << Q_FUNC_INFO << "upload"; // Get a unique filename QTemporaryFile *tmpfile = new QTemporaryFile (QDir::temp().absoluteFilePath("qBT-XXXXXX.torrent")); @@ -454,35 +454,35 @@ void HttpConnection::respondCommand(const QString& command) { write(); return; } - if(command == "resumeall") { + if (command == "resumeall") { emit resumeAllTorrents(); return; } - if(command == "pauseall") { + if (command == "pauseall") { emit pauseAllTorrents(); return; } - if(command == "resume") { + if (command == "resume") { emit resumeTorrent(m_parser.post("hash")); return; } - if(command == "setPreferences") { + if (command == "setPreferences") { QString json_str = m_parser.post("json"); EventManager* manager = m_httpserver->eventManager(); manager->setGlobalPreferences(json::fromJson(json_str)); return; } - if(command == "setFilePrio") { + if (command == "setFilePrio") { QString hash = m_parser.post("hash"); int file_id = m_parser.post("id").toInt(); int priority = m_parser.post("priority").toInt(); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(h.is_valid() && h.has_metadata()) { + if (h.is_valid() && h.has_metadata()) { h.file_priority(file_id, priority); } return; } - if(command == "getGlobalUpLimit") { + if (command == "getGlobalUpLimit") { m_generator.setStatusLine(200, "OK"); m_generator.setContentTypeByExt("html"); #if LIBTORRENT_VERSION_MINOR > 15 @@ -493,7 +493,7 @@ void HttpConnection::respondCommand(const QString& command) { write(); return; } - if(command == "getGlobalDlLimit") { + if (command == "getGlobalDlLimit") { m_generator.setStatusLine(200, "OK"); m_generator.setContentTypeByExt("html"); #if LIBTORRENT_VERSION_MINOR > 15 @@ -504,10 +504,10 @@ void HttpConnection::respondCommand(const QString& command) { write(); return; } - if(command == "getTorrentUpLimit") { + if (command == "getTorrentUpLimit") { QString hash = m_parser.post("hash"); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(h.is_valid()) { + if (h.is_valid()) { m_generator.setStatusLine(200, "OK"); m_generator.setContentTypeByExt("html"); m_generator.setMessage(QString::number(h.upload_limit())); @@ -515,10 +515,10 @@ void HttpConnection::respondCommand(const QString& command) { } return; } - if(command == "getTorrentDlLimit") { + if (command == "getTorrentDlLimit") { QString hash = m_parser.post("hash"); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(h.is_valid()) { + if (h.is_valid()) { m_generator.setStatusLine(200, "OK"); m_generator.setContentTypeByExt("html"); m_generator.setMessage(QString::number(h.download_limit())); @@ -526,81 +526,81 @@ void HttpConnection::respondCommand(const QString& command) { } return; } - if(command == "setTorrentUpLimit") { + if (command == "setTorrentUpLimit") { QString hash = m_parser.post("hash"); qlonglong limit = m_parser.post("limit").toLongLong(); - if(limit == 0) limit = -1; + if (limit == 0) limit = -1; QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(h.is_valid()) { + if (h.is_valid()) { h.set_upload_limit(limit); } return; } - if(command == "setTorrentDlLimit") { + if (command == "setTorrentDlLimit") { QString hash = m_parser.post("hash"); qlonglong limit = m_parser.post("limit").toLongLong(); - if(limit == 0) limit = -1; + if (limit == 0) limit = -1; QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(h.is_valid()) { + if (h.is_valid()) { h.set_download_limit(limit); } return; } - if(command == "setGlobalUpLimit") { + if (command == "setGlobalUpLimit") { qlonglong limit = m_parser.post("limit").toLongLong(); - if(limit == 0) limit = -1; + if (limit == 0) limit = -1; QBtSession::instance()->setUploadRateLimit(limit); Preferences().setGlobalUploadLimit(limit/1024.); return; } - if(command == "setGlobalDlLimit") { + if (command == "setGlobalDlLimit") { qlonglong limit = m_parser.post("limit").toLongLong(); - if(limit == 0) limit = -1; + if (limit == 0) limit = -1; QBtSession::instance()->setDownloadRateLimit(limit); Preferences().setGlobalDownloadLimit(limit/1024.); return; } - if(command == "pause") { + if (command == "pause") { emit pauseTorrent(m_parser.post("hash")); return; } - if(command == "delete") { + if (command == "delete") { QStringList hashes = m_parser.post("hashes").split("|"); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { emit deleteTorrent(hash, false); } return; } - if(command == "deletePerm") { + if (command == "deletePerm") { QStringList hashes = m_parser.post("hashes").split("|"); - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { emit deleteTorrent(hash, true); } return; } - if(command == "increasePrio") { + if (command == "increasePrio") { increaseTorrentsPriority(m_parser.post("hashes").split("|")); return; } - if(command == "decreasePrio") { + if (command == "decreasePrio") { decreaseTorrentsPriority(m_parser.post("hashes").split("|")); return; } - if(command == "topPrio") { - foreach(const QString &hash, m_parser.post("hashes").split("|")) { + if (command == "topPrio") { + foreach (const QString &hash, m_parser.post("hashes").split("|")) { QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(h.is_valid()) h.queue_position_top(); + if (h.is_valid()) h.queue_position_top(); } return; } - if(command == "bottomPrio") { - foreach(const QString &hash, m_parser.post("hashes").split("|")) { + if (command == "bottomPrio") { + foreach (const QString &hash, m_parser.post("hashes").split("|")) { QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(h.is_valid()) h.queue_position_bottom(); + if (h.is_valid()) h.queue_position_bottom(); } return; } - if(command == "recheck"){ + if (command == "recheck"){ QBtSession::instance()->recheckTorrent(m_parser.post("hash")); return; } @@ -612,10 +612,10 @@ void HttpConnection::decreaseTorrentsPriority(const QStringList &hashes) { std::vector >, std::less > > torrent_queue; // Sort torrents by priority - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { try { QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(!h.is_seed()) { + if (!h.is_seed()) { torrent_queue.push(qMakePair(h.queue_position(), h)); } }catch(invalid_handle&){} @@ -637,10 +637,10 @@ void HttpConnection::increaseTorrentsPriority(const QStringList &hashes) std::vector >, std::greater > > torrent_queue; // Sort torrents by priority - foreach(const QString &hash, hashes) { + foreach (const QString &hash, hashes) { try { QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); - if(!h.is_seed()) { + if (!h.is_seed()) { torrent_queue.push(qMakePair(h.queue_position(), h)); } }catch(invalid_handle&){} diff --git a/src/webui/httprequestparser.cpp b/src/webui/httprequestparser.cpp index 01301ef13..f0ba21598 100644 --- a/src/webui/httprequestparser.cpp +++ b/src/webui/httprequestparser.cpp @@ -87,7 +87,7 @@ void HttpRequestParser::writeMessage(const QByteArray& ba) { qDebug() << Q_FUNC_INFO << "m_data.size(): " << m_data.size(); // Parse POST data - if(m_header.contentType() == "application/x-www-form-urlencoded") { + if (m_header.contentType() == "application/x-www-form-urlencoded") { QUrl url; url.setEncodedQuery(m_data); QListIterator > i(url.queryItems()); diff --git a/src/webui/httpresponsegenerator.cpp b/src/webui/httpresponsegenerator.cpp index c18512971..37c4840b7 100644 --- a/src/webui/httpresponsegenerator.cpp +++ b/src/webui/httpresponsegenerator.cpp @@ -42,23 +42,23 @@ void HttpResponseGenerator::setMessage(const QString& message) { } void HttpResponseGenerator::setContentTypeByExt(const QString& ext) { - if(ext == "css") { + if (ext == "css") { setContentType("text/css"); return; } - if(ext == "gif") { + if (ext == "gif") { setContentType("image/gif"); return; } - if(ext == "htm" || ext == "html") { + if (ext == "htm" || ext == "html") { setContentType("text/html"); return; } - if(ext == "js") { + if (ext == "js") { setContentType("text/javascript"); return; } - if(ext == "png") { + if (ext == "png") { setContentType("image/x-png"); return; } diff --git a/src/webui/httpserver.cpp b/src/webui/httpserver.cpp index 1e2526ad6..303decfc5 100644 --- a/src/webui/httpserver.cpp +++ b/src/webui/httpserver.cpp @@ -76,7 +76,7 @@ int HttpServer::NbFailedAttemptsForIp(const QString& ip) const { void HttpServer::increaseNbFailedAttemptsForIp(const QString& ip) { const int nb_fail = m_clientFailedAttempts.value(ip, 0) + 1; m_clientFailedAttempts.insert(ip, nb_fail); - if(nb_fail == MAX_AUTH_FAILED_ATTEMPTS) { + if (nb_fail == MAX_AUTH_FAILED_ATTEMPTS) { // Max number of failed attempts reached // Start ban period UnbanTimer* ubantimer = new UnbanTimer(ip, this); @@ -112,9 +112,9 @@ HttpServer::HttpServer(int msec, QObject* parent) : QTcpServer(parent), // Add torrents std::vector torrents = QBtSession::instance()->getTorrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { QTorrentHandle h = QTorrentHandle(*torrentIT); - if(h.is_valid()) + if (h.is_valid()) m_eventManager->addedTorrent(h); } @@ -217,9 +217,9 @@ void HttpServer::handleNewConnection(QTcpSocket *socket) void HttpServer::onTimer() { std::vector torrents = QBtSession::instance()->getTorrents(); std::vector::iterator torrentIT; - for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { + for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { QTorrentHandle h = QTorrentHandle(*torrentIT); - if(h.is_valid()) + if (h.is_valid()) m_eventManager->modifiedTorrent(h); } } @@ -245,28 +245,28 @@ bool HttpServer::isAuthorized(const QByteArray& auth, //qDebug("AUTH string is %s", auth.data()); // Get user name QRegExp regex_user(".*username=\"([^\"]+)\".*"); // Must be a quoted string - if(regex_user.indexIn(auth) < 0) return false; + if (regex_user.indexIn(auth) < 0) return false; QString prop_user = regex_user.cap(1); //qDebug("AUTH: Proposed username is %s, real username is %s", prop_user.toLocal8Bit().data(), username.data()); - if(prop_user != m_username) { + if (prop_user != m_username) { // User name is invalid, we can reject already qDebug("AUTH-PROB: Username is invalid"); return false; } // Get realm QRegExp regex_realm(".*realm=\"([^\"]+)\".*"); // Must be a quoted string - if(regex_realm.indexIn(auth) < 0) { + if (regex_realm.indexIn(auth) < 0) { qDebug("AUTH-PROB: Missing realm"); return false; } QByteArray prop_realm = regex_realm.cap(1).toLocal8Bit(); - if(prop_realm != QBT_REALM) { + if (prop_realm != QBT_REALM) { qDebug("AUTH-PROB: Wrong realm"); return false; } // get nonce QRegExp regex_nonce(".*nonce=[\"]?([\\w=]+)[\"]?.*"); - if(regex_nonce.indexIn(auth) < 0) { + if (regex_nonce.indexIn(auth) < 0) { qDebug("AUTH-PROB: missing nonce"); return false; } @@ -274,7 +274,7 @@ bool HttpServer::isAuthorized(const QByteArray& auth, //qDebug("prop nonce is: %s", prop_nonce.data()); // get uri QRegExp regex_uri(".*uri=\"([^\"]+)\".*"); - if(regex_uri.indexIn(auth) < 0) { + if (regex_uri.indexIn(auth) < 0) { qDebug("AUTH-PROB: Missing uri"); return false; } @@ -282,7 +282,7 @@ bool HttpServer::isAuthorized(const QByteArray& auth, //qDebug("prop uri is: %s", prop_uri.data()); // get response QRegExp regex_response(".*response=[\"]?([\\w=]+)[\"]?.*"); - if(regex_response.indexIn(auth) < 0) { + if (regex_response.indexIn(auth) < 0) { qDebug("AUTH-PROB: Missing response"); return false; } @@ -293,25 +293,25 @@ bool HttpServer::isAuthorized(const QByteArray& auth, md5_ha2.addData(method.toLocal8Bit() + ":" + prop_uri); QByteArray ha2 = md5_ha2.result().toHex(); QByteArray response = ""; - if(auth.contains("qop=")) { + if (auth.contains("qop=")) { QCryptographicHash md5_ha(QCryptographicHash::Md5); // Get nc QRegExp regex_nc(".*nc=[\"]?([\\w=]+)[\"]?.*"); - if(regex_nc.indexIn(auth) < 0) { + if (regex_nc.indexIn(auth) < 0) { qDebug("AUTH-PROB: qop but missing nc"); return false; } QByteArray prop_nc = regex_nc.cap(1).toLocal8Bit(); //qDebug("prop nc is: %s", prop_nc.data()); QRegExp regex_cnonce(".*cnonce=[\"]?([\\w=]+)[\"]?.*"); - if(regex_cnonce.indexIn(auth) < 0) { + if (regex_cnonce.indexIn(auth) < 0) { qDebug("AUTH-PROB: qop but missing cnonce"); return false; } QByteArray prop_cnonce = regex_cnonce.cap(1).toLocal8Bit(); //qDebug("prop cnonce is: %s", prop_cnonce.data()); QRegExp regex_qop(".*qop=[\"]?(\\w+)[\"]?.*"); - if(regex_qop.indexIn(auth) < 0) { + if (regex_qop.indexIn(auth) < 0) { qDebug("AUTH-PROB: missing qop"); return false; } diff --git a/src/webui/json.h b/src/webui/json.h index 05ba18940..153a57077 100644 --- a/src/webui/json.h +++ b/src/webui/json.h @@ -51,7 +51,7 @@ namespace json { case QVariant::StringList: case QVariant::List: { QStringList strList; - foreach(const QVariant &var, v.toList()) { + foreach (const QVariant &var, v.toList()) { strList << toJson(var); } return "["+strList.join(",")+"]"; @@ -59,7 +59,7 @@ namespace json { case QVariant::String: { QString s = v.value(); QString result = "\""; - for(int i=0; i& v) { QStringList res; - foreach(QVariantMap m, v) { + foreach (QVariantMap m, v) { QStringList vlist; QVariantMap::ConstIterator it; - for(it = m.constBegin(); it != m.constEnd(); it++) { + for (it = m.constBegin(); it != m.constEnd(); it++) { vlist << toJson(it.key())+":"+toJson(it.value()); } res << "{"+vlist.join(",")+"}";