Coding style clean up

This commit is contained in:
Christophe Dumez 2012-02-20 19:30:53 +02:00
parent 9acac03f14
commit a8a7b61ea9
77 changed files with 2194 additions and 2194 deletions

View file

@ -100,7 +100,7 @@ class about : public QDialog, private Ui::AboutDlg{
// License // License
te_license->append(QString::fromUtf8("<a name='top'></a>")); te_license->append(QString::fromUtf8("<a name='top'></a>"));
QFile licensefile(":/gpl.html"); QFile licensefile(":/gpl.html");
if(licensefile.open(QIODevice::ReadOnly|QIODevice::Text)) { if (licensefile.open(QIODevice::ReadOnly|QIODevice::Text)) {
te_license->setHtml(licensefile.readAll()); te_license->setHtml(licensefile.readAll());
licensefile.close(); licensefile.close();
} }

View file

@ -59,7 +59,7 @@ class DeletionConfirmationDlg : public QDialog, private Ui::confirmDeletionDlg {
static bool askForDeletionConfirmation(bool *delete_local_files) { static bool askForDeletionConfirmation(bool *delete_local_files) {
DeletionConfirmationDlg dlg; DeletionConfirmationDlg dlg;
if(dlg.exec() == QDialog::Accepted) { if (dlg.exec() == QDialog::Accepted) {
*delete_local_files = dlg.shouldDeleteLocalFiles(); *delete_local_files = dlg.shouldDeleteLocalFiles();
return true; return true;
} }

View file

@ -50,7 +50,7 @@ DNSUpdater::DNSUpdater(QObject *parent) :
m_ipCheckTimer.start(); m_ipCheckTimer.start();
// Check lastUpdate to avoid flooding // Check lastUpdate to avoid flooding
if(!m_lastIPCheckTime.isValid() || if (!m_lastIPCheckTime.isValid() ||
m_lastIPCheckTime.secsTo(QDateTime::currentDateTime())*1000 > IP_CHECK_INTERVAL_MS) { m_lastIPCheckTime.secsTo(QDateTime::currentDateTime())*1000 > IP_CHECK_INTERVAL_MS) {
checkPublicIP(); checkPublicIP();
} }
@ -79,19 +79,19 @@ void DNSUpdater::checkPublicIP()
void DNSUpdater::ipRequestFinished(QNetworkReply *reply) void DNSUpdater::ipRequestFinished(QNetworkReply *reply)
{ {
qDebug() << Q_FUNC_INFO; qDebug() << Q_FUNC_INFO;
if(reply->error()) { if (reply->error()) {
// Error // Error
qWarning() << Q_FUNC_INFO << "Error:" << reply->errorString(); qWarning() << Q_FUNC_INFO << "Error:" << reply->errorString();
} else { } else {
// Parse response // Parse response
QRegExp ipregex("Current IP Address:\\s+([^<]+)</body>"); QRegExp ipregex("Current IP Address:\\s+([^<]+)</body>");
QString ret = reply->readAll(); QString ret = reply->readAll();
if(ipregex.indexIn(ret) >= 0) { if (ipregex.indexIn(ret) >= 0) {
QString ip_str = ipregex.cap(1); QString ip_str = ipregex.cap(1);
qDebug() << Q_FUNC_INFO << "Regular expression captured the following IP:" << ip_str; qDebug() << Q_FUNC_INFO << "Regular expression captured the following IP:" << ip_str;
QHostAddress new_ip(ip_str); QHostAddress new_ip(ip_str);
if(!new_ip.isNull()) { if (!new_ip.isNull()) {
if(m_lastIP != new_ip) { if (m_lastIP != new_ip) {
qDebug() << Q_FUNC_INFO << "The IP address changed, report the change to DynDNS..."; qDebug() << Q_FUNC_INFO << "The IP address changed, report the change to DynDNS...";
qDebug() << m_lastIP.toString() << "->" << new_ip.toString(); qDebug() << m_lastIP.toString() << "->" << new_ip.toString();
m_lastIP = new_ip; m_lastIP = new_ip;
@ -157,7 +157,7 @@ QUrl DNSUpdater::getUpdateUrl() const
void DNSUpdater::ipUpdateFinished(QNetworkReply *reply) void DNSUpdater::ipUpdateFinished(QNetworkReply *reply)
{ {
if(reply->error()) { if (reply->error()) {
// Error // Error
qWarning() << Q_FUNC_INFO << "Error:" << reply->errorString(); qWarning() << Q_FUNC_INFO << "Error:" << reply->errorString();
} else { } else {
@ -174,11 +174,11 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
qDebug() << Q_FUNC_INFO << reply; qDebug() << Q_FUNC_INFO << reply;
QString code = reply.split(" ").first(); QString code = reply.split(" ").first();
qDebug() << Q_FUNC_INFO << "Code:" << code; 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"); QBtSession::instance()->addConsoleMessage(tr("Your dynamic DNS was successfuly updated."), "green");
return; 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."), QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: The service is temporarily unavailable, it will be retried in 30 minutes."),
"red"); "red");
m_lastIP.clear(); 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 // Everything bellow is an error, stop updating until the user updates something
m_ipCheckTimer.stop(); m_ipCheckTimer.stop();
m_lastIP.clear(); m_lastIP.clear();
if(code == "nohost") { if (code == "nohost") {
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: hostname supplied does not exist under specified account."), QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: hostname supplied does not exist under specified account."),
"red"); "red");
m_state = INVALID_CREDS; m_state = INVALID_CREDS;
return; return;
} }
if(code == "badauth") { if (code == "badauth") {
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: Invalid username/password."), "red"); QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: Invalid username/password."), "red");
m_state = INVALID_CREDS; m_state = INVALID_CREDS;
return; 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."), QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: qBittorrent was blacklisted by the service, please report a bug at http://bugs.qbittorrent.org."),
"red"); "red");
m_state = FATAL; m_state = FATAL;
return; 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"), 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"); "red");
m_state = FATAL; m_state = FATAL;
return; return;
} }
if(code == "abuse") { if (code == "abuse") {
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: Your username was blocked due to abuse."), QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: Your username was blocked due to abuse."),
"red"); "red");
m_state = FATAL; m_state = FATAL;
@ -221,18 +221,18 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
void DNSUpdater::updateCredentials() void DNSUpdater::updateCredentials()
{ {
if(m_state == FATAL) return; if (m_state == FATAL) return;
Preferences pref; Preferences pref;
bool change = false; bool change = false;
// Get DNS service information // Get DNS service information
if(m_service != pref.getDynDNSService()) { if (m_service != pref.getDynDNSService()) {
m_service = pref.getDynDNSService(); m_service = pref.getDynDNSService();
change = true; change = true;
} }
if(m_domain != pref.getDynDomainName()) { if (m_domain != pref.getDynDomainName()) {
m_domain = pref.getDynDomainName(); m_domain = pref.getDynDomainName();
QRegExp domain_regex("^(?:(?!\\d|-)[a-zA-Z0-9\\-]{1,63}\\.)+[a-zA-Z]{2,}$"); 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."), QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied domain name is invalid."),
"red"); "red");
m_lastIP.clear(); m_lastIP.clear();
@ -242,9 +242,9 @@ void DNSUpdater::updateCredentials()
} }
change = true; change = true;
} }
if(m_username != pref.getDynDNSUsername()) { if (m_username != pref.getDynDNSUsername()) {
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."), QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied username is too short."),
"red"); "red");
m_lastIP.clear(); m_lastIP.clear();
@ -254,9 +254,9 @@ void DNSUpdater::updateCredentials()
} }
change = true; change = true;
} }
if(m_password != pref.getDynDNSPassword()) { if (m_password != pref.getDynDNSPassword()) {
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."), QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied password is too short."),
"red"); "red");
m_lastIP.clear(); m_lastIP.clear();
@ -267,7 +267,7 @@ void DNSUpdater::updateCredentials()
change = true; change = true;
} }
if(m_state == INVALID_CREDS && change) { if (m_state == INVALID_CREDS && change) {
m_state = OK; // Try again m_state = OK; // Try again
m_ipCheckTimer.start(); m_ipCheckTimer.start();
checkPublicIP(); checkPublicIP();

View file

@ -50,7 +50,7 @@ class downloadFromURL : public QDialog, private Ui::downloadFromURL{
show(); show();
// Paste clipboard if there is an URL in it // Paste clipboard if there is an URL in it
QString clip_txt = qApp->clipboard()->text(); 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); textUrls->setText(clip_txt);
} }
} }
@ -66,15 +66,15 @@ class downloadFromURL : public QDialog, private Ui::downloadFromURL{
QStringList url_list = urls.split(QString::fromUtf8("\n")); QStringList url_list = urls.split(QString::fromUtf8("\n"));
QString url; QString url;
QStringList url_list_cleaned; QStringList url_list_cleaned;
foreach(url, url_list){ foreach (url, url_list){
url = url.trimmed(); url = url.trimmed();
if(!url.isEmpty()){ if (!url.isEmpty()){
if(url_list_cleaned.indexOf(QRegExp(url, Qt::CaseInsensitive, QRegExp::FixedString)) < 0){ if (url_list_cleaned.indexOf(QRegExp(url, Qt::CaseInsensitive, QRegExp::FixedString)) < 0){
url_list_cleaned << url; 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.")); QMessageBox::critical(0, tr("No URL entered"), tr("Please type at least one URL."));
return; return;
} }

View file

@ -55,7 +55,7 @@ void DownloadThread::processDlFinished(QNetworkReply* reply) {
QString url = reply->url().toString(); QString url = reply->url().toString();
qDebug("Download finished: %s", qPrintable(url)); qDebug("Download finished: %s", qPrintable(url));
// Check if the request was successful // Check if the request was successful
if(reply->error() != QNetworkReply::NoError) { if (reply->error() != QNetworkReply::NoError) {
// Failure // Failure
qDebug("Download failure (%s), reason: %s", qPrintable(url), qPrintable(errorCodeToString(reply->error()))); qDebug("Download failure (%s), reason: %s", qPrintable(url), qPrintable(errorCodeToString(reply->error())));
emit downloadFailure(url, 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 // Check if the server ask us to redirect somewhere lese
const QVariant redirection = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); const QVariant redirection = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if(redirection.isValid()) { if (redirection.isValid()) {
// We should redirect // We should redirect
QUrl newUrl = redirection.toUrl(); QUrl newUrl = redirection.toUrl();
// Resolve relative urls // Resolve relative urls
@ -78,7 +78,7 @@ void DownloadThread::processDlFinished(QNetworkReply* reply) {
return; return;
} }
// Checking if it was redirected, restoring initial URL // Checking if it was redirected, restoring initial URL
if(m_redirectMapping.contains(url)) { if (m_redirectMapping.contains(url)) {
url = m_redirectMapping.take(url); url = m_redirectMapping.take(url);
} }
// Success // Success
@ -87,7 +87,7 @@ void DownloadThread::processDlFinished(QNetworkReply* reply) {
if (tmpfile->open()) { if (tmpfile->open()) {
QString filePath = tmpfile->fileName(); QString filePath = tmpfile->fileName();
qDebug("Temporary filename is: %s", qPrintable(filePath)); 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 // TODO: Support GZIP compression
tmpfile->write(reply->readAll()); tmpfile->write(reply->readAll());
tmpfile->close(); tmpfile->close();
@ -115,9 +115,9 @@ void DownloadThread::loadCookies(const QString &host_name, QString url) {
QNetworkCookieJar *cookie_jar = m_networkManager.cookieJar(); QNetworkCookieJar *cookie_jar = m_networkManager.cookieJar();
QList<QNetworkCookie> cookies; QList<QNetworkCookie> cookies;
qDebug("Loading cookies for host name: %s", qPrintable(host_name)); 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<QByteArray> cookie_parts = raw_cookie.split('='); QList<QByteArray> cookie_parts = raw_cookie.split('=');
if(cookie_parts.size() == 2) { if (cookie_parts.size() == 2) {
qDebug("Loading cookie: %s", raw_cookie.constData()); qDebug("Loading cookie: %s", raw_cookie.constData());
cookies << QNetworkCookie(cookie_parts.first(), cookie_parts.last()); cookies << QNetworkCookie(cookie_parts.first(), cookie_parts.last());
} }
@ -139,7 +139,7 @@ QNetworkReply* DownloadThread::downloadUrl(const QString &url){
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
// Load cookies // Load cookies
QString host_name = QUrl::fromEncoded(url.toUtf8()).host(); QString host_name = QUrl::fromEncoded(url.toUtf8()).host();
if(!host_name.isEmpty()) if (!host_name.isEmpty())
loadCookies(host_name, url); loadCookies(host_name, url);
#endif #endif
// Process download request // 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"); 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("Downloading %s...", request.url().toEncoded().data());
qDebug("%d cookies for this URL", m_networkManager.cookieJar()->cookiesForUrl(url).size()); qDebug("%d cookies for this URL", m_networkManager.cookieJar()->cookiesForUrl(url).size());
for(int i=0; i<m_networkManager.cookieJar()->cookiesForUrl(url).size(); ++i) { for (int i=0; i<m_networkManager.cookieJar()->cookiesForUrl(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("%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())); 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) { void DownloadThread::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal) {
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if(!reply) return; if (!reply) return;
if(bytesTotal > 0) { if (bytesTotal > 0) {
// Total number of bytes is available // Total number of bytes is available
if(bytesTotal > 1048576) { if (bytesTotal > 1048576) {
// More than 1MB, this is probably not a torrent file, aborting... // More than 1MB, this is probably not a torrent file, aborting...
reply->abort(); reply->abort();
reply->deleteLater(); reply->deleteLater();
@ -171,7 +171,7 @@ void DownloadThread::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal)
disconnect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(checkDownloadSize(qint64,qint64))); disconnect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(checkDownloadSize(qint64,qint64)));
} }
} else { } else {
if(bytesReceived > 1048576) { if (bytesReceived > 1048576) {
// More than 1MB, this is probably not a torrent file, aborting... // More than 1MB, this is probably not a torrent file, aborting...
reply->abort(); reply->abort();
reply->deleteLater(); reply->deleteLater();
@ -182,13 +182,13 @@ void DownloadThread::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal)
void DownloadThread::applyProxySettings() { void DownloadThread::applyProxySettings() {
QNetworkProxy proxy; QNetworkProxy proxy;
const Preferences pref; const Preferences pref;
if(pref.isProxyEnabled()) { if (pref.isProxyEnabled()) {
// Proxy enabled // Proxy enabled
proxy.setHostName(pref.getProxyIp()); proxy.setHostName(pref.getProxyIp());
proxy.setPort(pref.getProxyPort()); proxy.setPort(pref.getProxyPort());
// Default proxy type is HTTP, we must change if it is SOCKS5 // Default proxy type is HTTP, we must change if it is SOCKS5
const int proxy_type = pref.getProxyType(); 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"; qDebug() << Q_FUNC_INFO << "using SOCKS proxy";
proxy.setType(QNetworkProxy::Socks5Proxy); proxy.setType(QNetworkProxy::Socks5Proxy);
} else { } else {
@ -196,7 +196,7 @@ void DownloadThread::applyProxySettings() {
proxy.setType(QNetworkProxy::HttpProxy); proxy.setType(QNetworkProxy::HttpProxy);
} }
// Authentication? // Authentication?
if(pref.isProxyAuthEnabled()) { if (pref.isProxyAuthEnabled()) {
qDebug("Proxy requires authentication, authenticating"); qDebug("Proxy requires authentication, authenticating");
proxy.setUser(pref.getProxyUsername()); proxy.setUser(pref.getProxyUsername());
proxy.setPassword(pref.getProxyPassword()); proxy.setPassword(pref.getProxyPassword());

View file

@ -50,10 +50,10 @@ ExecutionLog::ExecutionLog(QWidget *parent) :
ui->tabBan->layout()->addWidget(m_banList); ui->tabBan->layout()->addWidget(m_banList);
const QStringList log_msgs = QBtSession::instance()->getConsoleMessages(); const QStringList log_msgs = QBtSession::instance()->getConsoleMessages();
foreach(const QString& msg, log_msgs) foreach (const QString& msg, log_msgs)
addLogMessage(msg); addLogMessage(msg);
const QStringList ban_msgs = QBtSession::instance()->getPeerBanMessages(); const QStringList ban_msgs = QBtSession::instance()->getPeerBanMessages();
foreach(const QString& msg, ban_msgs) foreach (const QString& msg, ban_msgs)
addBanMessage(msg); addBanMessage(msg);
connect(QBtSession::instance(), SIGNAL(newConsoleMessage(QString)), SLOT(addLogMessage(QString))); connect(QBtSession::instance(), SIGNAL(newConsoleMessage(QString)), SLOT(addLogMessage(QString)));
connect(QBtSession::instance(), SIGNAL(newBanMessage(QString)), SLOT(addBanMessage(QString))); connect(QBtSession::instance(), SIGNAL(newBanMessage(QString)), SLOT(addBanMessage(QString)));

View file

@ -59,11 +59,11 @@ private:
private: private:
static bool isNetworkFileSystem(QString path) { static bool isNetworkFileSystem(QString path) {
QString file = path; QString file = path;
if(!file.endsWith(QDir::separator())) if (!file.endsWith(QDir::separator()))
file += QDir::separator(); file += QDir::separator();
file += "."; file += ".";
struct statfs buf; struct statfs buf;
if(!statfs(file.toLocal8Bit().constData(), &buf)) { if (!statfs(file.toLocal8Bit().constData(), &buf)) {
#ifdef Q_WS_MAC #ifdef Q_WS_MAC
// XXX: should we make sure HAVE_STRUCT_FSSTAT_F_FSTYPENAME is defined? // 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); 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() { ~FileSystemWatcher() {
#ifndef Q_WS_WIN #ifndef Q_WS_WIN
if(watch_timer) if (watch_timer)
delete watch_timer; delete watch_timer;
#endif #endif
if(m_partialTorrentTimer) if (m_partialTorrentTimer)
delete m_partialTorrentTimer; delete m_partialTorrentTimer;
} }
QStringList directories() const { QStringList directories() const {
QStringList dirs; QStringList dirs;
#ifndef Q_WS_WIN #ifndef Q_WS_WIN
if(watch_timer) { if (watch_timer) {
foreach (const QDir &dir, watched_folders) foreach (const QDir &dir, watched_folders)
dirs << dir.canonicalPath(); dirs << dir.canonicalPath();
} }
@ -149,7 +149,7 @@ public:
if (!dir.exists()) if (!dir.exists())
return; return;
// Check if the path points to a network file system or not // Check if the path points to a network file system or not
if(isNetworkFileSystem(path)) { if (isNetworkFileSystem(path)) {
// Network mode // Network mode
qDebug("Network folder detected: %s", qPrintable(path)); qDebug("Network folder detected: %s", qPrintable(path));
qDebug("Using file polling mode instead of inotify..."); qDebug("Using file polling mode instead of inotify...");
@ -194,7 +194,7 @@ protected slots:
// Local folders scan // Local folders scan
addTorrentsFromDir(QDir(path), torrents); addTorrentsFromDir(QDir(path), torrents);
// Report detected torrent files // Report detected torrent files
if(!torrents.empty()) { if (!torrents.empty()) {
qDebug("The following files are being reported: %s", qPrintable(torrents.join("\n"))); qDebug("The following files are being reported: %s", qPrintable(torrents.join("\n")));
emit torrentsAdded(torrents); emit torrentsAdded(torrents);
} }
@ -210,7 +210,7 @@ protected slots:
addTorrentsFromDir(dir, torrents); addTorrentsFromDir(dir, torrents);
} }
// Report detected torrent files // Report detected torrent files
if(!torrents.empty()) { if (!torrents.empty()) {
qDebug("The following files are being reported: %s", qPrintable(torrents.join("\n"))); qDebug("The following files are being reported: %s", qPrintable(torrents.join("\n")));
emit torrentsAdded(torrents); emit torrentsAdded(torrents);
} }
@ -221,16 +221,16 @@ protected slots:
QStringList no_longer_partial; QStringList no_longer_partial;
// Check which torrents are still partial // Check which torrents are still partial
foreach(const QString& torrent_path, m_partialTorrents.keys()) { foreach (const QString& torrent_path, m_partialTorrents.keys()) {
if(!QFile::exists(torrent_path)) { if (!QFile::exists(torrent_path)) {
m_partialTorrents.remove(torrent_path); m_partialTorrents.remove(torrent_path);
continue; continue;
} }
if(misc::isValidTorrentFile(torrent_path)) { if (misc::isValidTorrentFile(torrent_path)) {
no_longer_partial << torrent_path; no_longer_partial << torrent_path;
m_partialTorrents.remove(torrent_path); m_partialTorrents.remove(torrent_path);
} else { } else {
if(m_partialTorrents[torrent_path] >= MAX_PARTIAL_RETRIES) { if (m_partialTorrents[torrent_path] >= MAX_PARTIAL_RETRIES) {
m_partialTorrents.remove(torrent_path); m_partialTorrents.remove(torrent_path);
QFile::rename(torrent_path, torrent_path+".invalid"); QFile::rename(torrent_path, torrent_path+".invalid");
} else { } else {
@ -240,7 +240,7 @@ protected slots:
} }
// Stop the partial timer if necessary // Stop the partial timer if necessary
if(m_partialTorrents.empty()) { if (m_partialTorrents.empty()) {
m_partialTorrentTimer->stop(); m_partialTorrentTimer->stop();
m_partialTorrentTimer->deleteLater(); m_partialTorrentTimer->deleteLater();
qDebug("No longer any partial torrent."); qDebug("No longer any partial torrent.");
@ -249,7 +249,7 @@ protected slots:
m_partialTorrentTimer->start(WATCH_INTERVAL); m_partialTorrentTimer->start(WATCH_INTERVAL);
} }
// Notify of new torrents // Notify of new torrents
if(!no_longer_partial.isEmpty()) if (!no_longer_partial.isEmpty())
emit torrentsAdded(no_longer_partial); emit torrentsAdded(no_longer_partial);
} }
@ -259,7 +259,7 @@ signals:
private: private:
void startPartialTorrentTimer() { void startPartialTorrentTimer() {
Q_ASSERT(!m_partialTorrents.isEmpty()); Q_ASSERT(!m_partialTorrents.isEmpty());
if(!m_partialTorrentTimer) { if (!m_partialTorrentTimer) {
m_partialTorrentTimer = new QTimer(); m_partialTorrentTimer = new QTimer();
connect(m_partialTorrentTimer, SIGNAL(timeout()), SLOT(processPartialTorrents())); connect(m_partialTorrentTimer, SIGNAL(timeout()), SLOT(processPartialTorrents()));
m_partialTorrentTimer->setSingleShot(true); m_partialTorrentTimer->setSingleShot(true);
@ -269,19 +269,19 @@ private:
void addTorrentsFromDir(const QDir &dir, QStringList &torrents) { void addTorrentsFromDir(const QDir &dir, QStringList &torrents) {
const QStringList files = dir.entryList(m_filters, QDir::Files, QDir::Unsorted); 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); const QString file_abspath = dir.absoluteFilePath(file);
if(misc::isValidTorrentFile(file_abspath)) { if (misc::isValidTorrentFile(file_abspath)) {
torrents << file_abspath; torrents << file_abspath;
} else { } else {
if(!m_partialTorrents.contains(file_abspath)) { if (!m_partialTorrents.contains(file_abspath)) {
qDebug("Partial torrent detected at: %s", qPrintable(file_abspath)); qDebug("Partial torrent detected at: %s", qPrintable(file_abspath));
qDebug("Delay the file's processing..."); qDebug("Delay the file's processing...");
m_partialTorrents.insert(file_abspath, 0); m_partialTorrents.insert(file_abspath, 0);
} }
} }
} }
if(!m_partialTorrents.empty()) if (!m_partialTorrents.empty())
startPartialTorrentTimer(); startPartialTorrentTimer();
} }

View file

@ -70,14 +70,14 @@ using namespace libtorrent;
QString GeoIPManager::geoipFolder(bool embedded) { QString GeoIPManager::geoipFolder(bool embedded) {
#ifdef WITH_GEOIP_EMBEDDED #ifdef WITH_GEOIP_EMBEDDED
if(embedded) if (embedded)
return ":/geoip/"; return ":/geoip/";
return misc::QDesktopServicesDataLocation()+"geoip"+QDir::separator(); return misc::QDesktopServicesDataLocation()+"geoip"+QDir::separator();
#else #else
Q_UNUSED(embedded); 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/"; 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 "/var/lib/GeoIP/";
return "/usr/share/GeoIP/"; return "/usr/share/GeoIP/";
#endif #endif
@ -89,22 +89,22 @@ QString GeoIPManager::geoipDBpath(bool embedded) {
#ifdef WITH_GEOIP_EMBEDDED #ifdef WITH_GEOIP_EMBEDDED
void GeoIPManager::exportEmbeddedDb() { 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..."); qDebug("A local Geoip database update is required, proceeding...");
// Create geoip folder is necessary // Create geoip folder is necessary
QDir gfolder(geoipFolder(false)); QDir gfolder(geoipFolder(false));
if(!gfolder.exists()) { if (!gfolder.exists()) {
if(!gfolder.mkpath(geoipFolder(false))) { if (!gfolder.mkpath(geoipFolder(false))) {
std::cerr << "Failed to create geoip folder at " << qPrintable(geoipFolder(false)) << std::endl; std::cerr << "Failed to create geoip folder at " << qPrintable(geoipFolder(false)) << std::endl;
return; return;
} }
} }
// Remove destination files // Remove destination files
if(QFile::exists(geoipDBpath(false))) if (QFile::exists(geoipDBpath(false)))
QFile::remove(geoipDBpath(false)); QFile::remove(geoipDBpath(false));
// Copy from executable to hard disk // Copy from executable to hard disk
qDebug("%s -> %s", qPrintable(geoipDBpath(true)), qPrintable(geoipDBpath(false))); 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; std::cerr << "ERROR: Failed to copy geoip.dat from executable to hard disk" << std::endl;
} }
qDebug("Local Geoip database was updated"); qDebug("Local Geoip database was updated");
@ -116,7 +116,7 @@ void GeoIPManager::loadDatabase(session *s) {
#ifdef WITH_GEOIP_EMBEDDED #ifdef WITH_GEOIP_EMBEDDED
exportEmbeddedDb(); exportEmbeddedDb();
#endif #endif
if(QFile::exists(geoipDBpath(false))) { if (QFile::exists(geoipDBpath(false))) {
qDebug("Loading GeoIP database from %s...", qPrintable(geoipDBpath(false))); qDebug("Loading GeoIP database from %s...", qPrintable(geoipDBpath(false)));
s->load_country_db(geoipDBpath(false).toLocal8Bit().constData()); s->load_country_db(geoipDBpath(false).toLocal8Bit().constData());
} else { } else {
@ -183,9 +183,9 @@ const char * country_name[253] =
"Saint Barthelemy","Saint Martin"}; "Saint Barthelemy","Saint Martin"};
QString GeoIPManager::CountryISOCodeToName(const char* iso) { QString GeoIPManager::CountryISOCodeToName(const char* iso) {
if(iso[0] == 0) return "N/A"; if (iso[0] == 0) return "N/A";
for(uint i = 0; i < num_countries; ++i) { for (uint i = 0; i < num_countries; ++i) {
if(iso[0] == country_code[i][0] && iso[1] == country_code[i][1]) { if (iso[0] == country_code[i][0] && iso[1] == country_code[i][1]) {
return QLatin1String(country_name[i]); 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 // http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm
QIcon GeoIPManager::CountryISOCodeToIcon(const char* iso) { 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(); const QString isoStr = QString(QByteArray(iso, 2)).toLower();
return QIcon(":/Icons/flags/"+isoStr+".png"); return QIcon(":/Icons/flags/"+isoStr+".png");
} }

View file

@ -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("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; std::cout << qPrintable(tr("The Web UI administrator user name is: %1").arg(pref.getWebUiUsername())) << std::endl;
qDebug() << "Password:" << pref.getWebUiPassword(); 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("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; 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 right addTorrent function, considering
// the parameter type. // the parameter type.
void processParams(const QStringList& params) { void processParams(const QStringList& params) {
foreach(QString param, params) { foreach (QString param, params) {
param = param.trimmed(); 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); QBtSession::instance()->downloadFromUrl(param);
}else{ }else{
if(param.startsWith("bc://bt/", Qt::CaseInsensitive)) { if (param.startsWith("bc://bt/", Qt::CaseInsensitive)) {
qDebug("Converting bc link to magnet link"); qDebug("Converting bc link to magnet link");
param = misc::bcLinkToMagnet(param); param = misc::bcLinkToMagnet(param);
} }
if(param.startsWith("magnet:", Qt::CaseInsensitive)) { if (param.startsWith("magnet:", Qt::CaseInsensitive)) {
QBtSession::instance()->addMagnetUri(param); QBtSession::instance()->addMagnetUri(param);
} else { } else {
QBtSession::instance()->addTorrent(param); QBtSession::instance()->addTorrent(param);

View file

@ -44,7 +44,7 @@ public:
protected: protected:
void tabInserted(int index) { void tabInserted(int index) {
QTabWidget::tabInserted(index); QTabWidget::tabInserted(index);
if(count() == 1) { if (count() == 1) {
showTabBar(false); showTabBar(false);
} else { } else {
showTabBar(true); showTabBar(true);
@ -53,7 +53,7 @@ protected:
void tabRemoved(int index) { void tabRemoved(int index) {
QTabWidget::tabInserted(index); QTabWidget::tabInserted(index);
if(count() == 1) { if (count() == 1) {
showTabBar(false); showTabBar(false);
} else { } else {
showTabBar(true); showTabBar(true);

View file

@ -42,14 +42,14 @@ IconProvider::IconProvider()
IconProvider * IconProvider::instance() IconProvider * IconProvider::instance()
{ {
if(!m_instance) if (!m_instance)
m_instance = new IconProvider; m_instance = new IconProvider;
return m_instance; return m_instance;
} }
void IconProvider::drop() void IconProvider::drop()
{ {
if(m_instance) { if (m_instance) {
delete m_instance; delete m_instance;
m_instance = 0; m_instance = 0;
} }
@ -58,7 +58,7 @@ void IconProvider::drop()
QIcon IconProvider::getIcon(const QString &iconId) QIcon IconProvider::getIcon(const QString &iconId)
{ {
#if defined(Q_WS_X11) && (QT_VERSION >= QT_VERSION_CHECK(4,6,0)) #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")); QIcon icon = QIcon::fromTheme(iconId, QIcon(":/Icons/oxygen/"+iconId+".png"));
icon = generateDifferentSizes(icon); icon = generateDifferentSizes(icon);
return icon; return icon;
@ -84,14 +84,14 @@ QIcon IconProvider::generateDifferentSizes(const QIcon &icon)
required_sizes << QSize(16, 16) << QSize(24, 24); required_sizes << QSize(16, 16) << QSize(24, 24);
QList<QIcon::Mode> modes; QList<QIcon::Mode> modes;
modes << QIcon::Normal << QIcon::Active << QIcon::Selected << QIcon::Disabled; modes << QIcon::Normal << QIcon::Active << QIcon::Selected << QIcon::Disabled;
foreach(const QSize& size, required_sizes) { foreach (const QSize& size, required_sizes) {
foreach(QIcon::Mode mode, modes) { foreach (QIcon::Mode mode, modes) {
QPixmap pixoff = icon.pixmap(size, mode, QIcon::Off); 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); pixoff = pixoff.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
new_icon.addPixmap(pixoff, mode, QIcon::Off); new_icon.addPixmap(pixoff, mode, QIcon::Off);
QPixmap pixon = icon.pixmap(size, mode, QIcon::On); 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); pixon = pixoff.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
new_icon.addPixmap(pixon, mode, QIcon::On); new_icon.addPixmap(pixon, mode, QIcon::On);
} }
@ -103,11 +103,11 @@ QIcon IconProvider::generateDifferentSizes(const QIcon &icon)
QString IconProvider::getIconPath(const QString &iconId) QString IconProvider::getIconPath(const QString &iconId)
{ {
#if defined(Q_WS_X11) && (QT_VERSION >= QT_VERSION_CHECK(4,6,0)) #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"); QString path = QDir::temp().absoluteFilePath(iconId+".png");
if(!QFile::exists(path)) { if (!QFile::exists(path)) {
const QIcon icon = QIcon::fromTheme(iconId); 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); QPixmap px = icon.pixmap(32);
px.save(path); px.save(path);
} }

View file

@ -73,7 +73,7 @@ void LogListWidget::appendLine(const QString &line)
setItemWidget(item, lbl); setItemWidget(item, lbl);
const int nbLines = count(); const int nbLines = count();
// Limit log size // Limit log size
if(nbLines > m_maxLines) if (nbLines > m_maxLines)
delete takeItem(nbLines - 1); delete takeItem(nbLines - 1);
} }
@ -82,7 +82,7 @@ void LogListWidget::copySelection()
static QRegExp html_tag("<[^>]+>"); static QRegExp html_tag("<[^>]+>");
QList<QListWidgetItem*> items = selectedItems(); QList<QListWidgetItem*> items = selectedItems();
QStringList strings; QStringList strings;
foreach(QListWidgetItem* it, items) foreach (QListWidgetItem* it, items)
strings << static_cast<QLabel*>(itemWidget(it))->text().replace(html_tag, ""); strings << static_cast<QLabel*>(itemWidget(it))->text().replace(html_tag, "");
QApplication::clipboard()->setText(strings.join("\n")); QApplication::clipboard()->setText(strings.join("\n"));

View file

@ -87,14 +87,14 @@ class LegalNotice: public QObject {
public: public:
static bool userAgreesWithNotice() { static bool userAgreesWithNotice() {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); 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; return true;
#ifdef DISABLE_GUI #ifdef DISABLE_GUI
std::cout << std::endl << "*** " << qPrintable(tr("Legal Notice")) << " ***" << std::endl; 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("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; std::cout << qPrintable(tr("Press %1 key to accept and continue...").arg("'y'")) << std::endl;
char ret = getchar(); // Read pressed key char ret = getchar(); // Read pressed key
if(ret == 'y' || ret == 'Y') { if (ret == 'y' || ret == 'Y') {
// Save the answer // Save the answer
settings.setValue(QString::fromUtf8("LegalNotice/Accepted"), true); settings.setValue(QString::fromUtf8("LegalNotice/Accepted"), true);
return true; return true;
@ -109,7 +109,7 @@ public:
msgBox.show(); // Need to be shown or to moveToCenter does not work msgBox.show(); // Need to be shown or to moveToCenter does not work
msgBox.move(misc::screenCenter(&msgBox)); msgBox.move(misc::screenCenter(&msgBox));
msgBox.exec(); msgBox.exec();
if(msgBox.clickedButton() == agree_button) { if (msgBox.clickedButton() == agree_button) {
// Save the answer // Save the answer
settings.setValue(QString::fromUtf8("LegalNotice/Accepted"), true); settings.setValue(QString::fromUtf8("LegalNotice/Accepted"), true);
return true; return true;
@ -164,18 +164,18 @@ int main(int argc, char *argv[]){
#endif #endif
// Check if qBittorrent is already running for this user // Check if qBittorrent is already running for this user
if(app.isRunning()) { if (app.isRunning()) {
qDebug("qBittorrent is already running for this user."); qDebug("qBittorrent is already running for this user.");
//Pass program parameters if any //Pass program parameters if any
QString message; QString message;
for (int a = 1; a < argc; ++a) { for (int a = 1; a < argc; ++a) {
QString p = QString::fromLocal8Bit(argv[a]); QString p = QString::fromLocal8Bit(argv[a]);
if(p.startsWith("--")) continue; if (p.startsWith("--")) continue;
message += p; message += p;
if (a < argc-1) if (a < argc-1)
message += "|"; message += "|";
} }
if(!message.isEmpty()) { if (!message.isEmpty()) {
qDebug("Passing program parameters to running instance..."); qDebug("Passing program parameters to running instance...");
qDebug("Message: %s", qPrintable(message)); qDebug("Message: %s", qPrintable(message));
app.sendMessage(message); app.sendMessage(message);
@ -192,11 +192,11 @@ int main(int argc, char *argv[]){
QString locale = pref.getLocale(); QString locale = pref.getLocale();
QTranslator qtTranslator; QTranslator qtTranslator;
QTranslator translator; QTranslator translator;
if(locale.isEmpty()){ if (locale.isEmpty()){
locale = QLocale::system().name(); locale = QLocale::system().name();
pref.setLocale(locale); pref.setLocale(locale);
} }
if(qtTranslator.load( if (qtTranslator.load(
QString::fromUtf8("qt_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath) QString::fromUtf8("qt_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)
)){ )){
qDebug("Qt %s locale recognized, using translation.", qPrintable(locale)); 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)); qDebug("Qt %s locale unrecognized, using default (en_GB).", qPrintable(locale));
} }
app.installTranslator(&qtTranslator); 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)); qDebug("%s locale recognized, using translation.", qPrintable(locale));
}else{ }else{
qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale)); qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale));
} }
app.installTranslator(&translator); app.installTranslator(&translator);
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
if(locale.startsWith("ar")) { if (locale.startsWith("ar")) {
qDebug("Right to Left mode"); qDebug("Right to Left mode");
app.setLayoutDirection(Qt::RightToLeft); app.setLayoutDirection(Qt::RightToLeft);
} else { } else {
@ -221,28 +221,28 @@ int main(int argc, char *argv[]){
app.setApplicationName(QString::fromUtf8("qBittorrent")); app.setApplicationName(QString::fromUtf8("qBittorrent"));
// Check for executable parameters // Check for executable parameters
if(argc > 1){ if (argc > 1){
if(QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--version")){ if (QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--version")){
std::cout << "qBittorrent " << VERSION << '\n'; std::cout << "qBittorrent " << VERSION << '\n';
return 0; return 0;
} }
if(QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--help")){ if (QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--help")){
UsageDisplay::displayUsage(argv[0]); UsageDisplay::displayUsage(argv[0]);
return 0; return 0;
} }
for(int i=1; i<argc; ++i) { for (int i=1; i<argc; ++i) {
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
if(QString::fromLocal8Bit(argv[i]) == QString::fromUtf8("--no-splash")) { if (QString::fromLocal8Bit(argv[i]) == QString::fromUtf8("--no-splash")) {
no_splash = true; no_splash = true;
} else { } else {
#endif #endif
if(QString::fromLocal8Bit(argv[i]).startsWith("--webui-port=")) { if (QString::fromLocal8Bit(argv[i]).startsWith("--webui-port=")) {
QStringList parts = QString::fromLocal8Bit(argv[i]).split("="); QStringList parts = QString::fromLocal8Bit(argv[i]).split("=");
if(parts.size() == 2) { if (parts.size() == 2) {
bool ok = false; bool ok = false;
int new_port = parts.last().toInt(&ok); int new_port = parts.last().toInt(&ok);
if(ok && new_port > 0 && new_port <= 65535) { if (ok && new_port > 0 && new_port <= 65535) {
Preferences().setWebUiPort(new_port); Preferences().setWebUiPort(new_port);
} }
} }
@ -254,11 +254,11 @@ int main(int argc, char *argv[]){
} }
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
if(pref.isSlashScreenDisabled()) { if (pref.isSlashScreenDisabled()) {
no_splash = true; no_splash = true;
} }
QSplashScreen *splash = 0; QSplashScreen *splash = 0;
if(!no_splash) { if (!no_splash) {
QPixmap splash_img(":/Icons/skin/splash.png"); QPixmap splash_img(":/Icons/skin/splash.png");
QPainter painter(&splash_img); QPainter painter(&splash_img);
QString version = VERSION; QString version = VERSION;
@ -280,7 +280,7 @@ int main(int argc, char *argv[]){
app.setStyleSheet("QStatusBar::item { border-width: 0; }"); app.setStyleSheet("QStatusBar::item { border-width: 0; }");
#endif #endif
if(!LegalNotice::userAgreesWithNotice()) { if (!LegalNotice::userAgreesWithNotice()) {
return 0; return 0;
} }
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
@ -297,7 +297,7 @@ int main(int argc, char *argv[]){
// Remove first argument (program name) // Remove first argument (program name)
torrentCmdLine.removeFirst(); torrentCmdLine.removeFirst();
#ifndef QT_NO_DEBUG_OUTPUT #ifndef QT_NO_DEBUG_OUTPUT
foreach(const QString &argument, torrentCmdLine) { foreach (const QString &argument, torrentCmdLine) {
qDebug() << "Command line argument:" << argument; qDebug() << "Command line argument:" << argument;
} }
#endif #endif

View file

@ -247,14 +247,14 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo
#endif #endif
actionAutoExit_qBittorrent->setChecked(pref.shutdownqBTWhenDownloadsComplete()); actionAutoExit_qBittorrent->setChecked(pref.shutdownqBTWhenDownloadsComplete());
if(!autoShutdownGroup->checkedAction()) if (!autoShutdownGroup->checkedAction())
actionAutoShutdown_Disabled->setChecked(true); actionAutoShutdown_Disabled->setChecked(true);
// Load Window state and sizes // Load Window state and sizes
readSettings(); readSettings();
if(!ui_locked) { if (!ui_locked) {
if(pref.startMinimized() && systrayIcon) if (pref.startMinimized() && systrayIcon)
showMinimized(); showMinimized();
else { else {
show(); show();
@ -285,8 +285,8 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo
qDebug("GUI Built"); qDebug("GUI Built");
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
if(!pref.neverCheckFileAssoc() && (!Preferences::isTorrentFileAssocSet() || !Preferences::isMagnetLinkAssocSet())) { if (!pref.neverCheckFileAssoc() && (!Preferences::isTorrentFileAssocSet() || !Preferences::isMagnetLinkAssocSet())) {
if(QMessageBox::question(0, tr("Torrent file association"), 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?"), 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) { QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
Preferences::setTorrentFileAssoc(true); Preferences::setTorrentFileAssoc(true);
@ -301,7 +301,7 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo
#endif #endif
#if defined(Q_WS_WIN) || defined(Q_WS_MAC) #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
// Check for update // Check for update
if(pref.isUpdateCheckEnabled()) { if (pref.isUpdateCheckEnabled()) {
ProgramUpdater *updater = new ProgramUpdater(this); ProgramUpdater *updater = new ProgramUpdater(this);
connect(updater, SIGNAL(updateCheckFinished(bool, QString)), SLOT(handleUpdateCheckFinished(bool, QString))); connect(updater, SIGNAL(updateCheckFinished(bool, QString)), SLOT(handleUpdateCheckFinished(bool, QString)));
updater->checkForUpdates(); updater->checkForUpdates();
@ -337,37 +337,37 @@ MainWindow::~MainWindow() {
#endif #endif
disconnect(tabs, SIGNAL(currentChanged(int)), this, SLOT(tab_changed(int))); disconnect(tabs, SIGNAL(currentChanged(int)), this, SLOT(tab_changed(int)));
// Delete other GUI objects // Delete other GUI objects
if(executable_watcher) if (executable_watcher)
delete executable_watcher; delete executable_watcher;
delete status_bar; delete status_bar;
delete search_filter; delete search_filter;
delete transferList; delete transferList;
delete guiUpdater; delete guiUpdater;
if(createTorrentDlg) if (createTorrentDlg)
delete createTorrentDlg; delete createTorrentDlg;
if(m_executionLog) if (m_executionLog)
delete m_executionLog; delete m_executionLog;
if(aboutDlg) if (aboutDlg)
delete aboutDlg; delete aboutDlg;
if(options) if (options)
delete options; delete options;
if(downloadFromURLDialog) if (downloadFromURLDialog)
delete downloadFromURLDialog; delete downloadFromURLDialog;
if(rssWidget) if (rssWidget)
delete rssWidget; delete rssWidget;
if(searchEngine) if (searchEngine)
delete searchEngine; delete searchEngine;
delete transferListFilters; delete transferListFilters;
delete properties; delete properties;
delete hSplitter; delete hSplitter;
delete vSplitter; delete vSplitter;
if(systrayCreator) { if (systrayCreator) {
delete systrayCreator; delete systrayCreator;
} }
if(systrayIcon) { if (systrayIcon) {
delete systrayIcon; delete systrayIcon;
} }
if(myTrayIconMenu) { if (myTrayIconMenu) {
delete myTrayIconMenu; delete myTrayIconMenu;
} }
delete tabs; delete tabs;
@ -386,16 +386,16 @@ MainWindow::~MainWindow() {
void MainWindow::defineUILockPassword() { void MainWindow::defineUILockPassword() {
QString old_pass_md5 = Preferences().getUILockPasswordMD5(); 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; 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); 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(); 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")); QMessageBox::warning(this, tr("Invalid password"), tr("The password should contain at least 3 characters"));
return; return;
} }
if(new_clear_password != old_pass_md5) { if (new_clear_password != old_pass_md5) {
Preferences().setUILockPassword(new_clear_password); Preferences().setUILockPassword(new_clear_password);
} }
QMessageBox::information(this, tr("Password update"), tr("The UI lock password has been successfully updated")); 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() { void MainWindow::on_actionLock_qBittorrent_triggered() {
Preferences pref; Preferences pref;
// Check if there is a password // Check if there is a password
if(pref.getUILockPasswordMD5().isEmpty()) { if (pref.getUILockPasswordMD5().isEmpty()) {
// Ask for a password // Ask for a password
bool ok = false; bool ok = false;
QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok); 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); pref.setUILockPassword(clear_password);
} }
// Lock the interface // Lock the interface
@ -420,29 +420,29 @@ void MainWindow::on_actionLock_qBittorrent_triggered() {
} }
void MainWindow::displayRSSTab(bool enable) { void MainWindow::displayRSSTab(bool enable) {
if(enable) { if (enable) {
// RSS tab // RSS tab
if(!rssWidget) { if (!rssWidget) {
rssWidget = new RSSImp(tabs); rssWidget = new RSSImp(tabs);
int index_tab = tabs->addTab(rssWidget, tr("RSS")); int index_tab = tabs->addTab(rssWidget, tr("RSS"));
tabs->setTabIcon(index_tab, IconProvider::instance()->getIcon("application-rss+xml")); tabs->setTabIcon(index_tab, IconProvider::instance()->getIcon("application-rss+xml"));
} }
} else { } else {
if(rssWidget) { if (rssWidget) {
delete rssWidget; delete rssWidget;
} }
} }
} }
void MainWindow::displaySearchTab(bool enable) { void MainWindow::displaySearchTab(bool enable) {
if(enable) { if (enable) {
// RSS tab // RSS tab
if(!searchEngine) { if (!searchEngine) {
searchEngine = new SearchEngine(this); searchEngine = new SearchEngine(this);
tabs->insertTab(1, searchEngine, IconProvider::instance()->getIcon("edit-find"), tr("Search")); tabs->insertTab(1, searchEngine, IconProvider::instance()->getIcon("edit-find"), tr("Search"));
} }
} else { } else {
if(searchEngine) { if (searchEngine) {
delete searchEngine; delete searchEngine;
} }
} }
@ -468,12 +468,12 @@ void MainWindow::tab_changed(int new_tab) {
Q_UNUSED(new_tab); Q_UNUSED(new_tab);
// We cannot rely on the index new_tab // We cannot rely on the index new_tab
// because the tab order is undetermined now // because the tab order is undetermined now
if(tabs->currentWidget() == vSplitter) { if (tabs->currentWidget() == vSplitter) {
qDebug("Changed tab to transfer list, refreshing the list"); qDebug("Changed tab to transfer list, refreshing the list");
properties->loadDynamicData(); properties->loadDynamicData();
return; return;
} }
if(tabs->currentWidget() == searchEngine) { if (tabs->currentWidget() == searchEngine) {
qDebug("Changed tab to search engine, giving focus to search input"); qDebug("Changed tab to search engine, giving focus to search input");
searchEngine->giveFocusToSearchInput(); searchEngine->giveFocusToSearchInput();
} }
@ -492,12 +492,12 @@ void MainWindow::writeSettings() {
void MainWindow::readSettings() { void MainWindow::readSettings() {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
settings.beginGroup(QString::fromUtf8("MainWindow")); settings.beginGroup(QString::fromUtf8("MainWindow"));
if(settings.contains("geometry")) { if (settings.contains("geometry")) {
if(restoreGeometry(settings.value("geometry").toByteArray())) if (restoreGeometry(settings.value("geometry").toByteArray()))
m_posInitialized = true; m_posInitialized = true;
} }
const QByteArray splitterState = settings.value("vsplitterState").toByteArray(); const QByteArray splitterState = settings.value("vsplitterState").toByteArray();
if(splitterState.isEmpty()) { if (splitterState.isEmpty()) {
// Default sizes // Default sizes
vSplitter->setSizes(QList<int>() << 120 << vSplitter->width()-120); vSplitter->setSizes(QList<int>() << 120 << vSplitter->width()-120);
} else { } else {
@ -507,9 +507,9 @@ void MainWindow::readSettings() {
} }
void MainWindow::balloonClicked() { void MainWindow::balloonClicked() {
if(isHidden()) { if (isHidden()) {
show(); show();
if(isMinimized()) { if (isMinimized()) {
showNormal(); showNormal();
} }
raise(); raise();
@ -519,13 +519,13 @@ void MainWindow::balloonClicked() {
// called when a torrent has finished // called when a torrent has finished
void MainWindow::finishedTorrent(const QTorrentHandle& h) const { 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())); showNotificationBaloon(tr("Download completion"), tr("%1 has finished downloading.", "e.g: xxx.avi has finished downloading.").arg(h.name()));
} }
// Notification when disk is full // Notification when disk is full
void MainWindow::fullDiskError(const QTorrentHandle& h, QString msg) const { 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)); 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 { void MainWindow::displaySearchTab() const {
if(searchEngine) if (searchEngine)
tabs->setCurrentWidget(searchEngine); tabs->setCurrentWidget(searchEngine);
} }
void MainWindow::displayRSSTab() const { void MainWindow::displayRSSTab() const {
if(rssWidget) if (rssWidget)
tabs->setCurrentWidget(rssWidget); tabs->setCurrentWidget(rssWidget);
} }
@ -579,7 +579,7 @@ void MainWindow::displayRSSTab() const {
void MainWindow::askRecursiveTorrentDownloadConfirmation(const QTorrentHandle &h) { void MainWindow::askRecursiveTorrentDownloadConfirmation(const QTorrentHandle &h) {
Preferences pref; Preferences pref;
if(pref.recursiveDownloadDisabled()) return; if (pref.recursiveDownloadDisabled()) return;
// Get Torrent name // Get Torrent name
QString torrent_name; QString torrent_name;
try { try {
@ -592,12 +592,12 @@ void MainWindow::askRecursiveTorrentDownloadConfirmation(const QTorrentHandle &h
/*QPushButton *no = */confirmBox.addButton(tr("No"), QMessageBox::NoRole); /*QPushButton *no = */confirmBox.addButton(tr("No"), QMessageBox::NoRole);
QPushButton *never = confirmBox.addButton(tr("Never"), QMessageBox::NoRole); QPushButton *never = confirmBox.addButton(tr("Never"), QMessageBox::NoRole);
confirmBox.exec(); confirmBox.exec();
if(confirmBox.clickedButton() == 0) return; if (confirmBox.clickedButton() == 0) return;
if(confirmBox.clickedButton() == yes) { if (confirmBox.clickedButton() == yes) {
QBtSession::instance()->recursiveTorrentDownload(h); QBtSession::instance()->recursiveTorrentDownload(h);
return; return;
} }
if(confirmBox.clickedButton() == never) { if (confirmBox.clickedButton() == never) {
pref.disableRecursiveDownload(); pref.disableRecursiveDownload();
} }
} }
@ -616,10 +616,10 @@ void MainWindow::on_actionSet_global_upload_limit_triggered() {
int cur_limit = QBtSession::instance()->getSession()->upload_rate_limit(); int cur_limit = QBtSession::instance()->getSession()->upload_rate_limit();
#endif #endif
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), cur_limit); 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.); qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.);
QBtSession::instance()->setUploadRateLimit(new_limit); QBtSession::instance()->setUploadRateLimit(new_limit);
if(new_limit <= 0) if (new_limit <= 0)
Preferences().setGlobalUploadLimit(-1); Preferences().setGlobalUploadLimit(-1);
else else
Preferences().setGlobalUploadLimit(new_limit/1024.); 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(); int cur_limit = QBtSession::instance()->getSession()->download_rate_limit();
#endif #endif
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), cur_limit); 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.); qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.);
QBtSession::instance()->setDownloadRateLimit(new_limit); QBtSession::instance()->setDownloadRateLimit(new_limit);
if(new_limit <= 0) if (new_limit <= 0)
Preferences().setGlobalDownloadLimit(-1); Preferences().setGlobalDownloadLimit(-1);
else else
Preferences().setGlobalDownloadLimit(new_limit/1024.); Preferences().setGlobalDownloadLimit(new_limit/1024.);
@ -653,9 +653,9 @@ void MainWindow::on_actionExit_triggered() {
} }
QWidget* MainWindow::getCurrentTabWidget() const { QWidget* MainWindow::getCurrentTabWidget() const {
if(isMinimized() || !isVisible()) if (isMinimized() || !isVisible())
return 0; return 0;
if(tabs->currentIndex() == 0) if (tabs->currentIndex() == 0)
return transferList; return transferList;
return tabs->currentWidget(); return tabs->currentWidget();
} }
@ -667,13 +667,13 @@ void MainWindow::setTabText(int index, QString text) const {
bool MainWindow::unlockUI() { bool MainWindow::unlockUI() {
bool ok = false; bool ok = false;
QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok); 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; Preferences pref;
QString real_pass_md5 = pref.getUILockPasswordMD5(); QString real_pass_md5 = pref.getUILockPasswordMD5();
QCryptographicHash md5(QCryptographicHash::Md5); QCryptographicHash md5(QCryptographicHash::Md5);
md5.addData(clear_password.toLocal8Bit()); md5.addData(clear_password.toLocal8Bit());
QString password_md5 = md5.result().toHex(); QString password_md5 = md5.result().toHex();
if(real_pass_md5 == password_md5) { if (real_pass_md5 == password_md5) {
ui_locked = false; ui_locked = false;
pref.setUILocked(false); pref.setUILocked(false);
myTrayIconMenu->setEnabled(true); myTrayIconMenu->setEnabled(true);
@ -693,16 +693,16 @@ void MainWindow::notifyOfUpdate(QString) {
// Toggle Main window visibility // Toggle Main window visibility
void MainWindow::toggleVisibility(QSystemTrayIcon::ActivationReason e) { void MainWindow::toggleVisibility(QSystemTrayIcon::ActivationReason e) {
if(e == QSystemTrayIcon::Trigger || e == QSystemTrayIcon::DoubleClick) { if (e == QSystemTrayIcon::Trigger || e == QSystemTrayIcon::DoubleClick) {
if(isHidden()) { if (isHidden()) {
if(ui_locked) { if (ui_locked) {
// Ask for UI lock password // Ask for UI lock password
if(!unlockUI()) if (!unlockUI())
return; return;
} }
show(); show();
if(isMinimized()) { if (isMinimized()) {
if(isMaximized()) { if (isMaximized()) {
showMaximized(); showMaximized();
}else{ }else{
showNormal(); showNormal();
@ -720,7 +720,7 @@ void MainWindow::toggleVisibility(QSystemTrayIcon::ActivationReason e) {
// Display About Dialog // Display About Dialog
void MainWindow::on_actionAbout_triggered() { void MainWindow::on_actionAbout_triggered() {
//About dialog //About dialog
if(aboutDlg) { if (aboutDlg) {
aboutDlg->setFocus(); aboutDlg->setFocus();
} else { } else {
aboutDlg = new about(this); aboutDlg = new about(this);
@ -730,14 +730,14 @@ void MainWindow::on_actionAbout_triggered() {
void MainWindow::showEvent(QShowEvent *e) { void MainWindow::showEvent(QShowEvent *e) {
qDebug("** Show Event **"); qDebug("** Show Event **");
if(getCurrentTabWidget() == transferList) { if (getCurrentTabWidget() == transferList) {
properties->loadDynamicData(); properties->loadDynamicData();
} }
e->accept(); e->accept();
// Make sure the window is initially centered // Make sure the window is initially centered
if(!m_posInitialized) { if (!m_posInitialized) {
move(misc::screenCenter(this)); move(misc::screenCenter(this));
m_posInitialized = true; m_posInitialized = true;
} }
@ -747,14 +747,14 @@ void MainWindow::showEvent(QShowEvent *e) {
void MainWindow::closeEvent(QCloseEvent *e) { void MainWindow::closeEvent(QCloseEvent *e) {
Preferences pref; Preferences pref;
const bool goToSystrayOnExit = pref.closeToTray(); const bool goToSystrayOnExit = pref.closeToTray();
if(!force_exit && systrayIcon && goToSystrayOnExit && !this->isHidden()) { if (!force_exit && systrayIcon && goToSystrayOnExit && !this->isHidden()) {
hide(); hide();
e->accept(); e->accept();
return; return;
} }
if(pref.confirmOnExit() && QBtSession::instance()->hasActiveTorrents()) { if (pref.confirmOnExit() && QBtSession::instance()->hasActiveTorrents()) {
if(e->spontaneous() || force_exit) { if (e->spontaneous() || force_exit) {
if(!isVisible()) if (!isVisible())
show(); show();
QMessageBox confirmBox(QMessageBox::Question, tr("Exiting qBittorrent"), QMessageBox confirmBox(QMessageBox::Question, tr("Exiting qBittorrent"),
tr("Some files are currently transferring.\nAre you sure you want to quit 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); QPushButton *alwaysBtn = confirmBox.addButton(tr("Always"), QMessageBox::YesRole);
confirmBox.setDefaultButton(yesBtn); confirmBox.setDefaultButton(yesBtn);
confirmBox.exec(); confirmBox.exec();
if(!confirmBox.clickedButton() || confirmBox.clickedButton() == noBtn) { if (!confirmBox.clickedButton() || confirmBox.clickedButton() == noBtn) {
// Cancel exit // Cancel exit
e->ignore(); e->ignore();
force_exit = false; force_exit = false;
return; return;
} }
if(confirmBox.clickedButton() == alwaysBtn) { if (confirmBox.clickedButton() == alwaysBtn) {
// Remember choice // Remember choice
Preferences().setConfirmOnExit(false); Preferences().setConfirmOnExit(false);
} }
} }
} }
hide(); hide();
if(systrayIcon) { if (systrayIcon) {
// Hide tray icon // Hide tray icon
systrayIcon->hide(); systrayIcon->hide();
} }
@ -790,7 +790,7 @@ void MainWindow::closeEvent(QCloseEvent *e) {
// Display window to create a torrent // Display window to create a torrent
void MainWindow::on_actionCreate_torrent_triggered() { void MainWindow::on_actionCreate_torrent_triggered() {
if(createTorrentDlg) { if (createTorrentDlg) {
createTorrentDlg->setFocus(); createTorrentDlg->setFocus();
} else { } else {
createTorrentDlg = new TorrentCreatorDlg(this); createTorrentDlg = new TorrentCreatorDlg(this);
@ -803,20 +803,20 @@ bool MainWindow::event(QEvent * e) {
case QEvent::WindowStateChange: { case QEvent::WindowStateChange: {
qDebug("Window change event"); qDebug("Window change event");
//Now check to see if the window is minimised //Now check to see if the window is minimised
if(isMinimized()) { if (isMinimized()) {
qDebug("minimisation"); qDebug("minimisation");
if(systrayIcon && Preferences().minimizeToTray()) { if (systrayIcon && Preferences().minimizeToTray()) {
qDebug("Has active window: %d", (int)(qApp->activeWindow() != 0)); qDebug("Has active window: %d", (int)(qApp->activeWindow() != 0));
// Check if there is a modal window // Check if there is a modal window
bool has_modal_window = false; bool has_modal_window = false;
foreach (QWidget *widget, QApplication::allWidgets()) { foreach (QWidget *widget, QApplication::allWidgets()) {
if(widget->isModal()) { if (widget->isModal()) {
has_modal_window = true; has_modal_window = true;
break; break;
} }
} }
// Iconify if there is no modal window // Iconify if there is no modal window
if(!has_modal_window) { if (!has_modal_window) {
qDebug("Minimize to Tray enabled, hiding!"); qDebug("Minimize to Tray enabled, hiding!");
e->accept(); e->accept();
QTimer::singleShot(0, this, SLOT(hide())); QTimer::singleShot(0, this, SLOT(hide()));
@ -847,11 +847,11 @@ bool MainWindow::event(QEvent * e) {
void MainWindow::dropEvent(QDropEvent *event) { void MainWindow::dropEvent(QDropEvent *event) {
event->acceptProposedAction(); event->acceptProposedAction();
QStringList files; QStringList files;
if(event->mimeData()->hasUrls()) { if (event->mimeData()->hasUrls()) {
const QList<QUrl> urls = event->mimeData()->urls(); const QList<QUrl> urls = event->mimeData()->urls();
foreach(const QUrl &url, urls) { foreach (const QUrl &url, urls) {
if(!url.isEmpty()) { if (!url.isEmpty()) {
if(url.scheme().compare("file", Qt::CaseInsensitive) == 0) if (url.scheme().compare("file", Qt::CaseInsensitive) == 0)
files << url.toLocalFile(); files << url.toLocalFile();
else else
files << url.toString(); files << url.toString();
@ -863,19 +863,19 @@ void MainWindow::dropEvent(QDropEvent *event) {
// Add file to download list // Add file to download list
Preferences pref; Preferences pref;
const bool useTorrentAdditionDialog = pref.useAdditionDialog(); const bool useTorrentAdditionDialog = pref.useAdditionDialog();
foreach(QString file, files) { foreach (QString file, files) {
qDebug("Dropped file %s on download list", qPrintable(file)); qDebug("Dropped file %s on download list", qPrintable(file));
if(misc::isUrl(file)) { if (misc::isUrl(file)) {
QBtSession::instance()->downloadFromUrl(file); QBtSession::instance()->downloadFromUrl(file);
continue; continue;
} }
// Bitcomet or Magnet link // 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"); qDebug("Converting bc link to magnet link");
file = misc::bcLinkToMagnet(file); file = misc::bcLinkToMagnet(file);
} }
if(file.startsWith("magnet:", Qt::CaseInsensitive)) { if (file.startsWith("magnet:", Qt::CaseInsensitive)) {
if(useTorrentAdditionDialog) { if (useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoadMagnetURI(file); dialog->showLoadMagnetURI(file);
} else { } else {
@ -884,9 +884,9 @@ void MainWindow::dropEvent(QDropEvent *event) {
continue; continue;
} }
// Local file // Local file
if(useTorrentAdditionDialog) { if (useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
if(file.startsWith("file:", Qt::CaseInsensitive)) if (file.startsWith("file:", Qt::CaseInsensitive))
file = QUrl(file).toLocalFile(); file = QUrl(file).toLocalFile();
dialog->showLoad(file); dialog->showLoad(file);
}else{ }else{
@ -897,7 +897,7 @@ void MainWindow::dropEvent(QDropEvent *event) {
// Decode if we accept drag 'n drop or not // Decode if we accept drag 'n drop or not
void MainWindow::dragEnterEvent(QDragEnterEvent *event) { void MainWindow::dragEnterEvent(QDragEnterEvent *event) {
foreach(const QString &mime, event->mimeData()->formats()){ foreach (const QString &mime, event->mimeData()->formats()){
qDebug("mimeData: %s", mime.toLocal8Bit().data()); qDebug("mimeData: %s", mime.toLocal8Bit().data());
} }
if (event->mimeData()->hasFormat(QString::fromUtf8("text/plain")) || event->mimeData()->hasFormat(QString::fromUtf8("text/uri-list"))) { 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, const QStringList pathsList = QFileDialog::getOpenFileNames(0,
tr("Open Torrent Files"), settings.value(QString::fromUtf8("MainWindowLastDir"), QDir::homePath()).toString(), tr("Open Torrent Files"), settings.value(QString::fromUtf8("MainWindowLastDir"), QDir::homePath()).toString(),
tr("Torrent Files")+QString::fromUtf8(" (*.torrent)")); tr("Torrent Files")+QString::fromUtf8(" (*.torrent)"));
if(!pathsList.empty()) { if (!pathsList.empty()) {
const bool useTorrentAdditionDialog = pref.useAdditionDialog(); const bool useTorrentAdditionDialog = pref.useAdditionDialog();
const uint listSize = pathsList.size(); const uint listSize = pathsList.size();
for(uint i=0; i<listSize; ++i) { for (uint i=0; i<listSize; ++i) {
if(useTorrentAdditionDialog) { if (useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoad(pathsList.at(i)); dialog->showLoad(pathsList.at(i));
}else{ }else{
@ -950,24 +950,24 @@ void MainWindow::processParams(const QString& params_str) {
void MainWindow::processParams(const QStringList& params) { void MainWindow::processParams(const QStringList& params) {
Preferences pref; Preferences pref;
const bool useTorrentAdditionDialog = pref.useAdditionDialog(); const bool useTorrentAdditionDialog = pref.useAdditionDialog();
foreach(QString param, params) { foreach (QString param, params) {
param = param.trimmed(); param = param.trimmed();
if(misc::isUrl(param)) { if (misc::isUrl(param)) {
QBtSession::instance()->downloadFromUrl(param); QBtSession::instance()->downloadFromUrl(param);
}else{ }else{
if(param.startsWith("bc://bt/", Qt::CaseInsensitive)) { if (param.startsWith("bc://bt/", Qt::CaseInsensitive)) {
qDebug("Converting bc link to magnet link"); qDebug("Converting bc link to magnet link");
param = misc::bcLinkToMagnet(param); param = misc::bcLinkToMagnet(param);
} }
if(param.startsWith("magnet:", Qt::CaseInsensitive)) { if (param.startsWith("magnet:", Qt::CaseInsensitive)) {
if(useTorrentAdditionDialog) { if (useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoadMagnetURI(param); dialog->showLoadMagnetURI(param);
} else { } else {
QBtSession::instance()->addMagnetUri(param); QBtSession::instance()->addMagnetUri(param);
} }
} else { } else {
if(useTorrentAdditionDialog) { if (useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoad(param); dialog->showLoad(param);
}else{ }else{
@ -985,7 +985,7 @@ void MainWindow::addTorrent(QString path) {
void MainWindow::processDownloadedFiles(QString path, QString url) { void MainWindow::processDownloadedFiles(QString path, QString url) {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool(); const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool();
if(useTorrentAdditionDialog) { if (useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoad(path, url); dialog->showLoad(path, url);
}else{ }else{
@ -1003,11 +1003,11 @@ void MainWindow::loadPreferences(bool configure_session) {
const Preferences pref; const Preferences pref;
const bool newSystrayIntegration = pref.systrayIntegration(); const bool newSystrayIntegration = pref.systrayIntegration();
actionLock_qBittorrent->setEnabled(newSystrayIntegration); actionLock_qBittorrent->setEnabled(newSystrayIntegration);
if(newSystrayIntegration != (systrayIcon!=0)) { if (newSystrayIntegration != (systrayIcon!=0)) {
if(newSystrayIntegration) { if (newSystrayIntegration) {
// create the trayicon // create the trayicon
if(!QSystemTrayIcon::isSystemTrayAvailable()) { if (!QSystemTrayIcon::isSystemTrayAvailable()) {
if(!configure_session) { // Program startup if (!configure_session) { // Program startup
systrayCreator = new QTimer(this); systrayCreator = new QTimer(this);
connect(systrayCreator, SIGNAL(timeout()), this, SLOT(createSystrayDelayed())); connect(systrayCreator, SIGNAL(timeout()), this, SLOT(createSystrayDelayed()));
systrayCreator->setSingleShot(true); systrayCreator->setSingleShot(true);
@ -1026,11 +1026,11 @@ void MainWindow::loadPreferences(bool configure_session) {
} }
} }
// Reload systray icon // Reload systray icon
if(newSystrayIntegration && systrayIcon) { if (newSystrayIntegration && systrayIcon) {
systrayIcon->setIcon(getSystrayIcon()); systrayIcon->setIcon(getSystrayIcon());
} }
// General // General
if(pref.isToolbarDisplayed()) { if (pref.isToolbarDisplayed()) {
toolBar->setVisible(true); toolBar->setVisible(true);
} else { } else {
// Clear search filter before hiding the top toolbar // Clear search filter before hiding the top toolbar
@ -1038,7 +1038,7 @@ void MainWindow::loadPreferences(bool configure_session) {
toolBar->setVisible(false); toolBar->setVisible(false);
} }
if(pref.preventFromSuspend()) if (pref.preventFromSuspend())
{ {
preventTimer->start(PREVENT_SUSPEND_INTERVAL); preventTimer->start(PREVENT_SUSPEND_INTERVAL);
} }
@ -1055,8 +1055,8 @@ void MainWindow::loadPreferences(bool configure_session) {
properties->getTrackerList()->setAlternatingRowColors(pref.useAlternatingRowColors()); properties->getTrackerList()->setAlternatingRowColors(pref.useAlternatingRowColors());
properties->getPeerList()->setAlternatingRowColors(pref.useAlternatingRowColors()); properties->getPeerList()->setAlternatingRowColors(pref.useAlternatingRowColors());
// Queueing System // Queueing System
if(pref.isQueueingSystemEnabled()) { if (pref.isQueueingSystemEnabled()) {
if(!actionDecreasePriority->isVisible()) { if (!actionDecreasePriority->isVisible()) {
transferList->hidePriorityColumn(false); transferList->hidePriorityColumn(false);
actionDecreasePriority->setVisible(true); actionDecreasePriority->setVisible(true);
actionIncreasePriority->setVisible(true); actionIncreasePriority->setVisible(true);
@ -1064,7 +1064,7 @@ void MainWindow::loadPreferences(bool configure_session) {
prioSeparatorMenu->setVisible(true); prioSeparatorMenu->setVisible(true);
} }
} else { } else {
if(actionDecreasePriority->isVisible()) { if (actionDecreasePriority->isVisible()) {
transferList->hidePriorityColumn(true); transferList->hidePriorityColumn(true);
actionDecreasePriority->setVisible(false); actionDecreasePriority->setVisible(false);
actionIncreasePriority->setVisible(false); actionIncreasePriority->setVisible(false);
@ -1081,7 +1081,7 @@ void MainWindow::loadPreferences(bool configure_session) {
IconProvider::instance()->useSystemIconTheme(pref.useSystemIconTheme()); IconProvider::instance()->useSystemIconTheme(pref.useSystemIconTheme());
#endif #endif
if(configure_session) if (configure_session)
QBtSession::instance()->configureSession(); QBtSession::instance()->configureSession();
qDebug("GUI settings loaded"); qDebug("GUI settings loaded");
@ -1089,14 +1089,14 @@ void MainWindow::loadPreferences(bool configure_session) {
void MainWindow::addUnauthenticatedTracker(const QPair<QTorrentHandle,QString> &tracker) { void MainWindow::addUnauthenticatedTracker(const QPair<QTorrentHandle,QString> &tracker) {
// Trackers whose authentication was cancelled // Trackers whose authentication was cancelled
if(unauthenticated_trackers.indexOf(tracker) < 0) { if (unauthenticated_trackers.indexOf(tracker) < 0) {
unauthenticated_trackers << tracker; unauthenticated_trackers << tracker;
} }
} }
// Called when a tracker requires authentication // Called when a tracker requires authentication
void MainWindow::trackerAuthenticationRequired(const QTorrentHandle& h) { void MainWindow::trackerAuthenticationRequired(const QTorrentHandle& h) {
if(unauthenticated_trackers.indexOf(QPair<QTorrentHandle,QString>(h, h.current_tracker())) < 0) { if (unauthenticated_trackers.indexOf(QPair<QTorrentHandle,QString>(h, h.current_tracker())) < 0) {
// Tracker login // Tracker login
new trackerLogin(this, h); new trackerLogin(this, h);
} }
@ -1105,7 +1105,7 @@ void MainWindow::trackerAuthenticationRequired(const QTorrentHandle& h) {
// Check connection status and display right icon // Check connection status and display right icon
void MainWindow::updateGUI() { void MainWindow::updateGUI() {
// update global informations // update global informations
if(systrayIcon) { if (systrayIcon) {
#if defined(Q_WS_X11) || defined(Q_WS_MAC) #if defined(Q_WS_X11) || defined(Q_WS_MAC)
QString html = "<div style='background-color: #678db2; color: #fff;height: 18px; font-weight: bold; margin-bottom: 5px;'>"; QString html = "<div style='background-color: #678db2; color: #fff;height: 18px; font-weight: bold; margin-bottom: 5px;'>";
html += tr("qBittorrent"); html += tr("qBittorrent");
@ -1124,28 +1124,28 @@ void MainWindow::updateGUI() {
#endif #endif
systrayIcon->setToolTip(html); // tray icon 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))); 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 { 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) #if defined(Q_WS_X11) && defined(QT_DBUS_LIB)
org::freedesktop::Notifications notifications("org.freedesktop.Notifications", org::freedesktop::Notifications notifications("org.freedesktop.Notifications",
"/org/freedesktop/Notifications", "/org/freedesktop/Notifications",
QDBusConnection::sessionBus()); QDBusConnection::sessionBus());
if(notifications.isValid()) { if (notifications.isValid()) {
QVariantMap hints; QVariantMap hints;
hints["desktop-entry"] = "qBittorrent"; hints["desktop-entry"] = "qBittorrent";
QDBusPendingReply<uint> reply = notifications.Notify("qBittorrent", 0, "qbittorrent", title, QDBusPendingReply<uint> reply = notifications.Notify("qBittorrent", 0, "qbittorrent", title,
msg, QStringList(), hints, -1); msg, QStringList(), hints, -1);
reply.waitForFinished(); reply.waitForFinished();
if(!reply.isError()) if (!reply.isError())
return; return;
} }
#endif #endif
if(systrayIcon && QSystemTrayIcon::supportsMessages()) if (systrayIcon && QSystemTrayIcon::supportsMessages())
systrayIcon->showMessage(title, msg, QSystemTrayIcon::Information, TIME_TRAY_BALLOON); 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) { void MainWindow::downloadFromURLList(const QStringList& url_list) {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool(); const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool();
foreach(QString url, url_list) { foreach (QString url, url_list) {
if(url.startsWith("bc://bt/", Qt::CaseInsensitive)) { if (url.startsWith("bc://bt/", Qt::CaseInsensitive)) {
qDebug("Converting bc link to magnet link"); qDebug("Converting bc link to magnet link");
url = misc::bcLinkToMagnet(url); url = misc::bcLinkToMagnet(url);
} }
if(url.startsWith("magnet:", Qt::CaseInsensitive)) { if (url.startsWith("magnet:", Qt::CaseInsensitive)) {
if(useTorrentAdditionDialog) { if (useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoadMagnetURI(url); dialog->showLoadMagnetURI(url);
} else { } else {
@ -1184,13 +1184,13 @@ void MainWindow::downloadFromURLList(const QStringList& url_list) {
void MainWindow::createSystrayDelayed() { void MainWindow::createSystrayDelayed() {
static int timeout = 20; static int timeout = 20;
if(QSystemTrayIcon::isSystemTrayAvailable()) { if (QSystemTrayIcon::isSystemTrayAvailable()) {
// Ok, systray integration is now supported // Ok, systray integration is now supported
// Create systray icon // Create systray icon
createTrayIcon(); createTrayIcon();
delete systrayCreator; delete systrayCreator;
} else { } else {
if(timeout) { if (timeout) {
// Retry a bit later // Retry a bit later
systrayCreator->start(2000); systrayCreator->start(2000);
--timeout; --timeout;
@ -1210,7 +1210,7 @@ void MainWindow::updateAltSpeedsBtn(bool alternative) {
} }
QMenu* MainWindow::getTrayIconMenu() { QMenu* MainWindow::getTrayIconMenu() {
if(myTrayIconMenu) if (myTrayIconMenu)
return myTrayIconMenu; return myTrayIconMenu;
// Tray icon Menu // Tray icon Menu
myTrayIconMenu = new QMenu(this); myTrayIconMenu = new QMenu(this);
@ -1231,7 +1231,7 @@ QMenu* MainWindow::getTrayIconMenu() {
myTrayIconMenu->addAction(actionPause_All); myTrayIconMenu->addAction(actionPause_All);
myTrayIconMenu->addSeparator(); myTrayIconMenu->addSeparator();
myTrayIconMenu->addAction(actionExit); myTrayIconMenu->addAction(actionExit);
if(ui_locked) if (ui_locked)
myTrayIconMenu->setEnabled(false); myTrayIconMenu->setEnabled(false);
return myTrayIconMenu; return myTrayIconMenu;
} }
@ -1249,7 +1249,7 @@ void MainWindow::createTrayIcon() {
// Display Program Options // Display Program Options
void MainWindow::on_actionOptions_triggered() { void MainWindow::on_actionOptions_triggered() {
if(options) { if (options) {
// Get focus // Get focus
options->setFocus(); options->setFocus();
} else { } else {
@ -1267,7 +1267,7 @@ void MainWindow::on_actionTop_tool_bar_triggered() {
void MainWindow::on_actionSpeed_in_title_bar_triggered() { void MainWindow::on_actionSpeed_in_title_bar_triggered() {
displaySpeedInTitle = static_cast<QAction*>(sender())->isChecked(); displaySpeedInTitle = static_cast<QAction*>(sender())->isChecked();
Preferences().showSpeedInTitleBar(displaySpeedInTitle); Preferences().showSpeedInTitleBar(displaySpeedInTitle);
if(displaySpeedInTitle) if (displaySpeedInTitle)
updateGUI(); updateGUI();
else else
setWindowTitle(tr("qBittorrent %1", "e.g: qBittorrent v0.x").arg(QString::fromUtf8(VERSION))); 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 // Display an input dialog to prompt user for
// an url // an url
void MainWindow::on_actionDownload_from_URL_triggered() { void MainWindow::on_actionDownload_from_URL_triggered() {
if(!downloadFromURLDialog) { if (!downloadFromURLDialog) {
downloadFromURLDialog = new downloadFromURL(this); downloadFromURLDialog = new downloadFromURL(this);
connect(downloadFromURLDialog, SIGNAL(urlsReadyToBeDownloaded(QStringList)), this, SLOT(downloadFromURLList(QStringList))); 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) void MainWindow::handleUpdateCheckFinished(bool update_available, QString new_version)
{ {
if(update_available) { if (update_available) {
if(QMessageBox::question(this, tr("A newer version is 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), 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) { QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
// The user want to update, let's download the update // 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) 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)); 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) void MainWindow::on_actionExecution_Logs_triggered(bool checked)
{ {
if(checked) { if (checked) {
Q_ASSERT(!m_executionLog); Q_ASSERT(!m_executionLog);
m_executionLog = new ExecutionLog(tabs); m_executionLog = new ExecutionLog(tabs);
int index_tab = tabs->addTab(m_executionLog, tr("Execution Log")); int index_tab = tabs->addTab(m_executionLog, tr("Execution Log"));
tabs->setTabIcon(index_tab, IconProvider::instance()->getIcon("view-calendar-journal")); tabs->setTabIcon(index_tab, IconProvider::instance()->getIcon("view-calendar-journal"));
} else { } else {
if(m_executionLog) if (m_executionLog)
delete m_executionLog; delete m_executionLog;
} }
Preferences().setExecutionLogEnabled(checked); Preferences().setExecutionLogEnabled(checked);
@ -1381,7 +1381,7 @@ void MainWindow::on_actionAutoShutdown_system_toggled(bool enabled)
void MainWindow::checkForActiveTorrents() void MainWindow::checkForActiveTorrents()
{ {
const TorrentStatusReport report = transferList->getSourceModel()->getTorrentStatusReport(); 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); m_pwr->setActivityState(true);
else else
m_pwr->setActivityState(false); m_pwr->setActivityState(false);

View file

@ -107,7 +107,7 @@ QString misc::QDesktopServicesDataLocation() {
result = QString::fromWCharArray(path); result = QString::fromWCharArray(path);
if (!QCoreApplication::applicationName().isEmpty()) if (!QCoreApplication::applicationName().isEmpty())
result = result + QLatin1String("\\") + qApp->applicationName(); result = result + QLatin1String("\\") + qApp->applicationName();
if(!result.endsWith("\\")) if (!result.endsWith("\\"))
result += "\\"; result += "\\";
return result; return result;
#else #else
@ -208,16 +208,16 @@ QString misc::QDesktopServicesDownloadLocation() {
} }
long long misc::freeDiskSpaceOnPath(QString path) { long long misc::freeDiskSpaceOnPath(QString path) {
if(path.isEmpty()) return -1; if (path.isEmpty()) return -1;
path.replace("\\", "/"); path.replace("\\", "/");
QDir dir_path(path); QDir dir_path(path);
if(!dir_path.exists()) { if (!dir_path.exists()) {
QStringList parts = path.split("/"); QStringList parts = path.split("/");
while (parts.size() > 1 && !QDir(parts.join("/")).exists()) { while (parts.size() > 1 && !QDir(parts.join("/")).exists()) {
parts.removeLast(); parts.removeLast();
} }
dir_path = QDir(parts.join("/")); dir_path = QDir(parts.join("/"));
if(!dir_path.exists()) return -1; if (!dir_path.exists()) return -1;
} }
Q_ASSERT(dir_path.exists()); Q_ASSERT(dir_path.exists());
@ -226,7 +226,7 @@ long long misc::freeDiskSpaceOnPath(QString path) {
struct statfs stats; struct statfs stats;
const QString statfs_path = dir_path.path()+"/."; const QString statfs_path = dir_path.path()+"/.";
const int ret = statfs (qPrintable(statfs_path), &stats) ; const int ret = statfs (qPrintable(statfs_path), &stats) ;
if(ret == 0) { if (ret == 0) {
available = ((unsigned long long)stats.f_bavail) * available = ((unsigned long long)stats.f_bavail) *
((unsigned long long)stats.f_bsize) ; ((unsigned long long)stats.f_bsize) ;
return available; return available;
@ -264,11 +264,11 @@ long long misc::freeDiskSpaceOnPath(QString path) {
void misc::shutdownComputer(bool sleep) { void misc::shutdownComputer(bool sleep) {
#if defined(Q_WS_X11) && defined(QT_DBUS_LIB) #if defined(Q_WS_X11) && defined(QT_DBUS_LIB)
// Use dbus to power off / suspend the system // Use dbus to power off / suspend the system
if(sleep) { if (sleep) {
// Recent systems use UPower // Recent systems use UPower
QDBusInterface upowerIface("org.freedesktop.UPower", "/org/freedesktop/UPower", QDBusInterface upowerIface("org.freedesktop.UPower", "/org/freedesktop/UPower",
"org.freedesktop.UPower", QDBusConnection::systemBus()); "org.freedesktop.UPower", QDBusConnection::systemBus());
if(upowerIface.isValid()) { if (upowerIface.isValid()) {
upowerIface.call("Suspend"); upowerIface.call("Suspend");
return; return;
} }
@ -281,7 +281,7 @@ void misc::shutdownComputer(bool sleep) {
// Recent systems use ConsoleKit // Recent systems use ConsoleKit
QDBusInterface consolekitIface("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Manager", QDBusInterface consolekitIface("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Manager",
"org.freedesktop.ConsoleKit.Manager", QDBusConnection::systemBus()); "org.freedesktop.ConsoleKit.Manager", QDBusConnection::systemBus());
if(consolekitIface.isValid()) { if (consolekitIface.isValid()) {
consolekitIface.call("Stop"); consolekitIface.call("Stop");
return; return;
} }
@ -294,7 +294,7 @@ void misc::shutdownComputer(bool sleep) {
#endif #endif
#ifdef Q_WS_MAC #ifdef Q_WS_MAC
AEEventID EventToSend; AEEventID EventToSend;
if(sleep) if (sleep)
EventToSend = kAESleep; EventToSend = kAESleep;
else else
EventToSend = kAEShutDown; EventToSend = kAEShutDown;
@ -336,7 +336,7 @@ void misc::shutdownComputer(bool sleep) {
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
HANDLE hToken; // handle to process token HANDLE hToken; // handle to process token
TOKEN_PRIVILEGES tkp; // pointer to token structure 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; return;
// Get the LUID for shutdown privilege. // Get the LUID for shutdown privilege.
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
@ -355,7 +355,7 @@ void misc::shutdownComputer(bool sleep) {
if (GetLastError() != ERROR_SUCCESS) if (GetLastError() != ERROR_SUCCESS)
return; return;
if(sleep) if (sleep)
SetSuspendState(false, false, false); SetSuspendState(false, false, false);
else else
InitiateSystemShutdownA(0, tr("qBittorrent will shutdown the computer now because all downloads are complete.").toLocal8Bit().data(), 10, true, false); 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; //qDebug() << Q_FUNC_INFO << path;
path.replace("\\", "/"); path.replace("\\", "/");
QStringList parts = path.split("/", QString::SkipEmptyParts); QStringList parts = path.split("/", QString::SkipEmptyParts);
if(parts.isEmpty()) return path; if (parts.isEmpty()) return path;
QString last_part = parts.takeLast(); QString last_part = parts.takeLast();
QList<QString>::iterator it; QList<QString>::iterator it;
for(it = parts.begin(); it != parts.end(); it++) { for (it = parts.begin(); it != parts.end(); it++) {
QByteArray raw_filename = it->toLocal8Bit(); QByteArray raw_filename = it->toLocal8Bit();
// Make sure the filename is not too long // 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"; qDebug() << "Folder" << *it << "was cut because it was too long";
raw_filename.resize(MAX_FILENAME_LENGTH); raw_filename.resize(MAX_FILENAME_LENGTH);
*it = QString::fromLocal8Bit(raw_filename.constData()); *it = QString::fromLocal8Bit(raw_filename.constData());
@ -389,12 +389,12 @@ QString misc::fixFileNames(QString path) {
// Fix the last part (file name) // Fix the last part (file name)
QByteArray raw_lastPart = last_part.toLocal8Bit(); QByteArray raw_lastPart = last_part.toLocal8Bit();
qDebug() << "Last part length:" << raw_lastPart.length(); 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"; qDebug() << "Filename" << last_part << "was cut because it was too long";
// Shorten the name, keep the file extension // Shorten the name, keep the file extension
int point_index = raw_lastPart.lastIndexOf("."); int point_index = raw_lastPart.lastIndexOf(".");
QByteArray extension = ""; QByteArray extension = "";
if(point_index >= 0) { if (point_index >= 0) {
extension = raw_lastPart.mid(point_index); extension = raw_lastPart.mid(point_index);
raw_lastPart = raw_lastPart.left(point_index); raw_lastPart = raw_lastPart.left(point_index);
} }
@ -408,7 +408,7 @@ QString misc::fixFileNames(QString path) {
} }
QString misc::truncateRootFolder(boost::intrusive_ptr<torrent_info> t) { QString misc::truncateRootFolder(boost::intrusive_ptr<torrent_info> t) {
if(t->num_files() == 1) { if (t->num_files() == 1) {
// Single file torrent // Single file torrent
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
QString path = QString::fromUtf8(t->file_at(0).path.c_str()); QString path = QString::fromUtf8(t->file_at(0).path.c_str());
@ -421,14 +421,14 @@ QString misc::truncateRootFolder(boost::intrusive_ptr<torrent_info> t) {
return QString(); return QString();
} }
QString root_folder; QString root_folder;
for(int i=0; i<t->num_files(); ++i) { for (int i=0; i<t->num_files(); ++i) {
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
QString path = QString::fromUtf8(t->file_at(i).path.c_str()); QString path = QString::fromUtf8(t->file_at(i).path.c_str());
#else #else
QString path = QString::fromUtf8(t->file_at(i).path.string().c_str()); QString path = QString::fromUtf8(t->file_at(i).path.string().c_str());
#endif #endif
QStringList path_parts = path.split("/", QString::SkipEmptyParts); QStringList path_parts = path.split("/", QString::SkipEmptyParts);
if(path_parts.size() > 1) { if (path_parts.size() > 1) {
root_folder = path_parts.takeFirst(); root_folder = path_parts.takeFirst();
} }
path = fixFileNames(path_parts.join("/")); path = fixFileNames(path_parts.join("/"));
@ -439,7 +439,7 @@ QString misc::truncateRootFolder(boost::intrusive_ptr<torrent_info> t) {
QString misc::truncateRootFolder(libtorrent::torrent_handle h) { QString misc::truncateRootFolder(libtorrent::torrent_handle h) {
torrent_info t = h.get_torrent_info(); torrent_info t = h.get_torrent_info();
if(t.num_files() == 1) { if (t.num_files() == 1) {
// Single file torrent // Single file torrent
// Remove possible subfolders // Remove possible subfolders
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
@ -452,14 +452,14 @@ QString misc::truncateRootFolder(libtorrent::torrent_handle h) {
return QString(); return QString();
} }
QString root_folder; QString root_folder;
for(int i=0; i<t.num_files(); ++i) { for (int i=0; i<t.num_files(); ++i) {
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
QString path = QString::fromUtf8(t.file_at(i).path.c_str()); QString path = QString::fromUtf8(t.file_at(i).path.c_str());
#else #else
QString path = QString::fromUtf8(t.file_at(i).path.string().c_str()); QString path = QString::fromUtf8(t.file_at(i).path.string().c_str());
#endif #endif
QStringList path_parts = path.split("/", QString::SkipEmptyParts); QStringList path_parts = path.split("/", QString::SkipEmptyParts);
if(path_parts.size() > 1) { if (path_parts.size() > 1) {
root_folder = path_parts.takeFirst(); root_folder = path_parts.takeFirst();
} }
path = fixFileNames(path_parts.join("/")); 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) { bool misc::sameFiles(const QString &path1, const QString &path2) {
QFile f1(path1), f2(path2); QFile f1(path1), f2(path2);
if(!f1.exists() || !f2.exists()) return false; if (!f1.exists() || !f2.exists()) return false;
if(f1.size() != f2.size()) return false; if (f1.size() != f2.size()) return false;
if(!f1.open(QIODevice::ReadOnly)) return false; if (!f1.open(QIODevice::ReadOnly)) return false;
if(!f2.open(QIODevice::ReadOnly)) { if (!f2.open(QIODevice::ReadOnly)) {
f1.close(); f1.close();
return false; return false;
} }
bool same = true; bool same = true;
while(!f1.atEnd() && !f2.atEnd()) { while(!f1.atEnd() && !f2.atEnd()) {
if(f1.read(5) != f2.read(5)) { if (f1.read(5) != f2.read(5)) {
same = false; same = false;
break; 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) { 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) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
defaultSavePath.replace("\\", "/"); defaultSavePath.replace("\\", "/");
save_path.replace("\\", "/"); save_path.replace("\\", "/");
#endif #endif
qDebug("UpdateLabelInSavePath(%s, %s, %s)", qPrintable(save_path), qPrintable(old_label), qPrintable(new_label)); 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; QString new_save_path = save_path;
new_save_path.replace(defaultSavePath, ""); new_save_path.replace(defaultSavePath, "");
QStringList path_parts = new_save_path.split("/", QString::SkipEmptyParts); QStringList path_parts = new_save_path.split("/", QString::SkipEmptyParts);
if(path_parts.empty()) { if (path_parts.empty()) {
if(!new_label.isEmpty()) if (!new_label.isEmpty())
path_parts << new_label; path_parts << new_label;
} else { } else {
if(old_label.isEmpty() || path_parts.first() != old_label) { if (old_label.isEmpty() || path_parts.first() != old_label) {
if(path_parts.first() != new_label) if (path_parts.first() != new_label)
path_parts.prepend(new_label); path_parts.prepend(new_label);
} else { } else {
if(new_label.isEmpty()) { if (new_label.isEmpty()) {
path_parts.removeAt(0); path_parts.removeAt(0);
} else { } else {
if(path_parts.first() != new_label) if (path_parts.first() != new_label)
path_parts.replace(0, new_label); path_parts.replace(0, new_label);
} }
} }
} }
new_save_path = defaultSavePath; 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()); new_save_path += path_parts.join(QDir::separator());
qDebug("New save path is %s", qPrintable(new_save_path)); qDebug("New save path is %s", qPrintable(new_save_path));
return new_save_path; return new_save_path;
@ -531,7 +531,7 @@ QString misc::toValidFileSystemName(QString filename) {
} }
bool misc::isValidFileSystemName(const QString& filename) { bool misc::isValidFileSystemName(const QString& filename) {
if(filename.isEmpty()) return false; if (filename.isEmpty()) return false;
const QRegExp regex("[\\\\/:?\"*<>|]"); const QRegExp regex("[\\\\/:?\"*<>|]");
return !filename.contains(regex); return !filename.contains(regex);
} }
@ -542,9 +542,9 @@ QPoint misc::screenCenter(QWidget *win) {
int scrn = 0; int scrn = 0;
const QWidget *w = win->window(); const QWidget *w = win->window();
if(w) if (w)
scrn = QApplication::desktop()->screenNumber(w); scrn = QApplication::desktop()->screenNumber(w);
else if(QApplication::desktop()->isVirtualDesktop()) else if (QApplication::desktop()->isVirtualDesktop())
scrn = QApplication::desktop()->screenNumber(QCursor::pos()); scrn = QApplication::desktop()->screenNumber(QCursor::pos());
else else
scrn = QApplication::desktop()->screenNumber(win); scrn = QApplication::desktop()->screenNumber(win);
@ -585,7 +585,7 @@ QString misc::searchEngineLocation() {
const QString location = QDir::cleanPath(QDesktopServicesDataLocation() const QString location = QDir::cleanPath(QDesktopServicesDataLocation()
+ QDir::separator() + folder); + QDir::separator() + folder);
QDir locationDir(location); QDir locationDir(location);
if(!locationDir.exists()) if (!locationDir.exists())
locationDir.mkpath(locationDir.absolutePath()); locationDir.mkpath(locationDir.absolutePath());
return location; return location;
} }
@ -594,7 +594,7 @@ QString misc::BTBackupLocation() {
const QString location = QDir::cleanPath(QDesktopServicesDataLocation() const QString location = QDir::cleanPath(QDesktopServicesDataLocation()
+ QDir::separator() + "BT_backup"); + QDir::separator() + "BT_backup");
QDir locationDir(location); QDir locationDir(location);
if(!locationDir.exists()) if (!locationDir.exists())
locationDir.mkpath(locationDir.absolutePath()); locationDir.mkpath(locationDir.absolutePath());
return location; return location;
} }
@ -602,7 +602,7 @@ QString misc::BTBackupLocation() {
QString misc::cacheLocation() { QString misc::cacheLocation() {
QString location = QDir::cleanPath(QDesktopServicesCacheLocation()); QString location = QDir::cleanPath(QDesktopServicesCacheLocation());
QDir locationDir(location); QDir locationDir(location);
if(!locationDir.exists()) if (!locationDir.exists())
locationDir.mkpath(locationDir.absolutePath()); locationDir.mkpath(locationDir.absolutePath());
return location; return location;
} }
@ -612,61 +612,61 @@ QString misc::cacheLocation() {
// see http://en.wikipedia.org/wiki/Kilobyte // see http://en.wikipedia.org/wiki/Kilobyte
// value must be given in bytes // value must be given in bytes
QString misc::friendlyUnit(qreal val) { QString misc::friendlyUnit(qreal val) {
if(val < 0) if (val < 0)
return tr("Unknown", "Unknown (size)"); return tr("Unknown", "Unknown (size)");
int i = 0; int i = 0;
while(val >= 1024. && i++<6) while(val >= 1024. && i++<6)
val /= 1024.; val /= 1024.;
if(i == 0) if (i == 0)
return QString::number((long)val) + " " + tr(units[0].source, units[0].comment); 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); return QString::number(val, 'f', 1) + " " + tr(units[i].source, units[i].comment);
} }
bool misc::isPreviewable(QString extension){ bool misc::isPreviewable(QString extension){
if(extension.isEmpty()) return false; if (extension.isEmpty()) return false;
extension = extension.toUpper(); extension = extension.toUpper();
if(extension == "AVI") return true; if (extension == "AVI") return true;
if(extension == "MP3") return true; if (extension == "MP3") return true;
if(extension == "OGG") return true; if (extension == "OGG") return true;
if(extension == "OGV") return true; if (extension == "OGV") return true;
if(extension == "OGM") return true; if (extension == "OGM") return true;
if(extension == "WMV") return true; if (extension == "WMV") return true;
if(extension == "WMA") return true; if (extension == "WMA") return true;
if(extension == "MPEG") return true; if (extension == "MPEG") return true;
if(extension == "MPG") return true; if (extension == "MPG") return true;
if(extension == "ASF") return true; if (extension == "ASF") return true;
if(extension == "QT") return true; if (extension == "QT") return true;
if(extension == "RM") return true; if (extension == "RM") return true;
if(extension == "RMVB") return true; if (extension == "RMVB") return true;
if(extension == "RMV") return true; if (extension == "RMV") return true;
if(extension == "SWF") return true; if (extension == "SWF") return true;
if(extension == "FLV") return true; if (extension == "FLV") return true;
if(extension == "WAV") return true; if (extension == "WAV") return true;
if(extension == "MOV") return true; if (extension == "MOV") return true;
if(extension == "VOB") return true; if (extension == "VOB") return true;
if(extension == "MID") return true; if (extension == "MID") return true;
if(extension == "AC3") return true; if (extension == "AC3") return true;
if(extension == "MP4") return true; if (extension == "MP4") return true;
if(extension == "MP2") return true; if (extension == "MP2") return true;
if(extension == "AVI") return true; if (extension == "AVI") return true;
if(extension == "FLAC") return true; if (extension == "FLAC") return true;
if(extension == "AU") return true; if (extension == "AU") return true;
if(extension == "MPE") return true; if (extension == "MPE") return true;
if(extension == "MOV") return true; if (extension == "MOV") return true;
if(extension == "MKV") return true; if (extension == "MKV") return true;
if(extension == "AIF") return true; if (extension == "AIF") return true;
if(extension == "AIFF") return true; if (extension == "AIFF") return true;
if(extension == "AIFC") return true; if (extension == "AIFC") return true;
if(extension == "RA") return true; if (extension == "RA") return true;
if(extension == "RAM") return true; if (extension == "RAM") return true;
if(extension == "M4P") return true; if (extension == "M4P") return true;
if(extension == "M4A") return true; if (extension == "M4A") return true;
if(extension == "3GP") return true; if (extension == "3GP") return true;
if(extension == "AAC") return true; if (extension == "AAC") return true;
if(extension == "SWA") return true; if (extension == "SWA") return true;
if(extension == "MPC") return true; if (extension == "MPC") return true;
if(extension == "MPP") return true; if (extension == "MPP") return true;
if(extension == "M3U") return true; if (extension == "M3U") return true;
return false; return false;
} }
@ -676,7 +676,7 @@ QString misc::bcLinkToMagnet(QString bc_link) {
raw_bc = QByteArray::fromBase64(raw_bc); // Decode base64 raw_bc = QByteArray::fromBase64(raw_bc); // Decode base64
// Format is now AA/url_encoded_filename/size_bytes/info_hash/ZZ // Format is now AA/url_encoded_filename/size_bytes/info_hash/ZZ
QStringList parts = QString(raw_bc).split("/"); 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 filename = parts.at(1);
QString hash = parts.at(3); QString hash = parts.at(3);
QString magnet = "magnet:?xt=urn:btih:" + hash; QString magnet = "magnet:?xt=urn:btih:" + hash;
@ -688,7 +688,7 @@ QString misc::magnetUriToName(QString magnet_uri) {
QString name = ""; QString name = "";
QRegExp regHex("dn=([^&]+)"); QRegExp regHex("dn=([^&]+)");
const int pos = regHex.indexIn(magnet_uri); const int pos = regHex.indexIn(magnet_uri);
if(pos > -1) { if (pos > -1) {
const QString found = regHex.cap(1); const QString found = regHex.cap(1);
// URL decode // URL decode
name = QUrl::fromPercentEncoding(found.toLocal8Bit()).replace("+", " "); name = QUrl::fromPercentEncoding(found.toLocal8Bit()).replace("+", " ");
@ -701,10 +701,10 @@ QString misc::magnetUriToHash(QString magnet_uri) {
QRegExp regHex("urn:btih:([0-9A-Za-z]+)"); QRegExp regHex("urn:btih:([0-9A-Za-z]+)");
// Hex // Hex
int pos = regHex.indexIn(magnet_uri); int pos = regHex.indexIn(magnet_uri);
if(pos > -1) { if (pos > -1) {
const QString found = regHex.cap(1); const QString found = regHex.cap(1);
qDebug() << Q_FUNC_INFO << "regex found: " << found; qDebug() << Q_FUNC_INFO << "regex found: " << found;
if(found.length() == 40) { if (found.length() == 40) {
const sha1_hash sha1(QByteArray::fromHex(found.toAscii()).constData()); const sha1_hash sha1(QByteArray::fromHex(found.toAscii()).constData());
qDebug("magnetUriToHash (Hex): hash: %s", qPrintable(misc::toQString(sha1))); qDebug("magnetUriToHash (Hex): hash: %s", qPrintable(misc::toQString(sha1)));
return misc::toQString(sha1); return misc::toQString(sha1);
@ -713,9 +713,9 @@ QString misc::magnetUriToHash(QString magnet_uri) {
// Base 32 // Base 32
QRegExp regBase32("urn:btih:([A-Za-z2-7=]+)"); QRegExp regBase32("urn:btih:([A-Za-z2-7=]+)");
pos = regBase32.indexIn(magnet_uri); pos = regBase32.indexIn(magnet_uri);
if(pos > -1) { if (pos > -1) {
const QString found = regBase32.cap(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())); const sha1_hash sha1(base32decode(regBase32.cap(1).toStdString()));
hash = misc::toQString(sha1); hash = misc::toQString(sha1);
} }
@ -727,14 +727,14 @@ QString misc::magnetUriToHash(QString magnet_uri) {
// Replace ~ in path // Replace ~ in path
QString misc::expandPath(QString path) { QString misc::expandPath(QString path) {
path = path.trimmed(); path = path.trimmed();
if(path.isEmpty()) return path; if (path.isEmpty()) return path;
if(path.length() == 1) { if (path.length() == 1) {
if(path[0] == '~' ) return QDir::homePath(); 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()); path.replace(0, 1, QDir::homePath());
} else { } else {
if(QDir::isAbsolutePath(path)) { if (QDir::isAbsolutePath(path)) {
path = QDir(path).absolutePath(); path = QDir(path).absolutePath();
} }
} }
@ -744,27 +744,27 @@ QString misc::expandPath(QString path) {
// Take a number of seconds and return an user-friendly // Take a number of seconds and return an user-friendly
// time duration like "1d 2h 10m". // time duration like "1d 2h 10m".
QString misc::userFriendlyDuration(qlonglong seconds) { QString misc::userFriendlyDuration(qlonglong seconds) {
if(seconds < 0 || seconds >= MAX_ETA) { if (seconds < 0 || seconds >= MAX_ETA) {
return QString::fromUtf8(""); return QString::fromUtf8("");
} }
if(seconds == 0) { if (seconds == 0) {
return "0"; return "0";
} }
if(seconds < 60) { if (seconds < 60) {
return tr("< 1m", "< 1 minute"); return tr("< 1m", "< 1 minute");
} }
int minutes = seconds / 60; int minutes = seconds / 60;
if(minutes < 60) { if (minutes < 60) {
return tr("%1m","e.g: 10minutes").arg(QString::number(minutes)); return tr("%1m","e.g: 10minutes").arg(QString::number(minutes));
} }
int hours = minutes / 60; int hours = minutes / 60;
minutes = minutes - hours*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)); return tr("%1h %2m", "e.g: 3hours 5minutes").arg(QString::number(hours)).arg(QString::number(minutes));
} }
int days = hours / 24; int days = hours / 24;
hours = hours - days * 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 tr("%1d %2h", "e.g: 2days 10hours").arg(QString::number(days)).arg(QString::number(hours));
} }
return QString::fromUtf8(""); return QString::fromUtf8("");
@ -785,7 +785,7 @@ QString misc::getUserIDString() {
QStringList misc::toStringList(const QList<bool> &l) { QStringList misc::toStringList(const QList<bool> &l) {
QStringList ret; QStringList ret;
foreach(const bool &b, l) { foreach (const bool &b, l) {
ret << (b ? "1" : "0"); ret << (b ? "1" : "0");
} }
return ret; return ret;
@ -793,7 +793,7 @@ QStringList misc::toStringList(const QList<bool> &l) {
QList<int> misc::intListfromStringList(const QStringList &l) { QList<int> misc::intListfromStringList(const QStringList &l) {
QList<int> ret; QList<int> ret;
foreach(const QString &s, l) { foreach (const QString &s, l) {
ret << s.toInt(); ret << s.toInt();
} }
return ret; return ret;
@ -801,7 +801,7 @@ QList<int> misc::intListfromStringList(const QStringList &l) {
QList<bool> misc::boolListfromStringList(const QStringList &l) { QList<bool> misc::boolListfromStringList(const QStringList &l) {
QList<bool> ret; QList<bool> ret;
foreach(const QString &s, l) { foreach (const QString &s, l) {
ret << (s=="1"); ret << (s=="1");
} }
return ret; return ret;
@ -811,13 +811,13 @@ quint64 misc::computePathSize(QString path)
{ {
// Check if it is a file // Check if it is a file
QFileInfo fi(path); QFileInfo fi(path);
if(!fi.exists()) return 0; if (!fi.exists()) return 0;
if(fi.isFile()) return fi.size(); if (fi.isFile()) return fi.size();
// Compute folder size // Compute folder size
quint64 size = 0; quint64 size = 0;
foreach(const QFileInfo &subfi, QDir(path).entryInfoList(QDir::Dirs|QDir::Files)) { foreach (const QFileInfo &subfi, QDir(path).entryInfoList(QDir::Dirs|QDir::Files)) {
if(subfi.fileName().startsWith(".")) continue; if (subfi.fileName().startsWith(".")) continue;
if(subfi.isDir()) if (subfi.isDir())
size += misc::computePathSize(subfi.absoluteFilePath()); size += misc::computePathSize(subfi.absoluteFilePath());
else else
size += subfi.size(); size += subfi.size();
@ -828,7 +828,7 @@ quint64 misc::computePathSize(QString path)
bool misc::isValidTorrentFile(const QString &torrent_path) { bool misc::isValidTorrentFile(const QString &torrent_path) {
try { try {
boost::intrusive_ptr<libtorrent::torrent_info> t = new torrent_info(torrent_path.toUtf8().constData()); boost::intrusive_ptr<libtorrent::torrent_info> 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(); throw std::exception();
} catch(std::exception&) { } catch(std::exception&) {
return false; return false;
@ -842,13 +842,13 @@ bool misc::isValidTorrentFile(const QString &torrent_path) {
*/ */
QString misc::branchPath(QString file_path, bool uses_slashes) QString misc::branchPath(QString file_path, bool uses_slashes)
{ {
if(!uses_slashes) if (!uses_slashes)
file_path.replace("\\", "/"); file_path.replace("\\", "/");
Q_ASSERT(!file_path.contains("\\")); Q_ASSERT(!file_path.contains("\\"));
if(file_path.endsWith("/")) if (file_path.endsWith("/"))
file_path.chop(1); // Remove trailing slash file_path.chop(1); // Remove trailing slash
qDebug() << Q_FUNC_INFO << "before:" << file_path; qDebug() << Q_FUNC_INFO << "before:" << file_path;
if(file_path.contains("/")) if (file_path.contains("/"))
return file_path.left(file_path.lastIndexOf('/')); return file_path.left(file_path.lastIndexOf('/'));
return ""; return "";
} }
@ -864,7 +864,7 @@ QString misc::fileName(QString file_path)
{ {
file_path.replace("\\", "/"); file_path.replace("\\", "/");
const int slash_index = file_path.lastIndexOf('/'); const int slash_index = file_path.lastIndexOf('/');
if(slash_index == -1) if (slash_index == -1)
return file_path; return file_path;
return file_path.mid(slash_index+1); return file_path.mid(slash_index+1);
} }

View file

@ -81,7 +81,7 @@ public:
static inline QString file_extension(const QString &filename) { static inline QString file_extension(const QString &filename) {
QString extension; QString extension;
int point_index = filename.lastIndexOf("."); int point_index = filename.lastIndexOf(".");
if(point_index >= 0) { if (point_index >= 0) {
extension = filename.mid(point_index+1); extension = filename.mid(point_index+1);
} }
return extension; return extension;

View file

@ -56,13 +56,13 @@ PowerManagement::~PowerManagement()
void PowerManagement::setActivityState(bool busy) void PowerManagement::setActivityState(bool busy)
{ {
if(busy) setBusy(); if (busy) setBusy();
else setIdle(); else setIdle();
} }
void PowerManagement::setBusy() void PowerManagement::setBusy()
{ {
if(m_busy) return; if (m_busy) return;
m_busy = true; m_busy = true;
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
@ -71,13 +71,13 @@ void PowerManagement::setBusy()
m_inhibitor->RequestBusy(); m_inhibitor->RequestBusy();
#elif defined(Q_WS_MAC) #elif defined(Q_WS_MAC)
IOReturn success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &m_assertionID); IOReturn success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &m_assertionID);
if(success != kIOReturnSuccess) m_busy = false; if (success != kIOReturnSuccess) m_busy = false;
#endif #endif
} }
void PowerManagement::setIdle() void PowerManagement::setIdle()
{ {
if(!m_busy) return; if (!m_busy) return;
m_busy = false; m_busy = false;
#ifdef Q_WS_WIN #ifdef Q_WS_WIN

View file

@ -37,7 +37,7 @@
PowerManagementInhibitor::PowerManagementInhibitor(QObject *parent) : QObject(parent) PowerManagementInhibitor::PowerManagementInhibitor(QObject *parent) : QObject(parent)
{ {
if(!QDBusConnection::sessionBus().isConnected()) if (!QDBusConnection::sessionBus().isConnected())
{ {
qDebug("D-Bus: Could not connect to session bus"); qDebug("D-Bus: Could not connect to session bus");
m_state = error; m_state = error;
@ -134,7 +134,7 @@ void PowerManagementInhibitor::OnAsyncReply(QDBusPendingCallWatcher *call)
{ {
QDBusPendingReply<> reply = *call; QDBusPendingReply<> reply = *call;
if(reply.isError()) if (reply.isError())
{ {
qDebug("D-Bus: Reply: Error: %s", qPrintable(reply.error().message())); qDebug("D-Bus: Reply: Error: %s", qPrintable(reply.error().message()));
m_state = error; m_state = error;
@ -150,7 +150,7 @@ void PowerManagementInhibitor::OnAsyncReply(QDBusPendingCallWatcher *call)
{ {
QDBusPendingReply<uint> reply = *call; QDBusPendingReply<uint> reply = *call;
if(reply.isError()) if (reply.isError())
{ {
qDebug("D-Bus: Reply: Error: %s", qPrintable(reply.error().message())); qDebug("D-Bus: Reply: Error: %s", qPrintable(reply.error().message()));

View file

@ -84,7 +84,7 @@ public slots:
// Super seeding // Super seeding
pref.enableSuperSeeding(cb_super_seeding.isChecked()); pref.enableSuperSeeding(cb_super_seeding.isChecked());
// Network interface // Network interface
if(combo_iface.currentIndex() == 0) { if (combo_iface.currentIndex() == 0) {
// All interfaces (default) // All interfaces (default)
pref.setNetworkInterface(QString::null); pref.setNetworkInterface(QString::null);
} else { } else {
@ -92,7 +92,7 @@ public slots:
} }
// Network address // Network address
QHostAddress addr(txt_network_address.text().trimmed()); QHostAddress addr(txt_network_address.text().trimmed());
if(addr.isNull()) if (addr.isNull())
pref.setNetworkAddress(""); pref.setNetworkAddress("");
else else
pref.setNetworkAddress(addr.toString()); pref.setNetworkAddress(addr.toString());
@ -199,10 +199,10 @@ private slots:
combo_iface.addItem(tr("Any interface", "i.e. Any network interface")); combo_iface.addItem(tr("Any interface", "i.e. Any network interface"));
const QString current_iface = pref.getNetworkInterface(); const QString current_iface = pref.getNetworkInterface();
int i = 1; int i = 1;
foreach(const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) { foreach (const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) {
if(iface.flags() & QNetworkInterface::IsLoopBack) continue; if (iface.flags() & QNetworkInterface::IsLoopBack) continue;
combo_iface.addItem(iface.name()); 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); combo_iface.setCurrentIndex(i);
++i; ++i;
} }

View file

@ -81,8 +81,8 @@ options_imp::options_imp(QWidget *parent):
hsplitter->setCollapsible(1, false); hsplitter->setCollapsible(1, false);
// Get apply button in button box // Get apply button in button box
QList<QAbstractButton *> buttons = buttonBox->buttons(); QList<QAbstractButton *> buttons = buttonBox->buttons();
foreach(QAbstractButton *button, buttons){ foreach (QAbstractButton *button, buttons){
if(buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole){ if (buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole){
applyButton = button; applyButton = button;
break; break;
} }
@ -98,7 +98,7 @@ options_imp::options_imp(QWidget *parent):
initializeLanguageCombo(); initializeLanguageCombo();
// Load week days (scheduler) // Load week days (scheduler)
for(uint i=1; i<=7; ++i) { for (uint i=1; i<=7; ++i) {
#if QT_VERSION >= 0x040500 #if QT_VERSION >= 0x040500
schedule_days->addItem(QDate::longDayName(i, QDate::StandaloneFormat)); schedule_days->addItem(QDate::longDayName(i, QDate::StandaloneFormat));
#else #else
@ -109,7 +109,7 @@ options_imp::options_imp(QWidget *parent):
// Load options // Load options
loadOptions(); loadOptions();
// Disable systray integration if it is not supported by the system // Disable systray integration if it is not supported by the system
if(!QSystemTrayIcon::isSystemTrayAvailable()){ if (!QSystemTrayIcon::isSystemTrayAvailable()){
checkShowSystray->setChecked(false); checkShowSystray->setChecked(false);
checkShowSystray->setEnabled(false); checkShowSystray->setEnabled(false);
} }
@ -267,7 +267,7 @@ void options_imp::initializeLanguageCombo()
// List language files // List language files
const QDir lang_dir(":/lang"); const QDir lang_dir(":/lang");
const QStringList lang_files = lang_dir.entryList(QStringList() << "qbittorrent_*.qm", QDir::Files); 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_" QString localeStr = lang_file.mid(12); // remove "qbittorrent_"
localeStr.chop(3); // Remove ".qm" localeStr.chop(3); // Remove ".qm"
QLocale locale(localeStr); QLocale locale(localeStr);
@ -297,13 +297,13 @@ void options_imp::loadWindowState() {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
resize(settings.value(QString::fromUtf8("Preferences/State/size"), sizeFittingScreen()).toSize()); resize(settings.value(QString::fromUtf8("Preferences/State/size"), sizeFittingScreen()).toSize());
QPoint p = settings.value(QString::fromUtf8("Preferences/State/pos"), QPoint()).toPoint(); QPoint p = settings.value(QString::fromUtf8("Preferences/State/pos"), QPoint()).toPoint();
if(!p.isNull()) if (!p.isNull())
move(p); move(p);
// Load slider size // Load slider size
const QStringList sizes_str = settings.value("Preferences/State/hSplitterSizes", QStringList()).toStringList(); const QStringList sizes_str = settings.value("Preferences/State/hSplitterSizes", QStringList()).toStringList();
// Splitter size // Splitter size
QList<int> sizes; QList<int> sizes;
if(sizes_str.size() == 2) { if (sizes_str.size() == 2) {
sizes << sizes_str.first().toInt(); sizes << sizes_str.first().toInt();
sizes << sizes_str.last().toInt(); sizes << sizes_str.last().toInt();
} else { } else {
@ -328,16 +328,16 @@ QSize options_imp::sizeFittingScreen() const {
int scrn = 0; int scrn = 0;
QWidget *w = this->topLevelWidget(); QWidget *w = this->topLevelWidget();
if(w) if (w)
scrn = QApplication::desktop()->screenNumber(w); scrn = QApplication::desktop()->screenNumber(w);
else if(QApplication::desktop()->isVirtualDesktop()) else if (QApplication::desktop()->isVirtualDesktop())
scrn = QApplication::desktop()->screenNumber(QCursor::pos()); scrn = QApplication::desktop()->screenNumber(QCursor::pos());
else else
scrn = QApplication::desktop()->screenNumber(this); scrn = QApplication::desktop()->screenNumber(this);
QRect desk(QApplication::desktop()->availableGeometry(scrn)); QRect desk(QApplication::desktop()->availableGeometry(scrn));
if(width() > desk.width() || height() > desk.height()) { if (width() > desk.width() || height() > desk.height()) {
if(desk.width() > 0 && desk.height() > 0) if (desk.width() > 0 && desk.height() > 0)
return QSize(desk.width(), desk.height()); return QSize(desk.width(), desk.height());
} }
return size(); return size();
@ -348,9 +348,9 @@ void options_imp::saveOptions(){
Preferences pref; Preferences pref;
// Load the translation // Load the translation
QString locale = getLocale(); QString locale = getLocale();
if(pref.getLocale() != locale) { if (pref.getLocale() != locale) {
QTranslator *translator = new QTranslator; 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)); qDebug("%s locale recognized, using translation.", qPrintable(locale));
}else{ }else{
qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale)); qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale));
@ -454,7 +454,7 @@ void options_imp::saveOptions(){
// Misc preferences // Misc preferences
// * IPFilter // * IPFilter
pref.setFilteringEnabled(isFilteringEnabled()); pref.setFilteringEnabled(isFilteringEnabled());
if(isFilteringEnabled()){ if (isFilteringEnabled()){
QString filter_path = textFilterPath->text(); QString filter_path = textFilterPath->text();
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
filter_path.replace("\\", "/"); filter_path.replace("\\", "/");
@ -471,12 +471,12 @@ void options_imp::saveOptions(){
// End Queueing system preferences // End Queueing system preferences
// Web UI // Web UI
pref.setWebUiEnabled(isWebUiEnabled()); pref.setWebUiEnabled(isWebUiEnabled());
if(isWebUiEnabled()) if (isWebUiEnabled())
{ {
pref.setWebUiPort(webUiPort()); pref.setWebUiPort(webUiPort());
pref.setUPnPForWebUIPort(checkWebUIUPnP->isChecked()); pref.setUPnPForWebUIPort(checkWebUIUPnP->isChecked());
pref.setWebUiHttpsEnabled(checkWebUiHttps->isChecked()); pref.setWebUiHttpsEnabled(checkWebUiHttps->isChecked());
if(checkWebUiHttps->isChecked()) if (checkWebUiHttps->isChecked())
{ {
pref.setWebUiHttpsCertificate(m_sslCert); pref.setWebUiHttpsCertificate(m_sslCert);
pref.setWebUiHttpsKey(m_sslKey); pref.setWebUiHttpsKey(m_sslKey);
@ -508,12 +508,12 @@ int options_imp::getProxyType() const{
return Proxy::SOCKS4; return Proxy::SOCKS4;
break; break;
case 2: case 2:
if(isProxyAuthEnabled()){ if (isProxyAuthEnabled()){
return Proxy::SOCKS5_PW; return Proxy::SOCKS5_PW;
} }
return Proxy::SOCKS5; return Proxy::SOCKS5;
case 3: case 3:
if(isProxyAuthEnabled()){ if (isProxyAuthEnabled()){
return Proxy::HTTP_PW; return Proxy::HTTP_PW;
} }
return Proxy::HTTP; return Proxy::HTTP;
@ -532,7 +532,7 @@ void options_imp::loadOptions(){
checkAltRowColors->setChecked(pref.useAlternatingRowColors()); checkAltRowColors->setChecked(pref.useAlternatingRowColors());
checkShowSystray->setChecked(pref.systrayIntegration()); checkShowSystray->setChecked(pref.systrayIntegration());
checkShowSplash->setChecked(!pref.isSlashScreenDisabled()); checkShowSplash->setChecked(!pref.isSlashScreenDisabled());
if(checkShowSystray->isChecked()) { if (checkShowSystray->isChecked()) {
checkCloseToSystray->setChecked(pref.closeToTray()); checkCloseToSystray->setChecked(pref.closeToTray());
checkMinimizeToSysTray->setChecked(pref.minimizeToTray()); checkMinimizeToSysTray->setChecked(pref.minimizeToTray());
checkStartMinimized->setChecked(pref.startMinimized()); checkStartMinimized->setChecked(pref.startMinimized());
@ -552,7 +552,7 @@ void options_imp::loadOptions(){
save_path.replace("/", "\\"); save_path.replace("/", "\\");
#endif #endif
textSavePath->setText(save_path); textSavePath->setText(save_path);
if(pref.isTempPathEnabled()) { if (pref.isTempPathEnabled()) {
// enable // enable
checkTempFolder->setChecked(true); checkTempFolder->setChecked(true);
} else { } else {
@ -570,7 +570,7 @@ void options_imp::loadOptions(){
checkStartPaused->setChecked(pref.addTorrentsInPause()); checkStartPaused->setChecked(pref.addTorrentsInPause());
strValue = pref.getExportDir(); strValue = pref.getExportDir();
if(strValue.isEmpty()) { if (strValue.isEmpty()) {
// Disable // Disable
checkExportDir->setChecked(false); checkExportDir->setChecked(false);
} else { } else {
@ -591,11 +591,11 @@ void options_imp::loadOptions(){
autoRunBox->setChecked(pref.isAutoRunEnabled()); autoRunBox->setChecked(pref.isAutoRunEnabled());
autoRun_txt->setText(pref.getAutoRunProgram()); autoRun_txt->setText(pref.getAutoRunProgram());
intValue = pref.getActionOnDblClOnTorrentDl(); intValue = pref.getActionOnDblClOnTorrentDl();
if(intValue >= actionTorrentDlOnDblClBox->count()) if (intValue >= actionTorrentDlOnDblClBox->count())
intValue = 0; intValue = 0;
actionTorrentDlOnDblClBox->setCurrentIndex(intValue); actionTorrentDlOnDblClBox->setCurrentIndex(intValue);
intValue = pref.getActionOnDblClOnTorrentFn(); intValue = pref.getActionOnDblClOnTorrentFn();
if(intValue >= actionTorrentFnOnDblClBox->count()) if (intValue >= actionTorrentFnOnDblClBox->count())
intValue = 1; intValue = 1;
actionTorrentFnOnDblClBox->setCurrentIndex(intValue); actionTorrentFnOnDblClBox->setCurrentIndex(intValue);
// End Downloads preferences // End Downloads preferences
@ -603,7 +603,7 @@ void options_imp::loadOptions(){
spinPort->setValue(pref.getSessionPort()); spinPort->setValue(pref.getSessionPort());
checkUPnP->setChecked(pref.isUPnPEnabled()); checkUPnP->setChecked(pref.isUPnPEnabled());
intValue = pref.getGlobalDownloadLimit(); intValue = pref.getGlobalDownloadLimit();
if(intValue > 0) { if (intValue > 0) {
// Enabled // Enabled
checkDownloadLimit->setChecked(true); checkDownloadLimit->setChecked(true);
spinDownloadLimit->setEnabled(true); spinDownloadLimit->setEnabled(true);
@ -614,7 +614,7 @@ void options_imp::loadOptions(){
spinDownloadLimit->setEnabled(false); spinDownloadLimit->setEnabled(false);
} }
intValue = pref.getGlobalUploadLimit(); intValue = pref.getGlobalUploadLimit();
if(intValue != -1) { if (intValue != -1) {
// Enabled // Enabled
checkUploadLimit->setChecked(true); checkUploadLimit->setChecked(true);
spinUploadLimit->setEnabled(true); spinUploadLimit->setEnabled(true);
@ -653,7 +653,7 @@ void options_imp::loadOptions(){
comboProxyType->setCurrentIndex(0); comboProxyType->setCurrentIndex(0);
} }
enableProxy(comboProxyType->currentIndex()); enableProxy(comboProxyType->currentIndex());
//if(isProxyEnabled()) { //if (isProxyEnabled()) {
// Proxy is enabled, save settings // Proxy is enabled, save settings
textProxyIP->setText(pref.getProxyIp()); textProxyIP->setText(pref.getProxyIp());
spinProxyPort->setValue(pref.getProxyPort()); spinProxyPort->setValue(pref.getProxyPort());
@ -665,7 +665,7 @@ void options_imp::loadOptions(){
// End Connection preferences // End Connection preferences
// Bittorrent preferences // Bittorrent preferences
intValue = pref.getMaxConnecs(); intValue = pref.getMaxConnecs();
if(intValue > 0) { if (intValue > 0) {
// enable // enable
checkMaxConnecs->setChecked(true); checkMaxConnecs->setChecked(true);
spinMaxConnec->setEnabled(true); spinMaxConnec->setEnabled(true);
@ -676,7 +676,7 @@ void options_imp::loadOptions(){
spinMaxConnec->setEnabled(false); spinMaxConnec->setEnabled(false);
} }
intValue = pref.getMaxConnecsPerTorrent(); intValue = pref.getMaxConnecsPerTorrent();
if(intValue > 0) { if (intValue > 0) {
// enable // enable
checkMaxConnecsPerTorrent->setChecked(true); checkMaxConnecsPerTorrent->setChecked(true);
spinMaxConnecPerTorrent->setEnabled(true); spinMaxConnecPerTorrent->setEnabled(true);
@ -687,7 +687,7 @@ void options_imp::loadOptions(){
spinMaxConnecPerTorrent->setEnabled(false); spinMaxConnecPerTorrent->setEnabled(false);
} }
intValue = pref.getMaxUploadsPerTorrent(); intValue = pref.getMaxUploadsPerTorrent();
if(intValue > 0) { if (intValue > 0) {
// enable // enable
checkMaxUploadsPerTorrent->setChecked(true); checkMaxUploadsPerTorrent->setChecked(true);
spinMaxUploadsPerTorrent->setEnabled(true); spinMaxUploadsPerTorrent->setEnabled(true);
@ -708,7 +708,7 @@ void options_imp::loadOptions(){
#endif #endif
// Ratio limit // Ratio limit
floatValue = pref.getGlobalMaxRatio(); floatValue = pref.getGlobalMaxRatio();
if(floatValue >= 0.) { if (floatValue >= 0.) {
// Enable // Enable
checkMaxRatio->setChecked(true); checkMaxRatio->setChecked(true);
spinMaxRatio->setEnabled(true); spinMaxRatio->setEnabled(true);
@ -783,12 +783,12 @@ int options_imp::getMaxActiveTorrents() const {
} }
bool options_imp::minimizeToTray() const{ bool options_imp::minimizeToTray() const{
if(!checkShowSystray->isChecked()) return false; if (!checkShowSystray->isChecked()) return false;
return checkMinimizeToSysTray->isChecked(); return checkMinimizeToSysTray->isChecked();
} }
bool options_imp::closeToTray() const{ bool options_imp::closeToTray() const{
if(!checkShowSystray->isChecked()) return false; if (!checkShowSystray->isChecked()) return false;
return checkCloseToSystray->isChecked(); return checkCloseToSystray->isChecked();
} }
@ -812,17 +812,17 @@ bool options_imp::isUPnPEnabled() const{
// [download,upload] // [download,upload]
QPair<int,int> options_imp::getGlobalBandwidthLimits() const{ QPair<int,int> options_imp::getGlobalBandwidthLimits() const{
int DL = -1, UP = -1; int DL = -1, UP = -1;
if(checkDownloadLimit->isChecked()){ if (checkDownloadLimit->isChecked()){
DL = spinDownloadLimit->value(); DL = spinDownloadLimit->value();
} }
if(checkUploadLimit->isChecked()){ if (checkUploadLimit->isChecked()){
UP = spinUploadLimit->value(); UP = spinUploadLimit->value();
} }
return qMakePair(DL, UP); return qMakePair(DL, UP);
} }
bool options_imp::startMinimized() const { bool options_imp::startMinimized() const {
if(checkStartMinimized->isChecked()) return true; if (checkStartMinimized->isChecked()) return true;
return checkStartMinimized->isChecked(); return checkStartMinimized->isChecked();
} }
@ -837,7 +837,7 @@ int options_imp::getDHTPort() const {
// Return Share ratio // Return Share ratio
qreal options_imp::getMaxRatio() const{ qreal options_imp::getMaxRatio() const{
if(checkMaxRatio->isChecked()){ if (checkMaxRatio->isChecked()){
return spinMaxRatio->value(); return spinMaxRatio->value();
} }
return -1; return -1;
@ -845,7 +845,7 @@ qreal options_imp::getMaxRatio() const{
// Return Save Path // Return Save Path
QString options_imp::getSavePath() const{ QString options_imp::getSavePath() const{
if(textSavePath->text().trimmed().isEmpty()){ if (textSavePath->text().trimmed().isEmpty()){
QString save_path = Preferences().getSavePath(); QString save_path = Preferences().getSavePath();
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
save_path.replace("/", "\\"); save_path.replace("/", "\\");
@ -865,7 +865,7 @@ bool options_imp::isTempPathEnabled() const {
// Return max connections number // Return max connections number
int options_imp::getMaxConnecs() const{ int options_imp::getMaxConnecs() const{
if(!checkMaxConnecs->isChecked()){ if (!checkMaxConnecs->isChecked()){
return -1; return -1;
}else{ }else{
return spinMaxConnec->value(); return spinMaxConnec->value();
@ -873,7 +873,7 @@ int options_imp::getMaxConnecs() const{
} }
int options_imp::getMaxConnecsPerTorrent() const{ int options_imp::getMaxConnecsPerTorrent() const{
if(!checkMaxConnecsPerTorrent->isChecked()){ if (!checkMaxConnecsPerTorrent->isChecked()){
return -1; return -1;
}else{ }else{
return spinMaxConnecPerTorrent->value(); return spinMaxConnecPerTorrent->value();
@ -881,7 +881,7 @@ int options_imp::getMaxConnecsPerTorrent() const{
} }
int options_imp::getMaxUploadsPerTorrent() const{ int options_imp::getMaxUploadsPerTorrent() const{
if(!checkMaxUploadsPerTorrent->isChecked()){ if (!checkMaxUploadsPerTorrent->isChecked()){
return -1; return -1;
}else{ }else{
return spinMaxUploadsPerTorrent->value(); return spinMaxUploadsPerTorrent->value();
@ -889,7 +889,7 @@ int options_imp::getMaxUploadsPerTorrent() const{
} }
void options_imp::on_buttonBox_accepted(){ void options_imp::on_buttonBox_accepted(){
if(applyButton->isEnabled()){ if (applyButton->isEnabled()){
saveOptions(); saveOptions();
applyButton->setEnabled(false); applyButton->setEnabled(false);
this->hide(); this->hide();
@ -900,7 +900,7 @@ void options_imp::on_buttonBox_accepted(){
} }
void options_imp::applySettings(QAbstractButton* button) { void options_imp::applySettings(QAbstractButton* button) {
if(button == applyButton){ if (button == applyButton){
saveOptions(); saveOptions();
emit status_changed(); emit status_changed();
} }
@ -925,14 +925,14 @@ void options_imp::enableApplyButton(){
} }
void options_imp::enableProxy(int index){ void options_imp::enableProxy(int index){
if(index){ if (index){
//enable //enable
lblProxyIP->setEnabled(true); lblProxyIP->setEnabled(true);
textProxyIP->setEnabled(true); textProxyIP->setEnabled(true);
lblProxyPort->setEnabled(true); lblProxyPort->setEnabled(true);
spinProxyPort->setEnabled(true); spinProxyPort->setEnabled(true);
checkProxyPeerConnecs->setEnabled(true); checkProxyPeerConnecs->setEnabled(true);
if(index > 1) { if (index > 1) {
checkProxyAuth->setEnabled(true); checkProxyAuth->setEnabled(true);
} else { } else {
checkProxyAuth->setEnabled(false); checkProxyAuth->setEnabled(false);
@ -1008,7 +1008,7 @@ void options_imp::setLocale(const QString &localeStr) {
QLocale locale(localeStr); QLocale locale(localeStr);
// Attempt to find exact match // Attempt to find exact match
int index = comboI18n->findData(locale.name(), Qt::UserRole); int index = comboI18n->findData(locale.name(), Qt::UserRole);
if(index < 0) { if (index < 0) {
// Unreconized, use US English // Unreconized, use US English
index = comboI18n->findData(QLocale("en").name(), Qt::UserRole); index = comboI18n->findData(QLocale("en").name(), Qt::UserRole);
Q_ASSERT(index >= 0); Q_ASSERT(index >= 0);
@ -1017,21 +1017,21 @@ void options_imp::setLocale(const QString &localeStr) {
} }
QString options_imp::getExportDir() const { QString options_imp::getExportDir() const {
if(checkExportDir->isChecked()) if (checkExportDir->isChecked())
return misc::expandPath(textExportDir->text()); return misc::expandPath(textExportDir->text());
return QString(); return QString();
} }
// Return action on double-click on a downloading torrent set in options // Return action on double-click on a downloading torrent set in options
int options_imp::getActionOnDblClOnTorrentDl() const { int options_imp::getActionOnDblClOnTorrentDl() const {
if(actionTorrentDlOnDblClBox->currentIndex() < 1) if (actionTorrentDlOnDblClBox->currentIndex() < 1)
return 0; return 0;
return actionTorrentDlOnDblClBox->currentIndex(); return actionTorrentDlOnDblClBox->currentIndex();
} }
// Return action on double-click on a finished torrent set in options // Return action on double-click on a finished torrent set in options
int options_imp::getActionOnDblClOnTorrentFn() const { int options_imp::getActionOnDblClOnTorrentFn() const {
if(actionTorrentFnOnDblClBox->currentIndex() < 1) if (actionTorrentFnOnDblClBox->currentIndex() < 1)
return 0; return 0;
return actionTorrentFnOnDblClBox->currentIndex(); return actionTorrentFnOnDblClBox->currentIndex();
} }
@ -1079,12 +1079,12 @@ void options_imp::on_browseExportDirButton_clicked() {
const QString export_path = misc::expandPath(textExportDir->text()); const QString export_path = misc::expandPath(textExportDir->text());
QDir exportDir(export_path); QDir exportDir(export_path);
QString dir; QString dir;
if(!export_path.isEmpty() && exportDir.exists()) { if (!export_path.isEmpty() && exportDir.exists()) {
dir = QFileDialog::getExistingDirectory(this, tr("Choose export directory"), exportDir.absolutePath()); dir = QFileDialog::getExistingDirectory(this, tr("Choose export directory"), exportDir.absolutePath());
} else { } else {
dir = QFileDialog::getExistingDirectory(this, tr("Choose export directory"), QDir::homePath()); 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) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
dir.replace("/", "\\"); dir.replace("/", "\\");
#endif #endif
@ -1096,12 +1096,12 @@ void options_imp::on_browseFilterButton_clicked() {
const QString filter_path = misc::expandPath(textFilterPath->text()); const QString filter_path = misc::expandPath(textFilterPath->text());
QDir filterDir(filter_path); QDir filterDir(filter_path);
QString ipfilter; 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)")); ipfilter = QFileDialog::getOpenFileName(this, tr("Choose an ip filter file"), filterDir.absolutePath(), tr("Filters")+QString(" (*.dat *.p2p *.p2b)"));
} else { } else {
ipfilter = QFileDialog::getOpenFileName(this, tr("Choose an ip filter file"), QDir::homePath(), tr("Filters")+QString(" (*.dat *.p2p *.p2b)")); 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) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
ipfilter.replace("/", "\\"); ipfilter.replace("/", "\\");
#endif #endif
@ -1114,12 +1114,12 @@ void options_imp::on_browseSaveDirButton_clicked(){
const QString save_path = misc::expandPath(textSavePath->text()); const QString save_path = misc::expandPath(textSavePath->text());
QDir saveDir(save_path); QDir saveDir(save_path);
QString dir; 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()); dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), saveDir.absolutePath());
} else { } else {
dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), QDir::homePath()); 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) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
dir.replace("/", "\\"); dir.replace("/", "\\");
#endif #endif
@ -1131,12 +1131,12 @@ void options_imp::on_browseTempDirButton_clicked(){
const QString temp_path = misc::expandPath(textTempPath->text()); const QString temp_path = misc::expandPath(textTempPath->text());
QDir tempDir(temp_path); QDir tempDir(temp_path);
QString dir; 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()); dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), tempDir.absolutePath());
} else { } else {
dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), QDir::homePath()); 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) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
dir.replace("/", "\\"); dir.replace("/", "\\");
#endif #endif
@ -1178,7 +1178,7 @@ void options_imp::showConnectionTab()
void options_imp::on_btnWebUiCrt_clicked() { void options_imp::on_btnWebUiCrt_clicked() {
QString filename = QFileDialog::getOpenFileName(this, QString(), QString(), tr("SSL Certificate (*.crt *.pem)")); QString filename = QFileDialog::getOpenFileName(this, QString(), QString(), tr("SSL Certificate (*.crt *.pem)"));
if(filename.isNull()) if (filename.isNull())
return; return;
QFile file(filename); QFile file(filename);
if (file.open(QIODevice::ReadOnly)) { if (file.open(QIODevice::ReadOnly)) {
@ -1189,7 +1189,7 @@ void options_imp::on_btnWebUiCrt_clicked() {
void options_imp::on_btnWebUiKey_clicked() { void options_imp::on_btnWebUiKey_clicked() {
QString filename = QFileDialog::getOpenFileName(this, QString(), QString(), tr("SSL Key (*.key *.pem)")); QString filename = QFileDialog::getOpenFileName(this, QString(), QString(), tr("SSL Key (*.key *.pem)"));
if(filename.isNull()) if (filename.isNull())
return; return;
QFile file(filename); QFile file(filename);
if (file.open(QIODevice::ReadOnly)) { if (file.open(QIODevice::ReadOnly)) {
@ -1203,7 +1203,7 @@ void options_imp::on_registerDNSBtn_clicked() {
} }
void options_imp::on_IpFilterRefreshBtn_clicked() { void options_imp::on_IpFilterRefreshBtn_clicked() {
if(m_refreshingIpFilter) return; if (m_refreshingIpFilter) return;
m_refreshingIpFilter = true; m_refreshingIpFilter = true;
// Updating program preferences // Updating program preferences
Preferences pref; Preferences pref;
@ -1218,7 +1218,7 @@ void options_imp::on_IpFilterRefreshBtn_clicked() {
void options_imp::handleIPFilterParsed(bool error, int ruleCount) void options_imp::handleIPFilterParsed(bool error, int ruleCount)
{ {
setCursor(QCursor(Qt::ArrowCursor)); setCursor(QCursor(Qt::ArrowCursor));
if(error) { if (error) {
QMessageBox::warning(this, tr("Parsing error"), tr("Failed to parse the provided IP filter")); QMessageBox::warning(this, tr("Parsing error"), tr("Failed to parse the provided IP filter"));
} else { } else {
QMessageBox::information(this, tr("Successfully refreshed"), tr("Successfuly parsed the provided IP filter: %1 rules were applied.", "%1 is a number").arg(ruleCount)); 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::Catalan: return QString::fromUtf8("Català");
case QLocale::Galician: return QString::fromUtf8("Galego"); case QLocale::Galician: return QString::fromUtf8("Galego");
case QLocale::Portuguese: { case QLocale::Portuguese: {
if(country == "br") if (country == "br")
return QString::fromUtf8("Português brasileiro"); return QString::fromUtf8("Português brasileiro");
return QString::fromUtf8("Português"); 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::Georgian: return QString::fromUtf8("ქართული");
case QLocale::Byelorussian: return QString::fromUtf8("Беларуская"); case QLocale::Byelorussian: return QString::fromUtf8("Беларуская");
case QLocale::Chinese: { case QLocale::Chinese: {
if(country == "cn") if (country == "cn")
return QString::fromUtf8("中文 (简体)"); return QString::fromUtf8("中文 (简体)");
return QString::fromUtf8("中文 (繁體)"); return QString::fromUtf8("中文 (繁體)");
} }

View file

@ -280,7 +280,7 @@ public:
void setExportDir(QString path) { void setExportDir(QString path) {
path = path.trimmed(); path = path.trimmed();
if(path.isEmpty()) if (path.isEmpty())
path = QString(); path = QString();
setValue(QString::fromUtf8("Preferences/Downloads/TorrentExport"), path); setValue(QString::fromUtf8("Preferences/Downloads/TorrentExport"), path);
} }
@ -379,7 +379,7 @@ public:
} }
void setGlobalDownloadLimit(int limit) { void setGlobalDownloadLimit(int limit) {
if(limit <= 0) limit = -1; if (limit <= 0) limit = -1;
setValue("Preferences/Connection/GlobalDLLimit", limit); setValue("Preferences/Connection/GlobalDLLimit", limit);
} }
@ -388,31 +388,31 @@ public:
} }
void setGlobalUploadLimit(int limit) { void setGlobalUploadLimit(int limit) {
if(limit <= 0) limit = -1; if (limit <= 0) limit = -1;
setValue("Preferences/Connection/GlobalUPLimit", limit); setValue("Preferences/Connection/GlobalUPLimit", limit);
} }
int getAltGlobalDownloadLimit() const { int getAltGlobalDownloadLimit() const {
int ret = value(QString::fromUtf8("Preferences/Connection/GlobalDLLimitAlt"), 10).toInt(); int ret = value(QString::fromUtf8("Preferences/Connection/GlobalDLLimitAlt"), 10).toInt();
if(ret <= 0) if (ret <= 0)
ret = 10; ret = 10;
return ret; return ret;
} }
void setAltGlobalDownloadLimit(int limit) { void setAltGlobalDownloadLimit(int limit) {
if(limit <= 0) limit = -1; if (limit <= 0) limit = -1;
setValue("Preferences/Connection/GlobalDLLimitAlt", limit); setValue("Preferences/Connection/GlobalDLLimitAlt", limit);
} }
int getAltGlobalUploadLimit() const { int getAltGlobalUploadLimit() const {
int ret = value(QString::fromUtf8("Preferences/Connection/GlobalUPLimitAlt"), 10).toInt(); int ret = value(QString::fromUtf8("Preferences/Connection/GlobalUPLimitAlt"), 10).toInt();
if(ret <= 0) if (ret <= 0)
ret = 10; ret = 10;
return ret; return ret;
} }
void setAltGlobalUploadLimit(int limit) { void setAltGlobalUploadLimit(int limit) {
if(limit <= 0) limit = -1; if (limit <= 0) limit = -1;
setValue("Preferences/Connection/GlobalUPLimitAlt", limit); setValue("Preferences/Connection/GlobalUPLimitAlt", limit);
} }
@ -523,7 +523,7 @@ public:
} }
void setMaxConnecs(int val) { void setMaxConnecs(int val) {
if(val <= 0) val = -1; if (val <= 0) val = -1;
setValue(QString::fromUtf8("Preferences/Bittorrent/MaxConnecs"), val); setValue(QString::fromUtf8("Preferences/Bittorrent/MaxConnecs"), val);
} }
@ -532,7 +532,7 @@ public:
} }
void setMaxConnecsPerTorrent(int val) { void setMaxConnecsPerTorrent(int val) {
if(val <= 0) val = -1; if (val <= 0) val = -1;
setValue(QString::fromUtf8("Preferences/Bittorrent/MaxConnecsPerTorrent"), val); setValue(QString::fromUtf8("Preferences/Bittorrent/MaxConnecsPerTorrent"), val);
} }
@ -541,7 +541,7 @@ public:
} }
void setMaxUploadsPerTorrent(int val) { void setMaxUploadsPerTorrent(int val) {
if(val <= 0) val = -1; if (val <= 0) val = -1;
setValue(QString::fromUtf8("Preferences/Bittorrent/MaxUploadsPerTorrent"), val); setValue(QString::fromUtf8("Preferences/Bittorrent/MaxUploadsPerTorrent"), val);
} }
@ -644,7 +644,7 @@ public:
void banIP(const QString &ip) { void banIP(const QString &ip) {
QStringList banned_ips = value(QString::fromUtf8("Preferences/IPFilter/BannedIPs"), QStringList()).toStringList(); QStringList banned_ips = value(QString::fromUtf8("Preferences/IPFilter/BannedIPs"), QStringList()).toStringList();
if(!banned_ips.contains(ip)) { if (!banned_ips.contains(ip)) {
banned_ips << ip; banned_ips << ip;
setValue("Preferences/IPFilter/BannedIPs", banned_ips); setValue("Preferences/IPFilter/BannedIPs", banned_ips);
} }
@ -687,7 +687,7 @@ public:
} }
void setMaxActiveDownloads(int val) { void setMaxActiveDownloads(int val) {
if(val < 0) val = -1; if (val < 0) val = -1;
setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveDownloads"), val); setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveDownloads"), val);
} }
@ -696,7 +696,7 @@ public:
} }
void setMaxActiveUploads(int val) { void setMaxActiveUploads(int val) {
if(val < 0) val = -1; if (val < 0) val = -1;
setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveUploads"), val); setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveUploads"), val);
} }
@ -705,7 +705,7 @@ public:
} }
void setMaxActiveTorrents(int val) { void setMaxActiveTorrents(int val) {
if(val < 0) val = -1; if (val < 0) val = -1;
setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveTorrents"), val); setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveTorrents"), val);
} }
@ -761,7 +761,7 @@ public:
// Get current password md5 // Get current password md5
QString current_pass_md5 = getWebUiPassword(); QString current_pass_md5 = getWebUiPassword();
// Check if password did not change // 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 // Encode to md5 and save
QCryptographicHash md5(QCryptographicHash::Md5); QCryptographicHash md5(QCryptographicHash::Md5);
md5.addData(getWebUiUsername().toLocal8Bit()+":"+QBT_REALM+":"); md5.addData(getWebUiUsername().toLocal8Bit()+":"+QBT_REALM+":");
@ -772,7 +772,7 @@ public:
QString getWebUiPassword() const { QString getWebUiPassword() const {
QString pass_ha1 = value("Preferences/WebUI/Password_ha1", "").toString(); QString pass_ha1 = value("Preferences/WebUI/Password_ha1", "").toString();
if(pass_ha1.isEmpty()) { if (pass_ha1.isEmpty()) {
QCryptographicHash md5(QCryptographicHash::Md5); QCryptographicHash md5(QCryptographicHash::Md5);
md5.addData(getWebUiUsername().toLocal8Bit()+":"+QBT_REALM+":"); md5.addData(getWebUiUsername().toLocal8Bit()+":"+QBT_REALM+":");
md5.addData("adminadmin"); md5.addData("adminadmin");
@ -988,12 +988,12 @@ public:
int getMaxHalfOpenConnections() const { int getMaxHalfOpenConnections() const {
const int val = value(QString::fromUtf8("Preferences/Connection/MaxHalfOpenConnec"), 50).toInt(); const int val = value(QString::fromUtf8("Preferences/Connection/MaxHalfOpenConnec"), 50).toInt();
if(val <= 0) return -1; if (val <= 0) return -1;
return val; return val;
} }
void setMaxHalfOpenConnections(int value) { void setMaxHalfOpenConnections(int value) {
if(value <= 0) value = -1; if (value <= 0) value = -1;
setValue(QString::fromUtf8("Preferences/Connection/MaxHalfOpenConnec"), value); setValue(QString::fromUtf8("Preferences/Connection/MaxHalfOpenConnec"), value);
} }
@ -1055,14 +1055,14 @@ public:
void addTorrentLabel(const QString& label) { void addTorrentLabel(const QString& label) {
QStringList labels = value("TransferListFilters/customLabels").toStringList(); QStringList labels = value("TransferListFilters/customLabels").toStringList();
if(!labels.contains(label)) if (!labels.contains(label))
labels << label; labels << label;
setValue("TransferListFilters/customLabels", labels); setValue("TransferListFilters/customLabels", labels);
} }
void removeTorrentLabel(const QString& label) { void removeTorrentLabel(const QString& label) {
QStringList labels = value("TransferListFilters/customLabels").toStringList(); QStringList labels = value("TransferListFilters/customLabels").toStringList();
if(labels.contains(label)) if (labels.contains(label))
labels.removeOne(label); labels.removeOne(label);
setValue("TransferListFilters/customLabels", labels); setValue("TransferListFilters/customLabels", labels);
} }
@ -1086,7 +1086,7 @@ public:
const QString version = versions.takeLast(); const QString version = versions.takeLast();
qDebug("Detected possible Python v%s location", qPrintable(version)); qDebug("Detected possible Python v%s location", qPrintable(version));
QString path = reg_python.value(version+"/InstallPath/Default", "").toString().replace("/", "\\"); 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)); qDebug("Found python.exe at %s", qPrintable(path));
return path; return path;
} }
@ -1094,8 +1094,8 @@ public:
// Fallback: Detect python from default locations // Fallback: Detect python from default locations
QStringList supported_versions; QStringList supported_versions;
supported_versions << "32" << "31" << "30" << "27" << "26" << "25"; supported_versions << "32" << "31" << "30" << "27" << "26" << "25";
foreach(const QString &v, supported_versions) { foreach (const QString &v, supported_versions) {
if(QFile::exists("C:/Python"+v+"/python.exe")) { if (QFile::exists("C:/Python"+v+"/python.exe")) {
reg_python.setValue(v[0]+"."+v[1]+"/InstallPath/Default", QString("C:\\Python"+v)); reg_python.setValue(v[0]+"."+v[1]+"/InstallPath/Default", QString("C:\\Python"+v));
return "C:\\Python"+v; return "C:\\Python"+v;
} }
@ -1113,7 +1113,7 @@ public:
static bool isTorrentFileAssocSet() { static bool isTorrentFileAssocSet() {
QSettings settings("HKEY_CLASSES_ROOT", QIniSettings::NativeFormat); QSettings settings("HKEY_CLASSES_ROOT", QIniSettings::NativeFormat);
if(settings.value(".torrent/Default").toString() != "qBittorrent") { if (settings.value(".torrent/Default").toString() != "qBittorrent") {
qDebug(".torrent != qBittorrent"); qDebug(".torrent != qBittorrent");
return false; return false;
} }
@ -1121,15 +1121,15 @@ public:
QString shell_command = settings.value("qBittorrent/shell/open/command/Default", "").toString(); QString shell_command = settings.value("qBittorrent/shell/open/command/Default", "").toString();
qDebug("Shell command is: %s", qPrintable(shell_command)); qDebug("Shell command is: %s", qPrintable(shell_command));
QRegExp exe_reg("\"([^\"]+)\".*"); QRegExp exe_reg("\"([^\"]+)\".*");
if(exe_reg.indexIn(shell_command) < 0) if (exe_reg.indexIn(shell_command) < 0)
return false; return false;
QString assoc_exe = exe_reg.cap(1); QString assoc_exe = exe_reg.cap(1);
qDebug("exe: %s", qPrintable(assoc_exe)); 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 false;
// Icon // Icon
const QString icon_str = "\""+qApp->applicationFilePath().replace("/", "\\")+"\",1"; 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 false;
return true; return true;
@ -1141,11 +1141,11 @@ public:
// Check magnet link assoc // Check magnet link assoc
QRegExp exe_reg("\"([^\"]+)\".*"); QRegExp exe_reg("\"([^\"]+)\".*");
QString shell_command = settings.value("Magnet/shell/open/command/Default", "").toString(); 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; return false;
QString assoc_exe = exe_reg.cap(1); QString assoc_exe = exe_reg.cap(1);
qDebug("exe: %s", qPrintable(assoc_exe)); 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 false;
return true; return true;
} }

View file

@ -56,10 +56,10 @@ PreviewSelect::PreviewSelect(QWidget* parent, QTorrentHandle h): QDialog(parent)
std::vector<libtorrent::size_type> fp; std::vector<libtorrent::size_type> fp;
h.file_progress(fp); h.file_progress(fp);
unsigned int nbFiles = h.num_files(); unsigned int nbFiles = h.num_files();
for(unsigned int i=0; i<nbFiles; ++i){ for (unsigned int i=0; i<nbFiles; ++i){
QString fileName = h.filename_at(i); QString fileName = h.filename_at(i);
QString extension = fileName.split(QString::fromUtf8(".")).last().toUpper(); QString extension = fileName.split(QString::fromUtf8(".")).last().toUpper();
if(misc::isPreviewable(extension)) { if (misc::isPreviewable(extension)) {
int row = previewListModel->rowCount(); int row = previewListModel->rowCount();
previewListModel->insertRow(row); previewListModel->insertRow(row);
previewListModel->setData(previewListModel->index(row, NAME), QVariant(fileName)); 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, NAME), QItemSelectionModel::Select);
previewList->selectionModel()->select(previewListModel->index(0, SIZE), QItemSelectionModel::Select); previewList->selectionModel()->select(previewListModel->index(0, SIZE), QItemSelectionModel::Select);
previewList->selectionModel()->select(previewListModel->index(0, PROGRESS), 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")); QMessageBox::critical(0, tr("Preview impossible"), tr("Sorry, we can't preview this file"));
close(); close();
} }
connect(this, SIGNAL(readyToPreviewFile(QString)), parent, SLOT(previewFile(QString))); 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"); qDebug("Torrent file only contains one file, no need to display selection dialog before preview");
// Only one file : no choice // Only one file : no choice
on_previewButton_clicked(); on_previewButton_clicked();
@ -95,15 +95,15 @@ PreviewSelect::~PreviewSelect(){
void PreviewSelect::on_previewButton_clicked(){ void PreviewSelect::on_previewButton_clicked(){
QModelIndex index; QModelIndex index;
QModelIndexList selectedIndexes = previewList->selectionModel()->selectedRows(NAME); QModelIndexList selectedIndexes = previewList->selectionModel()->selectedRows(NAME);
if(selectedIndexes.size() == 0) return; if (selectedIndexes.size() == 0) return;
// Flush data // Flush data
h.flush_cache(); h.flush_cache();
QString path; QString path;
foreach(index, selectedIndexes){ foreach (index, selectedIndexes){
path = h.absolute_files_path().at(indexes.at(index.row())); path = h.absolute_files_path().at(indexes.at(index.row()));
// File // File
if(QFile::exists(path)){ if (QFile::exists(path)){
emit readyToPreviewFile(path); emit readyToPreviewFile(path);
} else { } else {
QMessageBox::critical(0, tr("Preview impossible"), tr("Sorry, we can't preview this file")); QMessageBox::critical(0, tr("Preview impossible"), tr("Sorry, we can't preview this file"));

View file

@ -55,7 +55,7 @@ ProgramUpdater::ProgramUpdater(QObject *parent) :
mp_manager = new QNetworkAccessManager(this); mp_manager = new QNetworkAccessManager(this);
Preferences pref; Preferences pref;
// Proxy support // Proxy support
if(pref.isProxyEnabled()) { if (pref.isProxyEnabled()) {
QNetworkProxy proxy; QNetworkProxy proxy;
switch(pref.getProxyType()) { switch(pref.getProxyType()) {
case Proxy::SOCKS4: case Proxy::SOCKS4:
@ -69,7 +69,7 @@ ProgramUpdater::ProgramUpdater(QObject *parent) :
proxy.setHostName(pref.getProxyIp()); proxy.setHostName(pref.getProxyIp());
proxy.setPort(pref.getProxyPort()); proxy.setPort(pref.getProxyPort());
// Proxy authentication // Proxy authentication
if(pref.isProxyAuthEnabled()) { if (pref.isProxyAuthEnabled()) {
proxy.setUser(pref.getProxyUsername()); proxy.setUser(pref.getProxyUsername());
proxy.setPassword(pref.getProxyPassword()); proxy.setPassword(pref.getProxyPassword());
} }
@ -101,7 +101,7 @@ void ProgramUpdater::rssDownloadFinished(QNetworkReply *reply)
disconnect(mp_manager, 0, this, 0); disconnect(mp_manager, 0, this, 0);
qDebug("Finished downloading the new qBittorrent updates RSS"); qDebug("Finished downloading the new qBittorrent updates RSS");
QString new_version; QString new_version;
if(!reply->error()) { if (!reply->error()) {
qDebug("No download error, good."); qDebug("No download error, good.");
QXmlStreamReader xml(reply); QXmlStreamReader xml(reply);
QString item_title; QString item_title;
@ -117,16 +117,16 @@ void ProgramUpdater::rssDownloadFinished(QNetworkReply *reply)
in_item = true; in_item = true;
} }
} else if (xml.isEndElement()) { } else if (xml.isEndElement()) {
if(in_item && xml.name() == "title") { if (in_item && xml.name() == "title") {
in_title = false; in_title = false;
const QString ext = misc::file_extension(item_title).toUpper(); const QString ext = misc::file_extension(item_title).toUpper();
qDebug("Found an update with file extension: %s", qPrintable(ext)); 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)); qDebug("The last update available is %s", qPrintable(item_title));
new_version = extractVersionNumber(item_title); new_version = extractVersionNumber(item_title);
if(!new_version.isEmpty()) { if (!new_version.isEmpty()) {
qDebug("Detected version is %s", qPrintable(new_version)); qDebug("Detected version is %s", qPrintable(new_version));
if(isVersionMoreRecent(new_version)) if (isVersionMoreRecent(new_version))
setUpdateUrl(item_title); setUpdateUrl(item_title);
} }
break; break;
@ -135,7 +135,7 @@ void ProgramUpdater::rssDownloadFinished(QNetworkReply *reply)
in_item = false; in_item = false;
} }
} else if (xml.isCharacters() && !xml.isWhitespace()) { } else if (xml.isCharacters() && !xml.isWhitespace()) {
if(in_item && in_title) if (in_item && in_title)
item_title += xml.text().toString(); item_title += xml.text().toString();
} }
} }
@ -161,14 +161,14 @@ void ProgramUpdater::updateProgram()
// Disconnect SIGNAL/SLOT // Disconnect SIGNAL/SLOT
disconnect(mp_manager, 0, this, 0); disconnect(mp_manager, 0, this, 0);
// Process the download // Process the download
if(!reply->error()) { if (!reply->error()) {
// Save the file // Save the file
const QString installer_path = QDir::temp().absoluteFilePath("qbittorrent_update."+FILE_EXT.toLower()); const QString installer_path = QDir::temp().absoluteFilePath("qbittorrent_update."+FILE_EXT.toLower());
QFile update_installer(installer_path); QFile update_installer(installer_path);
if(update_installer.exists()) { if (update_installer.exists()) {
update_installer.remove(); update_installer.remove();
} }
if(update_installer.open(QIODevice::WriteOnly)) { if (update_installer.open(QIODevice::WriteOnly)) {
update_installer.write(reply->readAll()); update_installer.write(reply->readAll());
reply->close(); reply->close();
update_installer.close(); update_installer.close();

View file

@ -59,7 +59,7 @@ public:
QString getIP() const { QString getIP() const {
QHostAddress ip(lineIP->text()); QHostAddress ip(lineIP->text());
if(!ip.isNull()) { if (!ip.isNull()) {
// QHostAddress::toString() cleans up the IP for libtorrent // QHostAddress::toString() cleans up the IP for libtorrent
return ip.toString(); return ip.toString();
} }
@ -73,11 +73,11 @@ public:
static libtorrent::asio::ip::tcp::endpoint askForPeerEndpoint() { static libtorrent::asio::ip::tcp::endpoint askForPeerEndpoint() {
libtorrent::asio::ip::tcp::endpoint ep; libtorrent::asio::ip::tcp::endpoint ep;
PeerAdditionDlg dlg; PeerAdditionDlg dlg;
if(dlg.exec() == QDialog::Accepted) { if (dlg.exec() == QDialog::Accepted) {
QString ip = dlg.getIP(); QString ip = dlg.getIP();
boost::system::error_code ec; boost::system::error_code ec;
libtorrent::address addr = libtorrent::address::from_string(qPrintable(ip), 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)); qDebug("Unable to parse the provided IP: %s", qPrintable(ip));
return ep; return ep;
} }
@ -90,7 +90,7 @@ public:
protected slots: protected slots:
void validateInput() { void validateInput() {
if(getIP().isEmpty()) { if (getIP().isEmpty()) {
QMessageBox::warning(this, tr("Invalid IP"), QMessageBox::warning(this, tr("Invalid IP"),
tr("The IP you provided is invalid."), tr("The IP you provided is invalid."),
QMessageBox::Ok); QMessageBox::Ok);

View file

@ -92,30 +92,30 @@ PeerListWidget::~PeerListWidget() {
delete proxyModel; delete proxyModel;
delete listModel; delete listModel;
delete listDelegate; delete listDelegate;
if(resolver) if (resolver)
delete resolver; delete resolver;
} }
void PeerListWidget::updatePeerHostNameResolutionState() { void PeerListWidget::updatePeerHostNameResolutionState() {
if(Preferences().resolvePeerHostNames()) { if (Preferences().resolvePeerHostNames()) {
if(!resolver) { if (!resolver) {
resolver = new ReverseResolution(this); resolver = new ReverseResolution(this);
connect(resolver, SIGNAL(ip_resolved(QString,QString)), this, SLOT(handleResolved(QString,QString))); connect(resolver, SIGNAL(ip_resolved(QString,QString)), this, SLOT(handleResolved(QString,QString)));
loadPeers(properties->getCurrentTorrent(), true); loadPeers(properties->getCurrentTorrent(), true);
} }
} else { } else {
if(resolver) { if (resolver) {
delete resolver; delete resolver;
} }
} }
} }
void PeerListWidget::updatePeerCountryResolutionState() { void PeerListWidget::updatePeerCountryResolutionState() {
if(Preferences().resolvePeerCountries() != display_flags) { if (Preferences().resolvePeerCountries() != display_flags) {
display_flags = !display_flags; display_flags = !display_flags;
if(display_flags) { if (display_flags) {
const QTorrentHandle h = properties->getCurrentTorrent(); const QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) return; if (!h.is_valid()) return;
loadPeers(h); loadPeers(h);
} }
} }
@ -125,17 +125,17 @@ void PeerListWidget::showPeerListMenu(QPoint) {
QMenu menu; QMenu menu;
bool empty_menu = true; bool empty_menu = true;
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) return; if (!h.is_valid()) return;
QModelIndexList selectedIndexes = selectionModel()->selectedRows(); QModelIndexList selectedIndexes = selectionModel()->selectedRows();
QStringList selectedPeerIPs; QStringList selectedPeerIPs;
foreach(const QModelIndex &index, selectedIndexes) { foreach (const QModelIndex &index, selectedIndexes) {
int row = proxyModel->mapToSource(index).row(); int row = proxyModel->mapToSource(index).row();
QString myip = listModel->data(listModel->index(row, PeerListDelegate::IP_HIDDEN)).toString(); QString myip = listModel->data(listModel->index(row, PeerListDelegate::IP_HIDDEN)).toString();
selectedPeerIPs << myip; selectedPeerIPs << myip;
} }
// Add Peer Action // Add Peer Action
QAction *addPeerAct = 0; 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...")); addPeerAct = menu.addAction(IconProvider::instance()->getIcon("user-group-new"), tr("Add a new peer..."));
empty_menu = false; empty_menu = false;
} }
@ -144,7 +144,7 @@ void PeerListWidget::showPeerListMenu(QPoint) {
QAction *dlLimitAct = 0; QAction *dlLimitAct = 0;
QAction *banAct = 0; QAction *banAct = 0;
QAction *copyIPAct = 0; QAction *copyIPAct = 0;
if(!selectedPeerIPs.isEmpty()) { if (!selectedPeerIPs.isEmpty()) {
copyIPAct = menu.addAction(IconProvider::instance()->getIcon("edit-copy"), tr("Copy IP")); copyIPAct = menu.addAction(IconProvider::instance()->getIcon("edit-copy"), tr("Copy IP"));
menu.addSeparator(); menu.addSeparator();
dlLimitAct = menu.addAction(QIcon(":/Icons/skin/download.png"), tr("Limit download rate...")); 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")); banAct = menu.addAction(IconProvider::instance()->getIcon("user-group-delete"), tr("Ban peer permanently"));
empty_menu = false; empty_menu = false;
} }
if(empty_menu) return; if (empty_menu) return;
QAction *act = menu.exec(QCursor::pos()); QAction *act = menu.exec(QCursor::pos());
if(act == 0) return; if (act == 0) return;
if(act == addPeerAct) { if (act == addPeerAct) {
libtorrent::asio::ip::tcp::endpoint ep = PeerAdditionDlg::askForPeerEndpoint(); libtorrent::asio::ip::tcp::endpoint ep = PeerAdditionDlg::askForPeerEndpoint();
if(ep != libtorrent::asio::ip::tcp::endpoint()) { if (ep != libtorrent::asio::ip::tcp::endpoint()) {
try { try {
h.connect_peer(ep); h.connect_peer(ep);
QMessageBox::information(0, tr("Peer addition"), tr("The peer was added to this torrent.")); QMessageBox::information(0, tr("Peer addition"), tr("The peer was added to this torrent."));
@ -170,19 +170,19 @@ void PeerListWidget::showPeerListMenu(QPoint) {
} }
return; return;
} }
if(act == upLimitAct) { if (act == upLimitAct) {
limitUpRateSelectedPeers(selectedPeerIPs); limitUpRateSelectedPeers(selectedPeerIPs);
return; return;
} }
if(act == dlLimitAct) { if (act == dlLimitAct) {
limitDlRateSelectedPeers(selectedPeerIPs); limitDlRateSelectedPeers(selectedPeerIPs);
return; return;
} }
if(act == banAct) { if (act == banAct) {
banSelectedPeers(selectedPeerIPs); banSelectedPeers(selectedPeerIPs);
return; return;
} }
if(act == copyIPAct) { if (act == copyIPAct) {
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
QApplication::clipboard()->setText(selectedPeerIPs.join("\r\n")); QApplication::clipboard()->setText(selectedPeerIPs.join("\r\n"));
#else #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?"), 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"), tr("&Yes"), tr("&No"),
QString(), 0, 1); QString(), 0, 1);
if(ret) return; if (ret) return;
foreach(const QString &ip, peer_ips) { foreach (const QString &ip, peer_ips) {
qDebug("Banning peer %s...", ip.toLocal8Bit().data()); qDebug("Banning peer %s...", ip.toLocal8Bit().data());
QBtSession::instance()->addConsoleMessage(tr("Manually banning peer %1...").arg(ip)); QBtSession::instance()->addConsoleMessage(tr("Manually banning peer %1...").arg(ip));
QBtSession::instance()->banIP(ip); QBtSession::instance()->banIP(ip);
@ -207,22 +207,22 @@ void PeerListWidget::banSelectedPeers(QStringList peer_ips) {
} }
void PeerListWidget::limitUpRateSelectedPeers(QStringList peer_ips) { void PeerListWidget::limitUpRateSelectedPeers(QStringList peer_ips) {
if(peer_ips.empty()) return; if (peer_ips.empty()) return;
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) return; if (!h.is_valid()) return;
bool ok=false; bool ok=false;
int cur_limit = -1; int cur_limit = -1;
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
libtorrent::asio::ip::tcp::endpoint first_ep = peerEndpoints.value(peer_ips.first(), libtorrent::asio::ip::tcp::endpoint first_ep = peerEndpoints.value(peer_ips.first(),
libtorrent::asio::ip::tcp::endpoint()); 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); cur_limit = h.get_peer_upload_limit(first_ep);
#endif #endif
long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Upload rate limiting"), cur_limit, Preferences().getGlobalUploadLimit()*1024.); long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Upload rate limiting"), cur_limit, Preferences().getGlobalUploadLimit()*1024.);
if(!ok) return; if (!ok) return;
foreach(const QString &ip, peer_ips) { foreach (const QString &ip, peer_ips) {
libtorrent::asio::ip::tcp::endpoint ep = peerEndpoints.value(ip, libtorrent::asio::ip::tcp::endpoint()); 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()); qDebug("Settings Upload limit of %.1f Kb/s to peer %s", limit/1024., ip.toLocal8Bit().data());
try { try {
h.set_peer_upload_limit(ep, limit); h.set_peer_upload_limit(ep, limit);
@ -237,20 +237,20 @@ void PeerListWidget::limitUpRateSelectedPeers(QStringList peer_ips) {
void PeerListWidget::limitDlRateSelectedPeers(QStringList peer_ips) { void PeerListWidget::limitDlRateSelectedPeers(QStringList peer_ips) {
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) return; if (!h.is_valid()) return;
bool ok=false; bool ok=false;
int cur_limit = -1; int cur_limit = -1;
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
libtorrent::asio::ip::tcp::endpoint first_ep = peerEndpoints.value(peer_ips.first(), libtorrent::asio::ip::tcp::endpoint first_ep = peerEndpoints.value(peer_ips.first(),
libtorrent::asio::ip::tcp::endpoint()); 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); cur_limit = h.get_peer_download_limit(first_ep);
#endif #endif
long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Download rate limiting"), cur_limit, Preferences().getGlobalDownloadLimit()*1024.); long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Download rate limiting"), cur_limit, Preferences().getGlobalDownloadLimit()*1024.);
if(!ok) return; if (!ok) return;
foreach(const QString &ip, peer_ips) { foreach (const QString &ip, peer_ips) {
libtorrent::asio::ip::tcp::endpoint ep = peerEndpoints.value(ip, libtorrent::asio::ip::tcp::endpoint()); 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()); qDebug("Settings Download limit of %.1f Kb/s to peer %s", limit/1024., ip.toLocal8Bit().data());
try { try {
h.set_peer_download_limit(ep, limit); h.set_peer_download_limit(ep, limit);
@ -270,7 +270,7 @@ void PeerListWidget::clear() {
peerEndpoints.clear(); peerEndpoints.clear();
missingFlags.clear(); missingFlags.clear();
int nbrows = listModel->rowCount(); int nbrows = listModel->rowCount();
if(nbrows > 0) { if (nbrows > 0) {
qDebug("Cleared %d peers", nbrows); qDebug("Cleared %d peers", nbrows);
listModel->removeRows(0, nbrows); listModel->removeRows(0, nbrows);
} }
@ -287,24 +287,24 @@ void PeerListWidget::saveSettings() const {
} }
void PeerListWidget::loadPeers(const QTorrentHandle &h, bool force_hostname_resolution) { 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; boost::system::error_code ec;
std::vector<peer_info> peers; std::vector<peer_info> peers;
h.get_peer_info(peers); h.get_peer_info(peers);
std::vector<peer_info>::iterator itr; std::vector<peer_info>::iterator itr;
QSet<QString> old_peers_set = peerItems.keys().toSet(); QSet<QString> 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; peer_info peer = *itr;
QString peer_ip = misc::toQString(peer.ip.address().to_string(ec)); QString peer_ip = misc::toQString(peer.ip.address().to_string(ec));
if(ec) continue; if (ec) continue;
if(peerItems.contains(peer_ip)) { if (peerItems.contains(peer_ip)) {
// Update existing peer // Update existing peer
updatePeer(peer_ip, peer); updatePeer(peer_ip, peer);
old_peers_set.remove(peer_ip); old_peers_set.remove(peer_ip);
if(force_hostname_resolution) { if (force_hostname_resolution) {
if(resolver) { if (resolver) {
const QString host = resolver->getHostFromCache(peer.ip); const QString host = resolver->getHostFromCache(peer.ip);
if(host.isNull()) { if (host.isNull()) {
resolver->resolve(peer.ip); resolver->resolve(peer.ip);
} else { } else {
qDebug("Got peer IP from cache"); qDebug("Got peer IP from cache");
@ -334,20 +334,20 @@ QStandardItem* PeerListWidget::addPeer(QString ip, peer_info peer) {
// Adding Peer to peer list // Adding Peer to peer list
listModel->insertRow(row); listModel->insertRow(row);
QString host; QString host;
if(resolver) { if (resolver) {
host = resolver->getHostFromCache(peer.ip); host = resolver->getHostFromCache(peer.ip);
} }
if(host.isNull()) if (host.isNull())
listModel->setData(listModel->index(row, PeerListDelegate::IP), ip); listModel->setData(listModel->index(row, PeerListDelegate::IP), ip);
else else
listModel->setData(listModel->index(row, PeerListDelegate::IP), host); listModel->setData(listModel->index(row, PeerListDelegate::IP), host);
listModel->setData(listModel->index(row, PeerListDelegate::IP_HIDDEN), ip); listModel->setData(listModel->index(row, PeerListDelegate::IP_HIDDEN), ip);
// Resolve peer host name is asked // Resolve peer host name is asked
if(resolver && host.isNull()) if (resolver && host.isNull())
resolver->resolve(peer.ip); resolver->resolve(peer.ip);
if(display_flags) { if (display_flags) {
const QIcon ico = GeoIPManager::CountryISOCodeToIcon(peer.country); const QIcon ico = GeoIPManager::CountryISOCodeToIcon(peer.country);
if(!ico.isNull()) { if (!ico.isNull()) {
listModel->setData(listModel->index(row, PeerListDelegate::IP), ico, Qt::DecorationRole); listModel->setData(listModel->index(row, PeerListDelegate::IP), ico, Qt::DecorationRole);
const QString country_name = GeoIPManager::CountryISOCodeToName(peer.country); const QString country_name = GeoIPManager::CountryISOCodeToName(peer.country);
listModel->setData(listModel->index(row, PeerListDelegate::IP), country_name, Qt::ToolTipRole); 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) { void PeerListWidget::updatePeer(QString ip, peer_info peer) {
QStandardItem *item = peerItems.value(ip); QStandardItem *item = peerItems.value(ip);
int row = item->row(); int row = item->row();
if(display_flags) { if (display_flags) {
const QIcon ico = GeoIPManager::CountryISOCodeToIcon(peer.country); const QIcon ico = GeoIPManager::CountryISOCodeToIcon(peer.country);
if(!ico.isNull()) { if (!ico.isNull()) {
listModel->setData(listModel->index(row, PeerListDelegate::IP), ico, Qt::DecorationRole); listModel->setData(listModel->index(row, PeerListDelegate::IP), ico, Qt::DecorationRole);
const QString country_name = GeoIPManager::CountryISOCodeToName(peer.country); const QString country_name = GeoIPManager::CountryISOCodeToName(peer.country);
listModel->setData(listModel->index(row, PeerListDelegate::IP), country_name, Qt::ToolTipRole); 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) { void PeerListWidget::handleResolved(const QString &ip, const QString &hostname) {
QStandardItem *item = peerItems.value(ip, 0); QStandardItem *item = peerItems.value(ip, 0);
if(item) { if (item) {
qDebug("Resolved %s -> %s", qPrintable(ip), qPrintable(hostname)); qDebug("Resolved %s -> %s", qPrintable(ip), qPrintable(hostname));
item->setData(hostname, Qt::DisplayRole); item->setData(hostname, Qt::DisplayRole);
//listModel->setData(listModel->index(item->row(), IP), 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) void PeerListWidget::handleSortColumnChanged(int col)
{ {
if(col == 0) { if (col == 0) {
qDebug("Sorting by decoration"); qDebug("Sorting by decoration");
proxyModel->setSortRole(Qt::ToolTipRole); proxyModel->setSortRole(Qt::ToolTipRole);
} else { } else {

View file

@ -140,7 +140,7 @@ void PropertiesWidget::showPiecesAvailability(bool show) {
avail_pieces_lbl->setVisible(show); avail_pieces_lbl->setVisible(show);
pieces_availability->setVisible(show); pieces_availability->setVisible(show);
avail_average_lbl->setVisible(show); avail_average_lbl->setVisible(show);
if(show || (!show && !downloaded_pieces->isVisible())) if (show || (!show && !downloaded_pieces->isVisible()))
line_2->setVisible(show); line_2->setVisible(show);
} }
@ -148,12 +148,12 @@ void PropertiesWidget::showPiecesDownloaded(bool show) {
downloaded_pieces_lbl->setVisible(show); downloaded_pieces_lbl->setVisible(show);
downloaded_pieces->setVisible(show); downloaded_pieces->setVisible(show);
progress_lbl->setVisible(show); progress_lbl->setVisible(show);
if(show || (!show && !pieces_availability->isVisible())) if (show || (!show && !pieces_availability->isVisible()))
line_2->setVisible(show); line_2->setVisible(show);
} }
void PropertiesWidget::setVisibility(bool visible) { void PropertiesWidget::setVisibility(bool visible) {
if(!visible && state == VISIBLE) { if (!visible && state == VISIBLE) {
QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget()); QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
stackedProperties->setVisible(false); stackedProperties->setVisible(false);
slideSizes = hSplitter->sizes(); slideSizes = hSplitter->sizes();
@ -165,7 +165,7 @@ void PropertiesWidget::setVisibility(bool visible) {
return; return;
} }
if(visible && state == REDUCED) { if (visible && state == REDUCED) {
stackedProperties->setVisible(true); stackedProperties->setVisible(true);
QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget()); QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
hSplitter->handle(1)->setDisabled(false); hSplitter->handle(1)->setDisabled(false);
@ -212,13 +212,13 @@ QTorrentHandle PropertiesWidget::getCurrentTorrent() const {
} }
void PropertiesWidget::updateSavePath(const QTorrentHandle& _h) { void PropertiesWidget::updateSavePath(const QTorrentHandle& _h) {
if(h.is_valid() && h == _h) { if (h.is_valid() && h == _h) {
QString p; QString p;
if(h.has_metadata() && h.num_files() == 1) { if (h.has_metadata() && h.num_files() == 1) {
p = h.firstFileSavePath(); p = h.firstFileSavePath();
} else { } else {
p = TorrentPersistentData::getSavePath(h.hash()); p = TorrentPersistentData::getSavePath(h.hash());
if(p.isEmpty()) if (p.isEmpty())
p = h.save_path(); p = h.save_path();
} }
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #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) { void PropertiesWidget::updateTorrentInfos(const QTorrentHandle& _h) {
if(h.is_valid() && h == _h) { if (h.is_valid() && h == _h) {
loadTorrentInfos(h); loadTorrentInfos(h);
} }
} }
@ -237,7 +237,7 @@ void PropertiesWidget::updateTorrentInfos(const QTorrentHandle& _h) {
void PropertiesWidget::loadTorrentInfos(const QTorrentHandle &_h) { void PropertiesWidget::loadTorrentInfos(const QTorrentHandle &_h) {
clear(); clear();
h = _h; h = _h;
if(!h.is_valid()) { if (!h.is_valid()) {
clear(); clear();
return; return;
} }
@ -250,7 +250,7 @@ void PropertiesWidget::loadTorrentInfos(const QTorrentHandle &_h) {
// Hash // Hash
hash_lbl->setText(h.hash()); hash_lbl->setText(h.hash());
PropListModel->model()->clear(); PropListModel->model()->clear();
if(h.has_metadata()) { if (h.has_metadata()) {
// Creation date // Creation date
lbl_creationDate->setText(h.creation_date()); lbl_creationDate->setText(h.creation_date());
// Pieces size // Pieces size
@ -273,7 +273,7 @@ void PropertiesWidget::readSettings() {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
// Restore splitter sizes // Restore splitter sizes
QStringList sizes_str = settings.value(QString::fromUtf8("TorrentProperties/SplitterSizes"), QString()).toString().split(","); 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.first().toInt();
slideSizes << sizes_str.last().toInt(); slideSizes << sizes_str.last().toInt();
QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget()); QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
@ -284,7 +284,7 @@ void PropertiesWidget::readSettings() {
} }
const int current_tab = settings.value("TorrentProperties/CurrentTab", -1).toInt(); const int current_tab = settings.value("TorrentProperties/CurrentTab", -1).toInt();
m_tabBar->setCurrentIndex(current_tab); m_tabBar->setCurrentIndex(current_tab);
if(!settings.value("TorrentProperties/Visible", false).toBool()) { if (!settings.value("TorrentProperties/Visible", false).toBool()) {
setVisibility(false); setVisibility(false);
} }
} }
@ -295,12 +295,12 @@ void PropertiesWidget::saveSettings() {
// Splitter sizes // Splitter sizes
QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget()); QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
QList<int> sizes; QList<int> sizes;
if(state == VISIBLE) if (state == VISIBLE)
sizes = hSplitter->sizes(); sizes = hSplitter->sizes();
else else
sizes = slideSizes; sizes = slideSizes;
qDebug("Sizes: %d", sizes.size()); 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(QString::fromUtf8("TorrentProperties/SplitterSizes"), QVariant(QString::number(sizes.first())+','+QString::number(sizes.last())));
} }
settings.setValue("TorrentProperties/FilesListState", filesList->header()->saveState()); settings.setValue("TorrentProperties/FilesListState", filesList->header()->saveState());
@ -316,27 +316,27 @@ void PropertiesWidget::reloadPreferences() {
void PropertiesWidget::loadDynamicData() { void PropertiesWidget::loadDynamicData() {
// Refresh only if the torrent handle is valid and if visible // 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 { try {
// Transfer infos // 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())); 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")+")"); 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")+")"); 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("")); lbl_uplimit->setText(QString::fromUtf8(""));
else else
lbl_uplimit->setText(misc::friendlyUnit(h.upload_limit())+tr("/s", "/second (i.e. per second)")); 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("")); lbl_dllimit->setText(QString::fromUtf8(""));
else else
lbl_dllimit->setText(misc::friendlyUnit(h.download_limit())+tr("/s", "/second (i.e. per second)")); lbl_dllimit->setText(misc::friendlyUnit(h.download_limit())+tr("/s", "/second (i.e. per second)"));
QString elapsed_txt = misc::userFriendlyDuration(h.active_time()); 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()))+")"; elapsed_txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(misc::userFriendlyDuration(h.seeding_time()))+")";
} }
lbl_elapsed->setText(elapsed_txt); 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()))+")"); lbl_connections->setText(QString::number(h.num_connections())+" ("+tr("%1 max", "e.g. 10 max").arg(QString::number(h.connections_limit()))+")");
else else
lbl_connections->setText(QString::number(h.num_connections())); lbl_connections->setText(QString::number(h.num_connections()));
@ -344,18 +344,18 @@ void PropertiesWidget::loadDynamicData() {
reannounce_lbl->setText(h.next_announce()); reannounce_lbl->setText(h.next_announce());
// Update ratio info // Update ratio info
const qreal ratio = QBtSession::instance()->getRealRatio(h.hash()); const qreal ratio = QBtSession::instance()->getRealRatio(h.hash());
if(ratio > QBtSession::MAX_RATIO) if (ratio > QBtSession::MAX_RATIO)
shareRatio->setText(QString::fromUtf8("")); shareRatio->setText(QString::fromUtf8(""));
else else
shareRatio->setText(QString(QByteArray::number(ratio, 'f', 2))); shareRatio->setText(QString(QByteArray::number(ratio, 'f', 2)));
if(!h.is_seed()) { if (!h.is_seed()) {
showPiecesDownloaded(true); showPiecesDownloaded(true);
// Downloaded pieces // Downloaded pieces
bitfield bf(h.get_torrent_info().num_pieces(), 0); bitfield bf(h.get_torrent_info().num_pieces(), 0);
h.downloading_pieces(bf); h.downloading_pieces(bf);
downloaded_pieces->setProgress(h.pieces(), bf); downloaded_pieces->setProgress(h.pieces(), bf);
// Pieces availability // 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); showPiecesAvailability(true);
std::vector<int> avail; std::vector<int> avail;
h.piece_availability(avail); h.piece_availability(avail);
@ -366,7 +366,7 @@ void PropertiesWidget::loadDynamicData() {
} }
// Progress // Progress
qreal progress = h.progress()*100.; qreal progress = h.progress()*100.;
if(progress > 99.94 && progress < 100.) if (progress > 99.94 && progress < 100.)
progress = 99.9; progress = 99.9;
progress_lbl->setText(QString::number(progress, 'f', 1)+"%"); progress_lbl->setText(QString::number(progress, 'f', 1)+"%");
} else { } else {
@ -375,19 +375,19 @@ void PropertiesWidget::loadDynamicData() {
} }
return; return;
} }
if(stackedProperties->currentIndex() == PropTabBar::TRACKERS_TAB) { if (stackedProperties->currentIndex() == PropTabBar::TRACKERS_TAB) {
// Trackers // Trackers
trackerList->loadTrackers(); trackerList->loadTrackers();
return; return;
} }
if(stackedProperties->currentIndex() == PropTabBar::PEERS_TAB) { if (stackedProperties->currentIndex() == PropTabBar::PEERS_TAB) {
// Load peers // Load peers
peersList->loadPeers(h); peersList->loadPeers(h);
return; return;
} }
if(stackedProperties->currentIndex() == PropTabBar::FILES_TAB) { if (stackedProperties->currentIndex() == PropTabBar::FILES_TAB) {
// Files progress // Files progress
if(h.is_valid() && h.has_metadata()) { if (h.is_valid() && h.has_metadata()) {
qDebug("Updating priorities in files tab"); qDebug("Updating priorities in files tab");
filesList->setUpdatesEnabled(false); filesList->setUpdatesEnabled(false);
std::vector<size_type> fp; std::vector<size_type> fp;
@ -405,16 +405,16 @@ void PropertiesWidget::loadUrlSeeds(){
qDebug("Loading URL seeds"); qDebug("Loading URL seeds");
const QStringList hc_seeds = h.url_seeds(); const QStringList hc_seeds = h.url_seeds();
// Add 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)); qDebug("Loading URL seed: %s", qPrintable(hc_seed));
new QListWidgetItem(hc_seed, listWebSeeds); new QListWidgetItem(hc_seed, listWebSeeds);
} }
} }
void PropertiesWidget::openDoubleClickedFile(QModelIndex index) { void PropertiesWidget::openDoubleClickedFile(QModelIndex index) {
if(!index.isValid()) return; if (!index.isValid()) return;
if(!h.is_valid() || !h.has_metadata()) return; if (!h.is_valid() || !h.has_metadata()) return;
if(PropListModel->getType(index) == TorrentFileItem::TFILE) { if (PropListModel->getType(index) == TorrentFileItem::TFILE) {
int i = PropListModel->getFileIndex(index); int i = PropListModel->getFileIndex(index);
const QDir saveDir(h.save_path()); const QDir saveDir(h.save_path());
const QString filename = h.filepath_at(i); 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)); qDebug("Trying to open file at %s", qPrintable(file_path));
// Flush data // Flush data
h.flush_cache(); h.flush_cache();
if(QFile::exists(file_path)) { if (QFile::exists(file_path)) {
QDesktopServices::openUrl(QUrl::fromLocalFile(file_path)); QDesktopServices::openUrl(QUrl::fromLocalFile(file_path));
} else { } else {
QMessageBox::warning(this, tr("I/O Error"), tr("This file does not exist yet.")); 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)); qDebug("Trying to open folder at %s", qPrintable(file_path));
// Flush data // Flush data
h.flush_cache(); h.flush_cache();
if(QFile::exists(file_path)) { if (QFile::exists(file_path)) {
QDesktopServices::openUrl(QUrl::fromLocalFile(file_path)); QDesktopServices::openUrl(QUrl::fromLocalFile(file_path));
} else { } else {
QMessageBox::warning(this, tr("I/O Error"), tr("This folder does not exist yet.")); 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; QMenu myFilesLlistMenu;
QModelIndexList selectedRows = filesList->selectionModel()->selectedRows(0); QModelIndexList selectedRows = filesList->selectionModel()->selectedRows(0);
QAction *actRename = 0; QAction *actRename = 0;
if(selectedRows.size() == 1) { if (selectedRows.size() == 1) {
actRename = myFilesLlistMenu.addAction(IconProvider::instance()->getIcon("edit-rename"), tr("Rename...")); actRename = myFilesLlistMenu.addAction(IconProvider::instance()->getIcon("edit-rename"), tr("Rename..."));
myFilesLlistMenu.addSeparator(); myFilesLlistMenu.addSeparator();
} }
QMenu subMenu; QMenu subMenu;
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
if(!h.status(0x0).is_seeding) { if (!h.status(0x0).is_seeding) {
#else #else
if(!static_cast<torrent_handle>(h).is_seed()) { if (!static_cast<torrent_handle>(h).is_seed()) {
#endif #endif
subMenu.setTitle(tr("Priority")); subMenu.setTitle(tr("Priority"));
subMenu.addAction(actionNot_downloaded); subMenu.addAction(actionNot_downloaded);
@ -473,24 +473,24 @@ void PropertiesWidget::displayFilesListMenu(const QPoint&){
} }
// Call menu // Call menu
const QAction *act = myFilesLlistMenu.exec(QCursor::pos()); const QAction *act = myFilesLlistMenu.exec(QCursor::pos());
if(act) { if (act) {
if(act == actRename) { if (act == actRename) {
renameSelectedFile(); renameSelectedFile();
} else { } else {
int prio = 1; int prio = 1;
if(act == actionHigh) { if (act == actionHigh) {
prio = prio::HIGH; prio = prio::HIGH;
} else { } else {
if(act == actionMaximum) { if (act == actionMaximum) {
prio = prio::MAXIMUM; prio = prio::MAXIMUM;
} else { } else {
if(act == actionNot_downloaded) { if (act == actionNot_downloaded) {
prio = prio::IGNORED; prio = prio::IGNORED;
} }
} }
} }
qDebug("Setting files priority"); qDebug("Setting files priority");
foreach(QModelIndex index, selectedRows) { foreach (QModelIndex index, selectedRows) {
qDebug("Setting priority(%d) for file at row %d", prio, index.row()); qDebug("Setting priority(%d) for file at row %d", prio, index.row());
PropListModel->setData(PropListModel->index(index.row(), PRIORITY, index.parent()), prio); PropListModel->setData(PropListModel->index(index.row(), PRIORITY, index.parent()), prio);
} }
@ -510,36 +510,36 @@ void PropertiesWidget::renameSelectedFile() {
tr("New name:"), QLineEdit::Normal, tr("New name:"), QLineEdit::Normal,
index.data().toString(), &ok); index.data().toString(), &ok);
if (ok && !new_name_last.isEmpty()) { 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"), QMessageBox::warning(this, tr("The file could not be renamed"),
tr("This file name contains forbidden characters, please choose a different one."), tr("This file name contains forbidden characters, please choose a different one."),
QMessageBox::Ok); QMessageBox::Ok);
return; return;
} }
if(PropListModel->getType(index) == TorrentFileItem::TFILE) { if (PropListModel->getType(index) == TorrentFileItem::TFILE) {
// File renaming // File renaming
const int file_index = PropListModel->getFileIndex(index); 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("\\", "/"); 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"; new_name_last += ".!qB";
} }
QStringList path_items = old_name.split("/"); QStringList path_items = old_name.split("/");
path_items.removeLast(); path_items.removeLast();
path_items << new_name_last; path_items << new_name_last;
QString new_name = path_items.join("/"); QString new_name = path_items.join("/");
if(old_name == new_name) { if (old_name == new_name) {
qDebug("Name did not change"); qDebug("Name did not change");
return; return;
} }
new_name = QDir::cleanPath(new_name); new_name = QDir::cleanPath(new_name);
// Check if that name is already used // Check if that name is already used
for(int i=0; i<h.num_files(); ++i) { for (int i=0; i<h.num_files(); ++i) {
if(i == file_index) continue; if (i == file_index) continue;
#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) #if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
if(h.filepath_at(i).compare(new_name, Qt::CaseSensitive) == 0) { if (h.filepath_at(i).compare(new_name, Qt::CaseSensitive) == 0) {
#else #else
if(h.filepath_at(i).compare(new_name, Qt::CaseInsensitive) == 0) { if (h.filepath_at(i).compare(new_name, Qt::CaseInsensitive) == 0) {
#endif #endif
// Display error message // Display error message
QMessageBox::warning(this, tr("The file could not be renamed"), QMessageBox::warning(this, tr("The file could not be renamed"),
@ -552,9 +552,9 @@ void PropertiesWidget::renameSelectedFile() {
qDebug("Renaming %s to %s", qPrintable(old_name), qPrintable(new_name)); qDebug("Renaming %s to %s", qPrintable(old_name), qPrintable(new_name));
h.rename_file(file_index, new_name); h.rename_file(file_index, new_name);
// Force recheck // Force recheck
if(force_recheck) h.force_recheck(); if (force_recheck) h.force_recheck();
// Rename if torrent files model too // Rename if torrent files model too
if(new_name_last.endsWith(".!qB")) if (new_name_last.endsWith(".!qB"))
new_name_last.chop(4); new_name_last.chop(4);
PropListModel->setData(index, new_name_last); PropListModel->setData(index, new_name_last);
} else { } else {
@ -570,15 +570,15 @@ void PropertiesWidget::renameSelectedFile() {
path_items.removeLast(); path_items.removeLast();
path_items << new_name_last; path_items << new_name_last;
QString new_path = path_items.join("/"); QString new_path = path_items.join("/");
if(!new_path.endsWith("/")) new_path += "/"; if (!new_path.endsWith("/")) new_path += "/";
// Check for overwriting // Check for overwriting
const int num_files = h.num_files(); const int num_files = h.num_files();
for(int i=0; i<num_files; ++i) { for (int i=0; i<num_files; ++i) {
const QString current_name = h.filepath_at(i); const QString current_name = h.filepath_at(i);
#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) #if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
if(current_name.startsWith(new_path, Qt::CaseSensitive)) { if (current_name.startsWith(new_path, Qt::CaseSensitive)) {
#else #else
if(current_name.startsWith(new_path, Qt::CaseInsensitive)) { if (current_name.startsWith(new_path, Qt::CaseInsensitive)) {
#endif #endif
QMessageBox::warning(this, tr("The folder could not be renamed"), QMessageBox::warning(this, tr("The folder could not be renamed"),
tr("This name is already in use in this folder. Please use a different name."), tr("This name is already in use in this folder. Please use a different name."),
@ -588,12 +588,12 @@ void PropertiesWidget::renameSelectedFile() {
} }
bool force_recheck = false; bool force_recheck = false;
// Replace path in all files // Replace path in all files
for(int i=0; i<num_files; ++i) { for (int i=0; i<num_files; ++i) {
const QString current_name = h.filepath_at(i); const QString current_name = h.filepath_at(i);
if(current_name.startsWith(old_path)) { if (current_name.startsWith(old_path)) {
QString new_name = current_name; QString new_name = current_name;
new_name.replace(0, old_path.length(), new_path); new_name.replace(0, old_path.length(), new_path);
if(!force_recheck && QDir(h.save_path()).exists(new_name)) if (!force_recheck && QDir(h.save_path()).exists(new_name))
force_recheck = true; force_recheck = true;
new_name = QDir::cleanPath(new_name); new_name = QDir::cleanPath(new_name);
qDebug("Rename %s to %s", qPrintable(current_name), qPrintable(new_name)); qDebug("Rename %s to %s", qPrintable(current_name), qPrintable(new_name));
@ -601,7 +601,7 @@ void PropertiesWidget::renameSelectedFile() {
} }
} }
// Force recheck // Force recheck
if(force_recheck) h.force_recheck(); if (force_recheck) h.force_recheck();
// Rename folder in torrent files model too // Rename folder in torrent files model too
PropListModel->setData(index, new_name_last); PropListModel->setData(index, new_name_last);
// Remove old folder // Remove old folder
@ -622,9 +622,9 @@ void PropertiesWidget::askWebSeed(){
const QString url_seed = QInputDialog::getText(this, tr("New url seed", "New HTTP source"), const QString url_seed = QInputDialog::getText(this, tr("New url seed", "New HTTP source"),
tr("New url seed:"), QLineEdit::Normal, tr("New url seed:"), QLineEdit::Normal,
QString::fromUtf8("http://www."), &ok); QString::fromUtf8("http://www."), &ok);
if(!ok) return; if (!ok) return;
qDebug("Adding %s web seed", qPrintable(url_seed)); 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"), QMessageBox::warning(this, tr("qBittorrent"),
tr("This url seed is already in the list."), tr("This url seed is already in the list."),
QMessageBox::Ok); QMessageBox::Ok);
@ -638,12 +638,12 @@ void PropertiesWidget::askWebSeed(){
void PropertiesWidget::deleteSelectedUrlSeeds(){ void PropertiesWidget::deleteSelectedUrlSeeds(){
const QList<QListWidgetItem *> selectedItems = listWebSeeds->selectedItems(); const QList<QListWidgetItem *> selectedItems = listWebSeeds->selectedItems();
bool change = false; bool change = false;
foreach(const QListWidgetItem *item, selectedItems){ foreach (const QListWidgetItem *item, selectedItems){
QString url_seed = item->text(); QString url_seed = item->text();
h.remove_url_seed(url_seed); h.remove_url_seed(url_seed);
change = true; change = true;
} }
if(change){ if (change){
// Refresh list // Refresh list
loadUrlSeeds(); loadUrlSeeds();
} }
@ -658,45 +658,45 @@ bool PropertiesWidget::applyPriorities() {
qDebug("prioritize files: %d", priorities[0]); qDebug("prioritize files: %d", priorities[0]);
h.prioritize_files(priorities); h.prioritize_files(priorities);
// Restore first/last piece first option if necessary // Restore first/last piece first option if necessary
if(first_last_piece_first) if (first_last_piece_first)
h.prioritize_first_last_piece(true); h.prioritize_first_last_piece(true);
return true; return true;
} }
void PropertiesWidget::on_changeSavePathButton_clicked() { void PropertiesWidget::on_changeSavePathButton_clicked() {
if(!h.is_valid()) return; if (!h.is_valid()) return;
QString new_path; 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()); new_path = QFileDialog::getSaveFileName(this, tr("Choose save path"), h.firstFileSavePath());
} else { } else {
const QDir saveDir(TorrentPersistentData::getSavePath(h.hash())); const QDir saveDir(TorrentPersistentData::getSavePath(h.hash()));
new_path = QFileDialog::getExistingDirectory(this, tr("Choose save path"), saveDir.absolutePath(), new_path = QFileDialog::getExistingDirectory(this, tr("Choose save path"), saveDir.absolutePath(),
QFileDialog::DontConfirmOverwrite|QFileDialog::ShowDirsOnly|QFileDialog::HideNameFilterDetails); QFileDialog::DontConfirmOverwrite|QFileDialog::ShowDirsOnly|QFileDialog::HideNameFilterDetails);
} }
if(!new_path.isEmpty()){ if (!new_path.isEmpty()){
// Check if savePath exists // Check if savePath exists
QString save_path_dir = new_path.replace("\\", "/"); QString save_path_dir = new_path.replace("\\", "/");
QString new_file_name; 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 new_file_name = misc::fileName(save_path_dir); // New file name
save_path_dir = misc::branchPath(save_path_dir, true); // Skip file name save_path_dir = misc::branchPath(save_path_dir, true); // Skip file name
} }
QDir savePath(misc::expandPath(save_path_dir)); QDir savePath(misc::expandPath(save_path_dir));
// Actually move storage // Actually move storage
if(!QBtSession::instance()->useTemporaryFolder() || h.is_seed()) { if (!QBtSession::instance()->useTemporaryFolder() || h.is_seed()) {
if(!savePath.exists()) savePath.mkpath(savePath.absolutePath()); if (!savePath.exists()) savePath.mkpath(savePath.absolutePath());
h.move_storage(savePath.absolutePath()); h.move_storage(savePath.absolutePath());
} }
// Update save_path in dialog // Update save_path in dialog
QString display_path; QString display_path;
if(h.has_metadata() && h.num_files() == 1) { if (h.has_metadata() && h.num_files() == 1) {
// Rename the file // Rename the file
Q_ASSERT(!new_file_name.isEmpty()); Q_ASSERT(!new_file_name.isEmpty());
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #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 #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 #endif
qDebug("Renaming single file to %s", qPrintable(new_file_name)); qDebug("Renaming single file to %s", qPrintable(new_file_name));
h.rename_file(0, new_file_name); h.rename_file(0, new_file_name);
@ -715,7 +715,7 @@ void PropertiesWidget::on_changeSavePathButton_clicked() {
} }
void PropertiesWidget::filteredFilesChanged() { void PropertiesWidget::filteredFilesChanged() {
if(h.is_valid()) { if (h.is_valid()) {
applyPriorities(); applyPriorities();
} }
} }

View file

@ -80,7 +80,7 @@ public:
newopt.rect = opt.rect; newopt.rect = opt.rect;
// We don't want to display 100% unless // We don't want to display 100% unless
// the torrent is really complete // the torrent is really complete
if(progress > 99.94 && progress < 100.) if (progress > 99.94 && progress < 100.)
progress = 99.9; progress = 99.9;
newopt.text = QString(QByteArray::number(progress, 'f', 1))+QString::fromUtf8("%"); newopt.text = QString(QByteArray::number(progress, 'f', 1))+QString::fromUtf8("%");
newopt.progress = (int)progress; newopt.progress = (int)progress;
@ -158,16 +158,16 @@ public:
} }
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &index) const { QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &index) const {
if(index.column() != PRIORITY) return 0; if (index.column() != PRIORITY) return 0;
if(properties) { if (properties) {
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
#if LIBTORRENT_VERSION_MINOR > 15 #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 #else
if(!h.is_valid() || !h.has_metadata() || static_cast<libtorrent::torrent_handle>(h).is_seed()) return 0; if (!h.is_valid() || !h.has_metadata() || static_cast<libtorrent::torrent_handle>(h).is_seed()) return 0;
#endif #endif
} }
if(index.data().toInt() <= 0) { if (index.data().toInt() <= 0) {
// IGNORED or MIXED // IGNORED or MIXED
return 0; return 0;
} }

View file

@ -87,7 +87,7 @@ PropTabBar::PropTabBar(QWidget *parent) :
// SIGNAL/SLOT // SIGNAL/SLOT
connect(m_btnGroup, SIGNAL(buttonClicked(int)), SLOT(setCurrentIndex(int))); connect(m_btnGroup, SIGNAL(buttonClicked(int)), SLOT(setCurrentIndex(int)));
// Disable buttons focus // Disable buttons focus
foreach(QAbstractButton *btn, m_btnGroup->buttons()) { foreach (QAbstractButton *btn, m_btnGroup->buttons()) {
btn->setFocusPolicy(Qt::NoFocus); btn->setFocusPolicy(Qt::NoFocus);
} }
} }
@ -103,11 +103,11 @@ int PropTabBar::currentIndex() const
void PropTabBar::setCurrentIndex(int index) void PropTabBar::setCurrentIndex(int index)
{ {
if(index >= m_btnGroup->buttons().size()) if (index >= m_btnGroup->buttons().size())
index = 0; index = 0;
// If asked to hide or if the currently selected tab is clicked // If asked to hide or if the currently selected tab is clicked
if(index < 0 || m_currentIndex == index) { if (index < 0 || m_currentIndex == index) {
if(m_currentIndex >= 0) { if (m_currentIndex >= 0) {
m_btnGroup->button(m_currentIndex)->setStyleSheet(DEFAULT_BUTTON_CSS); m_btnGroup->button(m_currentIndex)->setStyleSheet(DEFAULT_BUTTON_CSS);
m_currentIndex = -1; m_currentIndex = -1;
emit visibilityToggled(false); emit visibilityToggled(false);
@ -115,7 +115,7 @@ void PropTabBar::setCurrentIndex(int index)
return; return;
} }
// Unselect previous tab // Unselect previous tab
if(m_currentIndex >= 0) { if (m_currentIndex >= 0) {
m_btnGroup->button(m_currentIndex)->setStyleSheet(DEFAULT_BUTTON_CSS); m_btnGroup->button(m_currentIndex)->setStyleSheet(DEFAULT_BUTTON_CSS);
} else { } else {
// Nothing was selected, show! // Nothing was selected, show!

View file

@ -83,8 +83,8 @@ TrackerList::~TrackerList() {
QList<QTreeWidgetItem*> TrackerList::getSelectedTrackerItems() const { QList<QTreeWidgetItem*> TrackerList::getSelectedTrackerItems() const {
QList<QTreeWidgetItem*> selected_items = selectedItems(); QList<QTreeWidgetItem*> selected_items = selectedItems();
QList<QTreeWidgetItem*> selected_trackers; QList<QTreeWidgetItem*> selected_trackers;
foreach(QTreeWidgetItem *item, selectedItems()) { foreach (QTreeWidgetItem *item, selectedItems()) {
if(indexOfTopLevelItem(item) >= NB_STICKY_ITEM) { // Ignore STICKY ITEMS if (indexOfTopLevelItem(item) >= NB_STICKY_ITEM) { // Ignore STICKY ITEMS
selected_trackers << item; selected_trackers << item;
} }
} }
@ -94,37 +94,37 @@ QList<QTreeWidgetItem*> TrackerList::getSelectedTrackerItems() const {
void TrackerList::setRowColor(int row, QColor color) { void TrackerList::setRowColor(int row, QColor color) {
unsigned int nbColumns = columnCount(); unsigned int nbColumns = columnCount();
QTreeWidgetItem *item = topLevelItem(row); QTreeWidgetItem *item = topLevelItem(row);
for(unsigned int i=0; i<nbColumns; ++i) { for (unsigned int i=0; i<nbColumns; ++i) {
item->setData(i, Qt::ForegroundRole, color); item->setData(i, Qt::ForegroundRole, color);
} }
} }
void TrackerList::moveSelectionUp() { void TrackerList::moveSelectionUp() {
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) { if (!h.is_valid()) {
clear(); clear();
return; return;
} }
QList<QTreeWidgetItem *> selected_items = getSelectedTrackerItems(); QList<QTreeWidgetItem *> selected_items = getSelectedTrackerItems();
if(selected_items.isEmpty()) return; if (selected_items.isEmpty()) return;
bool change = false; bool change = false;
foreach(QTreeWidgetItem *item, selected_items){ foreach (QTreeWidgetItem *item, selected_items){
int index = indexOfTopLevelItem(item); int index = indexOfTopLevelItem(item);
if(index > NB_STICKY_ITEM) { if (index > NB_STICKY_ITEM) {
insertTopLevelItem(index-1, takeTopLevelItem(index)); insertTopLevelItem(index-1, takeTopLevelItem(index));
change = true; change = true;
} }
} }
if(!change) return; if (!change) return;
// Restore selection // Restore selection
QItemSelectionModel *selection = selectionModel(); QItemSelectionModel *selection = selectionModel();
foreach(QTreeWidgetItem *item, selected_items) { foreach (QTreeWidgetItem *item, selected_items) {
selection->select(indexFromItem(item), QItemSelectionModel::Rows|QItemSelectionModel::Select); selection->select(indexFromItem(item), QItemSelectionModel::Rows|QItemSelectionModel::Select);
} }
setSelectionModel(selection); setSelectionModel(selection);
// Update torrent trackers // Update torrent trackers
std::vector<announce_entry> trackers; std::vector<announce_entry> trackers;
for(int i=NB_STICKY_ITEM; i<topLevelItemCount(); ++i) { for (int i=NB_STICKY_ITEM; i<topLevelItemCount(); ++i) {
QString tracker_url = topLevelItem(i)->data(COL_URL, Qt::DisplayRole).toString(); QString tracker_url = topLevelItem(i)->data(COL_URL, Qt::DisplayRole).toString();
announce_entry e(tracker_url.toStdString()); announce_entry e(tracker_url.toStdString());
e.tier = i-NB_STICKY_ITEM; e.tier = i-NB_STICKY_ITEM;
@ -137,30 +137,30 @@ void TrackerList::moveSelectionUp() {
void TrackerList::moveSelectionDown() { void TrackerList::moveSelectionDown() {
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) { if (!h.is_valid()) {
clear(); clear();
return; return;
} }
QList<QTreeWidgetItem *> selected_items = getSelectedTrackerItems(); QList<QTreeWidgetItem *> selected_items = getSelectedTrackerItems();
if(selected_items.isEmpty()) return; if (selected_items.isEmpty()) return;
bool change = false; 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)); int index = indexOfTopLevelItem(selected_items.at(i));
if(index < topLevelItemCount()-1) { if (index < topLevelItemCount()-1) {
insertTopLevelItem(index+1, takeTopLevelItem(index)); insertTopLevelItem(index+1, takeTopLevelItem(index));
change = true; change = true;
} }
} }
if(!change) return; if (!change) return;
// Restore selection // Restore selection
QItemSelectionModel *selection = selectionModel(); QItemSelectionModel *selection = selectionModel();
foreach(QTreeWidgetItem *item, selected_items) { foreach (QTreeWidgetItem *item, selected_items) {
selection->select(indexFromItem(item), QItemSelectionModel::Rows|QItemSelectionModel::Select); selection->select(indexFromItem(item), QItemSelectionModel::Rows|QItemSelectionModel::Select);
} }
setSelectionModel(selection); setSelectionModel(selection);
// Update torrent trackers // Update torrent trackers
std::vector<announce_entry> trackers; std::vector<announce_entry> trackers;
for(int i=NB_STICKY_ITEM; i<topLevelItemCount(); ++i) { for (int i=NB_STICKY_ITEM; i<topLevelItemCount(); ++i) {
QString tracker_url = topLevelItem(i)->data(COL_URL, Qt::DisplayRole).toString(); QString tracker_url = topLevelItem(i)->data(COL_URL, Qt::DisplayRole).toString();
announce_entry e(tracker_url.toStdString()); announce_entry e(tracker_url.toStdString());
e.tier = i-NB_STICKY_ITEM; e.tier = i-NB_STICKY_ITEM;
@ -192,32 +192,32 @@ void TrackerList::loadStickyItems(const QTorrentHandle &h) {
std::vector<peer_info> peers; std::vector<peer_info> peers;
h.get_peer_info(peers); h.get_peer_info(peers);
std::vector<peer_info>::iterator it; std::vector<peer_info>::iterator it;
for(it=peers.begin(); it!=peers.end(); it++) { for (it=peers.begin(); it!=peers.end(); it++) {
if(it->source & peer_info::dht) if (it->source & peer_info::dht)
++nb_dht; ++nb_dht;
if(it->source & peer_info::lsd) if (it->source & peer_info::lsd)
++nb_lsd; ++nb_lsd;
if(it->source & peer_info::pex) if (it->source & peer_info::pex)
++nb_pex; ++nb_pex;
} }
// load DHT information // 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")); dht_item->setText(COL_STATUS, tr("Working"));
} else { } else {
dht_item->setText(COL_STATUS, tr("Disabled")); dht_item->setText(COL_STATUS, tr("Disabled"));
} }
dht_item->setText(COL_PEERS, QString::number(nb_dht)); 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")); dht_item->setText(COL_MSG, tr("This torrent is private"));
} }
// Load PeX Information // Load PeX Information
if(QBtSession::instance()->isPexEnabled()) if (QBtSession::instance()->isPexEnabled())
pex_item->setText(COL_STATUS, tr("Working")); pex_item->setText(COL_STATUS, tr("Working"));
else else
pex_item->setText(COL_STATUS, tr("Disabled")); pex_item->setText(COL_STATUS, tr("Disabled"));
pex_item->setText(COL_PEERS, QString::number(nb_pex)); pex_item->setText(COL_PEERS, QString::number(nb_pex));
// Load LSD Information // Load LSD Information
if(QBtSession::instance()->isLSDEnabled()) if (QBtSession::instance()->isLSDEnabled())
lsd_item->setText(COL_STATUS, tr("Working")); lsd_item->setText(COL_STATUS, tr("Working"));
else else
lsd_item->setText(COL_STATUS, tr("Disabled")); lsd_item->setText(COL_STATUS, tr("Disabled"));
@ -227,16 +227,16 @@ void TrackerList::loadStickyItems(const QTorrentHandle &h) {
void TrackerList::loadTrackers() { void TrackerList::loadTrackers() {
// Load trackers from torrent handle // Load trackers from torrent handle
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) return; if (!h.is_valid()) return;
loadStickyItems(h); loadStickyItems(h);
// Load actual trackers information // Load actual trackers information
QHash<QString, TrackerInfos> trackers_data = QBtSession::instance()->getTrackersInfo(h.hash()); QHash<QString, TrackerInfos> trackers_data = QBtSession::instance()->getTrackersInfo(h.hash());
QStringList old_trackers_urls = tracker_items.keys(); QStringList old_trackers_urls = tracker_items.keys();
const std::vector<announce_entry> trackers = h.trackers(); const std::vector<announce_entry> trackers = h.trackers();
for(std::vector<announce_entry>::const_iterator it = trackers.begin(); it != trackers.end(); it++) { for (std::vector<announce_entry>::const_iterator it = trackers.begin(); it != trackers.end(); it++) {
QString tracker_url = misc::toQString(it->url); QString tracker_url = misc::toQString(it->url);
QTreeWidgetItem *item = tracker_items.value(tracker_url, 0); QTreeWidgetItem *item = tracker_items.value(tracker_url, 0);
if(!item) { if (!item) {
item = new QTreeWidgetItem(); item = new QTreeWidgetItem();
item->setText(COL_TIER, QString::number(it->tier)); item->setText(COL_TIER, QString::number(it->tier));
item->setText(COL_URL, tracker_url); item->setText(COL_URL, tracker_url);
@ -247,15 +247,15 @@ void TrackerList::loadTrackers() {
} }
TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url)); TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url));
QString error_message = data.last_message.trimmed(); QString error_message = data.last_message.trimmed();
if(it->verified) { if (it->verified) {
item->setText(COL_STATUS, tr("Working")); item->setText(COL_STATUS, tr("Working"));
item->setText(COL_MSG, ""); item->setText(COL_MSG, "");
} else { } else {
if(it->updating && it->fails == 0) { if (it->updating && it->fails == 0) {
item->setText(COL_STATUS, tr("Updating...")); item->setText(COL_STATUS, tr("Updating..."));
item->setText(COL_MSG, ""); item->setText(COL_MSG, "");
} else { } else {
if(it->fails > 0) { if (it->fails > 0) {
item->setText(COL_STATUS, tr("Not working")); item->setText(COL_STATUS, tr("Not working"));
item->setText(COL_MSG, error_message); item->setText(COL_MSG, error_message);
} else { } else {
@ -267,7 +267,7 @@ void TrackerList::loadTrackers() {
item->setText(COL_PEERS, QString::number(trackers_data.value(tracker_url, TrackerInfos(tracker_url)).num_peers)); item->setText(COL_PEERS, QString::number(trackers_data.value(tracker_url, TrackerInfos(tracker_url)).num_peers));
} }
// Remove old trackers // Remove old trackers
foreach(const QString &tracker, old_trackers_urls) { foreach (const QString &tracker, old_trackers_urls) {
delete tracker_items.take(tracker); delete tracker_items.take(tracker);
} }
} }
@ -275,11 +275,11 @@ void TrackerList::loadTrackers() {
// Ask the user for new trackers and add them to the torrent // Ask the user for new trackers and add them to the torrent
void TrackerList::askForTrackers(){ void TrackerList::askForTrackers(){
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) return; if (!h.is_valid()) return;
QStringList trackers = TrackersAdditionDlg::askForTrackers(h); QStringList trackers = TrackersAdditionDlg::askForTrackers(h);
if(!trackers.empty()) { if (!trackers.empty()) {
foreach(const QString& tracker, trackers) { foreach (const QString& tracker, trackers) {
if(tracker.trimmed().isEmpty()) continue; if (tracker.trimmed().isEmpty()) continue;
announce_entry url(tracker.toStdString()); announce_entry url(tracker.toStdString());
url.tier = 0; url.tier = 0;
h.add_tracker(url); h.add_tracker(url);
@ -293,14 +293,14 @@ void TrackerList::askForTrackers(){
void TrackerList::deleteSelectedTrackers(){ void TrackerList::deleteSelectedTrackers(){
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) { if (!h.is_valid()) {
clear(); clear();
return; return;
} }
QList<QTreeWidgetItem *> selected_items = getSelectedTrackerItems(); QList<QTreeWidgetItem *> selected_items = getSelectedTrackerItems();
if(selected_items.isEmpty()) return; if (selected_items.isEmpty()) return;
QStringList urls_to_remove; QStringList urls_to_remove;
foreach(QTreeWidgetItem *item, selected_items){ foreach (QTreeWidgetItem *item, selected_items){
QString tracker_url = item->data(COL_URL, Qt::DisplayRole).toString(); QString tracker_url = item->data(COL_URL, Qt::DisplayRole).toString();
urls_to_remove << tracker_url; urls_to_remove << tracker_url;
tracker_items.remove(tracker_url); tracker_items.remove(tracker_url);
@ -310,8 +310,8 @@ void TrackerList::deleteSelectedTrackers(){
std::vector<announce_entry> remaining_trackers; std::vector<announce_entry> remaining_trackers;
std::vector<announce_entry> trackers = h.trackers(); std::vector<announce_entry> trackers = h.trackers();
std::vector<announce_entry>::iterator it; std::vector<announce_entry>::iterator it;
for(it = trackers.begin(); it != trackers.end(); it++) { for (it = trackers.begin(); it != trackers.end(); it++) {
if(!urls_to_remove.contains(misc::toQString((*it).url))) { if (!urls_to_remove.contains(misc::toQString((*it).url))) {
remaining_trackers.push_back(*it); remaining_trackers.push_back(*it);
} }
} }
@ -323,28 +323,28 @@ void TrackerList::deleteSelectedTrackers(){
void TrackerList::showTrackerListMenu(QPoint) { void TrackerList::showTrackerListMenu(QPoint) {
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) return; if (!h.is_valid()) return;
//QList<QTreeWidgetItem*> selected_items = getSelectedTrackerItems(); //QList<QTreeWidgetItem*> selected_items = getSelectedTrackerItems();
QMenu menu; QMenu menu;
// Add actions // Add actions
QAction *addAct = menu.addAction(IconProvider::instance()->getIcon("list-add"), tr("Add a new tracker...")); QAction *addAct = menu.addAction(IconProvider::instance()->getIcon("list-add"), tr("Add a new tracker..."));
QAction *delAct = 0; QAction *delAct = 0;
if(!getSelectedTrackerItems().isEmpty()) { if (!getSelectedTrackerItems().isEmpty()) {
delAct = menu.addAction(IconProvider::instance()->getIcon("list-remove"), tr("Remove tracker")); delAct = menu.addAction(IconProvider::instance()->getIcon("list-remove"), tr("Remove tracker"));
} }
menu.addSeparator(); menu.addSeparator();
QAction *reannounceAct = menu.addAction(IconProvider::instance()->getIcon("view-refresh"), tr("Force reannounce")); QAction *reannounceAct = menu.addAction(IconProvider::instance()->getIcon("view-refresh"), tr("Force reannounce"));
QAction *act = menu.exec(QCursor::pos()); QAction *act = menu.exec(QCursor::pos());
if(act == 0) return; if (act == 0) return;
if(act == addAct) { if (act == addAct) {
askForTrackers(); askForTrackers();
return; return;
} }
if(act == delAct) { if (act == delAct) {
deleteSelectedTrackers(); deleteSelectedTrackers();
return; return;
} }
if(act == reannounceAct) { if (act == reannounceAct) {
properties->getCurrentTorrent().force_reannounce(); properties->getCurrentTorrent().force_reannounce();
return; return;
} }
@ -352,7 +352,7 @@ void TrackerList::showTrackerListMenu(QPoint) {
void TrackerList::loadSettings() { void TrackerList::loadSettings() {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); 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(0, 30);
setColumnWidth(1, 300); setColumnWidth(1, 300);
} }

View file

@ -94,18 +94,18 @@ public slots:
} }
// Load from current user list // Load from current user list
QStringList tmp = trackers_list->toPlainText().split("\n"); 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); QUrl user_url(user_url_str);
if(!existingTrackers.contains(user_url)) if (!existingTrackers.contains(user_url))
existingTrackers << user_url; existingTrackers << user_url;
} }
// Add new trackers to the list // 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"); trackers_list->insertPlainText("\n");
int nb = 0; int nb = 0;
while (!list_file.atEnd()) { while (!list_file.atEnd()) {
const QByteArray line = list_file.readLine().trimmed(); const QByteArray line = list_file.readLine().trimmed();
if(line.isEmpty()) continue; if (line.isEmpty()) continue;
QUrl url(line); QUrl url(line);
if (!existingTrackers.contains(url)) { if (!existingTrackers.contains(url)) {
trackers_list->insertPlainText(line + "\n"); trackers_list->insertPlainText(line + "\n");
@ -119,7 +119,7 @@ public slots:
setCursor(Qt::ArrowCursor); setCursor(Qt::ArrowCursor);
uTorrentListButton->setEnabled(true); uTorrentListButton->setEnabled(true);
// Display information message if necessary // 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); QMessageBox::information(this, tr("No change"), tr("No additional trackers were found."), QMessageBox::Ok);
} }
sender()->deleteLater(); sender()->deleteLater();
@ -138,7 +138,7 @@ public:
static QStringList askForTrackers(QTorrentHandle h) { static QStringList askForTrackers(QTorrentHandle h) {
QStringList trackers; QStringList trackers;
TrackersAdditionDlg dlg(h); TrackersAdditionDlg dlg(h);
if(dlg.exec() == QDialog::Accepted) { if (dlg.exec() == QDialog::Accepted) {
return dlg.newTrackers(); return dlg.newTrackers();
} }
return trackers; return trackers;

View file

@ -56,14 +56,14 @@ public:
QVariant value(const QString & key, const QVariant &defaultValue = QVariant()) const { QVariant value(const QString & key, const QVariant &defaultValue = QVariant()) const {
QString key_tmp(key); QString key_tmp(key);
QVariant ret = QSettings::value(key_tmp); QVariant ret = QSettings::value(key_tmp);
if(ret.isNull()) if (ret.isNull())
return defaultValue; return defaultValue;
return ret; return ret;
} }
void setValue(const QString &key, const QVariant &val) { void setValue(const QString &key, const QVariant &val) {
QString key_tmp(key); QString key_tmp(key);
if(format() == QSettings::NativeFormat) if (format() == QSettings::NativeFormat)
key_tmp.replace("\\", "/"); key_tmp.replace("\\", "/");
QSettings::setValue(key_tmp, val); QSettings::setValue(key_tmp, val);
} }

View file

@ -44,7 +44,7 @@ bool QMacApplication::event(QEvent * ev) {
case QEvent::FileOpen: case QEvent::FileOpen:
{ {
QString path = static_cast<QFileOpenEvent *>(ev)->file(); QString path = static_cast<QFileOpenEvent *>(ev)->file();
if(path.isEmpty()) { if (path.isEmpty()) {
// Get the url instead // Get the url instead
path = static_cast<QFileOpenEvent *>(ev)->url().toString(); path = static_cast<QFileOpenEvent *>(ev)->url().toString();
} }

View file

@ -29,7 +29,7 @@ public slots:
QTime startAltSpeeds = pref.getSchedulerStartTime(); QTime startAltSpeeds = pref.getSchedulerStartTime();
QTime endAltSpeeds = pref.getSchedulerEndTime(); 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 << "Error: bandwidth scheduler have the same start time and end time." << std::endl;
std::cerr << "The bandwidth scheduler will be disabled" << std::endl; std::cerr << "The bandwidth scheduler will be disabled" << std::endl;
stop(); stop();
@ -41,7 +41,7 @@ public slots:
QTime now = QTime::currentTime(); QTime now = QTime::currentTime();
uint time_to_start = secsTo(now, startAltSpeeds); uint time_to_start = secsTo(now, startAltSpeeds);
uint time_to_end = secsTo(now, endAltSpeeds); 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 // We should be in alternative mode
in_alternative_mode = true; in_alternative_mode = true;
// Start counting // Start counting
@ -61,9 +61,9 @@ public slots:
// Get the day this mode was started (either today or yesterday) // Get the day this mode was started (either today or yesterday)
QDate current_date = QDateTime::currentDateTime().toLocalTime().date(); QDate current_date = QDateTime::currentDateTime().toLocalTime().date();
int day = current_date.dayOfWeek(); int day = current_date.dayOfWeek();
if(in_alternative_mode) { if (in_alternative_mode) {
// It is possible that starttime was yesterday // 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 current_date.addDays(-1); // Go to yesterday
day = current_date.day(); day = current_date.day();
} }
@ -75,17 +75,17 @@ public slots:
emit switchToAlternativeMode(!in_alternative_mode); emit switchToAlternativeMode(!in_alternative_mode);
break; break;
case WEEK_ENDS: case WEEK_ENDS:
if(day == Qt::Saturday || day == Qt::Sunday) if (day == Qt::Saturday || day == Qt::Sunday)
emit switchToAlternativeMode(!in_alternative_mode); emit switchToAlternativeMode(!in_alternative_mode);
break; break;
case WEEK_DAYS: case WEEK_DAYS:
if(day != Qt::Saturday && day != Qt::Sunday) if (day != Qt::Saturday && day != Qt::Sunday)
emit switchToAlternativeMode(!in_alternative_mode); emit switchToAlternativeMode(!in_alternative_mode);
break; break;
default: default:
// Convert our enum index to Qt enum index // Convert our enum index to Qt enum index
int scheduler_day = ((int)pref.getSchedulerDays()) - 2; int scheduler_day = ((int)pref.getSchedulerDays()) - 2;
if(day == scheduler_day) if (day == scheduler_day)
emit switchToAlternativeMode(!in_alternative_mode); emit switchToAlternativeMode(!in_alternative_mode);
break; break;
} }
@ -101,7 +101,7 @@ private:
// don't want that // don't want that
uint secsTo(QTime now, QTime t) { uint secsTo(QTime now, QTime t) {
int diff = now.secsTo(t); int diff = now.secsTo(t);
if(diff < 0) { if (diff < 0) {
// 86400 seconds in a day // 86400 seconds in a day
diff += 86400; diff += 86400;
} }

View file

@ -69,7 +69,7 @@ public:
int ruleCount = 0; int ruleCount = 0;
QFile file(filePath); QFile file(filePath);
if (file.exists()){ 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; std::cerr << "I/O Error: Could not open ip filer file in read mode." << std::endl;
return ruleCount; return ruleCount;
} }
@ -79,9 +79,9 @@ public:
QByteArray line = file.readLine(); QByteArray line = file.readLine();
// Ignoring empty lines // Ignoring empty lines
line = line.trimmed(); line = line.trimmed();
if(line.isEmpty()) continue; if (line.isEmpty()) continue;
// Ignoring commented lines // Ignoring commented lines
if(line.startsWith('#') || line.startsWith("//")) continue; if (line.startsWith('#') || line.startsWith("//")) continue;
// Line should be splitted by commas // Line should be splitted by commas
QList<QByteArray> partsList = line.split(','); QList<QByteArray> partsList = line.split(',');
@ -89,7 +89,7 @@ public:
// IP Range should be splitted by a dash // IP Range should be splitted by a dash
QList<QByteArray> IPs = partsList.first().split('-'); QList<QByteArray> IPs = partsList.first().split('-');
if(IPs.size() != 2) { if (IPs.size() != 2) {
qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
qDebug("Line was %s", line.constData()); qDebug("Line was %s", line.constData());
continue; continue;
@ -97,30 +97,30 @@ public:
boost::system::error_code ec; boost::system::error_code ec;
const QString strStartIP = cleanupIPAddress(IPs.at(0)); const QString strStartIP = cleanupIPAddress(IPs.at(0));
if(strStartIP.isEmpty()) { if (strStartIP.isEmpty()) {
qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
qDebug("Start IP of the range is malformated: %s", qPrintable(strStartIP)); qDebug("Start IP of the range is malformated: %s", qPrintable(strStartIP));
continue; continue;
} }
libtorrent::address startAddr = libtorrent::address::from_string(qPrintable(strStartIP), ec); libtorrent::address startAddr = libtorrent::address::from_string(qPrintable(strStartIP), ec);
if(ec) { if (ec) {
qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
qDebug("Start IP of the range is malformated: %s", qPrintable(strStartIP)); qDebug("Start IP of the range is malformated: %s", qPrintable(strStartIP));
continue; continue;
} }
const QString strEndIP = cleanupIPAddress(IPs.at(1)); const QString strEndIP = cleanupIPAddress(IPs.at(1));
if(strEndIP.isEmpty()) { if (strEndIP.isEmpty()) {
qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
qDebug("End IP of the range is malformated: %s", qPrintable(strEndIP)); qDebug("End IP of the range is malformated: %s", qPrintable(strEndIP));
continue; continue;
} }
libtorrent::address endAddr = libtorrent::address::from_string(qPrintable(strEndIP), ec); libtorrent::address endAddr = libtorrent::address::from_string(qPrintable(strEndIP), ec);
if(ec) { if (ec) {
qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
qDebug("End IP of the range is malformated: %s", qPrintable(strEndIP)); qDebug("End IP of the range is malformated: %s", qPrintable(strEndIP));
continue; continue;
} }
if(startAddr.is_v4() != endAddr.is_v4()) { if (startAddr.is_v4() != endAddr.is_v4()) {
qDebug("Ipfilter.dat: line %d is malformed.", nbLine); qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
qDebug("One IP is IPv4 and the other is IPv6!"); qDebug("One IP is IPv4 and the other is IPv6!");
continue; continue;
@ -128,12 +128,12 @@ public:
// Check if there is an access value (apparently not mandatory) // Check if there is an access value (apparently not mandatory)
int nbAccess = 0; int nbAccess = 0;
if(nbElem > 1) { if (nbElem > 1) {
// There is possibly one // There is possibly one
nbAccess = partsList.at(1).trimmed().toInt(); nbAccess = partsList.at(1).trimmed().toInt();
} }
if(nbAccess > 127) { if (nbAccess > 127) {
// Ignoring this rule because access value is too high // Ignoring this rule because access value is too high
continue; continue;
} }
@ -155,7 +155,7 @@ public:
int ruleCount = 0; int ruleCount = 0;
QFile file(filePath); QFile file(filePath);
if (file.exists()){ 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; std::cerr << "I/O Error: Could not open ip filer file in read mode." << std::endl;
return ruleCount; return ruleCount;
} }
@ -163,48 +163,48 @@ public:
while (!file.atEnd() && !abort) { while (!file.atEnd() && !abort) {
++nbLine; ++nbLine;
QByteArray line = file.readLine().trimmed(); QByteArray line = file.readLine().trimmed();
if(line.isEmpty()) continue; if (line.isEmpty()) continue;
// Ignoring commented lines // Ignoring commented lines
if(line.startsWith('#') || line.startsWith("//")) continue; if (line.startsWith('#') || line.startsWith("//")) continue;
// Line is splitted by : // Line is splitted by :
QList<QByteArray> partsList = line.split(':'); QList<QByteArray> partsList = line.split(':');
if(partsList.size() < 2){ if (partsList.size() < 2){
qDebug("p2p file: line %d is malformed.", nbLine); qDebug("p2p file: line %d is malformed.", nbLine);
continue; continue;
} }
// Get IP range // Get IP range
QList<QByteArray> IPs = partsList.last().split('-'); QList<QByteArray> IPs = partsList.last().split('-');
if(IPs.size() != 2) { if (IPs.size() != 2) {
qDebug("p2p file: line %d is malformed.", nbLine); qDebug("p2p file: line %d is malformed.", nbLine);
qDebug("line was: %s", line.constData()); qDebug("line was: %s", line.constData());
continue; continue;
} }
boost::system::error_code ec; boost::system::error_code ec;
QString strStartIP = cleanupIPAddress(IPs.at(0)); QString strStartIP = cleanupIPAddress(IPs.at(0));
if(strStartIP.isEmpty()) { if (strStartIP.isEmpty()) {
qDebug("p2p file: line %d is malformed.", nbLine); qDebug("p2p file: line %d is malformed.", nbLine);
qDebug("Start IP is invalid: %s", qPrintable(strStartIP)); qDebug("Start IP is invalid: %s", qPrintable(strStartIP));
continue; continue;
} }
libtorrent::address startAddr = libtorrent::address::from_string(qPrintable(strStartIP), ec); libtorrent::address startAddr = libtorrent::address::from_string(qPrintable(strStartIP), ec);
if(ec) { if (ec) {
qDebug("p2p file: line %d is malformed.", nbLine); qDebug("p2p file: line %d is malformed.", nbLine);
qDebug("Start IP is invalid: %s", qPrintable(strStartIP)); qDebug("Start IP is invalid: %s", qPrintable(strStartIP));
continue; continue;
} }
QString strEndIP = cleanupIPAddress(IPs.at(1)); QString strEndIP = cleanupIPAddress(IPs.at(1));
if(strEndIP.isEmpty()) { if (strEndIP.isEmpty()) {
qDebug("p2p file: line %d is malformed.", nbLine); qDebug("p2p file: line %d is malformed.", nbLine);
qDebug("End IP is invalid: %s", qPrintable(strStartIP)); qDebug("End IP is invalid: %s", qPrintable(strStartIP));
continue; continue;
} }
libtorrent::address endAddr = libtorrent::address::from_string(qPrintable(strEndIP), ec); libtorrent::address endAddr = libtorrent::address::from_string(qPrintable(strEndIP), ec);
if(ec) { if (ec) {
qDebug("p2p file: line %d is malformed.", nbLine); qDebug("p2p file: line %d is malformed.", nbLine);
qDebug("End IP is invalid: %s", qPrintable(strStartIP)); qDebug("End IP is invalid: %s", qPrintable(strStartIP));
continue; continue;
} }
if(startAddr.is_v4() != endAddr.is_v4()) { if (startAddr.is_v4() != endAddr.is_v4()) {
qDebug("p2p file: line %d is malformed.", nbLine); qDebug("p2p file: line %d is malformed.", nbLine);
qDebug("Line was: %s", line.constData()); qDebug("Line was: %s", line.constData());
continue; continue;
@ -230,8 +230,8 @@ public:
do { do {
read = stream.readRawData(&c, 1); read = stream.readRawData(&c, 1);
total_read += read; total_read += read;
if(read > 0) { if (read > 0) {
if(c != delim) { if (c != delim) {
name += c; name += c;
} else { } else {
// Delim found // Delim found
@ -247,7 +247,7 @@ public:
int ruleCount = 0; int ruleCount = 0;
QFile file(filePath); QFile file(filePath);
if (file.exists()){ 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; std::cerr << "I/O Error: Could not open ip filer file in read mode." << std::endl;
return ruleCount; return ruleCount;
} }
@ -255,7 +255,7 @@ public:
// Read header // Read header
char buf[7]; char buf[7];
unsigned char version; unsigned char version;
if( if (
!stream.readRawData(buf, sizeof(buf)) || !stream.readRawData(buf, sizeof(buf)) ||
memcmp(buf, "\xFF\xFF\xFF\xFFP2B", 7) || memcmp(buf, "\xFF\xFF\xFF\xFFP2B", 7) ||
!stream.readRawData((char*)&version, sizeof(version)) !stream.readRawData((char*)&version, sizeof(version))
@ -264,13 +264,13 @@ public:
return ruleCount; return ruleCount;
} }
if(version==1 || version==2) { if (version==1 || version==2) {
qDebug ("p2b version 1 or 2"); qDebug ("p2b version 1 or 2");
unsigned int start, end; unsigned int start, end;
string name; string name;
while(getlineInStream(stream, name, '\0') && !abort) { while(getlineInStream(stream, name, '\0') && !abort) {
if( if (
!stream.readRawData((char*)&start, sizeof(start)) || !stream.readRawData((char*)&start, sizeof(start)) ||
!stream.readRawData((char*)&end, sizeof(end)) !stream.readRawData((char*)&end, sizeof(end))
) { ) {
@ -289,26 +289,26 @@ public:
} catch(std::exception&) {} } catch(std::exception&) {}
} }
} }
else if(version==3) { else if (version==3) {
qDebug ("p2b version 3"); qDebug ("p2b version 3");
unsigned int namecount; 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; std::cerr << "Parsing Error: The filter file is not a valid PeerGuardian P2B file." << std::endl;
return ruleCount; return ruleCount;
} }
namecount=ntohl(namecount); namecount=ntohl(namecount);
// Reading names although, we don't really care about them // Reading names although, we don't really care about them
for(unsigned int i=0; i<namecount; i++) { for (unsigned int i=0; i<namecount; i++) {
string name; string name;
if(!getlineInStream(stream, name, '\0')) { if (!getlineInStream(stream, name, '\0')) {
std::cerr << "Parsing Error: The filter file is not a valid PeerGuardian P2B file." << std::endl; std::cerr << "Parsing Error: The filter file is not a valid PeerGuardian P2B file." << std::endl;
return ruleCount; return ruleCount;
} }
if(abort) return ruleCount; if (abort) return ruleCount;
} }
// Reading the ranges // Reading the ranges
unsigned int rangecount; unsigned int rangecount;
if(!stream.readRawData((char*)&rangecount, sizeof(rangecount))) { if (!stream.readRawData((char*)&rangecount, sizeof(rangecount))) {
std::cerr << "Parsing Error: The filter file is not a valid PeerGuardian P2B file." << std::endl; std::cerr << "Parsing Error: The filter file is not a valid PeerGuardian P2B file." << std::endl;
return ruleCount; return ruleCount;
} }
@ -316,8 +316,8 @@ public:
unsigned int name, start, end; unsigned int name, start, end;
for(unsigned int i=0; i<rangecount; i++) { for (unsigned int i=0; i<rangecount; i++) {
if( if (
!stream.readRawData((char*)&name, sizeof(name)) || !stream.readRawData((char*)&name, sizeof(name)) ||
!stream.readRawData((char*)&start, sizeof(start)) || !stream.readRawData((char*)&start, sizeof(start)) ||
!stream.readRawData((char*)&end, sizeof(end)) !stream.readRawData((char*)&end, sizeof(end))
@ -335,7 +335,7 @@ public:
filter.add_rule(first, last, libtorrent::ip_filter::blocked); filter.add_rule(first, last, libtorrent::ip_filter::blocked);
++ruleCount; ++ruleCount;
} catch(std::exception&) {} } catch(std::exception&) {}
if(abort) return ruleCount; if (abort) return ruleCount;
} }
} else { } else {
std::cerr << "Parsing Error: The filter file is not a valid PeerGuardian P2B file." << std::endl; std::cerr << "Parsing Error: The filter file is not a valid PeerGuardian P2B file." << std::endl;
@ -354,7 +354,7 @@ public:
void processFilterFile(QString _filePath){ void processFilterFile(QString _filePath){
// First, import current filter // First, import current filter
filter = s->get_ip_filter(); filter = s->get_ip_filter();
if(isRunning()) { if (isRunning()) {
// Already parsing a filter, abort first // Already parsing a filter, abort first
abort = true; abort = true;
wait(); wait();
@ -368,12 +368,12 @@ public:
static void processFilterList(libtorrent::session *s, const QStringList& IPs) { static void processFilterList(libtorrent::session *s, const QStringList& IPs) {
// First, import current filter // First, import current filter
libtorrent::ip_filter filter = s->get_ip_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()); qDebug("Manual ban of peer %s", ip.toLocal8Bit().constData());
boost::system::error_code ec; boost::system::error_code ec;
libtorrent::address addr = libtorrent::address::from_string(ip.toLocal8Bit().constData(), ec); libtorrent::address addr = libtorrent::address::from_string(ip.toLocal8Bit().constData(), ec);
Q_ASSERT(!ec); Q_ASSERT(!ec);
if(!ec) if (!ec)
filter.add_rule(addr, addr, libtorrent::ip_filter::blocked); filter.add_rule(addr, addr, libtorrent::ip_filter::blocked);
} }
s->set_ip_filter(filter); s->set_ip_filter(filter);
@ -386,7 +386,7 @@ signals:
protected: protected:
QString cleanupIPAddress(QString _ip) { QString cleanupIPAddress(QString _ip) {
QHostAddress ip(_ip.trimmed()); QHostAddress ip(_ip.trimmed());
if(ip.isNull()) { if (ip.isNull()) {
return QString(); return QString();
} }
return ip.toString(); return ip.toString();
@ -395,11 +395,11 @@ protected:
void run(){ void run(){
qDebug("Processing filter file"); qDebug("Processing filter file");
int ruleCount = 0; int ruleCount = 0;
if(filePath.endsWith(".p2p", Qt::CaseInsensitive)) { if (filePath.endsWith(".p2p", Qt::CaseInsensitive)) {
// PeerGuardian p2p file // PeerGuardian p2p file
ruleCount = parseP2PFilterFile(filePath); ruleCount = parseP2PFilterFile(filePath);
} else { } else {
if(filePath.endsWith(".p2b", Qt::CaseInsensitive)) { if (filePath.endsWith(".p2b", Qt::CaseInsensitive)) {
// PeerGuardian p2b file // PeerGuardian p2b file
ruleCount = parseP2BFilterFile(filePath); ruleCount = parseP2BFilterFile(filePath);
} else { } else {
@ -407,7 +407,7 @@ protected:
ruleCount = parseDATFilterFile(filePath); ruleCount = parseDATFilterFile(filePath);
} }
} }
if(abort) if (abort)
return; return;
try { try {
s->set_ip_filter(filter); s->set_ip_filter(filter);

File diff suppressed because it is too large Load diff

View file

@ -56,7 +56,7 @@ using namespace std;
#if LIBTORRENT_VERSION_MINOR < 16 #if LIBTORRENT_VERSION_MINOR < 16
static QString boostTimeToQString(const boost::posix_time::ptime &boostDate) { 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; struct std::tm tm;
try { try {
tm = boost::posix_time::to_tm(boostDate); tm = boost::posix_time::to_tm(boostDate);
@ -81,7 +81,7 @@ QString QTorrentHandle::hash() const {
QString QTorrentHandle::name() const { QString QTorrentHandle::name() const {
QString name = TorrentPersistentData::getName(hash()); QString name = TorrentPersistentData::getName(hash());
if(name.isEmpty()) { if (name.isEmpty()) {
name = misc::toQStringU(torrent_handle::name()); name = misc::toQStringU(torrent_handle::name());
} }
return name; return name;
@ -124,7 +124,7 @@ qreal QTorrentHandle::progress() const {
#else #else
torrent_status st = torrent_handle::status(); torrent_status st = torrent_handle::status();
#endif #endif
if(!st.total_wanted) if (!st.total_wanted)
return 0.; return 0.;
if (st.total_wanted_done == st.total_wanted) if (st.total_wanted_done == st.total_wanted)
return 1.; return 1.;
@ -182,19 +182,19 @@ int QTorrentHandle::num_pieces() const {
bool QTorrentHandle::first_last_piece_first() const { bool QTorrentHandle::first_last_piece_first() const {
// Detect first media file // Detect first media file
int index = 0; int index = 0;
for(index = 0; index < num_files(); ++index) { for (index = 0; index < num_files(); ++index) {
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
QString path = misc::toQStringU(get_torrent_info().file_at(index).path); QString path = misc::toQStringU(get_torrent_info().file_at(index).path);
#else #else
QString path = misc::toQStringU(get_torrent_info().file_at(index).path.string()); QString path = misc::toQStringU(get_torrent_info().file_at(index).path.string());
#endif #endif
const QString ext = misc::file_extension(path); 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; break;
} }
++index; ++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); file_entry media_file = torrent_handle::get_torrent_info().file_at(index);
int piece_size = torrent_handle::get_torrent_info().piece_length(); int piece_size = torrent_handle::get_torrent_info().piece_length();
Q_ASSERT(piece_size>0); Q_ASSERT(piece_size>0);
@ -285,7 +285,7 @@ QStringList QTorrentHandle::url_seeds() const {
try { try {
const std::set<std::string> existing_seeds = torrent_handle::url_seeds(); const std::set<std::string> existing_seeds = torrent_handle::url_seeds();
std::set<std::string>::const_iterator it; std::set<std::string>::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()); qDebug("URL Seed: %s", it->c_str());
res << misc::toQString(*it); res << misc::toQString(*it);
} }
@ -306,8 +306,8 @@ size_type QTorrentHandle::actual_size() const {
bool QTorrentHandle::has_filtered_pieces() const { bool QTorrentHandle::has_filtered_pieces() const {
std::vector<int> piece_priorities = torrent_handle::piece_priorities(); std::vector<int> piece_priorities = torrent_handle::piece_priorities();
for(unsigned int i = 0; i<piece_priorities.size(); ++i) { for (unsigned int i = 0; i<piece_priorities.size(); ++i) {
if(!piece_priorities[i]) return true; if (!piece_priorities[i]) return true;
} }
return false; return false;
} }
@ -432,7 +432,7 @@ size_type QTorrentHandle::total_payload_upload() const {
QStringList QTorrentHandle::absolute_files_path() const { QStringList QTorrentHandle::absolute_files_path() const {
QDir saveDir(save_path()); QDir saveDir(save_path());
QStringList res; QStringList res;
for(int i = 0; i<num_files(); ++i) { for (int i = 0; i<num_files(); ++i) {
res << QDir::cleanPath(saveDir.absoluteFilePath(filepath_at(i))); res << QDir::cleanPath(saveDir.absoluteFilePath(filepath_at(i)));
} }
return res; return res;
@ -442,10 +442,10 @@ QStringList QTorrentHandle::absolute_files_path_uneeded() const {
QDir saveDir(save_path()); QDir saveDir(save_path());
QStringList res; QStringList res;
std::vector<int> fp = torrent_handle::file_priorities(); std::vector<int> fp = torrent_handle::file_priorities();
for(uint i = 0; i < fp.size(); ++i) { for (uint i = 0; i < fp.size(); ++i) {
if(fp[i] == 0) { if (fp[i] == 0) {
const QString file_path = QDir::cleanPath(saveDir.absoluteFilePath(filepath_at(i))); const QString file_path = QDir::cleanPath(saveDir.absoluteFilePath(filepath_at(i)));
if(file_path.contains(".unwanted")) if (file_path.contains(".unwanted"))
res << file_path; res << file_path;
} }
} }
@ -454,14 +454,14 @@ QStringList QTorrentHandle::absolute_files_path_uneeded() const {
bool QTorrentHandle::has_missing_files() const { bool QTorrentHandle::has_missing_files() const {
const QStringList paths = absolute_files_path(); const QStringList paths = absolute_files_path();
foreach(const QString &path, paths) { foreach (const QString &path, paths) {
if(!QFile::exists(path)) return true; if (!QFile::exists(path)) return true;
} }
return false; return false;
} }
int QTorrentHandle::queue_position() const { int QTorrentHandle::queue_position() const {
if(torrent_handle::queue_position() < 0) if (torrent_handle::queue_position() < 0)
return -1; return -1;
return torrent_handle::queue_position()+1; return torrent_handle::queue_position()+1;
} }
@ -540,14 +540,14 @@ bool QTorrentHandle::priv() const {
QString QTorrentHandle::firstFileSavePath() const { QString QTorrentHandle::firstFileSavePath() const {
Q_ASSERT(has_metadata()); Q_ASSERT(has_metadata());
QString fsave_path = TorrentPersistentData::getSavePath(hash()); QString fsave_path = TorrentPersistentData::getSavePath(hash());
if(fsave_path.isEmpty()) if (fsave_path.isEmpty())
fsave_path = save_path(); fsave_path = save_path();
fsave_path.replace("\\", "/"); fsave_path.replace("\\", "/");
if(!fsave_path.endsWith("/")) if (!fsave_path.endsWith("/"))
fsave_path += "/"; fsave_path += "/";
fsave_path += filepath_at(0); fsave_path += filepath_at(0);
// Remove .!qB extension // Remove .!qB extension
if(fsave_path.endsWith(".!qB", Qt::CaseInsensitive)) if (fsave_path.endsWith(".!qB", Qt::CaseInsensitive))
fsave_path.chop(4); fsave_path.chop(4);
return fsave_path; return fsave_path;
} }
@ -572,7 +572,7 @@ QString QTorrentHandle::error() const {
void QTorrentHandle::downloading_pieces(bitfield &bf) const { void QTorrentHandle::downloading_pieces(bitfield &bf) const {
std::vector<partial_piece_info> queue; std::vector<partial_piece_info> queue;
torrent_handle::get_download_queue(queue); torrent_handle::get_download_queue(queue);
for(std::vector<partial_piece_info>::iterator it=queue.begin(); it!= queue.end(); it++) { for (std::vector<partial_piece_info>::iterator it=queue.begin(); it!= queue.end(); it++) {
bf.set_bit(it->piece_index); bf.set_bit(it->piece_index);
} }
return; return;
@ -609,22 +609,22 @@ void QTorrentHandle::pause() const {
} }
void QTorrentHandle::resume() const { void QTorrentHandle::resume() const {
if(has_error()) torrent_handle::clear_error(); if (has_error()) torrent_handle::clear_error();
const QString torrent_hash = hash(); const QString torrent_hash = hash();
bool has_persistant_error = TorrentPersistentData::hasError(torrent_hash); bool has_persistant_error = TorrentPersistentData::hasError(torrent_hash);
TorrentPersistentData::setErrorState(torrent_hash, false); TorrentPersistentData::setErrorState(torrent_hash, false);
bool temp_path_enabled = Preferences().isTempPathEnabled(); 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 // Torrent was supposed to be seeding, checking again in final destination
qDebug("Resuming a torrent with error..."); qDebug("Resuming a torrent with error...");
const QString final_save_path = TorrentPersistentData::getSavePath(torrent_hash); const QString final_save_path = TorrentPersistentData::getSavePath(torrent_hash);
qDebug("Torrent final path is: %s", qPrintable(final_save_path)); 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); move_storage(final_save_path);
} }
torrent_handle::auto_managed(true); torrent_handle::auto_managed(true);
torrent_handle::resume(); torrent_handle::resume();
if(has_persistant_error && temp_path_enabled) { if (has_persistant_error && temp_path_enabled) {
// Force recheck // Force recheck
torrent_handle::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 { 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()); TorrentPersistentData::setPreviousSavePath(hash(), save_path());
// Create destination directory if necessary // Create destination directory if necessary
// or move_storage() will fail... // 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 { 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 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); entry torrent_entry(entry::dictionary_t);
torrent_entry["info"] = meta; torrent_entry["info"] = meta;
if(!torrent_handle::trackers().empty()) if (!torrent_handle::trackers().empty())
torrent_entry["announce"] = torrent_handle::trackers().front().url; torrent_entry["announce"] = torrent_handle::trackers().front().url;
vector<char> out; vector<char> out;
@ -677,14 +677,14 @@ bool QTorrentHandle::save_torrent_file(QString path) const {
void QTorrentHandle::file_priority(int index, int priority) const { void QTorrentHandle::file_priority(int index, int priority) const {
vector<int> priorities = torrent_handle::file_priorities(); vector<int> priorities = torrent_handle::file_priorities();
if(priorities[index] != priority) { if (priorities[index] != priority) {
priorities[index] = priority; priorities[index] = priority;
prioritize_files(priorities); prioritize_files(priorities);
} }
} }
void QTorrentHandle::prioritize_files(const vector<int> &files) const { void QTorrentHandle::prioritize_files(const vector<int> &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; qDebug() << Q_FUNC_INFO;
bool was_seed = is_seed(); bool was_seed = is_seed();
vector<size_type> progress; vector<size_type> progress;
@ -692,25 +692,25 @@ void QTorrentHandle::prioritize_files(const vector<int> &files) const {
qDebug() << Q_FUNC_INFO << "Changing files priorities..."; qDebug() << Q_FUNC_INFO << "Changing files priorities...";
torrent_handle::prioritize_files(files); torrent_handle::prioritize_files(files);
qDebug() << Q_FUNC_INFO << "Moving unwanted files to .unwanted folder..."; qDebug() << Q_FUNC_INFO << "Moving unwanted files to .unwanted folder...";
for(uint i=0; i<files.size(); ++i) { for (uint i=0; i<files.size(); ++i) {
// Move unwanted files to a .unwanted subfolder // Move unwanted files to a .unwanted subfolder
if(files[i] == 0 && progress[i] < filesize_at(i)) { if (files[i] == 0 && progress[i] < filesize_at(i)) {
QString old_path = filepath_at(i); QString old_path = filepath_at(i);
// Make sure the file does not already exists // Make sure the file does not already exists
if(QFile::exists(QDir(save_path()).absoluteFilePath(old_path))) { if (QFile::exists(QDir(save_path()).absoluteFilePath(old_path))) {
qWarning() << "File" << old_path << "already exists at destination."; qWarning() << "File" << old_path << "already exists at destination.";
qWarning() << "We do not move it to .unwanted folder"; qWarning() << "We do not move it to .unwanted folder";
continue; continue;
} }
QString old_name = filename_at(i); QString old_name = filename_at(i);
QString parent_path = misc::branchPath(old_path); QString parent_path = misc::branchPath(old_path);
if(parent_path.isEmpty() || QDir(parent_path).dirName() != ".unwanted") { if (parent_path.isEmpty() || QDir(parent_path).dirName() != ".unwanted") {
QString unwanted_abspath = QDir::cleanPath(save_path()+"/"+parent_path+"/.unwanted"); QString unwanted_abspath = QDir::cleanPath(save_path()+"/"+parent_path+"/.unwanted");
qDebug() << "Unwanted path is" << unwanted_abspath; qDebug() << "Unwanted path is" << unwanted_abspath;
bool created = QDir().mkpath(unwanted_abspath); bool created = QDir().mkpath(unwanted_abspath);
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
qDebug() << "unwanted folder was created:" << created; qDebug() << "unwanted folder was created:" << created;
if(created) { if (created) {
// Hide the folder on Windows // Hide the folder on Windows
qDebug() << "Hiding folder (Windows)"; qDebug() << "Hiding folder (Windows)";
wstring win_path = unwanted_abspath.replace("/","\\").toStdWString(); wstring win_path = unwanted_abspath.replace("/","\\").toStdWString();
@ -721,16 +721,16 @@ void QTorrentHandle::prioritize_files(const vector<int> &files) const {
#else #else
Q_UNUSED(created); Q_UNUSED(created);
#endif #endif
if(!parent_path.isEmpty() && !parent_path.endsWith("/")) if (!parent_path.isEmpty() && !parent_path.endsWith("/"))
parent_path += "/"; parent_path += "/";
rename_file(i, parent_path+".unwanted/"+old_name); rename_file(i, parent_path+".unwanted/"+old_name);
} }
} }
// Move wanted files back to their original folder // Move wanted files back to their original folder
qDebug() << Q_FUNC_INFO << "Moving wanted files back from .unwanted 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)); 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 old_name = filename_at(i);
QString new_relpath = misc::branchPath(parent_relpath); QString new_relpath = misc::branchPath(parent_relpath);
if (new_relpath.isEmpty()) if (new_relpath.isEmpty())
@ -744,16 +744,16 @@ void QTorrentHandle::prioritize_files(const vector<int> &files) const {
} }
} }
if(was_seed && !is_seed()) { if (was_seed && !is_seed()) {
qDebug() << "Torrent is no longer SEEDING"; qDebug() << "Torrent is no longer SEEDING";
// Save seed status // Save seed status
TorrentPersistentData::saveSeedStatus(*this); TorrentPersistentData::saveSeedStatus(*this);
// Move to temp folder if necessary // Move to temp folder if necessary
const Preferences pref; const Preferences pref;
if(pref.isTempPathEnabled()) { if (pref.isTempPathEnabled()) {
QString tmp_path = pref.getTempPath(); QString tmp_path = pref.getTempPath();
QString root_folder = TorrentPersistentData::getRootFolder(hash()); QString root_folder = TorrentPersistentData::getRootFolder(hash());
if(!root_folder.isEmpty()) if (!root_folder.isEmpty())
tmp_path = QDir(tmp_path).absoluteFilePath(root_folder); tmp_path = QDir(tmp_path).absoluteFilePath(root_folder);
qDebug() << "tmp folder is enabled, move torrent to " << tmp_path << " from " << save_path(); qDebug() << "tmp folder is enabled, move torrent to " << tmp_path << " from " << save_path();
move_storage(tmp_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 { void QTorrentHandle::prioritize_first_last_piece(int file_index, bool b) const {
// Determine the priority to set // Determine the priority to set
int prio = 7; // MAX 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); file_entry file = get_torrent_info().file_at(file_index);
// Determine the first and last piece of the file // Determine the first and last piece of the file
int piece_size = torrent_handle::get_torrent_info().piece_length(); 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 { 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 // Download first and last pieces first for all media files in the torrent
int index = 0; 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 path = filepath_at(index);
const QString ext = misc::file_extension(path); 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"; qDebug() << "File" << path << "is previewable, toggle downloading of first/last pieces first";
prioritize_first_last_piece(index, b); prioritize_first_last_piece(index, b);
} }

View file

@ -41,7 +41,7 @@ TorrentModelItem::TorrentModelItem(const QTorrentHandle &h)
m_torrent = h; m_torrent = h;
m_hash = h.hash(); m_hash = h.hash();
m_name = TorrentPersistentData::getName(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_addedTime = TorrentPersistentData::getAddedDate(h.hash());
m_seedTime = TorrentPersistentData::getSeedDate(h.hash()); m_seedTime = TorrentPersistentData::getSeedDate(h.hash());
m_label = TorrentPersistentData::getLabel(h.hash()); m_label = TorrentPersistentData::getLabel(h.hash());
@ -51,13 +51,13 @@ TorrentModelItem::State TorrentModelItem::state() const
{ {
try { try {
// Pause or Queued // Pause or Queued
if(m_torrent.is_paused()) { if (m_torrent.is_paused()) {
m_icon = QIcon(":/Icons/skin/paused.png"); m_icon = QIcon(":/Icons/skin/paused.png");
m_fgColor = QColor("red"); m_fgColor = QColor("red");
return m_torrent.is_seed() ? STATE_PAUSED_UP : STATE_PAUSED_DL; return m_torrent.is_seed() ? STATE_PAUSED_UP : STATE_PAUSED_DL;
} }
if(m_torrent.is_queued()) { if (m_torrent.is_queued()) {
if(m_torrent.state() != torrent_status::queued_for_checking if (m_torrent.state() != torrent_status::queued_for_checking
&& m_torrent.state() != torrent_status::checking_resume_data && m_torrent.state() != torrent_status::checking_resume_data
&& m_torrent.state() != torrent_status::checking_files) { && m_torrent.state() != torrent_status::checking_files) {
m_icon = QIcon(":/Icons/skin/queued.png"); m_icon = QIcon(":/Icons/skin/queued.png");
@ -70,7 +70,7 @@ TorrentModelItem::State TorrentModelItem::state() const
case torrent_status::allocating: case torrent_status::allocating:
case torrent_status::downloading_metadata: case torrent_status::downloading_metadata:
case torrent_status::downloading: { 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_icon = QIcon(":/Icons/skin/downloading.png");
m_fgColor = QColor("green"); m_fgColor = QColor("green");
return STATE_DOWNLOADING; return STATE_DOWNLOADING;
@ -82,7 +82,7 @@ TorrentModelItem::State TorrentModelItem::state() const
} }
case torrent_status::finished: case torrent_status::finished:
case torrent_status::seeding: 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_icon = QIcon(":/Icons/skin/uploading.png");
m_fgColor = QColor("orange"); m_fgColor = QColor("orange");
return STATE_SEEDING; return STATE_SEEDING;
@ -112,7 +112,7 @@ TorrentModelItem::State TorrentModelItem::state() const
bool TorrentModelItem::setData(int column, const QVariant &value, int role) bool TorrentModelItem::setData(int column, const QVariant &value, int role)
{ {
qDebug() << Q_FUNC_INFO << column << value; 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 // Label and Name columns can be edited
switch(column) { switch(column) {
case TR_NAME: case TR_NAME:
@ -121,7 +121,7 @@ bool TorrentModelItem::setData(int column, const QVariant &value, int role)
return true; return true;
case TR_LABEL: { case TR_LABEL: {
QString new_label = value.toString(); QString new_label = value.toString();
if(m_label != new_label) { if (m_label != new_label) {
QString old_label = m_label; QString old_label = m_label;
m_label = new_label; m_label = new_label;
TorrentPersistentData::saveLabel(m_torrent.hash(), 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 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; return m_icon;
} }
if(role == Qt::ForegroundRole) { if (role == Qt::ForegroundRole) {
return m_fgColor; return m_fgColor;
} }
if(role != Qt::DisplayRole && role != Qt::UserRole) return QVariant(); if (role != Qt::DisplayRole && role != Qt::UserRole) return QVariant();
switch(column) { switch(column) {
case TR_NAME: case TR_NAME:
return m_name.isEmpty()? m_torrent.name() : m_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(); return m_torrent.upload_payload_rate();
case TR_ETA: { case TR_ETA: {
// XXX: Is this correct? // 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()); return QBtSession::instance()->getETA(m_torrent.hash());
} }
case TR_RATIO: case TR_RATIO:
@ -206,7 +206,7 @@ void TorrentModel::populate() {
// Load the torrents // Load the torrents
std::vector<torrent_handle> torrents = QBtSession::instance()->getSession()->get_torrents(); std::vector<torrent_handle> torrents = QBtSession::instance()->getSession()->get_torrents();
std::vector<torrent_handle>::const_iterator it; std::vector<torrent_handle>::const_iterator it;
for(it = torrents.begin(); it != torrents.end(); it++) { for (it = torrents.begin(); it != torrents.end(); it++) {
addTorrent(QTorrentHandle(*it)); addTorrent(QTorrentHandle(*it));
} }
// Refresh timer // Refresh timer
@ -234,7 +234,7 @@ QVariant TorrentModel::headerData(int section, Qt::Orientation orientation,
int role) const int role) const
{ {
if (orientation == Qt::Horizontal) { if (orientation == Qt::Horizontal) {
if(role == Qt::DisplayRole) { if (role == Qt::DisplayRole) {
switch(section) { switch(section) {
case TorrentModelItem::TR_NAME: return tr("Name", "i.e: torrent name"); case TorrentModelItem::TR_NAME: return tr("Name", "i.e: torrent name");
case TorrentModelItem::TR_PRIORITY: return "#"; case TorrentModelItem::TR_PRIORITY: return "#";
@ -260,7 +260,7 @@ QVariant TorrentModel::headerData(int section, Qt::Orientation orientation,
return QVariant(); return QVariant();
} }
} }
if(role == Qt::TextAlignmentRole) { if (role == Qt::TextAlignmentRole) {
switch(section) { switch(section) {
case TorrentModelItem::TR_PRIORITY: case TorrentModelItem::TR_PRIORITY:
case TorrentModelItem::TR_SIZE: 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 QVariant TorrentModel::data(const QModelIndex &index, int role) const
{ {
if(!index.isValid()) return QVariant(); if (!index.isValid()) return QVariant();
try { 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); return m_torrents[index.row()]->data(index.column(), role);
} catch(invalid_handle&) {} } catch(invalid_handle&) {}
return QVariant(); 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) bool TorrentModel::setData(const QModelIndex &index, const QVariant &value, int role)
{ {
qDebug() << Q_FUNC_INFO << value; 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"); qDebug("Index is valid and role is DisplayRole");
try { 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); bool change = m_torrents[index.row()]->setData(index.column(), value, role);
if(change) if (change)
notifyTorrentChanged(index.row()); notifyTorrentChanged(index.row());
return change; return change;
} }
@ -315,8 +315,8 @@ int TorrentModel::torrentRow(const QString &hash) const
{ {
QList<TorrentModelItem*>::const_iterator it; QList<TorrentModelItem*>::const_iterator it;
int row = 0; int row = 0;
for(it = m_torrents.constBegin(); it != m_torrents.constEnd(); it++) { for (it = m_torrents.constBegin(); it != m_torrents.constEnd(); it++) {
if((*it)->hash() == hash) return row; if ((*it)->hash() == hash) return row;
++row; ++row;
} }
return -1; return -1;
@ -324,7 +324,7 @@ int TorrentModel::torrentRow(const QString &hash) const
void TorrentModel::addTorrent(const QTorrentHandle &h) void TorrentModel::addTorrent(const QTorrentHandle &h)
{ {
if(torrentRow(h.hash()) < 0) { if (torrentRow(h.hash()) < 0) {
beginInsertTorrent(m_torrents.size()); beginInsertTorrent(m_torrents.size());
TorrentModelItem *item = new TorrentModelItem(h); TorrentModelItem *item = new TorrentModelItem(h);
connect(item, SIGNAL(labelChanged(QString,QString)), SLOT(handleTorrentLabelChange(QString,QString))); 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); const int row = torrentRow(hash);
qDebug() << Q_FUNC_INFO << hash << row; qDebug() << Q_FUNC_INFO << hash << row;
if(row >= 0) { if (row >= 0) {
beginRemoveTorrent(row); beginRemoveTorrent(row);
m_torrents.removeAt(row); m_torrents.removeAt(row);
endRemoveTorrent(); endRemoveTorrent();
@ -368,7 +368,7 @@ void TorrentModel::endRemoveTorrent()
void TorrentModel::handleTorrentUpdate(const QTorrentHandle &h) void TorrentModel::handleTorrentUpdate(const QTorrentHandle &h)
{ {
const int row = torrentRow(h.hash()); const int row = torrentRow(h.hash());
if(row >= 0) { if (row >= 0) {
notifyTorrentChanged(row); notifyTorrentChanged(row);
} }
} }
@ -380,7 +380,7 @@ void TorrentModel::notifyTorrentChanged(int row)
void TorrentModel::setRefreshInterval(int refreshInterval) void TorrentModel::setRefreshInterval(int refreshInterval)
{ {
if(m_refreshInterval != refreshInterval) { if (m_refreshInterval != refreshInterval) {
m_refreshInterval = refreshInterval; m_refreshInterval = refreshInterval;
m_refreshTimer.stop(); m_refreshTimer.stop();
m_refreshTimer.start(m_refreshInterval); m_refreshTimer.start(m_refreshInterval);
@ -396,7 +396,7 @@ TorrentStatusReport TorrentModel::getTorrentStatusReport() const
{ {
TorrentStatusReport report; TorrentStatusReport report;
QList<TorrentModelItem*>::const_iterator it; QList<TorrentModelItem*>::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()) { switch((*it)->data(TorrentModelItem::TR_STATUS).toInt()) {
case TorrentModelItem::STATE_DOWNLOADING: case TorrentModelItem::STATE_DOWNLOADING:
++report.nb_active; ++report.nb_active;
@ -446,7 +446,7 @@ void TorrentModel::handleTorrentLabelChange(QString previous, QString current)
QString TorrentModel::torrentHash(int row) const QString TorrentModel::torrentHash(int row) const
{ {
if(row >= 0 && row < rowCount()) if (row >= 0 && row < rowCount())
return m_torrents.at(row)->hash(); return m_torrents.at(row)->hash();
return QString(); return QString();
} }
@ -454,7 +454,7 @@ QString TorrentModel::torrentHash(int row) const
void TorrentModel::handleTorrentAboutToBeRemoved(const QTorrentHandle &h) void TorrentModel::handleTorrentAboutToBeRemoved(const QTorrentHandle &h)
{ {
const int row = torrentRow(h.hash()); const int row = torrentRow(h.hash());
if(row >= 0) { if (row >= 0) {
emit torrentAboutToBeRemoved(m_torrents.at(row)); emit torrentAboutToBeRemoved(m_torrents.at(row));
} }
} }

View file

@ -79,13 +79,13 @@ void TorrentSpeedMonitor::run()
void SpeedSample::addSample(int s) void SpeedSample::addSample(int s)
{ {
m_speedSamples << s; m_speedSamples << s;
if(m_speedSamples.size() > max_samples) if (m_speedSamples.size() > max_samples)
m_speedSamples.removeFirst(); m_speedSamples.removeFirst();
} }
qreal SpeedSample::average() const qreal SpeedSample::average() const
{ {
if(m_speedSamples.empty()) return 0; if (m_speedSamples.empty()) return 0;
qlonglong sum = 0; qlonglong sum = 0;
foreach (int s, m_speedSamples) { foreach (int s, m_speedSamples) {
sum += s; sum += s;
@ -113,9 +113,9 @@ qlonglong TorrentSpeedMonitor::getETA(const QString &hash) const
{ {
QMutexLocker locker(&m_mutex); QMutexLocker locker(&m_mutex);
QTorrentHandle h = m_session->getTorrentHandle(hash); 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(); 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; return (h.total_wanted() - h.total_done()) / speed_average;
} }
@ -123,14 +123,14 @@ void TorrentSpeedMonitor::getSamples()
{ {
const std::vector<torrent_handle> torrents = m_session->getSession()->get_torrents(); const std::vector<torrent_handle> torrents = m_session->getSession()->get_torrents();
std::vector<torrent_handle>::const_iterator it; std::vector<torrent_handle>::const_iterator it;
for(it = torrents.begin(); it != torrents.end(); it++) { for (it = torrents.begin(); it != torrents.end(); it++) {
try { try {
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
torrent_status st = it->status(0x0); torrent_status st = it->status(0x0);
if(!st.paused) if (!st.paused)
m_samples[misc::toQString(it->info_hash())].addSample(st.download_payload_rate); m_samples[misc::toQString(it->info_hash())].addSample(st.download_payload_rate);
#else #else
if(!it->is_paused()) if (!it->is_paused())
m_samples[misc::toQString(it->info_hash())].addSample(it->status().download_payload_rate); m_samples[misc::toQString(it->info_hash())].addSample(it->status().download_payload_rate);
#endif #endif
} catch(invalid_handle&){} } catch(invalid_handle&){}

View file

@ -148,7 +148,7 @@ bool QtLocalPeer::sendMessage(const QString &message, int timeout)
QLocalSocket socket; QLocalSocket socket;
bool connOk = false; 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 // Try twice, in case the other instance is just starting up
socket.connectToServer(socketName); socket.connectToServer(socketName);
connOk = socket.waitForConnected(timeout/2); connOk = socket.waitForConnected(timeout/2);

View file

@ -64,7 +64,7 @@ public:
const QString ip_str = misc::toQString(ip.address().to_string(ec)); const QString ip_str = misc::toQString(ip.address().to_string(ec));
if (ec) return QString(); if (ec) return QString();
QString ret; QString ret;
if(m_cache.contains(ip_str)) { if (m_cache.contains(ip_str)) {
qDebug("Got host name from cache"); qDebug("Got host name from cache");
ret = *m_cache.object(ip_str); ret = *m_cache.object(ip_str);
} else { } else {
@ -77,7 +77,7 @@ public:
boost::system::error_code ec; boost::system::error_code ec;
const QString ip_str = misc::toQString(ip.address().to_string(ec)); const QString ip_str = misc::toQString(ip.address().to_string(ec));
if (ec) return; if (ec) return;
if(m_cache.contains(ip_str)) { if (m_cache.contains(ip_str)) {
qDebug("Resolved host name using cache"); qDebug("Resolved host name using cache");
emit ip_resolved(ip_str, *m_cache.object(ip_str)); emit ip_resolved(ip_str, *m_cache.object(ip_str));
return; return;
@ -93,9 +93,9 @@ private slots:
void hostResolved(const QHostInfo& host) { void hostResolved(const QHostInfo& host) {
if (host.error() == QHostInfo::NoError) { if (host.error() == QHostInfo::NoError) {
const QString hostname = host.hostName(); 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(); const QString ip = host.addresses().first().toString();
if(hostname != ip) { if (hostname != ip) {
//qDebug() << Q_FUNC_INFO << ip << QString("->") << hostname; //qDebug() << Q_FUNC_INFO << ip << QString("->") << hostname;
m_cache.insert(ip, new QString(hostname)); m_cache.insert(ip, new QString(hostname));
emit ip_resolved(ip, hostname); emit ip_resolved(ip, hostname);

View file

@ -122,19 +122,19 @@ void AutomatedRssDownloader::saveSettings()
void AutomatedRssDownloader::loadRulesList() void AutomatedRssDownloader::loadRulesList()
{ {
// Make sure we save the current item before clearing // Make sure we save the current item before clearing
if(m_editedRule) { if (m_editedRule) {
saveEditedRule(); saveEditedRule();
} }
ui->listRules->clear(); ui->listRules->clear();
foreach (const QString &rule_name, m_ruleList->ruleNames()) { foreach (const QString &rule_name, m_ruleList->ruleNames()) {
QListWidgetItem *item = new QListWidgetItem(rule_name, ui->listRules); QListWidgetItem *item = new QListWidgetItem(rule_name, ui->listRules);
item->setFlags(item->flags()|Qt::ItemIsUserCheckable); item->setFlags(item->flags()|Qt::ItemIsUserCheckable);
if(m_ruleList->getRule(rule_name)->isEnabled()) if (m_ruleList->getRule(rule_name)->isEnabled())
item->setCheckState(Qt::Checked); item->setCheckState(Qt::Checked);
else else
item->setCheckState(Qt::Unchecked); item->setCheckState(Qt::Unchecked);
} }
if(ui->listRules->count() > 0 && !ui->listRules->currentItem()) if (ui->listRules->count() > 0 && !ui->listRules->currentItem())
ui->listRules->setCurrentRow(0); ui->listRules->setCurrentRow(0);
} }
@ -144,11 +144,11 @@ void AutomatedRssDownloader::loadFeedList()
const QStringList feed_aliases = settings.getRssFeedsAliases(); const QStringList feed_aliases = settings.getRssFeedsAliases();
const QStringList feed_urls = settings.getRssFeedsUrls(); const QStringList feed_urls = settings.getRssFeedsUrls();
QStringList existing_urls; QStringList existing_urls;
for(int i=0; i<feed_aliases.size(); ++i) { for (int i=0; i<feed_aliases.size(); ++i) {
QString feed_url = feed_urls.at(i); QString feed_url = feed_urls.at(i);
feed_url = feed_url.split("\\").last(); feed_url = feed_url.split("\\").last();
qDebug() << Q_FUNC_INFO << feed_url; qDebug() << Q_FUNC_INFO << feed_url;
if(existing_urls.contains(feed_url)) continue; if (existing_urls.contains(feed_url)) continue;
QListWidgetItem *item = new QListWidgetItem(feed_aliases.at(i), ui->listFeeds); QListWidgetItem *item = new QListWidgetItem(feed_aliases.at(i), ui->listFeeds);
item->setData(Qt::UserRole, feed_url); item->setData(Qt::UserRole, feed_url);
item->setFlags(item->flags()|Qt::ItemIsUserCheckable); item->setFlags(item->flags()|Qt::ItemIsUserCheckable);
@ -159,18 +159,18 @@ void AutomatedRssDownloader::loadFeedList()
void AutomatedRssDownloader::updateFeedList() void AutomatedRssDownloader::updateFeedList()
{ {
disconnect(ui->listFeeds, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(handleFeedCheckStateChange(QListWidgetItem*))); disconnect(ui->listFeeds, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(handleFeedCheckStateChange(QListWidgetItem*)));
for(int i=0; i<ui->listFeeds->count(); ++i) { for (int i=0; i<ui->listFeeds->count(); ++i) {
QListWidgetItem *item = ui->listFeeds->item(i); QListWidgetItem *item = ui->listFeeds->item(i);
const QString feed_url = item->data(Qt::UserRole).toString(); const QString feed_url = item->data(Qt::UserRole).toString();
bool all_enabled = false; 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()); RssDownloadRulePtr rule = m_ruleList->getRule(ruleItem->text());
if(!rule) continue; if (!rule) continue;
qDebug() << "Rule" << rule->name() << "affects" << rule->rssFeeds().size() << "feeds."; qDebug() << "Rule" << rule->name() << "affects" << rule->rssFeeds().size() << "feeds.";
foreach(QString test, rule->rssFeeds()) { foreach (QString test, rule->rssFeeds()) {
qDebug() << "Feed is " << test; qDebug() << "Feed is " << test;
} }
if(rule->rssFeeds().contains(feed_url)) { if (rule->rssFeeds().contains(feed_url)) {
qDebug() << "Rule " << rule->name() << " affects feed " << feed_url; qDebug() << "Rule " << rule->name() << " affects feed " << feed_url;
all_enabled = true; all_enabled = true;
} else { } else {
@ -179,7 +179,7 @@ void AutomatedRssDownloader::updateFeedList()
break; break;
} }
} }
if(all_enabled) if (all_enabled)
item->setCheckState(Qt::Checked); item->setCheckState(Qt::Checked);
else else
item->setCheckState(Qt::Unchecked); item->setCheckState(Qt::Unchecked);
@ -201,7 +201,7 @@ void AutomatedRssDownloader::updateRuleDefinitionBox()
saveEditedRule(); saveEditedRule();
// Update rule definition box // Update rule definition box
const QList<QListWidgetItem*> selection = ui->listRules->selectedItems(); const QList<QListWidgetItem*> selection = ui->listRules->selectedItems();
if(selection.count() == 1) { if (selection.count() == 1) {
m_editedRule = selection.first(); m_editedRule = selection.first();
RssDownloadRulePtr rule = getCurrentRule(); RssDownloadRulePtr rule = getCurrentRule();
if (rule) { if (rule) {
@ -250,7 +250,7 @@ void AutomatedRssDownloader::clearRuleDefinitionBox()
RssDownloadRulePtr AutomatedRssDownloader::getCurrentRule() const RssDownloadRulePtr AutomatedRssDownloader::getCurrentRule() const
{ {
QListWidgetItem * current_item = ui->listRules->currentItem(); QListWidgetItem * current_item = ui->listRules->currentItem();
if(current_item) if (current_item)
return m_ruleList->getRule(current_item->text()); return m_ruleList->getRule(current_item->text());
return RssDownloadRulePtr(); return RssDownloadRulePtr();
} }
@ -259,16 +259,16 @@ void AutomatedRssDownloader::initLabelCombobox()
{ {
// Load custom labels // Load custom labels
const QStringList customLabels = Preferences().getTorrentLabels(); const QStringList customLabels = Preferences().getTorrentLabels();
foreach(const QString& label, customLabels) { foreach (const QString& label, customLabels) {
ui->comboLabel->addItem(label); ui->comboLabel->addItem(label);
} }
} }
void AutomatedRssDownloader::saveEditedRule() void AutomatedRssDownloader::saveEditedRule()
{ {
if(!m_editedRule) return; if (!m_editedRule) return;
qDebug() << Q_FUNC_INFO << m_editedRule; 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() << "Could not find rule" << m_editedRule->text() << "in the UI list";
qDebug() << "Probably removed the item, no need to save it"; qDebug() << "Probably removed the item, no need to save it";
return; return;
@ -284,13 +284,13 @@ void AutomatedRssDownloader::saveEditedRule()
rule->setUseRegex(ui->checkRegex->isChecked()); rule->setUseRegex(ui->checkRegex->isChecked());
rule->setMustContain(ui->lineContains->text()); rule->setMustContain(ui->lineContains->text());
rule->setMustNotContain(ui->lineNotContains->text()); rule->setMustNotContain(ui->lineNotContains->text());
if(ui->saveDiffDir_check->isChecked()) if (ui->saveDiffDir_check->isChecked())
rule->setSavePath(ui->lineSavePath->text()); rule->setSavePath(ui->lineSavePath->text());
else else
rule->setSavePath(""); rule->setSavePath("");
rule->setLabel(ui->comboLabel->currentText()); rule->setLabel(ui->comboLabel->currentText());
// Save new label // Save new label
if(!rule->label().isEmpty()) if (!rule->label().isEmpty())
Preferences().addTorrentLabel(rule->label()); Preferences().addTorrentLabel(rule->label());
//rule->setRssFeeds(getSelectedFeeds()); //rule->setRssFeeds(getSelectedFeeds());
// Save it // Save it
@ -302,9 +302,9 @@ void AutomatedRssDownloader::on_addRuleBtn_clicked()
{ {
// Ask for a rule name // 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->")); 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 // 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.")); QMessageBox::warning(this, tr("Rule name conflict"), tr("A rule with this name already exists, please choose another name."));
return; return;
} }
@ -319,16 +319,16 @@ void AutomatedRssDownloader::on_addRuleBtn_clicked()
void AutomatedRssDownloader::on_removeRuleBtn_clicked() void AutomatedRssDownloader::on_removeRuleBtn_clicked()
{ {
const QList<QListWidgetItem*> selection = ui->listRules->selectedItems(); const QList<QListWidgetItem*> selection = ui->listRules->selectedItems();
if(selection.isEmpty()) return; if (selection.isEmpty()) return;
// Ask for confirmation // Ask for confirmation
QString confirm_text; 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()); confirm_text = tr("Are you sure you want to remove the download rule named %1?").arg(selection.first()->text());
else else
confirm_text = tr("Are you sure you want to remove the selected download rules?"); 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; return;
foreach(QListWidgetItem *item, selection) { foreach (QListWidgetItem *item, selection) {
// Actually remove the item // Actually remove the item
ui->listRules->removeItemWidget(item); ui->listRules->removeItemWidget(item);
const QString rule_name = item->text(); const QString rule_name = item->text();
@ -343,22 +343,22 @@ void AutomatedRssDownloader::on_removeRuleBtn_clicked()
void AutomatedRssDownloader::on_browseSP_clicked() void AutomatedRssDownloader::on_browseSP_clicked()
{ {
QString save_path = QFileDialog::getExistingDirectory(this, tr("Destination directory"), QDir::homePath()); QString save_path = QFileDialog::getExistingDirectory(this, tr("Destination directory"), QDir::homePath());
if(!save_path.isEmpty()) if (!save_path.isEmpty())
ui->lineSavePath->setText(save_path); ui->lineSavePath->setText(save_path);
} }
void AutomatedRssDownloader::on_exportBtn_clicked() 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.")); QMessageBox::warning(this, tr("Invalid action"), tr("The list is empty, there is nothing to export."));
return; return;
} }
// Ask for a save path // 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)")); 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.isEmpty()) return;
if(!save_path.endsWith(".rssrules", Qt::CaseInsensitive)) if (!save_path.endsWith(".rssrules", Qt::CaseInsensitive))
save_path += ".rssrules"; 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")); QMessageBox::warning(this, tr("I/O Error"), tr("Failed to create the destination file"));
return; return;
} }
@ -368,9 +368,9 @@ void AutomatedRssDownloader::on_importBtn_clicked()
{ {
// Ask for filter path // 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)")); 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 // 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")); QMessageBox::warning(this, tr("Import Error"), tr("Failed to import the selected rules file"));
return; return;
} }
@ -386,8 +386,8 @@ void AutomatedRssDownloader::displayRulesListMenu(const QPoint &pos)
QAction *delAct = 0; QAction *delAct = 0;
QAction *renameAct = 0; QAction *renameAct = 0;
const QList<QListWidgetItem*> selection = ui->listRules->selectedItems(); const QList<QListWidgetItem*> selection = ui->listRules->selectedItems();
if(!selection.isEmpty()) { if (!selection.isEmpty()) {
if(selection.count() == 1) { if (selection.count() == 1) {
delAct = menu.addAction(IconProvider::instance()->getIcon("list-remove"), tr("Delete rule")); delAct = menu.addAction(IconProvider::instance()->getIcon("list-remove"), tr("Delete rule"));
menu.addSeparator(); menu.addSeparator();
renameAct = menu.addAction(IconProvider::instance()->getIcon("edit-rename"), tr("Rename rule->..")); 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()); QAction *act = menu.exec(QCursor::pos());
if(!act) return; if (!act) return;
if(act == addAct) { if (act == addAct) {
on_addRuleBtn_clicked(); on_addRuleBtn_clicked();
return; return;
} }
if(act == delAct) { if (act == delAct) {
on_removeRuleBtn_clicked(); on_removeRuleBtn_clicked();
return; return;
} }
if(act == renameAct) { if (act == renameAct) {
renameSelectedRule(); renameSelectedRule();
return; return;
} }
@ -414,12 +414,12 @@ void AutomatedRssDownloader::displayRulesListMenu(const QPoint &pos)
void AutomatedRssDownloader::renameSelectedRule() void AutomatedRssDownloader::renameSelectedRule()
{ {
QListWidgetItem *item = ui->listRules->currentItem(); QListWidgetItem *item = ui->listRules->currentItem();
if(!item) return; if (!item) return;
forever { forever {
QString new_name = QInputDialog::getText(this, tr("Rule renaming"), tr("Please type the new rule name"), QLineEdit::Normal, item->text()); 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(); new_name = new_name.trimmed();
if(new_name.isEmpty()) return; if (new_name.isEmpty()) return;
if(m_ruleList->ruleNames().contains(new_name, Qt::CaseInsensitive)) { 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.")); QMessageBox::warning(this, tr("Rule name conflict"), tr("A rule with this name already exists, please choose another name."));
} else { } else {
// Rename the rule // Rename the rule
@ -432,7 +432,7 @@ void AutomatedRssDownloader::renameSelectedRule()
void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feed_item) void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feed_item)
{ {
if(ui->ruleDefBox->isEnabled()) { if (ui->ruleDefBox->isEnabled()) {
// Make sure the current rule is saved // Make sure the current rule is saved
saveEditedRule(); saveEditedRule();
} }
@ -441,15 +441,15 @@ void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feed_it
RssDownloadRulePtr rule = m_ruleList->getRule(rule_item->text()); RssDownloadRulePtr rule = m_ruleList->getRule(rule_item->text());
Q_ASSERT(rule); Q_ASSERT(rule);
QStringList affected_feeds = rule->rssFeeds(); QStringList affected_feeds = rule->rssFeeds();
if(feed_item->checkState() == Qt::Checked) { if (feed_item->checkState() == Qt::Checked) {
if(!affected_feeds.contains(feed_url)) if (!affected_feeds.contains(feed_url))
affected_feeds << feed_url; affected_feeds << feed_url;
} else { } else {
if(affected_feeds.contains(feed_url)) if (affected_feeds.contains(feed_url))
affected_feeds.removeOne(feed_url); affected_feeds.removeOne(feed_url);
} }
// Save the updated rule // Save the updated rule
if(affected_feeds.size() != rule->rssFeeds().size()) { if (affected_feeds.size() != rule->rssFeeds().size()) {
rule->setRssFeeds(affected_feeds); rule->setRssFeeds(affected_feeds);
m_ruleList->saveRule(rule); m_ruleList->saveRule(rule);
} }
@ -461,7 +461,7 @@ void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feed_it
void AutomatedRssDownloader::updateMatchingArticles() void AutomatedRssDownloader::updateMatchingArticles()
{ {
ui->treeMatchingArticles->clear(); ui->treeMatchingArticles->clear();
if(ui->ruleDefBox->isEnabled()) { if (ui->ruleDefBox->isEnabled()) {
saveEditedRule(); saveEditedRule();
} }
RssManagerPtr manager = m_manager.toStrongRef(); RssManagerPtr manager = m_manager.toStrongRef();
@ -469,17 +469,17 @@ void AutomatedRssDownloader::updateMatchingArticles()
return; return;
const QHash<QString, RssFeedPtr> all_feeds = manager->getAllFeedsAsHash(); const QHash<QString, RssFeedPtr> 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()); RssDownloadRulePtr rule = m_ruleList->getRule(rule_item->text());
if(!rule) continue; if (!rule) continue;
foreach(const QString &feed_url, rule->rssFeeds()) { foreach (const QString &feed_url, rule->rssFeeds()) {
qDebug() << Q_FUNC_INFO << feed_url; 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); RssFeedPtr feed = all_feeds.value(feed_url);
Q_ASSERT(feed); Q_ASSERT(feed);
if(!feed) continue; if (!feed) continue;
const QStringList matching_articles = rule->findMatchingArticles(feed); const QStringList matching_articles = rule->findMatchingArticles(feed);
if(!matching_articles.isEmpty()) if (!matching_articles.isEmpty())
addFeedArticlesToTree(feed, matching_articles); addFeedArticlesToTree(feed, matching_articles);
} }
} }
@ -489,15 +489,15 @@ void AutomatedRssDownloader::addFeedArticlesToTree(const RssFeedPtr& feed, const
{ {
// Check if this feed is already in the tree // Check if this feed is already in the tree
QTreeWidgetItem *treeFeedItem = 0; QTreeWidgetItem *treeFeedItem = 0;
for(int i=0; i<ui->treeMatchingArticles->topLevelItemCount(); ++i) { for (int i=0; i<ui->treeMatchingArticles->topLevelItemCount(); ++i) {
QTreeWidgetItem *item = ui->treeMatchingArticles->topLevelItem(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; treeFeedItem = item;
break; break;
} }
} }
// If there is none, create it // If there is none, create it
if(!treeFeedItem) { if (!treeFeedItem) {
treeFeedItem = new QTreeWidgetItem(QStringList() << feed->displayName()); treeFeedItem = new QTreeWidgetItem(QStringList() << feed->displayName());
treeFeedItem->setToolTip(0, feed->displayName()); treeFeedItem->setToolTip(0, feed->displayName());
QFont f = treeFeedItem->font(0); QFont f = treeFeedItem->font(0);
@ -508,7 +508,7 @@ void AutomatedRssDownloader::addFeedArticlesToTree(const RssFeedPtr& feed, const
ui->treeMatchingArticles->addTopLevelItem(treeFeedItem); ui->treeMatchingArticles->addTopLevelItem(treeFeedItem);
} }
// Insert the articles // Insert the articles
foreach(const QString &art, articles) { foreach (const QString &art, articles) {
QTreeWidgetItem *item = new QTreeWidgetItem(QStringList() << art); QTreeWidgetItem *item = new QTreeWidgetItem(QStringList() << art);
item->setToolTip(0, art); item->setToolTip(0, art);
treeFeedItem->addChild(item); treeFeedItem->addChild(item);
@ -519,7 +519,7 @@ void AutomatedRssDownloader::addFeedArticlesToTree(const RssFeedPtr& feed, const
void AutomatedRssDownloader::updateFieldsToolTips(bool regex) void AutomatedRssDownloader::updateFieldsToolTips(bool regex)
{ {
QString tip; QString tip;
if(regex) { if (regex) {
tip = tr("Regex mode: use Perl-like regular expressions"); tip = tr("Regex mode: use Perl-like regular expressions");
ui->lineContains->setToolTip(tip); ui->lineContains->setToolTip(tip);
ui->lineNotContains->setToolTip(tip); ui->lineNotContains->setToolTip(tip);
@ -536,18 +536,18 @@ void AutomatedRssDownloader::updateMustLineValidity()
const QString text = ui->lineContains->text(); const QString text = ui->lineContains->text();
bool valid = true; bool valid = true;
QStringList tokens; QStringList tokens;
if(ui->checkRegex->isChecked()) if (ui->checkRegex->isChecked())
tokens << text; tokens << text;
else else
tokens << text.split(" "); 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); QRegExp reg(token, Qt::CaseInsensitive, ui->checkRegex->isChecked() ? QRegExp::RegExp : QRegExp::Wildcard);
if(!reg.isValid()) { if (!reg.isValid()) {
valid = false; valid = false;
break; break;
} }
} }
if(valid) { if (valid) {
ui->lineContains->setStyleSheet(""); ui->lineContains->setStyleSheet("");
ui->lbl_must_stat->setPixmap(QPixmap()); ui->lbl_must_stat->setPixmap(QPixmap());
} else { } else {
@ -561,18 +561,18 @@ void AutomatedRssDownloader::updateMustNotLineValidity()
const QString text = ui->lineNotContains->text(); const QString text = ui->lineNotContains->text();
bool valid = true; bool valid = true;
QStringList tokens; QStringList tokens;
if(ui->checkRegex->isChecked()) if (ui->checkRegex->isChecked())
tokens << text; tokens << text;
else else
tokens << text.split(QRegExp("[\\s|]")); 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); QRegExp reg(token, Qt::CaseInsensitive, ui->checkRegex->isChecked() ? QRegExp::RegExp : QRegExp::Wildcard);
if(!reg.isValid()) { if (!reg.isValid()) {
valid = false; valid = false;
break; break;
} }
} }
if(valid) { if (valid) {
ui->lineNotContains->setStyleSheet(""); ui->lineNotContains->setStyleSheet("");
ui->lbl_mustnot_stat->setPixmap(QPixmap()); ui->lbl_mustnot_stat->setPixmap(QPixmap());
} else { } else {

View file

@ -46,9 +46,9 @@ CookiesDlg::CookiesDlg(QWidget *parent, const QList<QByteArray> &raw_cookies) :
ui->del_btn->setIcon(IconProvider::instance()->getIcon("list-remove")); 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")); 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<QByteArray> cookie_parts = raw_cookie.split('='); QList<QByteArray> cookie_parts = raw_cookie.split('=');
if(cookie_parts.size() != 2) continue; if (cookie_parts.size() != 2) continue;
const int i = ui->cookiesTable->rowCount(); const int i = ui->cookiesTable->rowCount();
ui->cookiesTable->setRowCount(i+1); ui->cookiesTable->setRowCount(i+1);
ui->cookiesTable->setItem(i, COOKIE_KEY, new QTableWidgetItem(cookie_parts.first().data())); 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() { void CookiesDlg::on_del_btn_clicked() {
// Get selected cookie // Get selected cookie
QList<QTableWidgetItem*> selection = ui->cookiesTable->selectedItems(); QList<QTableWidgetItem*> selection = ui->cookiesTable->selectedItems();
if(!selection.isEmpty()) { if (!selection.isEmpty()) {
ui->cookiesTable->removeRow(selection.first()->row()); ui->cookiesTable->removeRow(selection.first()->row());
} }
} }
QList<QByteArray> CookiesDlg::getCookies() const { QList<QByteArray> CookiesDlg::getCookies() const {
QList<QByteArray> ret; QList<QByteArray> ret;
for(int i=0; i<ui->cookiesTable->rowCount(); ++i) { for (int i=0; i<ui->cookiesTable->rowCount(); ++i) {
QString key; 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(); key = ui->cookiesTable->item(i, COOKIE_KEY)->text().trimmed();
QString value; 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(); 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; const QString raw_cookie = key+"="+value;
qDebug("Cookie: %s", qPrintable(raw_cookie)); qDebug("Cookie: %s", qPrintable(raw_cookie));
ret << raw_cookie.toLocal8Bit(); ret << raw_cookie.toLocal8Bit();
@ -95,7 +95,7 @@ QList<QByteArray> CookiesDlg::getCookies() const {
QList<QByteArray> CookiesDlg::askForCookies(QWidget *parent, const QList<QByteArray> &raw_cookies, bool *ok) { QList<QByteArray> CookiesDlg::askForCookies(QWidget *parent, const QList<QByteArray> &raw_cookies, bool *ok) {
CookiesDlg dlg(parent, raw_cookies); CookiesDlg dlg(parent, raw_cookies);
if(dlg.exec()) { if (dlg.exec()) {
*ok = true; *ok = true;
return dlg.getCookies(); return dlg.getCookies();
} }

View file

@ -64,7 +64,7 @@ void FeedListWidget::itemAboutToBeRemoved(QTreeWidgetItem *item) {
m_feedsItems.remove(feed->id()); m_feedsItems.remove(feed->id());
} if (RssFolderPtr folder = qSharedPointerDynamicCast<RssFolder>(file)) { } if (RssFolderPtr folder = qSharedPointerDynamicCast<RssFolder>(file)) {
RssFeedList feeds = folder->getAllFeeds(); RssFeedList feeds = folder->getAllFeeds();
foreach(const RssFeedPtr& feed, feeds) { foreach (const RssFeedPtr& feed, feeds) {
m_feedsItems.remove(feed->id()); m_feedsItems.remove(feed->id());
} }
} }
@ -84,8 +84,8 @@ QTreeWidgetItem* FeedListWidget::stickyUnreadItem() const {
QStringList FeedListWidget::getItemPath(QTreeWidgetItem* item) const { QStringList FeedListWidget::getItemPath(QTreeWidgetItem* item) const {
QStringList path; QStringList path;
if(item) { if (item) {
if(item->parent()) if (item->parent())
path << getItemPath(item->parent()); path << getItemPath(item->parent());
path.append(getRSSItem(item)->id()); path.append(getRSSItem(item)->id());
} }
@ -95,19 +95,19 @@ QStringList FeedListWidget::getItemPath(QTreeWidgetItem* item) const {
QList<QTreeWidgetItem*> FeedListWidget::getAllOpenFolders(QTreeWidgetItem *parent) const { QList<QTreeWidgetItem*> FeedListWidget::getAllOpenFolders(QTreeWidgetItem *parent) const {
QList<QTreeWidgetItem*> open_folders; QList<QTreeWidgetItem*> open_folders;
int nbChildren; int nbChildren;
if(parent) if (parent)
nbChildren = parent->childCount(); nbChildren = parent->childCount();
else else
nbChildren = topLevelItemCount(); nbChildren = topLevelItemCount();
for(int i=0; i<nbChildren; ++i) { for (int i=0; i<nbChildren; ++i) {
QTreeWidgetItem *item; QTreeWidgetItem *item;
if(parent) if (parent)
item = parent->child(i); item = parent->child(i);
else else
item = topLevelItem(i); item = topLevelItem(i);
if(isFolder(item) && item->isExpanded()) { if (isFolder(item) && item->isExpanded()) {
QList<QTreeWidgetItem*> open_subfolders = getAllOpenFolders(item); QList<QTreeWidgetItem*> open_subfolders = getAllOpenFolders(item);
if(!open_subfolders.empty()) { if (!open_subfolders.empty()) {
open_folders << open_subfolders; open_folders << open_subfolders;
} else { } else {
open_folders << item; open_folders << item;
@ -120,9 +120,9 @@ QList<QTreeWidgetItem*> FeedListWidget::getAllOpenFolders(QTreeWidgetItem *paren
QList<QTreeWidgetItem*> FeedListWidget::getAllFeedItems(QTreeWidgetItem* folder) { QList<QTreeWidgetItem*> FeedListWidget::getAllFeedItems(QTreeWidgetItem* folder) {
QList<QTreeWidgetItem*> feeds; QList<QTreeWidgetItem*> feeds;
const int nbChildren = folder->childCount(); const int nbChildren = folder->childCount();
for(int i=0; i<nbChildren; ++i) { for (int i=0; i<nbChildren; ++i) {
QTreeWidgetItem *item = folder->child(i); QTreeWidgetItem *item = folder->child(i);
if(isFeed(item)) { if (isFeed(item)) {
feeds << item; feeds << item;
} else { } else {
feeds << getAllFeedItems(item); feeds << getAllFeedItems(item);
@ -166,21 +166,21 @@ QTreeWidgetItem* FeedListWidget::currentFeed() const {
} }
void FeedListWidget::updateCurrentFeed(QTreeWidgetItem* new_item) { void FeedListWidget::updateCurrentFeed(QTreeWidgetItem* new_item) {
if(!new_item) return; if (!new_item) return;
if(!m_rssMapping.contains(new_item)) return; if (!m_rssMapping.contains(new_item)) return;
if(isFeed(new_item) || new_item == m_unreadStickyItem) if (isFeed(new_item) || new_item == m_unreadStickyItem)
m_currentFeed = new_item; m_currentFeed = new_item;
} }
void FeedListWidget::dragMoveEvent(QDragMoveEvent * event) { void FeedListWidget::dragMoveEvent(QDragMoveEvent * event) {
QTreeWidgetItem *item = itemAt(event->pos()); QTreeWidgetItem *item = itemAt(event->pos());
if(item == m_unreadStickyItem) { if (item == m_unreadStickyItem) {
event->ignore(); event->ignore();
} else { } else {
if(item && isFolder(item)) if (item && isFolder(item))
event->ignore(); event->ignore();
else { else {
if(selectedItems().contains(m_unreadStickyItem)) { if (selectedItems().contains(m_unreadStickyItem)) {
event->ignore(); event->ignore();
} else { } else {
QTreeWidget::dragMoveEvent(event); QTreeWidget::dragMoveEvent(event);
@ -194,7 +194,7 @@ void FeedListWidget::dropEvent(QDropEvent *event) {
QList<QTreeWidgetItem*> folders_altered; QList<QTreeWidgetItem*> folders_altered;
QTreeWidgetItem *dest_folder_item = itemAt(event->pos()); QTreeWidgetItem *dest_folder_item = itemAt(event->pos());
RssFolderPtr dest_folder; RssFolderPtr dest_folder;
if(dest_folder_item) { if (dest_folder_item) {
dest_folder = qSharedPointerCast<RssFolder>(getRSSItem(dest_folder_item)); dest_folder = qSharedPointerCast<RssFolder>(getRSSItem(dest_folder_item));
folders_altered << dest_folder_item; folders_altered << dest_folder_item;
} else { } else {
@ -202,26 +202,26 @@ void FeedListWidget::dropEvent(QDropEvent *event) {
} }
QList<QTreeWidgetItem *> src_items = selectedItems(); QList<QTreeWidgetItem *> src_items = selectedItems();
// Check if there is not going to overwrite another file // 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); RssFilePtr file = getRSSItem(src_item);
if(dest_folder->hasChild(file->id())) { if (dest_folder->hasChild(file->id())) {
emit overwriteAttempt(file->id()); emit overwriteAttempt(file->id());
return; return;
} }
} }
// Proceed with the move // Proceed with the move
foreach(QTreeWidgetItem *src_item, src_items) { foreach (QTreeWidgetItem *src_item, src_items) {
QTreeWidgetItem *parent_folder = src_item->parent(); 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; folders_altered << parent_folder;
// Actually move the file // Actually move the file
RssFilePtr file = getRSSItem(src_item); RssFilePtr file = getRSSItem(src_item);
m_rssManager->moveFile(file, dest_folder); m_rssManager->moveFile(file, dest_folder);
} }
QTreeWidget::dropEvent(event); QTreeWidget::dropEvent(event);
if(dest_folder_item) if (dest_folder_item)
dest_folder_item->setExpanded(true); dest_folder_item->setExpanded(true);
// Emit signal for update // Emit signal for update
if(!folders_altered.empty()) if (!folders_altered.empty())
emit foldersAltered(folders_altered); emit foldersAltered(folders_altered);
} }

View file

@ -63,22 +63,22 @@ enum ArticleRoles {
// display a right-click menu // display a right-click menu
void RSSImp::displayRSSListMenu(const QPoint& pos){ 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 // No item under the mouse, clear selection
m_feedList->clearSelection(); m_feedList->clearSelection();
} }
QMenu myRSSListMenu(this); QMenu myRSSListMenu(this);
QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems(); QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems();
if(selectedItems.size() > 0) { if (selectedItems.size() > 0) {
myRSSListMenu.addAction(actionUpdate); myRSSListMenu.addAction(actionUpdate);
myRSSListMenu.addAction(actionMark_items_read); myRSSListMenu.addAction(actionMark_items_read);
myRSSListMenu.addSeparator(); myRSSListMenu.addSeparator();
if(selectedItems.size() == 1) { if (selectedItems.size() == 1) {
if(m_feedList->getRSSItem(selectedItems.first()) != m_rssManager) { if (m_feedList->getRSSItem(selectedItems.first()) != m_rssManager) {
myRSSListMenu.addAction(actionRename); myRSSListMenu.addAction(actionRename);
myRSSListMenu.addAction(actionDelete); myRSSListMenu.addAction(actionDelete);
myRSSListMenu.addSeparator(); myRSSListMenu.addSeparator();
if(m_feedList->isFolder(selectedItems.first())) { if (m_feedList->isFolder(selectedItems.first())) {
myRSSListMenu.addAction(actionNew_folder); myRSSListMenu.addAction(actionNew_folder);
} else { } else {
myRSSListMenu.addAction(actionManage_cookies); myRSSListMenu.addAction(actionManage_cookies);
@ -86,7 +86,7 @@ void RSSImp::displayRSSListMenu(const QPoint& pos){
} }
} }
myRSSListMenu.addAction(actionNew_subscription); myRSSListMenu.addAction(actionNew_subscription);
if(m_feedList->isFeed(selectedItems.first())) { if (m_feedList->isFeed(selectedItems.first())) {
myRSSListMenu.addSeparator(); myRSSListMenu.addSeparator();
myRSSListMenu.addAction(actionCopy_feed_URL); myRSSListMenu.addAction(actionCopy_feed_URL);
} }
@ -102,18 +102,18 @@ void RSSImp::displayRSSListMenu(const QPoint& pos){
void RSSImp::displayItemsListMenu(const QPoint&){ void RSSImp::displayItemsListMenu(const QPoint&){
QMenu myItemListMenu(this); QMenu myItemListMenu(this);
QList<QListWidgetItem*> selectedItems = listArticles->selectedItems(); QList<QListWidgetItem*> selectedItems = listArticles->selectedItems();
if(selectedItems.size() > 0) { if (selectedItems.size() > 0) {
bool has_attachment = false; 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(3) URL: %s", qPrintable(item->data(Article::FeedUrlRole).toString()));
qDebug("text(2) TITLE: %s", qPrintable(item->data(Article::TitleRole).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()) { ->getItem(item->data(Article::IdRole).toString())->hasAttachment()) {
has_attachment = true; has_attachment = true;
break; break;
} }
} }
if(has_attachment) if (has_attachment)
myItemListMenu.addAction(actionDownload_torrent); myItemListMenu.addAction(actionDownload_torrent);
myItemListMenu.addAction(actionOpen_news_URL); myItemListMenu.addAction(actionOpen_news_URL);
} }
@ -130,7 +130,7 @@ void RSSImp::on_actionManage_cookies_triggered() {
bool ok = false; bool ok = false;
RssSettings settings; RssSettings settings;
QList<QByteArray> raw_cookies = CookiesDlg::askForCookies(this, settings.getHostNameCookies(feed_hostname), &ok); QList<QByteArray> raw_cookies = CookiesDlg::askForCookies(this, settings.getHostNameCookies(feed_hostname), &ok);
if(ok) { if (ok) {
settings.setHostNameCookies(feed_hostname, raw_cookies); settings.setHostNameCookies(feed_hostname, raw_cookies);
} }
} }
@ -138,7 +138,7 @@ void RSSImp::on_actionManage_cookies_triggered() {
void RSSImp::askNewFolder() { void RSSImp::askNewFolder() {
QTreeWidgetItem *parent_item = 0; QTreeWidgetItem *parent_item = 0;
RssFolderPtr rss_parent; RssFolderPtr rss_parent;
if(m_feedList->selectedItems().size() > 0) { if (m_feedList->selectedItems().size() > 0) {
parent_item = m_feedList->selectedItems().at(0); parent_item = m_feedList->selectedItems().at(0);
rss_parent = qSharedPointerDynamicCast<RssFolder>(m_feedList->getRSSItem(parent_item)); rss_parent = qSharedPointerDynamicCast<RssFolder>(m_feedList->getRSSItem(parent_item));
Q_ASSERT(rss_parent); Q_ASSERT(rss_parent);
@ -147,10 +147,10 @@ void RSSImp::askNewFolder() {
} }
bool ok; bool ok;
QString new_name = QInputDialog::getText(this, tr("Please choose a folder name"), tr("Folder name:"), QLineEdit::Normal, tr("New folder"), &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); RssFolderPtr new_folder = rss_parent->addFolder(new_name);
QTreeWidgetItem* folder_item; QTreeWidgetItem* folder_item;
if(parent_item) if (parent_item)
folder_item = new QTreeWidgetItem(parent_item); folder_item = new QTreeWidgetItem(parent_item);
else else
folder_item = new QTreeWidgetItem(m_feedList); 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->setText(0, new_folder->displayName() + QString::fromUtf8(" (0)"));
folder_item->setData(0,Qt::DecorationRole, QVariant(IconProvider::instance()->getIcon("inode-directory"))); folder_item->setData(0,Qt::DecorationRole, QVariant(IconProvider::instance()->getIcon("inode-directory")));
// Expand parent folder to display new folder // Expand parent folder to display new folder
if(parent_item) if (parent_item)
parent_item->setExpanded(true); parent_item->setExpanded(true);
m_rssManager->saveStreamList(); m_rssManager->saveStreamList();
} }
@ -177,18 +177,18 @@ void RSSImp::on_newFeedButton_clicked() {
// Determine parent folder for new feed // Determine parent folder for new feed
QTreeWidgetItem *parent_item = 0; QTreeWidgetItem *parent_item = 0;
QList<QTreeWidgetItem *> selected_items = m_feedList->selectedItems(); QList<QTreeWidgetItem *> selected_items = m_feedList->selectedItems();
if(!selected_items.empty()) { if (!selected_items.empty()) {
parent_item = selected_items.first(); parent_item = selected_items.first();
// Consider the case where the user clicked on Unread item // 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; parent_item = 0;
} else { } else {
if(m_feedList->isFolder(parent_item)) if (m_feedList->isFolder(parent_item))
parent_item = parent_item->parent(); parent_item = parent_item->parent();
} }
} }
RssFolderPtr rss_parent; RssFolderPtr rss_parent;
if(parent_item) { if (parent_item) {
rss_parent = qSharedPointerCast<RssFolder>(m_feedList->getRSSItem(parent_item)); rss_parent = qSharedPointerCast<RssFolder>(m_feedList->getRSSItem(parent_item));
} else { } else {
rss_parent = m_rssManager; rss_parent = m_rssManager;
@ -197,14 +197,14 @@ void RSSImp::on_newFeedButton_clicked() {
bool ok; bool ok;
QString clip_txt = qApp->clipboard()->text(); QString clip_txt = qApp->clipboard()->text();
QString default_url = "http://"; 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; default_url = clip_txt;
} }
QString newUrl = QInputDialog::getText(this, tr("Please type a rss stream url"), tr("Stream URL:"), QLineEdit::Normal, default_url, &ok); 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(); newUrl = newUrl.trimmed();
if(!newUrl.isEmpty()){ if (!newUrl.isEmpty()){
if(m_feedList->hasFeed(newUrl)) { if (m_feedList->hasFeed(newUrl)) {
QMessageBox::warning(this, tr("qBittorrent"), QMessageBox::warning(this, tr("qBittorrent"),
tr("This rss feed is already in the list."), tr("This rss feed is already in the list."),
QMessageBox::Ok); QMessageBox::Ok);
@ -213,7 +213,7 @@ void RSSImp::on_newFeedButton_clicked() {
RssFeedPtr stream = rss_parent->addStream(m_rssManager.data(), newUrl); RssFeedPtr stream = rss_parent->addStream(m_rssManager.data(), newUrl);
// Create TreeWidget item // Create TreeWidget item
QTreeWidgetItem* item; QTreeWidgetItem* item;
if(parent_item) if (parent_item)
item = new QTreeWidgetItem(parent_item); item = new QTreeWidgetItem(parent_item);
else else
item = new QTreeWidgetItem(m_feedList); item = new QTreeWidgetItem(m_feedList);
@ -231,9 +231,9 @@ void RSSImp::on_newFeedButton_clicked() {
// delete a stream by a button // delete a stream by a button
void RSSImp::deleteSelectedItems() { void RSSImp::deleteSelectedItems() {
QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems(); QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems();
if(selectedItems.size() == 0) return; if (selectedItems.size() == 0) return;
int ret; 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?"), 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"), tr("&Yes"), tr("&No"),
QString(), 0, 1); 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?"), 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"), tr("&Yes"), tr("&No"),
QString(), 0, 1); QString(), 0, 1);
if(!ret) { if (!ret) {
foreach(QTreeWidgetItem *item, selectedItems){ foreach (QTreeWidgetItem *item, selectedItems){
if(m_feedList->currentFeed() == item){ if (m_feedList->currentFeed() == item){
textBrowser->clear(); textBrowser->clear();
m_currentArticle = 0; m_currentArticle = 0;
listArticles->clear(); listArticles->clear();
@ -272,22 +272,22 @@ void RSSImp::loadFoldersOpenState() {
settings.beginGroup("Rss"); settings.beginGroup("Rss");
QStringList open_folders = settings.value("open_folders", QStringList()).toStringList(); QStringList open_folders = settings.value("open_folders", QStringList()).toStringList();
settings.endGroup(); settings.endGroup();
foreach(QString var_path, open_folders) { foreach (QString var_path, open_folders) {
QStringList path = var_path.split("\\"); QStringList path = var_path.split("\\");
QTreeWidgetItem *parent = 0; QTreeWidgetItem *parent = 0;
foreach(QString name, path) { foreach (QString name, path) {
int nbChildren = 0; int nbChildren = 0;
if(parent) if (parent)
nbChildren = parent->childCount(); nbChildren = parent->childCount();
else else
nbChildren = m_feedList->topLevelItemCount(); nbChildren = m_feedList->topLevelItemCount();
for(int i=0; i<nbChildren; ++i) { for (int i=0; i<nbChildren; ++i) {
QTreeWidgetItem* child; QTreeWidgetItem* child;
if(parent) if (parent)
child = parent->child(i); child = parent->child(i);
else else
child = m_feedList->topLevelItem(i); child = m_feedList->topLevelItem(i);
if(m_feedList->getRSSItem(child)->id() == name) { if (m_feedList->getRSSItem(child)->id() == name) {
parent = child; parent = child;
parent->setExpanded(true); parent->setExpanded(true);
qDebug("expanding folder %s", qPrintable(name)); qDebug("expanding folder %s", qPrintable(name));
@ -301,7 +301,7 @@ void RSSImp::loadFoldersOpenState() {
void RSSImp::saveFoldersOpenState() { void RSSImp::saveFoldersOpenState() {
QStringList open_folders; QStringList open_folders;
QList<QTreeWidgetItem*> items = m_feedList->getAllOpenFolders(); QList<QTreeWidgetItem*> items = m_feedList->getAllOpenFolders();
foreach(QTreeWidgetItem* item, items) { foreach (QTreeWidgetItem* item, items) {
QString path = m_feedList->getItemPath(item).join("\\"); QString path = m_feedList->getItemPath(item).join("\\");
qDebug("saving open folder: %s", qPrintable(path)); qDebug("saving open folder: %s", qPrintable(path));
open_folders << path; open_folders << path;
@ -314,7 +314,7 @@ void RSSImp::saveFoldersOpenState() {
// refresh all streams by a button // refresh all streams by a button
void RSSImp::on_updateAllButton_clicked() { 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"))); item->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png")));
} }
m_rssManager->refresh(); m_rssManager->refresh();
@ -322,10 +322,10 @@ void RSSImp::on_updateAllButton_clicked() {
void RSSImp::downloadTorrent() { void RSSImp::downloadTorrent() {
QList<QListWidgetItem *> selected_items = listArticles->selectedItems(); QList<QListWidgetItem *> 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()) RssArticlePtr article = m_feedList->getRSSItemFromUrl(item->data(Article::FeedUrlRole).toString())
->getItem(item->data(Article::IdRole).toString()); ->getItem(item->data(Article::IdRole).toString());
if(article->hasAttachment()) { if (article->hasAttachment()) {
QBtSession::instance()->downloadFromUrl(article->torrentUrl()); QBtSession::instance()->downloadFromUrl(article->torrentUrl());
} else { } else {
QBtSession::instance()->downloadFromUrl(article->link()); QBtSession::instance()->downloadFromUrl(article->link());
@ -336,11 +336,11 @@ void RSSImp::downloadTorrent() {
// open the url of the news in a browser // open the url of the news in a browser
void RSSImp::openNewsUrl() { void RSSImp::openNewsUrl() {
QList<QListWidgetItem *> selected_items = listArticles->selectedItems(); QList<QListWidgetItem *> 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()) RssArticlePtr news = m_feedList->getRSSItemFromUrl(item->data(Article::FeedUrlRole).toString())
->getItem(item->data(Article::IdRole).toString()); ->getItem(item->data(Article::IdRole).toString());
const QString link = news->link(); const QString link = news->link();
if(!link.isEmpty()) if (!link.isEmpty())
QDesktopServices::openUrl(QUrl(link)); QDesktopServices::openUrl(QUrl(link));
} }
} }
@ -356,8 +356,8 @@ void RSSImp::renameFiles() {
do { 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); 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 // Check if name is already taken
if(ok) { if (ok) {
if(rss_item->parent()->hasChild(newName)) { 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.")); QMessageBox::warning(0, tr("Name already in use"), tr("This name is already used by another item, please choose another one."));
ok = false; ok = false;
} }
@ -374,11 +374,11 @@ void RSSImp::renameFiles() {
//right-click on stream : refresh it //right-click on stream : refresh it
void RSSImp::refreshSelectedItems() { void RSSImp::refreshSelectedItems() {
QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems(); QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems();
foreach(QTreeWidgetItem* item, selectedItems){ foreach (QTreeWidgetItem* item, selectedItems){
RssFilePtr file = m_feedList->getRSSItem(item); RssFilePtr file = m_feedList->getRSSItem(item);
// Update icons // Update icons
if(item == m_feedList->stickyUnreadItem()) { if (item == m_feedList->stickyUnreadItem()) {
foreach(QTreeWidgetItem *feed, m_feedList->getAllFeedItems()) { foreach (QTreeWidgetItem *feed, m_feedList->getAllFeedItems()) {
feed->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png"))); feed->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png")));
} }
file->refresh(); file->refresh();
@ -388,7 +388,7 @@ void RSSImp::refreshSelectedItems() {
item->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png"))); item->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png")));
} else if (qSharedPointerDynamicCast<RssFolder>(file)) { } else if (qSharedPointerDynamicCast<RssFolder>(file)) {
// Update feeds in the folder // 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"))); feed->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png")));
} }
} }
@ -402,8 +402,8 @@ void RSSImp::copySelectedFeedsURL() {
QStringList URLs; QStringList URLs;
QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems(); QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems();
QTreeWidgetItem* item; QTreeWidgetItem* item;
foreach(item, selectedItems){ foreach (item, selectedItems){
if(m_feedList->isFeed(item)) if (m_feedList->isFeed(item))
URLs << m_feedList->getItemID(item); URLs << m_feedList->getItemID(item);
} }
qApp->clipboard()->setText(URLs.join("\n")); qApp->clipboard()->setText(URLs.join("\n"));
@ -412,25 +412,25 @@ void RSSImp::copySelectedFeedsURL() {
void RSSImp::on_markReadButton_clicked() { void RSSImp::on_markReadButton_clicked() {
QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems(); QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems();
QTreeWidgetItem* item; QTreeWidgetItem* item;
foreach(item, selectedItems){ foreach (item, selectedItems){
RssFilePtr rss_item = m_feedList->getRSSItem(item); RssFilePtr rss_item = m_feedList->getRSSItem(item);
rss_item->markAsRead(); rss_item->markAsRead();
updateItemInfos(item); updateItemInfos(item);
} }
if(selectedItems.size()) if (selectedItems.size())
refreshArticleList(m_feedList->currentItem()); refreshArticleList(m_feedList->currentItem());
} }
void RSSImp::fillFeedsList(QTreeWidgetItem *parent, const RssFolderPtr& rss_parent) { void RSSImp::fillFeedsList(QTreeWidgetItem *parent, const RssFolderPtr& rss_parent) {
QList<RssFilePtr> children; QList<RssFilePtr> children;
if(parent) { if (parent) {
children = rss_parent->getContent(); children = rss_parent->getContent();
} else { } else {
children = m_rssManager->getContent(); children = m_rssManager->getContent();
} }
foreach (const RssFilePtr& rss_child, children){ foreach (const RssFilePtr& rss_child, children){
QTreeWidgetItem* item; QTreeWidgetItem* item;
if(!parent) if (!parent)
item = new QTreeWidgetItem(m_feedList); item = new QTreeWidgetItem(m_feedList);
else else
item = new QTreeWidgetItem(parent); item = new QTreeWidgetItem(parent);
@ -438,7 +438,7 @@ void RSSImp::fillFeedsList(QTreeWidgetItem *parent, const RssFolderPtr& rss_pare
// Notify TreeWidget of item addition // Notify TreeWidget of item addition
m_feedList->itemAdded(item, rss_child); m_feedList->itemAdded(item, rss_child);
// Set Icon // Set Icon
if(qSharedPointerDynamicCast<RssFeed>(rss_child)) { if (qSharedPointerDynamicCast<RssFeed>(rss_child)) {
item->setData(0,Qt::DecorationRole, QVariant(QIcon(QString::fromUtf8(":/Icons/loading.png")))); item->setData(0,Qt::DecorationRole, QVariant(QIcon(QString::fromUtf8(":/Icons/loading.png"))));
} else if (RssFolderPtr folder = qSharedPointerDynamicCast<RssFolder>(rss_child)) { } else if (RssFolderPtr folder = qSharedPointerDynamicCast<RssFolder>(rss_child)) {
item->setData(0,Qt::DecorationRole, QVariant(IconProvider::instance()->getIcon("inode-directory"))); 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 // fills the newsList
void RSSImp::refreshArticleList(QTreeWidgetItem* item) { void RSSImp::refreshArticleList(QTreeWidgetItem* item) {
if(!item) { if (!item) {
listArticles->clear(); listArticles->clear();
return; return;
} }
RssFilePtr rss_item = m_feedList->getRSSItem(item); RssFilePtr rss_item = m_feedList->getRSSItem(item);
if(!rss_item) return; if (!rss_item) return;
qDebug("Getting the list of news"); qDebug("Getting the list of news");
RssArticleList news; RssArticleList news;
if(rss_item == m_rssManager) if (rss_item == m_rssManager)
news = rss_item->unreadArticleList(); news = rss_item->unreadArticleList();
else if(rss_item) else if (rss_item)
news = rss_item->articleList(); news = rss_item->articleList();
// Sort // Sort
RssManager::sortNewsList(news); RssManager::sortNewsList(news);
@ -471,12 +471,12 @@ void RSSImp::refreshArticleList(QTreeWidgetItem* item) {
m_currentArticle = 0; m_currentArticle = 0;
listArticles->clear(); listArticles->clear();
qDebug("Got the list of news"); qDebug("Got the list of news");
foreach(const RssArticlePtr &article, news){ foreach (const RssArticlePtr &article, news){
QListWidgetItem* it = new QListWidgetItem(listArticles); QListWidgetItem* it = new QListWidgetItem(listArticles);
it->setData(Article::TitleRole, article->title()); it->setData(Article::TitleRole, article->title());
it->setData(Article::FeedUrlRole, article->parent()->url()); it->setData(Article::FeedUrlRole, article->parent()->url());
it->setData(Article::IdRole, article->guid()); it->setData(Article::IdRole, article->guid());
if(article->isRead()){ if (article->isRead()){
it->setData(Article::ColorRole, QVariant(QColor("grey"))); it->setData(Article::ColorRole, QVariant(QColor("grey")));
it->setData(Article::IconRole, QVariant(QIcon(":/Icons/sphere.png"))); it->setData(Article::IconRole, QVariant(QIcon(":/Icons/sphere.png")));
}else{ }else{
@ -491,14 +491,14 @@ void RSSImp::refreshArticleList(QTreeWidgetItem* item) {
// display a news // display a news
void RSSImp::refreshTextBrowser() { void RSSImp::refreshTextBrowser() {
QList<QListWidgetItem*> selection = listArticles->selectedItems(); QList<QListWidgetItem*> selection = listArticles->selectedItems();
if(selection.empty()) return; if (selection.empty()) return;
Q_ASSERT(selection.size() == 1); Q_ASSERT(selection.size() == 1);
QListWidgetItem *item = selection.first(); QListWidgetItem *item = selection.first();
Q_ASSERT(item); Q_ASSERT(item);
if(item == m_currentArticle) return; if (item == m_currentArticle) return;
// Stop displaying previous news if necessary // Stop displaying previous news if necessary
if(m_feedList->currentFeed() == m_feedList->stickyUnreadItem()) { if (m_feedList->currentFeed() == m_feedList->stickyUnreadItem()) {
if(m_currentArticle) { if (m_currentArticle) {
disconnect(listArticles, SIGNAL(itemSelectionChanged()), this, SLOT(refreshTextBrowser())); disconnect(listArticles, SIGNAL(itemSelectionChanged()), this, SLOT(refreshTextBrowser()));
listArticles->removeItemWidget(m_currentArticle); listArticles->removeItemWidget(m_currentArticle);
Q_ASSERT(m_currentArticle); Q_ASSERT(m_currentArticle);
@ -512,10 +512,10 @@ void RSSImp::refreshTextBrowser() {
QString html; QString html;
html += "<div style='border: 2px solid red; margin-left: 5px; margin-right: 5px; margin-bottom: 5px;'>"; html += "<div style='border: 2px solid red; margin-left: 5px; margin-right: 5px; margin-bottom: 5px;'>";
html += "<div style='background-color: #678db2; font-weight: bold; color: #fff;'>"+article->title() + "</div>"; html += "<div style='background-color: #678db2; font-weight: bold; color: #fff;'>"+article->title() + "</div>";
if(article->date().isValid()) { if (article->date().isValid()) {
html += "<div style='background-color: #efefef;'><b>"+tr("Date: ")+"</b>"+article->date().toLocalTime().toString(Qt::SystemLocaleLongDate)+"</div>"; html += "<div style='background-color: #efefef;'><b>"+tr("Date: ")+"</b>"+article->date().toLocalTime().toString(Qt::SystemLocaleLongDate)+"</div>";
} }
if(!article->author().isEmpty()) { if (!article->author().isEmpty()) {
html += "<div style='background-color: #efefef;'><b>"+tr("Author: ")+"</b>"+article->author()+"</div>"; html += "<div style='background-color: #efefef;'><b>"+tr("Author: ")+"</b>"+article->author()+"</div>";
} }
html += "</div>"; html += "</div>";
@ -540,17 +540,17 @@ void RSSImp::saveSlidersPosition() {
void RSSImp::restoreSlidersPosition() { void RSSImp::restoreSlidersPosition() {
QIniSettings settings("qBittorrent", "qBittorrent"); QIniSettings settings("qBittorrent", "qBittorrent");
QByteArray pos_h = settings.value("rss/splitter_h", QByteArray()).toByteArray(); QByteArray pos_h = settings.value("rss/splitter_h", QByteArray()).toByteArray();
if(!pos_h.isNull()) { if (!pos_h.isNull()) {
splitter_h->restoreState(pos_h); splitter_h->restoreState(pos_h);
} }
QByteArray pos_v = settings.value("rss/splitter_v", QByteArray()).toByteArray(); QByteArray pos_v = settings.value("rss/splitter_v", QByteArray()).toByteArray();
if(!pos_v.isNull()) { if (!pos_v.isNull()) {
splitter_v->restoreState(pos_v); splitter_v->restoreState(pos_v);
} }
} }
void RSSImp::updateItemsInfos(const QList<QTreeWidgetItem *> &items) { void RSSImp::updateItemsInfos(const QList<QTreeWidgetItem *> &items) {
foreach(QTreeWidgetItem* item, items) { foreach (QTreeWidgetItem* item, items) {
updateItemInfos(item); updateItemInfos(item);
} }
} }
@ -561,13 +561,13 @@ void RSSImp::updateItemInfos(QTreeWidgetItem *item) {
return; return;
QString name; QString name;
if(rss_item == m_rssManager) if (rss_item == m_rssManager)
name = tr("Unread"); name = tr("Unread");
else else
name = rss_item->displayName(); name = rss_item->displayName();
item->setText(0, name + QString::fromUtf8(" (") + QString::number(rss_item->unreadCount(), 10)+ QString(")")); item->setText(0, name + QString::fromUtf8(" (") + QString::number(rss_item->unreadCount(), 10)+ QString(")"));
// If item has a parent, update it too // If item has a parent, update it too
if(item->parent()) if (item->parent())
updateItemInfos(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); QTreeWidgetItem *item = m_feedList->getTreeItemFromUrl(url);
RssFeedPtr stream = qSharedPointerCast<RssFeed>(m_feedList->getRSSItem(item)); RssFeedPtr stream = qSharedPointerCast<RssFeed>(m_feedList->getRSSItem(item));
item->setText(0, display_name + QString::fromUtf8(" (") + QString::number(nbUnread, 10)+ QString(")")); 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()))); item->setData(0,Qt::DecorationRole, QVariant(QIcon(stream->icon())));
// Update parent // Update parent
if(item->parent()) if (item->parent())
updateItemInfos(item->parent()); updateItemInfos(item->parent());
// Update Unread item // Update Unread item
updateItemInfos(m_feedList->stickyUnreadItem()); updateItemInfos(m_feedList->stickyUnreadItem());
// If the feed is selected, update the displayed news // If the feed is selected, update the displayed news
if(m_feedList->currentItem() == item ){ if (m_feedList->currentItem() == item ){
refreshArticleList(item); refreshArticleList(item);
} else { } else {
// Update unread items // Update unread items
if(m_feedList->currentItem() == m_feedList->stickyUnreadItem()) { if (m_feedList->currentItem() == m_feedList->stickyUnreadItem()) {
refreshArticleList(m_feedList->stickyUnreadItem()); refreshArticleList(m_feedList->stickyUnreadItem());
} }
} }
@ -680,7 +680,7 @@ RSSImp::~RSSImp(){
void RSSImp::on_settingsButton_clicked() { void RSSImp::on_settingsButton_clicked() {
RssSettingsDlg dlg(this); RssSettingsDlg dlg(this);
if(dlg.exec()) if (dlg.exec())
updateRefreshInterval(RssSettings().getRSSRefreshInterval()); updateRefreshInterval(RssSettings().getRSSRefreshInterval());
} }
@ -688,6 +688,6 @@ void RSSImp::on_rssDownloaderBtn_clicked()
{ {
AutomatedRssDownloader dlg(m_rssManager, this); AutomatedRssDownloader dlg(m_rssManager, this);
dlg.exec(); dlg.exec();
if(dlg.isRssDownloaderEnabled()) if (dlg.isRssDownloaderEnabled())
on_updateAllButton_clicked(); on_updateAllButton_clicked();
} }

View file

@ -223,33 +223,33 @@ RssArticlePtr xmlToRssArticle(RssFeed* parent, QXmlStreamReader& xml)
while(!xml.atEnd()) { while(!xml.atEnd()) {
xml.readNext(); xml.readNext();
if(xml.isEndElement() && xml.name() == "item") if (xml.isEndElement() && xml.name() == "item")
break; break;
if(xml.isStartElement()) { if (xml.isStartElement()) {
if(xml.name() == "title") { if (xml.name() == "title") {
title = xml.readElementText(); title = xml.readElementText();
} }
else if(xml.name() == "enclosure") { else if (xml.name() == "enclosure") {
if(xml.attributes().value("type") == "application/x-bittorrent") { if (xml.attributes().value("type") == "application/x-bittorrent") {
torrentUrl = xml.attributes().value("url").toString(); torrentUrl = xml.attributes().value("url").toString();
} }
} }
else if(xml.name() == "link") { else if (xml.name() == "link") {
link = xml.readElementText(); link = xml.readElementText();
if(guid.isEmpty()) if (guid.isEmpty())
guid = link; guid = link;
} }
else if(xml.name() == "description") { else if (xml.name() == "description") {
description = xml.readElementText(); description = xml.readElementText();
} }
else if(xml.name() == "pubDate") { else if (xml.name() == "pubDate") {
date = RssArticle::parseDate(xml.readElementText()); date = RssArticle::parseDate(xml.readElementText());
} }
else if(xml.name() == "author") { else if (xml.name() == "author") {
author = xml.readElementText(); author = xml.readElementText();
} }
else if(xml.name() == "guid") { else if (xml.name() == "guid") {
guid = xml.readElementText(); guid = xml.readElementText();
} }
} }
@ -271,7 +271,7 @@ RssArticlePtr xmlToRssArticle(RssFeed* parent, QXmlStreamReader& xml)
RssArticlePtr hashToRssArticle(RssFeed* parent, const QVariantHash &h) { RssArticlePtr hashToRssArticle(RssFeed* parent, const QVariantHash &h) {
const QString guid = h.value("id").toString(); const QString guid = h.value("id").toString();
if(guid.isEmpty()) return RssArticlePtr(); if (guid.isEmpty()) return RssArticlePtr();
RssArticlePtr art(new RssArticle(parent, guid)); RssArticlePtr art(new RssArticle(parent, guid));
art->m_title = h.value("title", "").toString(); art->m_title = h.value("title", "").toString();
@ -302,7 +302,7 @@ QString RssArticle::link() const {
} }
QString RssArticle::description() const{ QString RssArticle::description() const{
if(m_description.isNull()) if (m_description.isNull())
return ""; return "";
return m_description; return m_description;
} }

View file

@ -43,26 +43,26 @@ RssDownloadRule::RssDownloadRule(): m_enabled(false), m_useRegex(false)
bool RssDownloadRule::matches(const QString &article_title) const bool RssDownloadRule::matches(const QString &article_title) const
{ {
foreach(const QString& token, m_mustContain) { foreach (const QString& token, m_mustContain) {
if(token.isEmpty() || token == "") if (token.isEmpty() || token == "")
continue; continue;
QRegExp reg(token, Qt::CaseInsensitive, m_useRegex ? QRegExp::RegExp : QRegExp::Wildcard); QRegExp reg(token, Qt::CaseInsensitive, m_useRegex ? QRegExp::RegExp : QRegExp::Wildcard);
//reg.setMinimal(false); //reg.setMinimal(false);
if(reg.indexIn(article_title) < 0) return false; if (reg.indexIn(article_title) < 0) return false;
} }
qDebug("Checking not matching tokens"); qDebug("Checking not matching tokens");
// Checking not matching // Checking not matching
foreach(const QString& token, m_mustNotContain) { foreach (const QString& token, m_mustNotContain) {
if(token.isEmpty()) continue; if (token.isEmpty()) continue;
QRegExp reg(token, Qt::CaseInsensitive, m_useRegex ? QRegExp::RegExp : QRegExp::Wildcard); 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; return true;
} }
void RssDownloadRule::setMustContain(const QString &tokens) void RssDownloadRule::setMustContain(const QString &tokens)
{ {
if(m_useRegex) if (m_useRegex)
m_mustContain = QStringList() << tokens; m_mustContain = QStringList() << tokens;
else else
m_mustContain = tokens.split(" "); m_mustContain = tokens.split(" ");
@ -70,7 +70,7 @@ void RssDownloadRule::setMustContain(const QString &tokens)
void RssDownloadRule::setMustNotContain(const QString &tokens) void RssDownloadRule::setMustNotContain(const QString &tokens)
{ {
if(m_useRegex) if (m_useRegex)
m_mustNotContain = QStringList() << tokens; m_mustNotContain = QStringList() << tokens;
else else
m_mustNotContain = tokens.split(QRegExp("[\\s|]")); m_mustNotContain = tokens.split(QRegExp("[\\s|]"));
@ -83,7 +83,7 @@ RssDownloadRulePtr RssDownloadRule::fromOldFormat(const QVariantHash &rule_hash,
rule->setName(rule_name); rule->setName(rule_name);
rule->setMustContain(rule_hash.value("matches", "").toString()); rule->setMustContain(rule_hash.value("matches", "").toString());
rule->setMustNotContain(rule_hash.value("not", "").toString()); rule->setMustNotContain(rule_hash.value("not", "").toString());
if(!feed_url.isEmpty()) if (!feed_url.isEmpty())
rule->setRssFeeds(QStringList() << feed_url); rule->setRssFeeds(QStringList() << feed_url);
rule->setSavePath(rule_hash.value("save_path", "").toString()); rule->setSavePath(rule_hash.value("save_path", "").toString());
// Is enabled? // Is enabled?
@ -128,7 +128,7 @@ bool RssDownloadRule::operator==(const RssDownloadRule &other) {
void RssDownloadRule::setSavePath(const QString &save_path) 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; m_savePath = save_path;
else else
m_savePath = QString(); m_savePath = QString();
@ -138,7 +138,7 @@ QStringList RssDownloadRule::findMatchingArticles(const RssFeedPtr& feed) const
{ {
QStringList ret; QStringList ret;
const RssArticleHash& feed_articles = feed->articleHash(); 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(); const QString title = artIt.value()->title();
if (matches(title)) if (matches(title))
ret << title; ret << title;

View file

@ -44,7 +44,7 @@ RssDownloadRuleList::RssDownloadRuleList(){
RssDownloadRuleList* RssDownloadRuleList::instance() RssDownloadRuleList* RssDownloadRuleList::instance()
{ {
if(!m_instance) if (!m_instance)
m_instance = new RssDownloadRuleList; m_instance = new RssDownloadRuleList;
return m_instance; return m_instance;
} }
@ -61,9 +61,9 @@ RssDownloadRulePtr RssDownloadRuleList::findMatchingRule(const QString &feed_url
{ {
Q_ASSERT(RssSettings().isRssDownloadingEnabled()); Q_ASSERT(RssSettings().isRssDownloadingEnabled());
QStringList rule_names = m_feedRules.value(feed_url); 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]; 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(); return RssDownloadRulePtr();
} }
@ -77,7 +77,7 @@ void RssDownloadRuleList::saveRulesToStorage()
void RssDownloadRuleList::loadRulesFromStorage() void RssDownloadRuleList::loadRulesFromStorage()
{ {
QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss"); QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss");
if(qBTRSS.contains("feed_filters")) { if (qBTRSS.contains("feed_filters")) {
importFeedsInOldFormat(qBTRSS.value("feed_filters").toHash()); importFeedsInOldFormat(qBTRSS.value("feed_filters").toHash());
// Remove outdated rules // Remove outdated rules
qBTRSS.remove("feed_filters"); qBTRSS.remove("feed_filters");
@ -91,16 +91,16 @@ void RssDownloadRuleList::loadRulesFromStorage()
void RssDownloadRuleList::importFeedsInOldFormat(const QHash<QString, QVariant> &rules) void RssDownloadRuleList::importFeedsInOldFormat(const QHash<QString, QVariant> &rules)
{ {
foreach(const QString &feed_url, rules.keys()) { foreach (const QString &feed_url, rules.keys()) {
importFeedRulesInOldFormat(feed_url, rules.value(feed_url).toHash()); importFeedRulesInOldFormat(feed_url, rules.value(feed_url).toHash());
} }
} }
void RssDownloadRuleList::importFeedRulesInOldFormat(const QString &feed_url, const QHash<QString, QVariant> &rules) void RssDownloadRuleList::importFeedRulesInOldFormat(const QString &feed_url, const QHash<QString, QVariant> &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); RssDownloadRulePtr rule = RssDownloadRule::fromOldFormat(rules.value(rule_name).toHash(), feed_url, rule_name);
if(!rule) continue; if (!rule) continue;
// Check for rule name clash // Check for rule name clash
while(m_rules.contains(rule->name())) { while(m_rules.contains(rule->name())) {
rule->setName(rule->name()+"_"); rule->setName(rule->name()+"_");
@ -113,7 +113,7 @@ void RssDownloadRuleList::importFeedRulesInOldFormat(const QString &feed_url, co
QVariantHash RssDownloadRuleList::toVariantHash() const QVariantHash RssDownloadRuleList::toVariantHash() const
{ {
QVariantHash ret; QVariantHash ret;
foreach(const RssDownloadRulePtr &rule, m_rules.values()) { foreach (const RssDownloadRulePtr &rule, m_rules.values()) {
ret.insert(rule->name(), rule->toVariantHash()); ret.insert(rule->name(), rule->toVariantHash());
} }
return ret; return ret;
@ -121,9 +121,9 @@ QVariantHash RssDownloadRuleList::toVariantHash() const
void RssDownloadRuleList::loadRulesFromVariantHash(const QVariantHash &h) void RssDownloadRuleList::loadRulesFromVariantHash(const QVariantHash &h)
{ {
foreach(const QVariant& v, h.values()) { foreach (const QVariant& v, h.values()) {
RssDownloadRulePtr rule = RssDownloadRule::fromNewFormat(v.toHash()); RssDownloadRulePtr rule = RssDownloadRule::fromNewFormat(v.toHash());
if(rule && !rule->name().isEmpty()) { if (rule && !rule->name().isEmpty()) {
saveRule(rule); saveRule(rule);
} }
} }
@ -133,13 +133,13 @@ void RssDownloadRuleList::saveRule(const RssDownloadRulePtr &rule)
{ {
qDebug() << Q_FUNC_INFO << rule->name(); qDebug() << Q_FUNC_INFO << rule->name();
Q_ASSERT(rule); Q_ASSERT(rule);
if(m_rules.contains(rule->name())) { if (m_rules.contains(rule->name())) {
qDebug("This is an update, removing old rule first"); qDebug("This is an update, removing old rule first");
removeRule(rule->name()); removeRule(rule->name());
} }
m_rules.insert(rule->name(), rule); m_rules.insert(rule->name(), rule);
// Update feedRules hashtable // Update feedRules hashtable
foreach(const QString &feed_url, rule->rssFeeds()) { foreach (const QString &feed_url, rule->rssFeeds()) {
m_feedRules[feed_url].append(rule->name()); m_feedRules[feed_url].append(rule->name());
} }
// Save rules // Save rules
@ -150,10 +150,10 @@ void RssDownloadRuleList::saveRule(const RssDownloadRulePtr &rule)
void RssDownloadRuleList::removeRule(const QString &name) void RssDownloadRuleList::removeRule(const QString &name)
{ {
qDebug() << Q_FUNC_INFO << name; qDebug() << Q_FUNC_INFO << name;
if(!m_rules.contains(name)) return; if (!m_rules.contains(name)) return;
RssDownloadRulePtr rule = m_rules.take(name); RssDownloadRulePtr rule = m_rules.take(name);
// Update feedRules hashtable // Update feedRules hashtable
foreach(const QString &feed_url, rule->rssFeeds()) { foreach (const QString &feed_url, rule->rssFeeds()) {
m_feedRules[feed_url].removeOne(rule->name()); m_feedRules[feed_url].removeOne(rule->name());
} }
// Save rules // Save rules
@ -162,12 +162,12 @@ void RssDownloadRuleList::removeRule(const QString &name)
void RssDownloadRuleList::renameRule(const QString &old_name, const QString &new_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); RssDownloadRulePtr rule = m_rules.take(old_name);
rule->setName(new_name); rule->setName(new_name);
m_rules.insert(new_name, rule); m_rules.insert(new_name, rule);
// Update feedRules hashtable // 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); m_feedRules[feed_url].replace(m_feedRules[feed_url].indexOf(old_name), new_name);
} }
// Save rules // Save rules
@ -182,7 +182,7 @@ RssDownloadRulePtr RssDownloadRuleList::getRule(const QString &name) const
bool RssDownloadRuleList::serialize(const QString& path) bool RssDownloadRuleList::serialize(const QString& path)
{ {
QFile f(path); QFile f(path);
if(f.open(QIODevice::WriteOnly)) { if (f.open(QIODevice::WriteOnly)) {
QDataStream out(&f); QDataStream out(&f);
out.setVersion(QDataStream::Qt_4_5); out.setVersion(QDataStream::Qt_4_5);
out << toVariantHash(); out << toVariantHash();
@ -196,16 +196,16 @@ bool RssDownloadRuleList::serialize(const QString& path)
bool RssDownloadRuleList::unserialize(const QString &path) bool RssDownloadRuleList::unserialize(const QString &path)
{ {
QFile f(path); QFile f(path);
if(f.open(QIODevice::ReadOnly)) { if (f.open(QIODevice::ReadOnly)) {
QDataStream in(&f); QDataStream in(&f);
if(path.endsWith(".filters", Qt::CaseInsensitive)) { if (path.endsWith(".filters", Qt::CaseInsensitive)) {
// Old format (< 2.5.0) // Old format (< 2.5.0)
qDebug("Old serialization format detected, processing..."); qDebug("Old serialization format detected, processing...");
in.setVersion(QDataStream::Qt_4_3); in.setVersion(QDataStream::Qt_4_3);
QVariantHash tmp; QVariantHash tmp;
in >> tmp; in >> tmp;
f.close(); f.close();
if(tmp.isEmpty()) return false; if (tmp.isEmpty()) return false;
qDebug("Processing was successful!"); qDebug("Processing was successful!");
// Unfortunately the feed_url is lost // Unfortunately the feed_url is lost
importFeedRulesInOldFormat("", tmp); importFeedRulesInOldFormat("", tmp);
@ -215,7 +215,7 @@ bool RssDownloadRuleList::unserialize(const QString &path)
QVariantHash tmp; QVariantHash tmp;
in >> tmp; in >> tmp;
f.close(); f.close();
if(tmp.isEmpty()) return false; if (tmp.isEmpty()) return false;
qDebug("Processing was successful!"); qDebug("Processing was successful!");
loadRulesFromVariantHash(tmp); loadRulesFromVariantHash(tmp);
} }

View file

@ -56,7 +56,7 @@ RssFeed::RssFeed(RssManager* manager, RssFolder* parent, const QString &url):
} }
RssFeed::~RssFeed(){ RssFeed::~RssFeed(){
if(!m_icon.startsWith(":/") && QFile::exists(m_icon)) if (!m_icon.startsWith(":/") && QFile::exists(m_icon))
QFile::remove(m_icon); QFile::remove(m_icon);
} }
@ -91,7 +91,7 @@ void RssFeed::loadItemsFromDisk() {
} }
void RssFeed::refresh() { void RssFeed::refresh() {
if(m_loading) { if (m_loading) {
qWarning() << Q_FUNC_INFO << "Feed" << this->displayName() << "is already being refreshed, ignoring request"; qWarning() << Q_FUNC_INFO << "Feed" << this->displayName() << "is already being refreshed, ignoring request";
return; 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 // Return the alias if the stream has one, the url if it has no alias
QString RssFeed::displayName() const { QString RssFeed::displayName() const {
if(!m_alias.isEmpty()) { if (!m_alias.isEmpty()) {
//qDebug("getName() returned alias: %s", (const char*)alias.toLocal8Bit()); //qDebug("getName() returned alias: %s", (const char*)alias.toLocal8Bit());
return m_alias; return m_alias;
} }
if(!m_title.isEmpty()) { if (!m_title.isEmpty()) {
//qDebug("getName() returned title: %s", (const char*)title.toLocal8Bit()); //qDebug("getName() returned title: %s", (const char*)title.toLocal8Bit());
return m_title; return m_title;
} }
@ -160,7 +160,7 @@ QString RssFeed::url() const{
} }
QString RssFeed::icon() const{ QString RssFeed::icon() const{
if(m_downloadFailure) if (m_downloadFailure)
return ":/Icons/oxygen/unavailable.png"; return ":/Icons/oxygen/unavailable.png";
return m_icon; return m_icon;
} }
@ -170,7 +170,7 @@ bool RssFeed::hasCustomIcon() const{
} }
void RssFeed::setIconPath(const QString &path) { void RssFeed::setIconPath(const QString &path) {
if(path.isEmpty() || !QFile::exists(path)) return; if (path.isEmpty() || !QFile::exists(path)) return;
m_icon = path; m_icon = path;
} }
@ -192,7 +192,7 @@ void RssFeed::markAsRead() {
uint RssFeed::unreadCount() const{ uint RssFeed::unreadCount() const{
uint nbUnread = 0; uint nbUnread = 0;
for (RssArticleHash::ConstIterator it=m_articles.begin(); it != m_articles.end(); it++) { for (RssArticleHash::ConstIterator it=m_articles.begin(); it != m_articles.end(); it++) {
if(!it.value()->isRead()) if (!it.value()->isRead())
++nbUnread; ++nbUnread;
} }
return nbUnread; return nbUnread;
@ -205,7 +205,7 @@ RssArticleList RssFeed::articleList() const{
RssArticleList RssFeed::unreadArticleList() const { RssArticleList RssFeed::unreadArticleList() const {
RssArticleList unread_news; RssArticleList unread_news;
for (RssArticleHash::ConstIterator it = m_articles.begin(); it != m_articles.end(); it++) { for (RssArticleHash::ConstIterator it = m_articles.begin(); it != m_articles.end(); it++) {
if(!it.value()->isRead()) if (!it.value()->isRead())
unread_news << it.value(); unread_news << it.value();
} }
return unread_news; return unread_news;
@ -229,8 +229,8 @@ bool RssFeed::parseRSS(QIODevice* device) {
} }
while (!xml.atEnd()) { while (!xml.atEnd()) {
xml.readNext(); xml.readNext();
if(xml.isStartElement()) { if (xml.isStartElement()) {
if(xml.name() != "rss") { if (xml.name() != "rss") {
qDebug("ERROR: this is not a rss file, root tag is <%s>", qPrintable(xml.name().toString())); qDebug("ERROR: this is not a rss file, root tag is <%s>", qPrintable(xml.name().toString()));
return false; return false;
} else { } else {
@ -242,37 +242,37 @@ bool RssFeed::parseRSS(QIODevice* device) {
while(!xml.atEnd()) { while(!xml.atEnd()) {
xml.readNext(); xml.readNext();
if(!xml.isStartElement()) if (!xml.isStartElement())
continue; continue;
if(xml.name() != "channel") if (xml.name() != "channel")
continue; continue;
// Parse channel content // Parse channel content
while(!xml.atEnd()) { while(!xml.atEnd()) {
xml.readNext(); xml.readNext();
if(xml.isEndElement() && xml.name() == "channel") if (xml.isEndElement() && xml.name() == "channel")
break; // End of this channel, parse the next one break; // End of this channel, parse the next one
if(!xml.isStartElement()) if (!xml.isStartElement())
continue; continue;
if(xml.name() == "title") { if (xml.name() == "title") {
m_title = xml.readElementText(); m_title = xml.readElementText();
if(m_alias == url()) if (m_alias == url())
rename(m_title); rename(m_title);
} }
else if(xml.name() == "image") { else if (xml.name() == "image") {
QString icon_path = xml.attributes().value("url").toString(); QString icon_path = xml.attributes().value("url").toString();
if(!icon_path.isEmpty()) { if (!icon_path.isEmpty()) {
m_iconUrl = icon_path; m_iconUrl = icon_path;
m_manager->rssDownloader()->downloadUrl(m_iconUrl); m_manager->rssDownloader()->downloadUrl(m_iconUrl);
} }
} }
else if(xml.name() == "item") { else if (xml.name() == "item") {
RssArticlePtr art = xmlToRssArticle(this, xml); RssArticlePtr art = xmlToRssArticle(this, xml);
if(art && !itemAlreadyExists(art->guid())) if (art && !itemAlreadyExists(art->guid()))
m_articles.insert(art->guid(), art); m_articles.insert(art->guid(), art);
} }
} }
@ -282,7 +282,7 @@ bool RssFeed::parseRSS(QIODevice* device) {
resizeList(); resizeList();
// RSS Feed Downloader // RSS Feed Downloader
if(RssSettings().isRssDownloadingEnabled()) if (RssSettings().isRssDownloadingEnabled())
downloadMatchingArticleTorrents(); downloadMatchingArticleTorrents();
// Save items to disk (for safety) // Save items to disk (for safety)
@ -295,15 +295,15 @@ void RssFeed::downloadMatchingArticleTorrents() {
Q_ASSERT(RssSettings().isRssDownloadingEnabled()); Q_ASSERT(RssSettings().isRssDownloadingEnabled());
for (RssArticleHash::ConstIterator it = m_articles.begin(); it != m_articles.end(); it++) { for (RssArticleHash::ConstIterator it = m_articles.begin(); it != m_articles.end(); it++) {
RssArticlePtr item = it.value(); RssArticlePtr item = it.value();
if(item->isRead()) continue; if (item->isRead()) continue;
QString torrent_url; QString torrent_url;
if(item->hasAttachment()) if (item->hasAttachment())
torrent_url = item->torrentUrl(); torrent_url = item->torrentUrl();
else else
torrent_url = item->link(); torrent_url = item->link();
// Check if the item should be automatically downloaded // Check if the item should be automatically downloaded
RssDownloadRulePtr matching_rule = RssDownloadRuleList::instance()->findMatchingRule(m_url, item->title()); RssDownloadRulePtr matching_rule = RssDownloadRuleList::instance()->findMatchingRule(m_url, item->title());
if(matching_rule) { if (matching_rule) {
// Item was downloaded, consider it as Read // Item was downloaded, consider it as Read
item->markAsRead(); item->markAsRead();
// Download the torrent // Download the torrent
@ -316,11 +316,11 @@ void RssFeed::downloadMatchingArticleTorrents() {
void RssFeed::resizeList() { void RssFeed::resizeList() {
const uint max_articles = RssSettings().getRSSMaxArticlesPerFeed(); const uint max_articles = RssSettings().getRSSMaxArticlesPerFeed();
const uint nb_articles = m_articles.size(); const uint nb_articles = m_articles.size();
if(nb_articles > max_articles) { if (nb_articles > max_articles) {
RssArticleList listItems = m_articles.values(); RssArticleList listItems = m_articles.values();
RssManager::sortNewsList(listItems); RssManager::sortNewsList(listItems);
const int excess = nb_articles - max_articles; const int excess = nb_articles - max_articles;
for(uint i=nb_articles-excess; i<nb_articles; ++i){ for (uint i=nb_articles-excess; i<nb_articles; ++i){
m_articles.remove(listItems.at(i)->guid()); m_articles.remove(listItems.at(i)->guid());
} }
} }
@ -330,9 +330,9 @@ void RssFeed::resizeList() {
bool RssFeed::parseXmlFile(const QString &file_path){ bool RssFeed::parseXmlFile(const QString &file_path){
qDebug("openRss() called"); qDebug("openRss() called");
QFile fileRss(file_path); 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)); 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(); fileRss.remove();
} }
return false; return false;
@ -341,25 +341,25 @@ bool RssFeed::parseXmlFile(const QString &file_path){
// start reading the xml // start reading the xml
bool ret = parseRSS(&fileRss); bool ret = parseRSS(&fileRss);
fileRss.close(); fileRss.close();
if(QFile::exists(file_path)) if (QFile::exists(file_path))
fileRss.remove(); fileRss.remove();
return ret; return ret;
} }
// read and store the downloaded rss' informations // read and store the downloaded rss' informations
void RssFeed::handleFinishedDownload(const QString& url, const QString &file_path) { 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; qDebug() << Q_FUNC_INFO << "Successfuly downloaded RSS feed at" << url;
m_downloadFailure = false; m_downloadFailure = false;
m_loading = false; m_loading = false;
// Parse the download RSS // Parse the download RSS
if(parseXmlFile(file_path)) { if (parseXmlFile(file_path)) {
m_refreshed = true; m_refreshed = true;
m_manager->forwardFeedInfosChanged(m_url, displayName(), unreadCount()); // XXX: Ugly m_manager->forwardFeedInfosChanged(m_url, displayName(), unreadCount()); // XXX: Ugly
qDebug() << Q_FUNC_INFO << "Feed parsed successfuly"; qDebug() << Q_FUNC_INFO << "Feed parsed successfuly";
} }
} }
else if(url == m_iconUrl) { else if (url == m_iconUrl) {
m_icon = file_path; m_icon = file_path;
qDebug() << Q_FUNC_INFO << "icon path:" << m_icon; qDebug() << Q_FUNC_INFO << "icon path:" << m_icon;
m_manager->forwardFeedIconChanged(m_url, m_icon); // XXX: Ugly 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) { void RssFeed::handleDownloadFailure(const QString &url, const QString& error) {
if(url != m_url) return; if (url != m_url) return;
m_downloadFailure = true; m_downloadFailure = true;
m_loading = false; m_loading = false;
m_manager->forwardFeedInfosChanged(m_url, displayName(), unreadCount()); // XXX: Ugly m_manager->forwardFeedInfosChanged(m_url, displayName(), unreadCount()); // XXX: Ugly

View file

@ -33,7 +33,7 @@
QStringList RssFile::pathHierarchy() const { QStringList RssFile::pathHierarchy() const {
QStringList path; QStringList path;
if(parent()) if (parent())
path << parent()->pathHierarchy(); path << parent()->pathHierarchy();
path << id(); path << id();
return path; return path;

View file

@ -186,7 +186,7 @@ void RssFolder::removeAllSettings() {
void RssFolder::saveItemsToDisk() void RssFolder::saveItemsToDisk()
{ {
foreach(const RssFilePtr& child, m_children.values()) { foreach (const RssFilePtr& child, m_children.values()) {
child->saveItemsToDisk(); child->saveItemsToDisk();
} }
} }

View file

@ -54,7 +54,7 @@ RssManager::~RssManager(){
} }
void RssManager::updateRefreshInterval(uint val){ void RssManager::updateRefreshInterval(uint val){
if(m_refreshInterval != val) { if (m_refreshInterval != val) {
m_refreshInterval = val; m_refreshInterval = val;
m_refreshTimer.start(m_refreshInterval*60000); m_refreshTimer.start(m_refreshInterval*60000);
qDebug("New RSS refresh interval is now every %dmin", m_refreshInterval); qDebug("New RSS refresh interval is now every %dmin", m_refreshInterval);
@ -65,20 +65,20 @@ void RssManager::loadStreamList() {
RssSettings settings; RssSettings settings;
const QStringList streamsUrl = settings.getRssFeedsUrls(); const QStringList streamsUrl = settings.getRssFeedsUrls();
const QStringList aliases = settings.getRssFeedsAliases(); const QStringList aliases = settings.getRssFeedsAliases();
if(streamsUrl.size() != aliases.size()){ if (streamsUrl.size() != aliases.size()){
std::cerr << "Corrupted Rss list, not loading it\n"; std::cerr << "Corrupted Rss list, not loading it\n";
return; return;
} }
uint i = 0; uint i = 0;
qDebug() << Q_FUNC_INFO << streamsUrl; qDebug() << Q_FUNC_INFO << streamsUrl;
foreach(QString s, streamsUrl){ foreach (QString s, streamsUrl){
QStringList path = s.split("\\", QString::SkipEmptyParts); QStringList path = s.split("\\", QString::SkipEmptyParts);
if(path.empty()) continue; if (path.empty()) continue;
const QString feed_url = path.takeLast(); const QString feed_url = path.takeLast();
qDebug() << "Feed URL:" << feed_url; qDebug() << "Feed URL:" << feed_url;
// Create feed path (if it does not exists) // Create feed path (if it does not exists)
RssFolder* feed_parent = this; RssFolder* feed_parent = this;
foreach(const QString &folder_name, path) { foreach (const QString &folder_name, path) {
qDebug() << "Adding parent folder:" << folder_name; qDebug() << "Adding parent folder:" << folder_name;
feed_parent = feed_parent->addFolder(folder_name).data(); feed_parent = feed_parent->addFolder(folder_name).data();
} }
@ -86,7 +86,7 @@ void RssManager::loadStreamList() {
qDebug() << "Adding feed to parent folder"; qDebug() << "Adding feed to parent folder";
RssFeedPtr stream = feed_parent->addStream(this, feed_url); RssFeedPtr stream = feed_parent->addStream(this, feed_url);
const QString alias = aliases.at(i); const QString alias = aliases.at(i);
if(!alias.isEmpty()) { if (!alias.isEmpty()) {
stream->rename(alias); stream->rename(alias);
} }
++i; ++i;
@ -104,7 +104,7 @@ void RssManager::forwardFeedIconChanged(const QString &url, const QString &icon_
void RssManager::moveFile(const RssFilePtr& file, const RssFolderPtr& dest_folder) { void RssManager::moveFile(const RssFilePtr& file, const RssFolderPtr& dest_folder) {
RssFolder* src_folder = file->parent(); RssFolder* src_folder = file->parent();
if(dest_folder != src_folder) { if (dest_folder != src_folder) {
// Remove reference in old folder // Remove reference in old folder
src_folder->takeChild(file->id()); src_folder->takeChild(file->id());
// add to new Folder // add to new Folder
@ -118,9 +118,9 @@ void RssManager::saveStreamList() const {
QStringList streamsUrl; QStringList streamsUrl;
QStringList aliases; QStringList aliases;
QList<RssFeedPtr> streams = getAllFeeds(); QList<RssFeedPtr> streams = getAllFeeds();
foreach(const RssFeedPtr& stream, streams) { foreach (const RssFeedPtr& stream, streams) {
QString stream_path = stream->pathHierarchy().join("\\"); QString stream_path = stream->pathHierarchy().join("\\");
if(stream_path.isNull()) { if (stream_path.isNull()) {
stream_path = ""; stream_path = "";
} }
qDebug("Saving stream path: %s", qPrintable(stream_path)); qDebug("Saving stream path: %s", qPrintable(stream_path));

View file

@ -89,7 +89,7 @@ public:
QList<QByteArray> getHostNameCookies(const QString &host_name) const { QList<QByteArray> getHostNameCookies(const QString &host_name) const {
QMap<QString, QVariant> hosts_table = value("Rss/hosts_cookies").toMap(); QMap<QString, QVariant> hosts_table = value("Rss/hosts_cookies").toMap();
if(!hosts_table.contains(host_name)) return QList<QByteArray>(); if (!hosts_table.contains(host_name)) return QList<QByteArray>();
QByteArray raw_cookies = hosts_table.value(host_name).toByteArray(); QByteArray raw_cookies = hosts_table.value(host_name).toByteArray();
return raw_cookies.split(':'); return raw_cookies.split(':');
} }
@ -97,10 +97,10 @@ public:
void setHostNameCookies(const QString &host_name, const QList<QByteArray> &cookies) { void setHostNameCookies(const QString &host_name, const QList<QByteArray> &cookies) {
QMap<QString, QVariant> hosts_table = value("Rss/hosts_cookies").toMap(); QMap<QString, QVariant> hosts_table = value("Rss/hosts_cookies").toMap();
QByteArray raw_cookies = ""; QByteArray raw_cookies = "";
foreach(const QByteArray& cookie, cookies) { foreach (const QByteArray& cookie, cookies) {
raw_cookies += cookie + ":"; raw_cookies += cookie + ":";
} }
if(raw_cookies.endsWith(":")) if (raw_cookies.endsWith(":"))
raw_cookies.chop(1); raw_cookies.chop(1);
hosts_table.insert(host_name, raw_cookies); hosts_table.insert(host_name, raw_cookies);
setValue("Rss/hosts_cookies", hosts_table); setValue("Rss/hosts_cookies", hosts_table);

View file

@ -76,15 +76,15 @@ engineSelectDlg::~engineSelectDlg() {
void engineSelectDlg::dropEvent(QDropEvent *event) { void engineSelectDlg::dropEvent(QDropEvent *event) {
event->acceptProposedAction(); event->acceptProposedAction();
QStringList files=event->mimeData()->text().split(QString::fromUtf8("\n")); QStringList files=event->mimeData()->text().split(QString::fromUtf8("\n"));
foreach(QString file, files) { foreach (QString file, files) {
qDebug("dropped %s", qPrintable(file)); qDebug("dropped %s", qPrintable(file));
if(misc::isUrl(file)) { if (misc::isUrl(file)) {
setCursor(QCursor(Qt::WaitCursor)); setCursor(QCursor(Qt::WaitCursor));
downloader->downloadUrl(file); downloader->downloadUrl(file);
continue; continue;
} }
if(file.endsWith(".py", Qt::CaseInsensitive)) { if (file.endsWith(".py", Qt::CaseInsensitive)) {
if(file.startsWith("file:", Qt::CaseInsensitive)) if (file.startsWith("file:", Qt::CaseInsensitive))
file = QUrl(file).toLocalFile(); file = QUrl(file).toLocalFile();
QString plugin_name = misc::fileName(file); QString plugin_name = misc::fileName(file);
plugin_name.chop(3); // Remove extension plugin_name.chop(3); // Remove extension
@ -96,7 +96,7 @@ void engineSelectDlg::dropEvent(QDropEvent *event) {
// Decode if we accept drag 'n drop or not // Decode if we accept drag 'n drop or not
void engineSelectDlg::dragEnterEvent(QDragEnterEvent *event) { void engineSelectDlg::dragEnterEvent(QDragEnterEvent *event) {
QString mime; QString mime;
foreach(mime, event->mimeData()->formats()){ foreach (mime, event->mimeData()->formats()){
qDebug("mimeData: %s", qPrintable(mime)); qDebug("mimeData: %s", qPrintable(mime));
} }
if (event->mimeData()->hasFormat(QString::fromUtf8("text/plain")) || event->mimeData()->hasFormat(QString::fromUtf8("text/uri-list"))) { 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) { void engineSelectDlg::toggleEngineState(QTreeWidgetItem *item, int) {
SupportedEngine *engine = supported_engines->value(item->text(ENGINE_ID)); SupportedEngine *engine = supported_engines->value(item->text(ENGINE_ID));
engine->setEnabled(!engine->isEnabled()); engine->setEnabled(!engine->isEnabled());
if(engine->isEnabled()) { if (engine->isEnabled()) {
item->setText(ENGINE_STATE, tr("Yes")); item->setText(ENGINE_STATE, tr("Yes"));
setRowColor(pluginsTree->indexOfTopLevelItem(item), "green"); setRowColor(pluginsTree->indexOfTopLevelItem(item), "green");
} else { } else {
@ -126,7 +126,7 @@ void engineSelectDlg::displayContextMenu(const QPoint&) {
QMenu myContextMenu(this); QMenu myContextMenu(this);
// Enable/disable pause/start action given the DL state // Enable/disable pause/start action given the DL state
QList<QTreeWidgetItem *> items = pluginsTree->selectedItems(); QList<QTreeWidgetItem *> items = pluginsTree->selectedItems();
if(items.isEmpty()) return; if (items.isEmpty()) return;
QString first_id = items.first()->text(ENGINE_ID); QString first_id = items.first()->text(ENGINE_ID);
actionEnable->setChecked(supported_engines->value(first_id)->isEnabled()); actionEnable->setChecked(supported_engines->value(first_id)->isEnabled());
myContextMenu.addAction(actionEnable); myContextMenu.addAction(actionEnable);
@ -143,11 +143,11 @@ void engineSelectDlg::on_actionUninstall_triggered() {
QList<QTreeWidgetItem *> items = pluginsTree->selectedItems(); QList<QTreeWidgetItem *> items = pluginsTree->selectedItems();
QTreeWidgetItem *item; QTreeWidgetItem *item;
bool error = false; bool error = false;
foreach(item, items) { foreach (item, items) {
int index = pluginsTree->indexOfTopLevelItem(item); int index = pluginsTree->indexOfTopLevelItem(item);
Q_ASSERT(index != -1); Q_ASSERT(index != -1);
QString id = item->text(ENGINE_ID); QString id = item->text(ENGINE_ID);
if(QFile::exists(":/nova/engines/"+id+".py")) { if (QFile::exists(":/nova/engines/"+id+".py")) {
error = true; error = true;
// Disable it instead // Disable it instead
supported_engines->value(id)->setEnabled(false); supported_engines->value(id)->setEnabled(false);
@ -162,7 +162,7 @@ void engineSelectDlg::on_actionUninstall_triggered() {
filters << id+".*"; filters << id+".*";
QStringList files = enginesFolder.entryList(filters, QDir::Files, QDir::Unsorted); QStringList files = enginesFolder.entryList(filters, QDir::Files, QDir::Unsorted);
QString file; QString file;
foreach(file, files) { foreach (file, files) {
enginesFolder.remove(file); enginesFolder.remove(file);
} }
// Remove it from supported engines // Remove it from supported engines
@ -170,7 +170,7 @@ void engineSelectDlg::on_actionUninstall_triggered() {
delete item; 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.")); 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 else
QMessageBox::information(0, tr("Uninstall success"), tr("All selected plugins were uninstalled successfully")); 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) { void engineSelectDlg::enableSelection(bool enable) {
QList<QTreeWidgetItem *> items = pluginsTree->selectedItems(); QList<QTreeWidgetItem *> items = pluginsTree->selectedItems();
QTreeWidgetItem *item; QTreeWidgetItem *item;
foreach(item, items) { foreach (item, items) {
int index = pluginsTree->indexOfTopLevelItem(item); int index = pluginsTree->indexOfTopLevelItem(item);
Q_ASSERT(index != -1); Q_ASSERT(index != -1);
QString id = item->text(ENGINE_ID); QString id = item->text(ENGINE_ID);
supported_engines->value(id)->setEnabled(enable); supported_engines->value(id)->setEnabled(enable);
if(enable) { if (enable) {
item->setText(ENGINE_STATE, tr("Yes")); item->setText(ENGINE_STATE, tr("Yes"));
setRowColor(index, "green"); setRowColor(index, "green");
} else { } else {
@ -197,16 +197,16 @@ void engineSelectDlg::enableSelection(bool enable) {
// Set the color of a row in data model // Set the color of a row in data model
void engineSelectDlg::setRowColor(int row, QString color){ void engineSelectDlg::setRowColor(int row, QString color){
QTreeWidgetItem *item = pluginsTree->topLevelItem(row); QTreeWidgetItem *item = pluginsTree->topLevelItem(row);
for(int i=0; i<pluginsTree->columnCount(); ++i){ for (int i=0; i<pluginsTree->columnCount(); ++i){
item->setData(i, Qt::ForegroundRole, QVariant(QColor(color))); item->setData(i, Qt::ForegroundRole, QVariant(QColor(color)));
} }
} }
QList<QTreeWidgetItem*> engineSelectDlg::findItemsWithUrl(QString url){ QList<QTreeWidgetItem*> engineSelectDlg::findItemsWithUrl(QString url){
QList<QTreeWidgetItem*> res; QList<QTreeWidgetItem*> res;
for(int i=0; i<pluginsTree->topLevelItemCount(); ++i) { for (int i=0; i<pluginsTree->topLevelItemCount(); ++i) {
QTreeWidgetItem *item = pluginsTree->topLevelItem(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; res << item;
} }
return res; return res;
@ -214,9 +214,9 @@ QList<QTreeWidgetItem*> engineSelectDlg::findItemsWithUrl(QString url){
QTreeWidgetItem* engineSelectDlg::findItemWithID(QString id){ QTreeWidgetItem* engineSelectDlg::findItemWithID(QString id){
QList<QTreeWidgetItem*> res; QList<QTreeWidgetItem*> res;
for(int i=0; i<pluginsTree->topLevelItemCount(); ++i) { for (int i=0; i<pluginsTree->topLevelItemCount(); ++i) {
QTreeWidgetItem *item = pluginsTree->topLevelItem(i); QTreeWidgetItem *item = pluginsTree->topLevelItem(i);
if(id == item->text(ENGINE_ID)) if (id == item->text(ENGINE_ID))
return item; return item;
} }
return 0; return 0;
@ -232,7 +232,7 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
qDebug("Asked to install plugin at %s", qPrintable(path)); qDebug("Asked to install plugin at %s", qPrintable(path));
qreal new_version = SearchEngine::getPluginVersion(path); qreal new_version = SearchEngine::getPluginVersion(path);
qDebug("Version to be installed: %.2f", new_version); 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"); 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)); 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; return;
@ -240,7 +240,7 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
// Process with install // Process with install
QString dest_path = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+plugin_name+".py"; QString dest_path = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+plugin_name+".py";
bool update = false; bool update = false;
if(QFile::exists(dest_path)) { if (QFile::exists(dest_path)) {
// Backup in case install fails // Backup in case install fails
QFile::copy(dest_path, dest_path+".bak"); QFile::copy(dest_path, dest_path+".bak");
QFile::remove(dest_path); QFile::remove(dest_path);
@ -252,8 +252,8 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
// Update supported plugins // Update supported plugins
supported_engines->update(); supported_engines->update();
// Check if this was correctly installed // Check if this was correctly installed
if(!supported_engines->contains(plugin_name)) { if (!supported_engines->contains(plugin_name)) {
if(update) { if (update) {
// Remove broken file // Remove broken file
QFile::remove(dest_path); QFile::remove(dest_path);
// restore backup // restore backup
@ -269,10 +269,10 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
} }
} }
// Install was successful, remove backup // Install was successful, remove backup
if(update) { if (update) {
QFile::remove(dest_path+".bak"); 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)); 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; return;
} else { } else {
@ -284,7 +284,7 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
void engineSelectDlg::loadSupportedSearchEngines() { void engineSelectDlg::loadSupportedSearchEngines() {
// Some clean up first // Some clean up first
pluginsTree->clear(); pluginsTree->clear();
foreach(QString name, supported_engines->keys()) { foreach (QString name, supported_engines->keys()) {
addNewEngine(name); addNewEngine(name);
} }
} }
@ -295,7 +295,7 @@ void engineSelectDlg::addNewEngine(QString engine_name) {
item->setText(ENGINE_NAME, engine->getFullName()); item->setText(ENGINE_NAME, engine->getFullName());
item->setText(ENGINE_URL, engine->getUrl()); item->setText(ENGINE_URL, engine->getUrl());
item->setText(ENGINE_ID, engine->getName()); item->setText(ENGINE_ID, engine->getName());
if(engine->isEnabled()) { if (engine->isEnabled()) {
item->setText(ENGINE_STATE, tr("Yes")); item->setText(ENGINE_STATE, tr("Yes"));
setRowColor(pluginsTree->indexOfTopLevelItem(item), "green"); setRowColor(pluginsTree->indexOfTopLevelItem(item), "green");
} else { } else {
@ -304,12 +304,12 @@ void engineSelectDlg::addNewEngine(QString engine_name) {
} }
// Handle icon // Handle icon
QString iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+engine->getName()+".png"; 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 // Good, we already have the icon
item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath))); item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath)));
} else { } else {
iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+engine->getName()+".ico"; 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))); item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath)));
} else { } else {
// Icon is missing, we must download it // Icon is missing, we must download it
@ -340,8 +340,8 @@ void engineSelectDlg::askForLocalPlugin() {
tr("Select search plugins"), QDir::homePath(), tr("Select search plugins"), QDir::homePath(),
tr("qBittorrent search plugins")+QString::fromUtf8(" (*.py)")); tr("qBittorrent search plugins")+QString::fromUtf8(" (*.py)"));
QString path; QString path;
foreach(path, pathsList) { foreach (path, pathsList) {
if(path.endsWith(".py", Qt::CaseInsensitive)) { if (path.endsWith(".py", Qt::CaseInsensitive)) {
QString plugin_name = path.split(QDir::separator()).last(); QString plugin_name = path.split(QDir::separator()).last();
plugin_name.replace(".py", "", Qt::CaseInsensitive); plugin_name.replace(".py", "", Qt::CaseInsensitive);
installPlugin(path, plugin_name); installPlugin(path, plugin_name);
@ -353,7 +353,7 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) {
qDebug("Checking if update is needed"); qDebug("Checking if update is needed");
bool file_correct = false; bool file_correct = false;
QFile versions(versions_file); 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"); qDebug("* Error: Could not read versions.txt file");
return false; return false;
} }
@ -362,19 +362,19 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) {
QByteArray line = versions.readLine(); QByteArray line = versions.readLine();
line.replace("\n", ""); line.replace("\n", "");
line = line.trimmed(); line = line.trimmed();
if(line.isEmpty()) continue; if (line.isEmpty()) continue;
if(line.startsWith("#")) continue; if (line.startsWith("#")) continue;
QList<QByteArray> list = line.split(' '); QList<QByteArray> list = line.split(' ');
if(list.size() != 2) continue; if (list.size() != 2) continue;
QString plugin_name = QString(list.first()); QString plugin_name = QString(list.first());
if(!plugin_name.endsWith(":")) continue; if (!plugin_name.endsWith(":")) continue;
plugin_name.chop(1); // remove trailing ':' plugin_name.chop(1); // remove trailing ':'
bool ok; bool ok;
qreal version = list.last().toFloat(&ok); qreal version = list.last().toFloat(&ok);
qDebug("read line %s: %.2f", qPrintable(plugin_name), version); qDebug("read line %s: %.2f", qPrintable(plugin_name), version);
if(!ok) continue; if (!ok) continue;
file_correct = true; file_correct = true;
if(isUpdateNeeded(plugin_name, version)) { if (isUpdateNeeded(plugin_name, version)) {
qDebug("Plugin: %s is outdated", qPrintable(plugin_name)); qDebug("Plugin: %s is outdated", qPrintable(plugin_name));
// Downloading update // Downloading update
setCursor(QCursor(Qt::WaitCursor)); setCursor(QCursor(Qt::WaitCursor));
@ -389,7 +389,7 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) {
versions.close(); versions.close();
// Clean up tmp file // Clean up tmp file
QFile::remove(versions_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.")); QMessageBox::information(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("All your plugins are already up to date."));
} }
return file_correct; return file_correct;
@ -398,18 +398,18 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) {
void engineSelectDlg::processDownloadedFile(QString url, QString filePath) { void engineSelectDlg::processDownloadedFile(QString url, QString filePath) {
setCursor(QCursor(Qt::ArrowCursor)); setCursor(QCursor(Qt::ArrowCursor));
qDebug("engineSelectDlg received %s", qPrintable(url)); qDebug("engineSelectDlg received %s", qPrintable(url));
if(url.endsWith("favicon.ico", Qt::CaseInsensitive)){ if (url.endsWith("favicon.ico", Qt::CaseInsensitive)){
// Icon downloaded // Icon downloaded
QImage fileIcon; QImage fileIcon;
if(fileIcon.load(filePath)) { if (fileIcon.load(filePath)) {
QList<QTreeWidgetItem*> items = findItemsWithUrl(url); QList<QTreeWidgetItem*> items = findItemsWithUrl(url);
QTreeWidgetItem *item; QTreeWidgetItem *item;
foreach(item, items){ foreach (item, items){
QString id = item->text(ENGINE_ID); QString id = item->text(ENGINE_ID);
QString iconPath; QString iconPath;
QFile icon(filePath); QFile icon(filePath);
icon.open(QIODevice::ReadOnly); icon.open(QIODevice::ReadOnly);
if(ICOHandler::canRead(&icon)) if (ICOHandler::canRead(&icon))
iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".ico"; iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".ico";
else else
iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".png"; iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".png";
@ -421,14 +421,14 @@ void engineSelectDlg::processDownloadedFile(QString url, QString filePath) {
QFile::remove(filePath); QFile::remove(filePath);
return; return;
} }
if(url.endsWith("versions.txt")) { if (url.endsWith("versions.txt")) {
if(!parseVersionsFile(filePath)) { if (!parseVersionsFile(filePath)) {
QMessageBox::warning(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("Sorry, update server is temporarily unavailable.")); QMessageBox::warning(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("Sorry, update server is temporarily unavailable."));
} }
QFile::remove(filePath); QFile::remove(filePath);
return; return;
} }
if(url.endsWith(".py", Qt::CaseInsensitive)) { if (url.endsWith(".py", Qt::CaseInsensitive)) {
QString plugin_name = misc::fileName(url); QString plugin_name = misc::fileName(url);
plugin_name.chop(3); // Remove extension plugin_name.chop(3); // Remove extension
installPlugin(filePath, plugin_name); installPlugin(filePath, plugin_name);
@ -439,15 +439,15 @@ void engineSelectDlg::processDownloadedFile(QString url, QString filePath) {
void engineSelectDlg::handleDownloadFailure(QString url, QString reason) { void engineSelectDlg::handleDownloadFailure(QString url, QString reason) {
setCursor(QCursor(Qt::ArrowCursor)); 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)); qDebug("Could not download favicon: %s, reason: %s", qPrintable(url), qPrintable(reason));
return; 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.")); QMessageBox::warning(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("Sorry, update server is temporarily unavailable."));
return; return;
} }
if(url.endsWith(".py", Qt::CaseInsensitive)) { if (url.endsWith(".py", Qt::CaseInsensitive)) {
// a plugin update download has been failed // a plugin update download has been failed
QString plugin_name = url.split('/').last(); QString plugin_name = url.split('/').last();
plugin_name.replace(".py", "", Qt::CaseInsensitive); plugin_name.replace(".py", "", Qt::CaseInsensitive);

View file

@ -114,7 +114,7 @@ void SearchEngine::fillCatCombobox() {
comboCategory->clear(); comboCategory->clear();
comboCategory->addItem(full_cat_names["all"], QVariant("all")); comboCategory->addItem(full_cat_names["all"], QVariant("all"));
QStringList supported_cat = supported_engines->supportedCategories(); QStringList supported_cat = supported_engines->supportedCategories();
foreach(QString cat, supported_cat) { foreach (QString cat, supported_cat) {
qDebug("Supported category: %s", qPrintable(cat)); qDebug("Supported category: %s", qPrintable(cat));
comboCategory->addItem(full_cat_names[cat], QVariant(cat)); comboCategory->addItem(full_cat_names[cat], QVariant(cat));
} }
@ -123,10 +123,10 @@ void SearchEngine::fillCatCombobox() {
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
bool SearchEngine::addPythonPathToEnv() { bool SearchEngine::addPythonPathToEnv() {
QString python_path = Preferences::getPythonPath(); QString python_path = Preferences::getPythonPath();
if(!python_path.isEmpty()) { if (!python_path.isEmpty()) {
// Add it to PATH envvar // Add it to PATH envvar
QString path_envar = QString::fromLocal8Bit(qgetenv("PATH").constData()); QString path_envar = QString::fromLocal8Bit(qgetenv("PATH").constData());
if(path_envar.isNull()) { if (path_envar.isNull()) {
path_envar = ""; path_envar = "";
} }
path_envar = python_path+";"+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!"); qDebug("Setup should be complete!");
// Reload search engine // Reload search engine
has_python = addPythonPathToEnv(); has_python = addPythonPathToEnv();
if(has_python) { if (has_python) {
supported_engines->update(); supported_engines->update();
// Launch the search again // Launch the search again
on_search_button_clicked(); on_search_button_clicked();
@ -189,7 +189,7 @@ SearchEngine::~SearchEngine(){
saveSearchHistory(); saveSearchHistory();
searchProcess->kill(); searchProcess->kill();
searchProcess->waitForFinished(); searchProcess->waitForFinished();
foreach(QProcess *downloader, downloaders) { foreach (QProcess *downloader, downloaders) {
// Make sure we disconnect the SIGNAL/SLOT first // Make sure we disconnect the SIGNAL/SLOT first
// To avoid qreal free // To avoid qreal free
downloader->disconnect(); downloader->disconnect();
@ -203,7 +203,7 @@ SearchEngine::~SearchEngine(){
delete searchTimeout; delete searchTimeout;
delete searchProcess; delete searchProcess;
delete supported_engines; delete supported_engines;
if(searchCompleter) if (searchCompleter)
delete searchCompleter; delete searchCompleter;
} }
@ -215,24 +215,24 @@ void SearchEngine::displayPatternContextMenu(QPoint) {
QAction clearAct(IconProvider::instance()->getIcon("edit-clear"), tr("Clear field"), &myMenu); QAction clearAct(IconProvider::instance()->getIcon("edit-clear"), tr("Clear field"), &myMenu);
QAction clearHistoryAct(IconProvider::instance()->getIcon("edit-clear-history"), tr("Clear completion history"), &myMenu); QAction clearHistoryAct(IconProvider::instance()->getIcon("edit-clear-history"), tr("Clear completion history"), &myMenu);
bool hasCopyAct = false; bool hasCopyAct = false;
if(search_pattern->hasSelectedText()) { if (search_pattern->hasSelectedText()) {
myMenu.addAction(&cutAct); myMenu.addAction(&cutAct);
myMenu.addAction(&copyAct); myMenu.addAction(&copyAct);
hasCopyAct = true; hasCopyAct = true;
} }
if(qApp->clipboard()->mimeData()->hasText()) { if (qApp->clipboard()->mimeData()->hasText()) {
myMenu.addAction(&pasteAct); myMenu.addAction(&pasteAct);
hasCopyAct = true; hasCopyAct = true;
} }
if(hasCopyAct) if (hasCopyAct)
myMenu.addSeparator(); myMenu.addSeparator();
myMenu.addAction(&clearHistoryAct); myMenu.addAction(&clearHistoryAct);
myMenu.addAction(&clearAct); myMenu.addAction(&clearAct);
QAction *act = myMenu.exec(QCursor::pos()); QAction *act = myMenu.exec(QCursor::pos());
if(act != 0) { if (act != 0) {
if(act == &clearHistoryAct) { if (act == &clearHistoryAct) {
// Ask for confirmation // 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 // Clear history
searchHistory.setStringList(QStringList()); searchHistory.setStringList(QStringList());
} }
@ -255,9 +255,9 @@ void SearchEngine::displayPatternContextMenu(QPoint) {
void SearchEngine::tab_changed(int t) void SearchEngine::tab_changed(int t)
{//when we switch from a tab that is not empty to another that is empty the download button {//when we switch from a tab that is not empty to another that is empty the download button
//doesn't have to be available //doesn't have to be available
if(t>-1) if (t>-1)
{//-1 = no more tab {//-1 = no more tab
if(all_tab.at(tabWidget->currentIndex())->getCurrentSearchListModel()->rowCount()) { if (all_tab.at(tabWidget->currentIndex())->getCurrentSearchListModel()->rowCount()) {
download_button->setEnabled(true); download_button->setEnabled(true);
goToDescBtn->setEnabled(true); goToDescBtn->setEnabled(true);
} else { } else {
@ -296,8 +296,8 @@ void SearchEngine::giveFocusToSearchInput() {
// Function called when we click on search button // Function called when we click on search button
void SearchEngine::on_search_button_clicked(){ void SearchEngine::on_search_button_clicked(){
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
if(!has_python) { if (!has_python) {
if(QMessageBox::question(this, tr("Missing Python Interpreter"), 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?"), 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) { QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
// Download and Install Python // Download and Install Python
@ -306,17 +306,17 @@ void SearchEngine::on_search_button_clicked(){
return; return;
} }
#endif #endif
if(searchProcess->state() != QProcess::NotRunning){ if (searchProcess->state() != QProcess::NotRunning){
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
searchProcess->kill(); searchProcess->kill();
#else #else
searchProcess->terminate(); searchProcess->terminate();
#endif #endif
search_stopped = true; search_stopped = true;
if(searchTimeout->isActive()) { if (searchTimeout->isActive()) {
searchTimeout->stop(); searchTimeout->stop();
} }
if(search_button->text() != tr("Search")) { if (search_button->text() != tr("Search")) {
search_button->setText(tr("Search")); search_button->setText(tr("Search"));
return; return;
} }
@ -327,7 +327,7 @@ void SearchEngine::on_search_button_clicked(){
const QString pattern = search_pattern->text().trimmed(); const QString pattern = search_pattern->text().trimmed();
// No search pattern entered // No search pattern entered
if(pattern.isEmpty()){ if (pattern.isEmpty()){
QMessageBox::critical(0, tr("Empty search pattern"), tr("Please type a search pattern first")); QMessageBox::critical(0, tr("Empty search pattern"), tr("Please type a search pattern first"));
return; return;
} }
@ -344,11 +344,11 @@ void SearchEngine::on_search_button_clicked(){
#endif #endif
// if the pattern is not in the pattern // if the pattern is not in the pattern
QStringList wordList = searchHistory.stringList(); QStringList wordList = searchHistory.stringList();
if(wordList.indexOf(pattern) == -1){ if (wordList.indexOf(pattern) == -1){
//update the searchHistory list //update the searchHistory list
wordList.append(pattern); wordList.append(pattern);
// verify the max size of the history // verify the max size of the history
if(wordList.size() > SEARCHHISTORY_MAXSIZE) if (wordList.size() > SEARCHHISTORY_MAXSIZE)
wordList = wordList.mid(wordList.size()/2); wordList = wordList.mid(wordList.size()/2);
searchHistory.setStringList(wordList); searchHistory.setStringList(wordList);
} }
@ -373,7 +373,7 @@ void SearchEngine::on_search_button_clicked(){
} }
void SearchEngine::createCompleter() { void SearchEngine::createCompleter() {
if(searchCompleter) if (searchCompleter)
delete searchCompleter; delete searchCompleter;
searchCompleter = new QCompleter(&searchHistory); searchCompleter = new QCompleter(&searchHistory);
searchCompleter->setCaseSensitivity(Qt::CaseInsensitive); searchCompleter->setCaseSensitivity(Qt::CaseInsensitive);
@ -381,14 +381,14 @@ void SearchEngine::createCompleter() {
} }
void SearchEngine::propagateSectionResized(int index, int , int newsize) { void SearchEngine::propagateSectionResized(int index, int , int newsize) {
foreach(SearchTab * tab, all_tab) { foreach (SearchTab * tab, all_tab) {
tab->getCurrentTreeView()->setColumnWidth(index, newsize); tab->getCurrentTreeView()->setColumnWidth(index, newsize);
} }
saveResultsColumnsWidth(); saveResultsColumnsWidth();
} }
void SearchEngine::saveResultsColumnsWidth() { void SearchEngine::saveResultsColumnsWidth() {
if(all_tab.size() > 0) { if (all_tab.size() > 0) {
QTreeView* treeview = all_tab.first()->getCurrentTreeView(); QTreeView* treeview = all_tab.first()->getCurrentTreeView();
QIniSettings settings("qBittorrent", "qBittorrent"); QIniSettings settings("qBittorrent", "qBittorrent");
QStringList width_list; QStringList width_list;
@ -396,14 +396,14 @@ void SearchEngine::saveResultsColumnsWidth() {
short nbColumns = all_tab.first()->getCurrentSearchListModel()->columnCount(); short nbColumns = all_tab.first()->getCurrentSearchListModel()->columnCount();
QString line = settings.value("SearchResultsColsWidth", QString()).toString(); QString line = settings.value("SearchResultsColsWidth", QString()).toString();
if(!line.isEmpty()) { if (!line.isEmpty()) {
width_list = line.split(' '); width_list = line.split(' ');
} }
for(short i=0; i<nbColumns; ++i){ for (short i=0; i<nbColumns; ++i){
if(treeview->columnWidth(i)<1 && width_list.size() == nbColumns && width_list.at(i).toInt()>=1) { if (treeview->columnWidth(i)<1 && width_list.size() == nbColumns && width_list.at(i).toInt()>=1) {
// load the former width // load the former width
new_width_list << width_list.at(i); 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 // usual case, save the current width
new_width_list << QString::number(treeview->columnWidth(i)); new_width_list << QString::number(treeview->columnWidth(i));
} else { } else {
@ -417,11 +417,11 @@ void SearchEngine::saveResultsColumnsWidth() {
} }
void SearchEngine::downloadTorrent(QString engine_url, QString torrent_url) { 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"); qDebug("Converting bc link to magnet link");
torrent_url = misc::bcLinkToMagnet(torrent_url); torrent_url = misc::bcLinkToMagnet(torrent_url);
} }
if(torrent_url.startsWith("magnet:")) { if (torrent_url.startsWith("magnet:")) {
QStringList urls; QStringList urls;
urls << torrent_url; urls << torrent_url;
mp_mainWindow->downloadFromURLList(urls); mp_mainWindow->downloadFromURLList(urls);
@ -453,24 +453,24 @@ void SearchEngine::readSearchOutput(){
QByteArray output = searchProcess->readAllStandardOutput(); QByteArray output = searchProcess->readAllStandardOutput();
output.replace("\r", ""); output.replace("\r", "");
QList<QByteArray> lines_list = output.split('\n'); QList<QByteArray> lines_list = output.split('\n');
if(!search_result_line_truncated.isEmpty()){ if (!search_result_line_truncated.isEmpty()){
QByteArray end_of_line = lines_list.takeFirst(); QByteArray end_of_line = lines_list.takeFirst();
lines_list.prepend(search_result_line_truncated+end_of_line); lines_list.prepend(search_result_line_truncated+end_of_line);
} }
search_result_line_truncated = lines_list.takeLast().trimmed(); search_result_line_truncated = lines_list.takeLast().trimmed();
foreach(const QByteArray &line, lines_list){ foreach (const QByteArray &line, lines_list){
appendSearchResult(QString::fromUtf8(line)); appendSearchResult(QString::fromUtf8(line));
} }
if(currentSearchTab) if (currentSearchTab)
currentSearchTab->getCurrentLabel()->setText(tr("Results")+QString::fromUtf8(" <i>(")+QString::number(nb_search_results)+QString::fromUtf8(")</i>:")); currentSearchTab->getCurrentLabel()->setText(tr("Results")+QString::fromUtf8(" <i>(")+QString::number(nb_search_results)+QString::fromUtf8(")</i>:"));
} }
void SearchEngine::downloadFinished(int exitcode, QProcess::ExitStatus) { void SearchEngine::downloadFinished(int exitcode, QProcess::ExitStatus) {
QProcess *downloadProcess = (QProcess*)sender(); QProcess *downloadProcess = (QProcess*)sender();
if(exitcode == 0) { if (exitcode == 0) {
QString line = QString::fromUtf8(downloadProcess->readAllStandardOutput()).trimmed(); QString line = QString::fromUtf8(downloadProcess->readAllStandardOutput()).trimmed();
QStringList parts = line.split(' '); QStringList parts = line.split(' ');
if(parts.size() == 2) { if (parts.size() == 2) {
QString path = parts[0]; QString path = parts[0];
QString url = parts[1]; QString url = parts[1];
QBtSession::instance()->processDownloadedFile(url, path); QBtSession::instance()->processDownloadedFile(url, path);
@ -490,7 +490,7 @@ void SearchEngine::updateNova() {
QFile package_file(search_dir.absoluteFilePath("__init__.py")); QFile package_file(search_dir.absoluteFilePath("__init__.py"));
package_file.open(QIODevice::WriteOnly | QIODevice::Text); package_file.open(QIODevice::WriteOnly | QIODevice::Text);
package_file.close(); package_file.close();
if(!search_dir.exists("engines")){ if (!search_dir.exists("engines")){
search_dir.mkdir("engines"); search_dir.mkdir("engines");
} }
QFile package_file2(search_dir.absolutePath().replace("\\", "/")+"/engines/__init__.py"); QFile package_file2(search_dir.absolutePath().replace("\\", "/")+"/engines/__init__.py");
@ -498,8 +498,8 @@ void SearchEngine::updateNova() {
package_file2.close(); package_file2.close();
// Copy search plugin files (if necessary) // Copy search plugin files (if necessary)
QString filePath = search_dir.absoluteFilePath("nova2.py"); QString filePath = search_dir.absoluteFilePath("nova2.py");
if(getPluginVersion(":/"+nova_folder+"/nova2.py") > getPluginVersion(filePath)) { if (getPluginVersion(":/"+nova_folder+"/nova2.py") > getPluginVersion(filePath)) {
if(QFile::exists(filePath)) { if (QFile::exists(filePath)) {
QFile::remove(filePath); QFile::remove(filePath);
QFile::remove(filePath+"c"); QFile::remove(filePath+"c");
} }
@ -507,8 +507,8 @@ void SearchEngine::updateNova() {
} }
filePath = search_dir.absoluteFilePath("nova2dl.py"); filePath = search_dir.absoluteFilePath("nova2dl.py");
if(getPluginVersion(":/"+nova_folder+"/nova2dl.py") > getPluginVersion(filePath)) { if (getPluginVersion(":/"+nova_folder+"/nova2dl.py") > getPluginVersion(filePath)) {
if(QFile::exists(filePath)){ if (QFile::exists(filePath)){
QFile::remove(filePath); QFile::remove(filePath);
QFile::remove(filePath+"c"); QFile::remove(filePath+"c");
} }
@ -516,8 +516,8 @@ void SearchEngine::updateNova() {
} }
filePath = search_dir.absoluteFilePath("novaprinter.py"); filePath = search_dir.absoluteFilePath("novaprinter.py");
if(getPluginVersion(":/"+nova_folder+"/novaprinter.py") > getPluginVersion(filePath)) { if (getPluginVersion(":/"+nova_folder+"/novaprinter.py") > getPluginVersion(filePath)) {
if(QFile::exists(filePath)){ if (QFile::exists(filePath)){
QFile::remove(filePath); QFile::remove(filePath);
QFile::remove(filePath+"c"); QFile::remove(filePath+"c");
} }
@ -525,8 +525,8 @@ void SearchEngine::updateNova() {
} }
filePath = search_dir.absoluteFilePath("helpers.py"); filePath = search_dir.absoluteFilePath("helpers.py");
if(getPluginVersion(":/"+nova_folder+"/helpers.py") > getPluginVersion(filePath)) { if (getPluginVersion(":/"+nova_folder+"/helpers.py") > getPluginVersion(filePath)) {
if(QFile::exists(filePath)){ if (QFile::exists(filePath)){
QFile::remove(filePath); QFile::remove(filePath);
QFile::remove(filePath+"c"); QFile::remove(filePath+"c");
} }
@ -534,7 +534,7 @@ void SearchEngine::updateNova() {
} }
filePath = search_dir.absoluteFilePath("socks.py"); filePath = search_dir.absoluteFilePath("socks.py");
if(QFile::exists(filePath)){ if (QFile::exists(filePath)){
QFile::remove(filePath); QFile::remove(filePath);
QFile::remove(filePath+"c"); QFile::remove(filePath+"c");
} }
@ -542,7 +542,7 @@ void SearchEngine::updateNova() {
if (nova_folder == "nova3") { if (nova_folder == "nova3") {
filePath = search_dir.absoluteFilePath("sgmllib3.py"); filePath = search_dir.absoluteFilePath("sgmllib3.py");
if(QFile::exists(filePath)){ if (QFile::exists(filePath)){
QFile::remove(filePath); QFile::remove(filePath);
QFile::remove(filePath+"c"); QFile::remove(filePath+"c");
} }
@ -551,14 +551,14 @@ void SearchEngine::updateNova() {
QDir destDir(QDir(misc::searchEngineLocation()).absoluteFilePath("engines")); QDir destDir(QDir(misc::searchEngineLocation()).absoluteFilePath("engines"));
QDir shipped_subDir(":/"+nova_folder+"/engines/"); QDir shipped_subDir(":/"+nova_folder+"/engines/");
QStringList files = shipped_subDir.entryList(); QStringList files = shipped_subDir.entryList();
foreach(const QString &file, files){ foreach (const QString &file, files){
QString shipped_file = shipped_subDir.absoluteFilePath(file); QString shipped_file = shipped_subDir.absoluteFilePath(file);
// Copy python classes // Copy python classes
if(file.endsWith(".py")) { if (file.endsWith(".py")) {
const QString dest_file = destDir.absoluteFilePath(file); 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)); 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)); qDebug("Removing old %s", qPrintable(dest_file));
QFile::remove(dest_file); QFile::remove(dest_file);
QFile::remove(dest_file+"c"); QFile::remove(dest_file+"c");
@ -568,8 +568,8 @@ void SearchEngine::updateNova() {
} }
} else { } else {
// Copy icons // Copy icons
if(file.endsWith(".png")) { if (file.endsWith(".png")) {
if(!QFile::exists(destDir.absoluteFilePath(file))) { if (!QFile::exists(destDir.absoluteFilePath(file))) {
QFile::copy(shipped_file, destDir.absoluteFilePath(file)); QFile::copy(shipped_file, destDir.absoluteFilePath(file));
} }
} }
@ -581,32 +581,32 @@ void SearchEngine::updateNova() {
// Search can be finished for 3 reasons : // Search can be finished for 3 reasons :
// Error | Stopped by user | Finished normally // Error | Stopped by user | Finished normally
void SearchEngine::searchFinished(int exitcode,QProcess::ExitStatus){ void SearchEngine::searchFinished(int exitcode,QProcess::ExitStatus){
if(searchTimeout->isActive()) { if (searchTimeout->isActive()) {
searchTimeout->stop(); searchTimeout->stop();
} }
QIniSettings settings("qBittorrent", "qBittorrent"); QIniSettings settings("qBittorrent", "qBittorrent");
bool useNotificationBalloons = settings.value("Preferences/General/NotificationBaloons", true).toBool(); 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")); mp_mainWindow->showNotificationBaloon(tr("Search Engine"), tr("Search has finished"));
} }
if(exitcode){ if (exitcode){
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
search_status->setText(tr("Search aborted")); search_status->setText(tr("Search aborted"));
#else #else
search_status->setText(tr("An error occured during search...")); search_status->setText(tr("An error occured during search..."));
#endif #endif
}else{ }else{
if(search_stopped){ if (search_stopped){
search_status->setText(tr("Search aborted")); search_status->setText(tr("Search aborted"));
}else{ }else{
if(no_search_results){ if (no_search_results){
search_status->setText(tr("Search returned no results")); search_status->setText(tr("Search returned no results"));
}else{ }else{
search_status->setText(tr("Search has finished")); search_status->setText(tr("Search has finished"));
} }
} }
} }
if(currentSearchTab) if (currentSearchTab)
currentSearchTab->getCurrentLabel()->setText(tr("Results", "i.e: Search results")+QString::fromUtf8(" <i>(")+QString::number(nb_search_results)+QString::fromUtf8(")</i>:")); currentSearchTab->getCurrentLabel()->setText(tr("Results", "i.e: Search results")+QString::fromUtf8(" <i>(")+QString::number(nb_search_results)+QString::fromUtf8(")</i>:"));
search_button->setText("Search"); search_button->setText("Search");
} }
@ -615,11 +615,11 @@ void SearchEngine::searchFinished(int exitcode,QProcess::ExitStatus){
// Line is in the following form : // Line is in the following form :
// file url | file name | file size | nb seeds | nb leechers | Search engine url // file url | file name | file size | nb seeds | nb leechers | Search engine url
void SearchEngine::appendSearchResult(const QString &line){ void SearchEngine::appendSearchResult(const QString &line){
if(!currentSearchTab) { if (!currentSearchTab) {
if(searchProcess->state() != QProcess::NotRunning){ if (searchProcess->state() != QProcess::NotRunning){
searchProcess->terminate(); searchProcess->terminate();
} }
if(searchTimeout->isActive()) { if (searchTimeout->isActive()) {
searchTimeout->stop(); searchTimeout->stop();
} }
search_stopped = true; search_stopped = true;
@ -627,7 +627,7 @@ void SearchEngine::appendSearchResult(const QString &line){
} }
const QStringList parts = line.split("|"); const QStringList parts = line.split("|");
const int nb_fields = parts.size(); 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; return;
} }
Q_ASSERT(currentSearchTab); 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 cur_model->setData(cur_model->index(row, SIZE), parts.at(PL_SIZE).trimmed().toLongLong()); // Size
bool ok = false; bool ok = false;
qlonglong nb_seeders = parts.at(PL_SEEDS).trimmed().toLongLong(&ok); 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 cur_model->setData(cur_model->index(row, SEEDS), tr("Unknown")); // Seeders
} else { } else {
cur_model->setData(cur_model->index(row, SEEDS), nb_seeders); // Seeders cur_model->setData(cur_model->index(row, SEEDS), nb_seeders); // Seeders
} }
qlonglong nb_leechers = parts.at(PL_LEECHS).trimmed().toLongLong(&ok); 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 cur_model->setData(cur_model->index(row, LEECHS), tr("Unknown")); // Leechers
} else { } else {
cur_model->setData(cur_model->index(row, LEECHS), nb_leechers); // Leechers 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 cur_model->setData(cur_model->index(row, ENGINE_URL), parts.at(PL_ENGINE_URL).trimmed()); // Engine URL
// Description Link // 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()); cur_model->setData(cur_model->index(row, DESC_LINK), parts.at(PL_DESC_LINK).trimmed());
no_search_results = false; no_search_results = false;
@ -667,19 +667,19 @@ void SearchEngine::appendSearchResult(const QString &line){
#if QT_VERSION >= 0x040500 #if QT_VERSION >= 0x040500
void SearchEngine::closeTab(int index) { void SearchEngine::closeTab(int index) {
if(index == tabWidget->indexOf(currentSearchTab)) { if (index == tabWidget->indexOf(currentSearchTab)) {
qDebug("Deleted current search Tab"); qDebug("Deleted current search Tab");
if(searchProcess->state() != QProcess::NotRunning){ if (searchProcess->state() != QProcess::NotRunning){
searchProcess->terminate(); searchProcess->terminate();
} }
if(searchTimeout->isActive()) { if (searchTimeout->isActive()) {
searchTimeout->stop(); searchTimeout->stop();
} }
search_stopped = true; search_stopped = true;
currentSearchTab = 0; currentSearchTab = 0;
} }
delete all_tab.takeAt(index); delete all_tab.takeAt(index);
if(!all_tab.size()) { if (!all_tab.size()) {
download_button->setEnabled(false); download_button->setEnabled(false);
goToDescBtn->setEnabled(false); goToDescBtn->setEnabled(false);
} }
@ -687,22 +687,22 @@ void SearchEngine::closeTab(int index) {
#else #else
// Clear search results list // Clear search results list
void SearchEngine::closeTab_button_clicked(){ void SearchEngine::closeTab_button_clicked(){
if(all_tab.size()) { if (all_tab.size()) {
qDebug("currentTab rank: %d", tabWidget->currentIndex()); qDebug("currentTab rank: %d", tabWidget->currentIndex());
qDebug("currentSearchTab rank: %d", tabWidget->indexOf(currentSearchTab)); qDebug("currentSearchTab rank: %d", tabWidget->indexOf(currentSearchTab));
if(tabWidget->currentIndex() == tabWidget->indexOf(currentSearchTab)) { if (tabWidget->currentIndex() == tabWidget->indexOf(currentSearchTab)) {
qDebug("Deleted current search Tab"); qDebug("Deleted current search Tab");
if(searchProcess->state() != QProcess::NotRunning){ if (searchProcess->state() != QProcess::NotRunning){
searchProcess->terminate(); searchProcess->terminate();
} }
if(searchTimeout->isActive()) { if (searchTimeout->isActive()) {
searchTimeout->stop(); searchTimeout->stop();
} }
search_stopped = true; search_stopped = true;
currentSearchTab = 0; currentSearchTab = 0;
} }
delete all_tab.takeAt(tabWidget->currentIndex()); delete all_tab.takeAt(tabWidget->currentIndex());
if(!all_tab.size()) { if (!all_tab.size()) {
closeTab_button->setEnabled(false); closeTab_button->setEnabled(false);
download_button->setEnabled(false); download_button->setEnabled(false);
} }
@ -714,8 +714,8 @@ void SearchEngine::closeTab_button_clicked(){
void SearchEngine::on_download_button_clicked(){ void SearchEngine::on_download_button_clicked(){
//QModelIndexList selectedIndexes = currentSearchTab->getCurrentTreeView()->selectionModel()->selectedIndexes(); //QModelIndexList selectedIndexes = currentSearchTab->getCurrentTreeView()->selectionModel()->selectedIndexes();
QModelIndexList selectedIndexes = all_tab.at(tabWidget->currentIndex())->getCurrentTreeView()->selectionModel()->selectedIndexes(); QModelIndexList selectedIndexes = all_tab.at(tabWidget->currentIndex())->getCurrentTreeView()->selectionModel()->selectedIndexes();
foreach(const QModelIndex &index, selectedIndexes){ foreach (const QModelIndex &index, selectedIndexes){
if(index.column() == NAME){ if (index.column() == NAME){
// Get Item url // Get Item url
QSortFilterProxyModel* model = all_tab.at(tabWidget->currentIndex())->getCurrentSearchListProxy(); QSortFilterProxyModel* model = all_tab.at(tabWidget->currentIndex())->getCurrentSearchListProxy();
QString torrent_url = model->data(model->index(index.row(), URL_COLUMN)).toString(); 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() void SearchEngine::on_goToDescBtn_clicked()
{ {
QModelIndexList selectedIndexes = all_tab.at(tabWidget->currentIndex())->getCurrentTreeView()->selectionModel()->selectedIndexes(); QModelIndexList selectedIndexes = all_tab.at(tabWidget->currentIndex())->getCurrentTreeView()->selectionModel()->selectedIndexes();
foreach(const QModelIndex &index, selectedIndexes){ foreach (const QModelIndex &index, selectedIndexes){
if(index.column() == NAME) { if (index.column() == NAME) {
QSortFilterProxyModel* model = all_tab.at(tabWidget->currentIndex())->getCurrentSearchListProxy(); QSortFilterProxyModel* model = all_tab.at(tabWidget->currentIndex())->getCurrentSearchListProxy();
const QString desc_url = model->data(model->index(index.row(), DESC_LINK)).toString(); 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())); QDesktopServices::openUrl(QUrl::fromEncoded(desc_url.toUtf8()));
} }
} }

View file

@ -65,17 +65,17 @@ public:
static qreal getPluginVersion(QString filePath) { static qreal getPluginVersion(QString filePath) {
QFile plugin(filePath); QFile plugin(filePath);
if(!plugin.exists()){ if (!plugin.exists()){
qDebug("%s plugin does not exist, returning 0.0", qPrintable(filePath)); qDebug("%s plugin does not exist, returning 0.0", qPrintable(filePath));
return 0.0; return 0.0;
} }
if(!plugin.open(QIODevice::ReadOnly | QIODevice::Text)){ if (!plugin.open(QIODevice::ReadOnly | QIODevice::Text)){
return 0.0; return 0.0;
} }
qreal version = 0.0; qreal version = 0.0;
while (!plugin.atEnd()){ while (!plugin.atEnd()){
QByteArray line = plugin.readLine(); QByteArray line = plugin.readLine();
if(line.startsWith("#VERSION: ")){ if (line.startsWith("#VERSION: ")){
line = line.split(' ').last().trimmed(); line = line.split(' ').last().trimmed();
version = line.toFloat(); version = line.toFloat();
qDebug("plugin %s version: %.2f", qPrintable(filePath), version); qDebug("plugin %s version: %.2f", qPrintable(filePath), version);

View file

@ -77,7 +77,7 @@ SearchTab::SearchTab(SearchEngine *parent) : QWidget(), parent(parent)
connect(resultsBrowser, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(downloadSelectedItem(const QModelIndex&))); connect(resultsBrowser, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(downloadSelectedItem(const QModelIndex&)));
// Load last columns width for search results list // Load last columns width for search results list
if(!loadColWidthResultsList()){ if (!loadColWidthResultsList()){
resultsBrowser->header()->resizeSection(0, 275); resultsBrowser->header()->resizeSection(0, 275);
} }
@ -108,13 +108,13 @@ QHeaderView* SearchTab::header() const {
bool SearchTab::loadColWidthResultsList() { bool SearchTab::loadColWidthResultsList() {
QIniSettings settings("qBittorrent", "qBittorrent"); QIniSettings settings("qBittorrent", "qBittorrent");
QString line = settings.value("SearchResultsColsWidth", QString()).toString(); QString line = settings.value("SearchResultsColsWidth", QString()).toString();
if(line.isEmpty()) if (line.isEmpty())
return false; return false;
QStringList width_list = line.split(' '); QStringList width_list = line.split(' ');
if(width_list.size() < SearchListModel->columnCount()) if (width_list.size() < SearchListModel->columnCount())
return false; return false;
unsigned int listSize = width_list.size(); unsigned int listSize = width_list.size();
for(unsigned int i=0; i<listSize; ++i){ for (unsigned int i=0; i<listSize; ++i){
resultsBrowser->header()->resizeSection(i, width_list.at(i).toInt()); resultsBrowser->header()->resizeSection(i, width_list.at(i).toInt());
} }
return true; return true;
@ -143,7 +143,7 @@ QStandardItemModel* SearchTab::getCurrentSearchListModel() const
// Set the color of a row in data model // Set the color of a row in data model
void SearchTab::setRowColor(int row, QString color){ void SearchTab::setRowColor(int row, QString color){
proxyModel->setDynamicSortFilter(false); proxyModel->setDynamicSortFilter(false);
for(int i=0; i<proxyModel->columnCount(); ++i){ for (int i=0; i<proxyModel->columnCount(); ++i){
proxyModel->setData(proxyModel->index(row, i), QVariant(QColor(color)), Qt::ForegroundRole); proxyModel->setData(proxyModel->index(row, i), QVariant(QColor(color)), Qt::ForegroundRole);
} }
proxyModel->setDynamicSortFilter(true); proxyModel->setDynamicSortFilter(true);

View file

@ -89,7 +89,7 @@ public:
// Save to Hard disk // Save to Hard disk
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
QStringList disabled_engines = settings.value(QString::fromUtf8("SearchEngines/disabledEngines"), QStringList()).toStringList(); QStringList disabled_engines = settings.value(QString::fromUtf8("SearchEngines/disabledEngines"), QStringList()).toStringList();
if(enabled) { if (enabled) {
disabled_engines.removeAll(name); disabled_engines.removeAll(name);
} else { } else {
disabled_engines.append(name); disabled_engines.append(name);
@ -106,7 +106,7 @@ signals:
public: public:
SupportedEngines(bool has_python = true) { SupportedEngines(bool has_python = true) {
if(has_python) if (has_python)
update(); update();
} }
@ -116,8 +116,8 @@ public:
QStringList enginesEnabled() const { QStringList enginesEnabled() const {
QStringList engines; QStringList engines;
foreach(const SupportedEngine *engine, values()) { foreach (const SupportedEngine *engine, values()) {
if(engine->isEnabled()) if (engine->isEnabled())
engines << engine->getName(); engines << engine->getName();
} }
return engines; return engines;
@ -125,12 +125,12 @@ public:
QStringList supportedCategories() const { QStringList supportedCategories() const {
QStringList supported_cat; QStringList supported_cat;
foreach(const SupportedEngine *engine, values()) { foreach (const SupportedEngine *engine, values()) {
if(engine->isEnabled()) { if (engine->isEnabled()) {
const QStringList &s = engine->getSupportedCategories(); const QStringList &s = engine->getSupportedCategories();
foreach(QString cat, s) { foreach (QString cat, s) {
cat = cat.trimmed(); cat = cat.trimmed();
if(!cat.isEmpty() && !supported_cat.contains(cat)) if (!cat.isEmpty() && !supported_cat.contains(cat))
supported_cat << cat; supported_cat << cat;
} }
} }
@ -150,21 +150,21 @@ public slots:
nova.waitForFinished(); nova.waitForFinished();
QString capabilities = QString(nova.readAll()); QString capabilities = QString(nova.readAll());
QDomDocument xml_doc; 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 << "Could not parse Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data() << std::endl;
std::cerr << "Error: " << nova.readAllStandardError().constData() << std::endl; std::cerr << "Error: " << nova.readAllStandardError().constData() << std::endl;
return; return;
} }
QDomElement root = xml_doc.documentElement(); 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; std::cout << "Invalid XML file for Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data() << std::endl;
return; 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(); QDomElement engine_elem = engine_node.toElement();
if(!engine_elem.isNull()) { if (!engine_elem.isNull()) {
SupportedEngine *s = new SupportedEngine(engine_elem); SupportedEngine *s = new SupportedEngine(engine_elem);
if(this->contains(s->getName())) { if (this->contains(s->getName())) {
// Already in the list // Already in the list
delete s; delete s;
} else { } else {

View file

@ -122,14 +122,14 @@ void Smtp::sendMail(const QString &from, const QString &to, const QString &subje
this->from = from; this->from = from;
rcpt = to; rcpt = to;
// Authentication // Authentication
if(pref.getMailNotificationSMTPAuth()) { if (pref.getMailNotificationSMTPAuth()) {
username = pref.getMailNotificationSMTPUsername(); username = pref.getMailNotificationSMTPUsername();
password = pref.getMailNotificationSMTPPassword(); password = pref.getMailNotificationSMTPPassword();
} }
// Connect to SMTP server // Connect to SMTP server
#ifndef QT_NO_OPENSSL #ifndef QT_NO_OPENSSL
if(pref.getMailNotificationSMTPSSL()) { if (pref.getMailNotificationSMTPSSL()) {
socket->connectToHostEncrypted(pref.getMailNotificationSMTP(), DEFAULT_PORT_SSL); socket->connectToHostEncrypted(pref.getMailNotificationSMTP(), DEFAULT_PORT_SSL);
use_ssl = true; use_ssl = true;
} else { } else {
@ -158,7 +158,7 @@ void Smtp::readyRead()
switch(state) { switch(state) {
case Init: { case Init: {
if(code[0] == '2') { if (code[0] == '2') {
// Connection was successful // Connection was successful
ehlo(); ehlo();
} else { } else {
@ -257,7 +257,7 @@ QByteArray Smtp::encode_mime_header(const QString& key, const QString& value, QT
if (!prefix.isEmpty()) line += prefix; if (!prefix.isEmpty()) line += prefix;
if (!value.contains("=?") && latin1->canEncode(value)) { if (!value.contains("=?") && latin1->canEncode(value)) {
bool firstWord = true; bool firstWord = true;
foreach(const QByteArray& word, value.toAscii().split(' ')) { foreach (const QByteArray& word, value.toAscii().split(' ')) {
if (line.size() > 78) { if (line.size() > 78) {
rv = rv + line + "\r\n"; rv = rv + line + "\r\n";
line.clear(); line.clear();
@ -292,7 +292,7 @@ QByteArray Smtp::encode_mime_header(const QString& key, const QString& value, QT
void Smtp::ehlo() void Smtp::ehlo()
{ {
QByteArray address = "127.0.0.1"; 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) if (addr == QHostAddress::LocalHost || addr == QHostAddress::LocalHostIPv6)
continue; continue;
@ -309,7 +309,7 @@ void Smtp::parseEhloResponse(const QByteArray& code, bool continued, const QStri
{ {
if (code != "250") { if (code != "250") {
// Error // Error
if(state == EhloSent) { if (state == EhloSent) {
// try to send HELO instead of EHLO // try to send HELO instead of EHLO
qDebug() << "EHLO failed, trying HELO instead..."; qDebug() << "EHLO failed, trying HELO instead...";
socket->write("helo\r\n"); socket->write("helo\r\n");

View file

@ -60,10 +60,10 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg {
dlg.setWindowTitle(title); dlg.setWindowTitle(title);
dlg.setMaxValue(max_value/1024.); dlg.setMaxValue(max_value/1024.);
dlg.setDefaultValue(default_value/1024.); dlg.setDefaultValue(default_value/1024.);
if(dlg.exec() == QDialog::Accepted) { if (dlg.exec() == QDialog::Accepted) {
*ok = true; *ok = true;
int val = dlg.getSpeedLimit(); int val = dlg.getSpeedLimit();
if(val <= 0) if (val <= 0)
return -1; return -1;
return val*1024; return val*1024;
} else { } else {
@ -75,7 +75,7 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg {
protected slots: protected slots:
void updateSpinValue(int val) const { void updateSpinValue(int val) const {
qDebug("Called updateSpinValue with %d", val); qDebug("Called updateSpinValue with %d", val);
if(val <= 0){ if (val <= 0){
spinBandwidth->setValue(0); spinBandwidth->setValue(0);
spinBandwidth->setSpecialValueText(QString::fromUtf8("")); spinBandwidth->setSpecialValueText(QString::fromUtf8(""));
spinBandwidth->setSuffix(QString::fromUtf8("")); spinBandwidth->setSuffix(QString::fromUtf8(""));
@ -86,7 +86,7 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg {
} }
void updateSliderValue(int val) const { void updateSliderValue(int val) const {
if(val <= 0) { if (val <= 0) {
spinBandwidth->setValue(0); spinBandwidth->setValue(0);
spinBandwidth->setSpecialValueText(QString::fromUtf8("")); spinBandwidth->setSpecialValueText(QString::fromUtf8(""));
spinBandwidth->setSuffix(QString::fromUtf8("")); spinBandwidth->setSuffix(QString::fromUtf8(""));
@ -96,21 +96,21 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg {
long getSpeedLimit() const { long getSpeedLimit() const {
long val = bandwidthSlider->value(); long val = bandwidthSlider->value();
if(val > 0) if (val > 0)
return val; return val;
return -1; return -1;
} }
void setMaxValue(long val) const { void setMaxValue(long val) const {
if(val > 0) { if (val > 0) {
bandwidthSlider->setMaximum(val); bandwidthSlider->setMaximum(val);
spinBandwidth->setMaximum(val); spinBandwidth->setMaximum(val);
} }
} }
void setDefaultValue(long val) const { void setDefaultValue(long val) const {
if(val < 0) val = 0; if (val < 0) val = 0;
if(val > bandwidthSlider->maximum()) val = bandwidthSlider->maximum(); if (val > bandwidthSlider->maximum()) val = bandwidthSlider->maximum();
bandwidthSlider->setValue(val); bandwidthSlider->setValue(val);
updateSpinValue(val); updateSpinValue(val);
} }

View file

@ -167,11 +167,11 @@ public slots:
void refreshStatusBar() { void refreshStatusBar() {
// Update connection status // Update connection status
const libtorrent::session_status sessionStatus = QBtSession::instance()->getSessionStatus(); 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->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/disconnected.png")));
connecStatusLblIcon->setToolTip(QString::fromUtf8("<b>")+tr("Connection Status:")+QString::fromUtf8("</b><br>")+tr("Offline. This usually means that qBittorrent failed to listen on the selected port for incoming connections.")); connecStatusLblIcon->setToolTip(QString::fromUtf8("<b>")+tr("Connection Status:")+QString::fromUtf8("</b><br>")+tr("Offline. This usually means that qBittorrent failed to listen on the selected port for incoming connections."));
} else { } else {
if(sessionStatus.has_incoming_connections) { if (sessionStatus.has_incoming_connections) {
// Connection OK // Connection OK
connecStatusLblIcon->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/connected.png"))); connecStatusLblIcon->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/connected.png")));
connecStatusLblIcon->setToolTip(QString::fromUtf8("<b>")+tr("Connection Status:")+QString::fromUtf8("</b><br>")+tr("Online")); connecStatusLblIcon->setToolTip(QString::fromUtf8("<b>")+tr("Connection Status:")+QString::fromUtf8("</b><br>")+tr("Online"));
@ -181,7 +181,7 @@ public slots:
} }
} }
// Update Number of DHT nodes // Update Number of DHT nodes
if(QBtSession::instance()->isDHTEnabled()) { if (QBtSession::instance()->isDHTEnabled()) {
DHTLbl->setVisible(true); DHTLbl->setVisible(true);
//statusSep1->setVisible(true); //statusSep1->setVisible(true);
DHTLbl->setText(tr("DHT: %1 nodes").arg(QString::number(sessionStatus.dht_nodes))); DHTLbl->setText(tr("DHT: %1 nodes").arg(QString::number(sessionStatus.dht_nodes)));
@ -195,7 +195,7 @@ public slots:
} }
void updateAltSpeedsBtn(bool alternative) { void updateAltSpeedsBtn(bool alternative) {
if(alternative) { if (alternative) {
altSpeedsBtn->setIcon(QIcon(":/Icons/slow.png")); altSpeedsBtn->setIcon(QIcon(":/Icons/slow.png"));
altSpeedsBtn->setToolTip(tr("Click to switch to regular speed limits")); altSpeedsBtn->setToolTip(tr("Click to switch to regular speed limits"));
altSpeedsBtn->setDown(true); altSpeedsBtn->setDown(true);
@ -218,18 +218,18 @@ public slots:
int cur_limit = QBtSession::instance()->getSession()->download_rate_limit(); int cur_limit = QBtSession::instance()->getSession()->download_rate_limit();
#endif #endif
long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), cur_limit); long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), cur_limit);
if(ok) { if (ok) {
Preferences pref; Preferences pref;
bool alt = pref.isAltBandwidthEnabled(); bool alt = pref.isAltBandwidthEnabled();
if(new_limit <= 0) { if (new_limit <= 0) {
qDebug("Setting global download rate limit to Unlimited"); qDebug("Setting global download rate limit to Unlimited");
QBtSession::instance()->setDownloadRateLimit(-1); QBtSession::instance()->setDownloadRateLimit(-1);
if(!alt) if (!alt)
pref.setGlobalDownloadLimit(-1); pref.setGlobalDownloadLimit(-1);
} else { } else {
qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.); qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.);
QBtSession::instance()->setDownloadRateLimit(new_limit); QBtSession::instance()->setDownloadRateLimit(new_limit);
if(!alt) if (!alt)
pref.setGlobalDownloadLimit(new_limit/1024.); pref.setGlobalDownloadLimit(new_limit/1024.);
} }
} }
@ -243,18 +243,18 @@ public slots:
int cur_limit = QBtSession::instance()->getSession()->upload_rate_limit(); int cur_limit = QBtSession::instance()->getSession()->upload_rate_limit();
#endif #endif
long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), cur_limit); long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), cur_limit);
if(ok) { if (ok) {
Preferences pref; Preferences pref;
bool alt = pref.isAltBandwidthEnabled(); bool alt = pref.isAltBandwidthEnabled();
if(new_limit <= 0) { if (new_limit <= 0) {
qDebug("Setting global upload rate limit to Unlimited"); qDebug("Setting global upload rate limit to Unlimited");
QBtSession::instance()->setUploadRateLimit(-1); QBtSession::instance()->setUploadRateLimit(-1);
if(!alt) if (!alt)
Preferences().setGlobalUploadLimit(-1); Preferences().setGlobalUploadLimit(-1);
} else { } else {
qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.); qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.);
QBtSession::instance()->setUploadRateLimit(new_limit); QBtSession::instance()->setUploadRateLimit(new_limit);
if(!alt) if (!alt)
Preferences().setGlobalUploadLimit(new_limit/1024.); Preferences().setGlobalUploadLimit(new_limit/1024.);
} }
} }

View file

@ -91,7 +91,7 @@ torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) :
appendLabelToSavePath = pref.appendTorrentLabel(); appendLabelToSavePath = pref.appendTorrentLabel();
QString display_path = defaultSavePath.replace("\\", "/"); QString display_path = defaultSavePath.replace("\\", "/");
if(!display_path.endsWith("/")) if (!display_path.endsWith("/"))
display_path += "/"; display_path += "/";
path_history << display_path; path_history << display_path;
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
@ -99,7 +99,7 @@ torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) :
#endif #endif
savePathTxt->addItem(display_path); savePathTxt->addItem(display_path);
if(pref.addTorrentsInPause()) { if (pref.addTorrentsInPause()) {
addInPause->setChecked(true); addInPause->setChecked(true);
//addInPause->setEnabled(false); //addInPause->setEnabled(false);
} }
@ -108,7 +108,7 @@ torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) :
settings.beginGroup(QString::fromUtf8("TransferListFilters")); settings.beginGroup(QString::fromUtf8("TransferListFilters"));
const QStringList customLabels = settings.value("customLabels", QStringList()).toStringList(); const QStringList customLabels = settings.value("customLabels", QStringList()).toStringList();
comboLabel->addItem(""); comboLabel->addItem("");
foreach(const QString& label, customLabels) { foreach (const QString& label, customLabels) {
comboLabel->addItem(label); comboLabel->addItem(label);
} }
@ -142,7 +142,7 @@ void torrentAdditionDialog::readSettings() {
} }
} }
if (m_showContentList) { 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..."; qDebug() << Q_FUNC_INFO << "First executation, resize first section to 400px...";
torrentContentList->header()->resizeSection(0, 400); // Default torrentContentList->header()->resizeSection(0, 400); // Default
} }
@ -162,16 +162,16 @@ void torrentAdditionDialog::limitDialogWidth() {
int scrn = 0; int scrn = 0;
const QWidget *w = this->window(); const QWidget *w = this->window();
if(w) if (w)
scrn = QApplication::desktop()->screenNumber(w); scrn = QApplication::desktop()->screenNumber(w);
else if(QApplication::desktop()->isVirtualDesktop()) else if (QApplication::desktop()->isVirtualDesktop())
scrn = QApplication::desktop()->screenNumber(QCursor::pos()); scrn = QApplication::desktop()->screenNumber(QCursor::pos());
else else
scrn = QApplication::desktop()->screenNumber(this); scrn = QApplication::desktop()->screenNumber(this);
QRect desk(QApplication::desktop()->availableGeometry(scrn)); QRect desk(QApplication::desktop()->availableGeometry(scrn));
int max_width = desk.width(); int max_width = desk.width();
if(max_width > 0) if (max_width > 0)
setMaximumWidth(max_width); setMaximumWidth(max_width);
} }
@ -179,12 +179,12 @@ void torrentAdditionDialog::hideTorrentContent() {
// Disable useless widgets // Disable useless widgets
torrentContentList->setVisible(false); torrentContentList->setVisible(false);
//torrentContentLbl->setVisible(false); //torrentContentLbl->setVisible(false);
for(int i=0; i<selectionBtnsLayout->count(); ++i) { for (int i=0; i<selectionBtnsLayout->count(); ++i) {
if(selectionBtnsLayout->itemAt(i)->widget()) if (selectionBtnsLayout->itemAt(i)->widget())
selectionBtnsLayout->itemAt(i)->widget()->setVisible(false); selectionBtnsLayout->itemAt(i)->widget()->setVisible(false);
} }
for(int i=0; i<contentFilterLayout->count(); ++i) { for (int i=0; i<contentFilterLayout->count(); ++i) {
if(contentFilterLayout->itemAt(i)->widget()) if (contentFilterLayout->itemAt(i)->widget())
contentFilterLayout->itemAt(i)->widget()->setVisible(false); contentFilterLayout->itemAt(i)->widget()->setVisible(false);
} }
contentFilterLayout->update(); contentFilterLayout->update();
@ -204,13 +204,13 @@ void torrentAdditionDialog::showLoadMagnetURI(QString magnet_uri) {
// Get torrent hash // Get torrent hash
hash = misc::magnetUriToHash(magnet_uri); 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")); QBtSession::instance()->addConsoleMessage(tr("Unable to decode magnet link:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red"));
return; return;
} }
// Set torrent name // Set torrent name
fileName = misc::magnetUriToName(magnet_uri); fileName = misc::magnetUriToName(magnet_uri);
if(fileName.isEmpty()) { if (fileName.isEmpty()) {
fileName = tr("Magnet Link"); fileName = tr("Magnet Link");
} }
fileNameLbl->setText(QString::fromUtf8("<center><b>")+fileName+QString::fromUtf8("</b></center>")); fileNameLbl->setText(QString::fromUtf8("<center><b>")+fileName+QString::fromUtf8("</b></center>"));
@ -234,10 +234,10 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
is_magnet = false; is_magnet = false;
// This is an URL to a local file, switch to local path // 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(); filePath = QUrl::fromEncoded(filePath.toLocal8Bit()).toLocalFile();
if(!QFile::exists(filePath)) { if (!QFile::exists(filePath)) {
close(); close();
return; return;
} }
@ -249,11 +249,11 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
// Getting torrent file informations // Getting torrent file informations
try { try {
t = new torrent_info(filePath.toUtf8().data()); t = new torrent_info(filePath.toUtf8().data());
if(!t->is_valid()) if (!t->is_valid())
throw std::exception(); throw std::exception();
} catch(std::exception&) { } catch(std::exception&) {
qDebug("Caught error loading torrent"); 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")); QBtSession::instance()->addConsoleMessage(tr("Unable to decode torrent file:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red"));
QFile::remove(filePath); QFile::remove(filePath);
}else{ }else{
@ -263,7 +263,7 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
return; return;
} }
nbFiles = t->num_files(); nbFiles = t->num_files();
if(nbFiles == 0) { if (nbFiles == 0) {
// Empty torrent file!? // Empty torrent file!?
close(); close();
return; return;
@ -278,18 +278,18 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
hash = misc::toQString(t->info_hash()); hash = misc::toQString(t->info_hash());
// Use left() to remove .old extension // Use left() to remove .old extension
QString newFileName; QString newFileName;
if(fileName.endsWith(QString::fromUtf8(".old"))){ if (fileName.endsWith(QString::fromUtf8(".old"))){
newFileName = fileName.left(fileName.size()-4); newFileName = fileName.left(fileName.size()-4);
}else{ }else{
newFileName = fileName; newFileName = fileName;
} }
fileNameLbl->setText(QString::fromUtf8("<center><b>")+newFileName+QString::fromUtf8("</b></center>")); fileNameLbl->setText(QString::fromUtf8("<center><b>")+newFileName+QString::fromUtf8("</b></center>"));
if(t->num_files() > 1) { if (t->num_files() > 1) {
// List files in torrent // List files in torrent
PropListModel->model()->setupModelData(*t); PropListModel->model()->setupModelData(*t);
connect(PropDelegate, SIGNAL(filteredFilesChanged()), this, SLOT(updateDiskSpaceLabels())); connect(PropDelegate, SIGNAL(filteredFilesChanged()), this, SLOT(updateDiskSpaceLabels()));
// Loads files path in the torrent // Loads files path in the torrent
for(uint i=0; i<nbFiles; ++i) { for (uint i=0; i<nbFiles; ++i) {
#if LIBTORRENT_VERSION_MINOR >= 16 #if LIBTORRENT_VERSION_MINOR >= 16
files_path << misc::toQStringU(fs.file_path(t->file_at(i))); files_path << misc::toQStringU(fs.file_path(t->file_at(i)));
#else #else
@ -310,13 +310,13 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
save_path.replace("/", "\\"); save_path.replace("/", "\\");
#endif #endif
if(!save_path.endsWith(QDir::separator())) if (!save_path.endsWith(QDir::separator()))
save_path += QDir::separator(); save_path += QDir::separator();
// If the torrent has a root folder, append it to the save path // 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; save_path += root_folder;
} }
if(nbFiles == 1) { if (nbFiles == 1) {
// single file torrent // single file torrent
#if LIBTORRENT_VERSION_MINOR >= 16 #if LIBTORRENT_VERSION_MINOR >= 16
QString single_file_relpath = misc::toQStringU(fs.file_path(t->file_at(0))); 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(); updateDiskSpaceLabels();
// Hide useless widgets // Hide useless widgets
if(t->num_files() <= 1) if (t->num_files() <= 1)
hideTorrentContent(); hideTorrentContent();
// Remember dialog geometry // Remember dialog geometry
@ -352,7 +352,7 @@ void torrentAdditionDialog::displayContentListMenu(const QPoint&) {
QMenu myFilesLlistMenu; QMenu myFilesLlistMenu;
const QModelIndexList selectedRows = torrentContentList->selectionModel()->selectedRows(0); const QModelIndexList selectedRows = torrentContentList->selectionModel()->selectedRows(0);
QAction *actRename = 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...")); actRename = myFilesLlistMenu.addAction(IconProvider::instance()->getIcon("edit-rename"), tr("Rename..."));
myFilesLlistMenu.addSeparator(); myFilesLlistMenu.addSeparator();
} }
@ -365,24 +365,24 @@ void torrentAdditionDialog::displayContentListMenu(const QPoint&) {
myFilesLlistMenu.addMenu(&subMenu); myFilesLlistMenu.addMenu(&subMenu);
// Call menu // Call menu
QAction *act = myFilesLlistMenu.exec(QCursor::pos()); QAction *act = myFilesLlistMenu.exec(QCursor::pos());
if(act) { if (act) {
if(act == actRename) { if (act == actRename) {
renameSelectedFile(); renameSelectedFile();
} else { } else {
int prio = 1; int prio = 1;
if(act == actionHigh) { if (act == actionHigh) {
prio = prio::HIGH; prio = prio::HIGH;
} else { } else {
if(act == actionMaximum) { if (act == actionMaximum) {
prio = prio::MAXIMUM; prio = prio::MAXIMUM;
} else { } else {
if(act == actionNot_downloaded) { if (act == actionNot_downloaded) {
prio = prio::IGNORED; prio = prio::IGNORED;
} }
} }
} }
qDebug("Setting files priority"); 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()); qDebug("Setting priority(%d) for file at row %d", prio, index.row());
PropListModel->setData(PropListModel->index(index.row(), PRIORITY, index.parent()), prio); PropListModel->setData(PropListModel->index(index.row(), PRIORITY, index.parent()), prio);
} }
@ -401,13 +401,13 @@ void torrentAdditionDialog::renameSelectedFile() {
tr("New name:"), QLineEdit::Normal, tr("New name:"), QLineEdit::Normal,
index.data().toString(), &ok); index.data().toString(), &ok);
if (ok && !new_name_last.isEmpty()) { 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"), QMessageBox::warning(this, tr("The file could not be renamed"),
tr("This file name contains forbidden characters, please choose a different one."), tr("This file name contains forbidden characters, please choose a different one."),
QMessageBox::Ok); QMessageBox::Ok);
return; return;
} }
if(PropListModel->getType(index) == TorrentFileItem::TFILE) { if (PropListModel->getType(index) == TorrentFileItem::TFILE) {
// File renaming // File renaming
const uint file_index = PropListModel->getFileIndex(index); const uint file_index = PropListModel->getFileIndex(index);
QString old_name = files_path.at(file_index); QString old_name = files_path.at(file_index);
@ -417,19 +417,19 @@ void torrentAdditionDialog::renameSelectedFile() {
path_items.removeLast(); path_items.removeLast();
path_items << new_name_last; path_items << new_name_last;
QString new_name = path_items.join("/"); QString new_name = path_items.join("/");
if(old_name == new_name) { if (old_name == new_name) {
qDebug("Name did not change"); qDebug("Name did not change");
return; return;
} }
new_name = QDir::cleanPath(new_name); new_name = QDir::cleanPath(new_name);
qDebug("New name: %s", qPrintable(new_name)); qDebug("New name: %s", qPrintable(new_name));
// Check if that name is already used // Check if that name is already used
for(uint i=0; i<nbFiles; ++i) { for (uint i=0; i<nbFiles; ++i) {
if(i == file_index) continue; if (i == file_index) continue;
#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) #if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
if(files_path.at(i).compare(new_name, Qt::CaseSensitive) == 0) { if (files_path.at(i).compare(new_name, Qt::CaseSensitive) == 0) {
#else #else
if(files_path.at(i).compare(new_name, Qt::CaseInsensitive) == 0) { if (files_path.at(i).compare(new_name, Qt::CaseInsensitive) == 0) {
#endif #endif
// Display error message // Display error message
QMessageBox::warning(this, tr("The file could not be renamed"), QMessageBox::warning(this, tr("The file could not be renamed"),
@ -457,14 +457,14 @@ void torrentAdditionDialog::renameSelectedFile() {
path_items.removeLast(); path_items.removeLast();
path_items << new_name_last; path_items << new_name_last;
QString new_path = path_items.join("/"); QString new_path = path_items.join("/");
if(!new_path.endsWith("/")) new_path += "/"; if (!new_path.endsWith("/")) new_path += "/";
// Check for overwriting // Check for overwriting
for(uint i=0; i<nbFiles; ++i) { for (uint i=0; i<nbFiles; ++i) {
const QString &current_name = files_path.at(i); const QString &current_name = files_path.at(i);
#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) #if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
if(current_name.startsWith(new_path, Qt::CaseSensitive)) { if (current_name.startsWith(new_path, Qt::CaseSensitive)) {
#else #else
if(current_name.startsWith(new_path, Qt::CaseInsensitive)) { if (current_name.startsWith(new_path, Qt::CaseInsensitive)) {
#endif #endif
QMessageBox::warning(this, tr("The folder could not be renamed"), QMessageBox::warning(this, tr("The folder could not be renamed"),
tr("This name is already in use in this folder. Please use a different name."), tr("This name is already in use in this folder. Please use a different name."),
@ -473,9 +473,9 @@ void torrentAdditionDialog::renameSelectedFile() {
} }
} }
// Replace path in all files // Replace path in all files
for(uint i=0; i<nbFiles; ++i) { for (uint i=0; i<nbFiles; ++i) {
const QString &current_name = files_path.at(i); const QString &current_name = files_path.at(i);
if(current_name.startsWith(old_path)) { if (current_name.startsWith(old_path)) {
QString new_name = current_name; QString new_name = current_name;
new_name.replace(0, old_path.length(), new_path); new_name.replace(0, old_path.length(), new_path);
new_name = QDir::cleanPath(new_name); new_name = QDir::cleanPath(new_name);
@ -494,15 +494,15 @@ void torrentAdditionDialog::updateDiskSpaceLabels() {
qDebug("Updating disk space label..."); qDebug("Updating disk space label...");
const long long available = misc::freeDiskSpaceOnPath(misc::expandPath(savePathTxt->currentText())); const long long available = misc::freeDiskSpaceOnPath(misc::expandPath(savePathTxt->currentText()));
lbl_disk_space->setText(misc::friendlyUnit(available)); lbl_disk_space->setText(misc::friendlyUnit(available));
if(!is_magnet) { if (!is_magnet) {
// Determine torrent size // Determine torrent size
qulonglong torrent_size = 0; qulonglong torrent_size = 0;
if(t->num_files() > 1) { if (t->num_files() > 1) {
const unsigned int nbFiles = t->num_files(); const unsigned int nbFiles = t->num_files();
const std::vector<int> priorities = PropListModel->model()->getFilesPriorities(nbFiles); const std::vector<int> priorities = PropListModel->model()->getFilesPriorities(nbFiles);
for(unsigned int i=0; i<nbFiles; ++i) { for (unsigned int i=0; i<nbFiles; ++i) {
if(priorities[i] > 0) if (priorities[i] > 0)
torrent_size += t->file_at(i).size; torrent_size += t->file_at(i).size;
} }
} else { } else {
@ -511,8 +511,8 @@ void torrentAdditionDialog::updateDiskSpaceLabels() {
lbl_torrent_size->setText(misc::friendlyUnit(torrent_size)); lbl_torrent_size->setText(misc::friendlyUnit(torrent_size));
// Check if free space is sufficient // Check if free space is sufficient
if(available > 0) { if (available > 0) {
if((unsigned long long)available > torrent_size) { if ((unsigned long long)available > torrent_size) {
// Space is sufficient // 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))); label_space_msg->setText(tr("(%1 left after torrent download)", "e.g. (100MiB left after torrent download)").arg(misc::friendlyUnit(available-torrent_size)));
} else { } else {
@ -531,13 +531,13 @@ void torrentAdditionDialog::on_browseButton_clicked(){
QString new_path; QString new_path;
QString root_folder; QString root_folder;
const QString label_name = comboLabel->currentText(); 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); 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("/"); QStringList path_parts = new_path.replace("\\", "/").split("/");
const QString filename = path_parts.takeLast(); const QString filename = path_parts.takeLast();
// Append label // 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; path_parts << label_name;
// Append file name // Append file name
path_parts << filename; path_parts << filename;
@ -546,26 +546,26 @@ void torrentAdditionDialog::on_browseButton_clicked(){
} }
} else { } else {
QString truncated_path = getCurrentTruncatedSavePath(&root_folder); 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); new_path = QFileDialog::getExistingDirectory(this, tr("Choose save path"), truncated_path);
}else{ }else{
new_path = QFileDialog::getExistingDirectory(this, tr("Choose save path"), QDir::homePath()); 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("/"); QStringList path_parts = new_path.replace("\\", "/").split("/");
if(path_parts.last().isEmpty()) if (path_parts.last().isEmpty())
path_parts.removeLast(); path_parts.removeLast();
// Append label // Append label
if(QDir(new_path) == QDir(defaultSavePath) && !label_name.isEmpty()) if (QDir(new_path) == QDir(defaultSavePath) && !label_name.isEmpty())
path_parts << label_name; path_parts << label_name;
// Append root folder // Append root folder
if(!root_folder.isEmpty()) if (!root_folder.isEmpty())
path_parts << root_folder; path_parts << root_folder;
// Construct new_path // Construct new_path
new_path = path_parts.join(QDir::separator()); 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 // Check if this new path already exists in the list
QString new_truncated_path = getTruncatedSavePath(new_path); QString new_truncated_path = getTruncatedSavePath(new_path);
#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) #if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
@ -573,7 +573,7 @@ void torrentAdditionDialog::on_browseButton_clicked(){
#else #else
const int cur_index = path_history.indexOf(QRegExp(new_truncated_path, Qt::CaseSensitive)); const int cur_index = path_history.indexOf(QRegExp(new_truncated_path, Qt::CaseSensitive));
#endif #endif
if(cur_index >= 0) { if (cur_index >= 0) {
savePathTxt->setCurrentIndex(cur_index); savePathTxt->setCurrentIndex(cur_index);
} }
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
@ -602,7 +602,7 @@ void torrentAdditionDialog::savePiecesPriorities(){
void torrentAdditionDialog::on_OkButton_clicked(){ void torrentAdditionDialog::on_OkButton_clicked(){
Preferences pref; Preferences pref;
qDebug() << "void torrentAdditionDialog::on_OkButton_clicked() - ENTER"; 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")); QMessageBox::critical(0, tr("Empty save path"), tr("Please enter a save path"));
return; return;
} }
@ -612,7 +612,7 @@ void torrentAdditionDialog::on_OkButton_clicked(){
#endif #endif
save_path = misc::expandPath(save_path); save_path = misc::expandPath(save_path);
qDebug("Save path is %s", qPrintable(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 // Remove file name
QStringList parts = save_path.split("/"); QStringList parts = save_path.split("/");
const QString single_file_name = parts.takeLast(); 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())); qDebug("Saving save path to temp data: %s", qPrintable(savePath.absolutePath()));
TorrentTempData::setSavePath(hash, savePath.absolutePath()); TorrentTempData::setSavePath(hash, savePath.absolutePath());
qDebug("Torrent label is: %s", qPrintable(comboLabel->currentText().trimmed())); qDebug("Torrent label is: %s", qPrintable(comboLabel->currentText().trimmed()));
if(!current_label.isEmpty()) if (!current_label.isEmpty())
TorrentTempData::setLabel(hash, current_label); TorrentTempData::setLabel(hash, current_label);
// Is download sequential? // Is download sequential?
TorrentTempData::setSequential(hash, checkIncrementalDL->isChecked()); TorrentTempData::setSequential(hash, checkIncrementalDL->isChecked());
// Save files path // Save files path
// Loads files path in the torrent // Loads files path in the torrent
if(!is_magnet) { if (!is_magnet) {
bool path_changed = false; bool path_changed = false;
for(uint i=0; i<nbFiles; ++i) { for (uint i=0; i<nbFiles; ++i) {
#if LIBTORRENT_VERSION_MINOR >= 16 #if LIBTORRENT_VERSION_MINOR >= 16
file_storage fs = t->files(); file_storage fs = t->files();
QString old_path = misc::toQStringU(fs.file_path(t->file_at(i))); 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()); QString old_path = misc::toQStringU(t->file_at(i).path.string());
#endif #endif
#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) #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 #else
if(files_path.at(i).compare(old_path, Qt::CaseInsensitive) != 0) { if (files_path.at(i).compare(old_path, Qt::CaseInsensitive) != 0) {
#endif #endif
path_changed = true; path_changed = true;
break; break;
} }
} }
if(path_changed) { if (path_changed) {
qDebug("Changing files paths"); qDebug("Changing files paths");
TorrentTempData::setFilesPath(hash, files_path); TorrentTempData::setFilesPath(hash, files_path);
} }
} }
// Skip file checking and directly start seeding // Skip file checking and directly start seeding
if(addInSeed->isChecked()) { if (addInSeed->isChecked()) {
// Check if local file(s) actually exist // 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); TorrentTempData::setSeedingMode(hash, true);
} else { } 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.")); 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 // 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")); QMessageBox::warning(0, tr("Invalid file selection"), tr("You must select at least one file in the torrent"));
return; return;
} }
@ -683,23 +683,23 @@ void torrentAdditionDialog::on_OkButton_clicked(){
pref.setSavePath(getCurrentTruncatedSavePath()); pref.setSavePath(getCurrentTruncatedSavePath());
// Check if savePath exists // Check if savePath exists
if(!savePath.exists()){ if (!savePath.exists()){
if(!savePath.mkpath(savePath.path())){ if (!savePath.mkpath(savePath.path())){
QMessageBox::critical(0, tr("Save path creation error"), tr("Could not create the save path")); QMessageBox::critical(0, tr("Save path creation error"), tr("Could not create the save path"));
return; return;
} }
} }
// save filtered files // save filtered files
if(!is_magnet && t->num_files() > 1) if (!is_magnet && t->num_files() > 1)
savePiecesPriorities(); savePiecesPriorities();
// Add to download list // Add to download list
QTorrentHandle h; QTorrentHandle h;
if(is_magnet) if (is_magnet)
h = QBtSession::instance()->addMagnetUri(from_url, false); h = QBtSession::instance()->addMagnetUri(from_url, false);
else else
h = QBtSession::instance()->addTorrent(filePath, false, from_url); h = QBtSession::instance()->addTorrent(filePath, false, from_url);
if(addInPause->isChecked() && h.is_valid()) { if (addInPause->isChecked() && h.is_valid()) {
h.pause(); h.pause();
} }
// Close the dialog // Close the dialog
@ -710,14 +710,14 @@ void torrentAdditionDialog::on_OkButton_clicked(){
void torrentAdditionDialog::resetComboLabelIndex(QString text) { void torrentAdditionDialog::resetComboLabelIndex(QString text) {
// Select first index // Select first index
if(text != comboLabel->itemText(comboLabel->currentIndex())) { if (text != comboLabel->itemText(comboLabel->currentIndex())) {
comboLabel->setItemText(0, text); comboLabel->setItemText(0, text);
comboLabel->setCurrentIndex(0); comboLabel->setCurrentIndex(0);
} }
} }
void torrentAdditionDialog::updateLabelInSavePath(QString label) { void torrentAdditionDialog::updateLabelInSavePath(QString label) {
if(appendLabelToSavePath) { if (appendLabelToSavePath) {
// Update Label in combobox // Update Label in combobox
savePathTxt->setItemText(0, misc::updateLabelInSavePath(defaultSavePath, savePathTxt->itemText(0), old_label, label)); savePathTxt->setItemText(0, misc::updateLabelInSavePath(defaultSavePath, savePathTxt->itemText(0), old_label, label));
// update edit text // update edit text
@ -735,15 +735,15 @@ void torrentAdditionDialog::updateSavePathCurrentText() {
QString root_folder_or_file_name = ""; QString root_folder_or_file_name = "";
getCurrentTruncatedSavePath(&root_folder_or_file_name); getCurrentTruncatedSavePath(&root_folder_or_file_name);
// Update other combo items // Update other combo items
for(int i=0; i<savePathTxt->count(); ++i) { for (int i=0; i<savePathTxt->count(); ++i) {
if(i == savePathTxt->currentIndex()) continue; if (i == savePathTxt->currentIndex()) continue;
QString item_path = path_history.at(i); QString item_path = path_history.at(i);
if(item_path.isEmpty()) continue; if (item_path.isEmpty()) continue;
// Append label // 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() + "/"; item_path += comboLabel->currentText() + "/";
// Append root_folder or filename // 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; item_path += root_folder_or_file_name;
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
item_path.replace("/", "\\"); item_path.replace("/", "\\");
@ -763,17 +763,17 @@ QString torrentAdditionDialog::getTruncatedSavePath(QString save_path, QString*
save_path = misc::expandPath(save_path); save_path = misc::expandPath(save_path);
QStringList parts = save_path.replace("\\", "/").split("/"); QStringList parts = save_path.replace("\\", "/").split("/");
// Remove torrent root folder // 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(); QString tmp = parts.takeLast();
if(root_folder_or_file_name) if (root_folder_or_file_name)
*root_folder_or_file_name = tmp; *root_folder_or_file_name = tmp;
} }
// Remove label // Remove label
if(appendLabelToSavePath && savePathTxt->currentIndex() == 0 && parts.last() == comboLabel->currentText()) { if (appendLabelToSavePath && savePathTxt->currentIndex() == 0 && parts.last() == comboLabel->currentText()) {
parts.removeLast(); parts.removeLast();
} }
QString truncated_path = parts.join("/"); QString truncated_path = parts.join("/");
if(!truncated_path.endsWith("/")) if (!truncated_path.endsWith("/"))
truncated_path += "/"; truncated_path += "/";
qDebug("Truncated save path: %s", qPrintable(truncated_path)); qDebug("Truncated save path: %s", qPrintable(truncated_path));
return truncated_path; return truncated_path;
@ -785,14 +785,14 @@ void torrentAdditionDialog::saveTruncatedPathHistory() {
// Get current history // Get current history
QStringList history = settings.value("TorrentAdditionDlg/save_path_history").toStringList(); QStringList history = settings.value("TorrentAdditionDlg/save_path_history").toStringList();
#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) #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 #else
if(!history.contains(current_save_path, Qt::CaseInsensitive)) { if (!history.contains(current_save_path, Qt::CaseInsensitive)) {
#endif #endif
// Add save path to history // Add save path to history
history << current_save_path; history << current_save_path;
// Limit list size // Limit list size
if(history.size() > 8) if (history.size() > 8)
history.removeFirst(); history.removeFirst();
// Save history // Save history
settings.setValue("TorrentAdditionDlg/save_path_history", history); settings.setValue("TorrentAdditionDlg/save_path_history", history);
@ -803,8 +803,8 @@ void torrentAdditionDialog::loadSavePathHistory() {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
// Load save path history // Load save path history
QStringList raw_path_history = settings.value("TorrentAdditionDlg/save_path_history").toStringList(); QStringList raw_path_history = settings.value("TorrentAdditionDlg/save_path_history").toStringList();
foreach(const QString &sp, raw_path_history) { foreach (const QString &sp, raw_path_history) {
if(QDir(sp) != QDir(defaultSavePath)) { if (QDir(sp) != QDir(defaultSavePath)) {
QString dsp = sp; QString dsp = sp;
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
dsp.replace("/", "\\"); dsp.replace("/", "\\");

View file

@ -63,7 +63,7 @@ TorrentCreatorDlg::TorrentCreatorDlg(QWidget *parent): QDialog(parent), creatorT
} }
TorrentCreatorDlg::~TorrentCreatorDlg() { TorrentCreatorDlg::~TorrentCreatorDlg() {
if(creatorThread) if (creatorThread)
delete creatorThread; delete creatorThread;
} }
@ -71,14 +71,14 @@ void TorrentCreatorDlg::on_addFolder_button_clicked(){
QIniSettings settings("qBittorrent", "qBittorrent"); QIniSettings settings("qBittorrent", "qBittorrent");
QString last_path = settings.value("CreateTorrent/last_add_path", QDir::homePath()).toString(); 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); 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); settings.setValue("CreateTorrent/last_add_path", dir);
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
dir.replace("/", "\\"); dir.replace("/", "\\");
#endif #endif
textInputPath->setText(dir); textInputPath->setText(dir);
// Update piece size // Update piece size
if(checkAutoPieceSize->isChecked()) if (checkAutoPieceSize->isChecked())
updateOptimalPieceSize(); updateOptimalPieceSize();
} }
} }
@ -87,14 +87,14 @@ void TorrentCreatorDlg::on_addFile_button_clicked(){
QIniSettings settings("qBittorrent", "qBittorrent"); QIniSettings settings("qBittorrent", "qBittorrent");
QString last_path = settings.value("CreateTorrent/last_add_path", QDir::homePath()).toString(); 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); 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)); settings.setValue("CreateTorrent/last_add_path", misc::branchPath(file));
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
file.replace("/", "\\"); file.replace("/", "\\");
#endif #endif
textInputPath->setText(file); textInputPath->setText(file);
// Update piece size // Update piece size
if(checkAutoPieceSize->isChecked()) if (checkAutoPieceSize->isChecked())
updateOptimalPieceSize(); updateOptimalPieceSize();
} }
} }
@ -108,21 +108,21 @@ void TorrentCreatorDlg::on_createButton_clicked(){
QString input = textInputPath->text().trimmed(); QString input = textInputPath->text().trimmed();
if (input.endsWith(QDir::separator())) if (input.endsWith(QDir::separator()))
input.chop(1); input.chop(1);
if(input.isEmpty()){ if (input.isEmpty()){
QMessageBox::critical(0, tr("No input path set"), tr("Please type an input path first")); QMessageBox::critical(0, tr("No input path set"), tr("Please type an input path first"));
return; return;
} }
QStringList trackers = trackers_list->toPlainText().split("\n"); QStringList trackers = trackers_list->toPlainText().split("\n");
if(!trackers_list->toPlainText().trimmed().isEmpty()) if (!trackers_list->toPlainText().trimmed().isEmpty())
saveTrackerList(); saveTrackerList();
QIniSettings settings("qBittorrent", "qBittorrent"); QIniSettings settings("qBittorrent", "qBittorrent");
QString last_path = settings.value("CreateTorrent/last_save_path", QDir::homePath()).toString(); 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)")); 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)); settings.setValue("CreateTorrent/last_save_path", misc::branchPath(destination));
if(!destination.toUpper().endsWith(".TORRENT")) if (!destination.toUpper().endsWith(".TORRENT"))
destination += QString::fromUtf8(".torrent"); destination += QString::fromUtf8(".torrent");
} else { } else {
return; return;
@ -154,7 +154,7 @@ void TorrentCreatorDlg::handleCreationFailure(QString msg) {
void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path) { void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path) {
// Remove busy cursor // Remove busy cursor
setCursor(QCursor(Qt::ArrowCursor)); setCursor(QCursor(Qt::ArrowCursor));
if(checkStartSeeding->isChecked()) { if (checkStartSeeding->isChecked()) {
QString root_folder; QString root_folder;
// Create save path temp data // Create save path temp data
boost::intrusive_ptr<torrent_info> t; boost::intrusive_ptr<torrent_info> t;
@ -167,7 +167,7 @@ void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path)
} }
QString hash = misc::toQString(t->info_hash()); QString hash = misc::toQString(t->info_hash());
QString save_path = branch_path; QString save_path = branch_path;
if(!root_folder.isEmpty()) { if (!root_folder.isEmpty()) {
save_path = QDir(save_path).absoluteFilePath(root_folder); save_path = QDir(save_path).absoluteFilePath(root_folder);
} }
TorrentTempData::setSavePath(hash, save_path); TorrentTempData::setSavePath(hash, save_path);
@ -181,7 +181,7 @@ void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path)
void TorrentCreatorDlg::on_cancelButton_clicked() { void TorrentCreatorDlg::on_cancelButton_clicked() {
// End torrent creation thread // End torrent creation thread
if(creatorThread && creatorThread->isRunning()) { if (creatorThread && creatorThread->isRunning()) {
creatorThread->abortCreation(); creatorThread->abortCreation();
creatorThread->terminate(); creatorThread->terminate();
// Wait for termination // Wait for termination
@ -219,7 +219,7 @@ void TorrentCreatorDlg::showProgressBar(bool show)
void TorrentCreatorDlg::on_checkAutoPieceSize_clicked(bool checked) void TorrentCreatorDlg::on_checkAutoPieceSize_clicked(bool checked)
{ {
comboPieceSize->setEnabled(!checked); comboPieceSize->setEnabled(!checked);
if(checked) { if (checked) {
updateOptimalPieceSize(); updateOptimalPieceSize();
} }
} }
@ -228,18 +228,18 @@ void TorrentCreatorDlg::updateOptimalPieceSize()
{ {
quint64 torrent_size = misc::computePathSize(textInputPath->text()); quint64 torrent_size = misc::computePathSize(textInputPath->text());
qDebug("Torrent size is %lld", torrent_size); qDebug("Torrent size is %lld", torrent_size);
if(torrent_size == 0) return; if (torrent_size == 0) return;
int i = 0; int i = 0;
qulonglong nb_pieces = 0; qulonglong nb_pieces = 0;
do { do {
nb_pieces = (double)torrent_size/(m_piece_sizes.at(i)*1024.); 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))); qDebug("nb_pieces=%lld with piece_size=%s", nb_pieces, qPrintable(comboPieceSize->itemText(i)));
if(nb_pieces <= NB_PIECES_MIN) { if (nb_pieces <= NB_PIECES_MIN) {
if(i > 1) if (i > 1)
--i; --i;
break; break;
} }
if(nb_pieces < NB_PIECES_MAX) { if (nb_pieces < NB_PIECES_MAX) {
qDebug("Good, nb_pieces=%lld < %d", nb_pieces, NB_PIECES_MAX); qDebug("Good, nb_pieces=%lld < %d", nb_pieces, NB_PIECES_MAX);
break; break;
} }

View file

@ -75,7 +75,7 @@ void TorrentCreatorThread::create(QString _input_path, QString _save_path, QStri
{ {
input_path = _input_path; input_path = _input_path;
save_path = _save_path; save_path = _save_path;
if(QFile(save_path).exists()) if (QFile(save_path).exists())
QFile::remove(save_path); QFile::remove(save_path);
trackers = _trackers; trackers = _trackers;
url_seeds = _url_seeds; url_seeds = _url_seeds;
@ -104,17 +104,17 @@ void TorrentCreatorThread::run() {
file_storage fs; file_storage fs;
// Adding files to the torrent // Adding files to the torrent
libtorrent::add_files(fs, input_path.toUtf8().constData(), file_filter); libtorrent::add_files(fs, input_path.toUtf8().constData(), file_filter);
if(abort) return; if (abort) return;
create_torrent t(fs, piece_size); create_torrent t(fs, piece_size);
// Add url seeds // Add url seeds
foreach(const QString &seed, url_seeds){ foreach (const QString &seed, url_seeds){
t.add_url_seed(seed.trimmed().toStdString()); t.add_url_seed(seed.trimmed().toStdString());
} }
foreach(const QString &tracker, trackers) { foreach (const QString &tracker, trackers) {
t.add_tracker(tracker.trimmed().toStdString()); t.add_tracker(tracker.trimmed().toStdString());
} }
if(abort) return; if (abort) return;
// calculate the hash for all pieces // calculate the hash for all pieces
const QString parent_path = misc::branchPath(input_path); const QString parent_path = misc::branchPath(input_path);
set_piece_hashes(t, parent_path.toUtf8().constData(), boost::bind<void>(&sendProgressUpdateSignal, _1, t.num_pieces(), this)); set_piece_hashes(t, parent_path.toUtf8().constData(), boost::bind<void>(&sendProgressUpdateSignal, _1, t.num_pieces(), this));
@ -124,13 +124,13 @@ void TorrentCreatorThread::run() {
t.set_comment(comment.toUtf8().constData()); t.set_comment(comment.toUtf8().constData());
// Is private ? // Is private ?
t.set_priv(is_private); t.set_priv(is_private);
if(abort) return; if (abort) return;
// create the torrent and print it to out // create the torrent and print it to out
qDebug("Saving to %s", qPrintable(save_path)); qDebug("Saving to %s", qPrintable(save_path));
std::vector<char> torrent; std::vector<char> torrent;
bencode(back_inserter(torrent), t.generate()); bencode(back_inserter(torrent), t.generate());
QFile outfile(save_path); 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.write(&torrent[0], torrent.size());
outfile.close(); outfile.close();
emit updateProgress(100); emit updateProgress(100);

View file

@ -75,7 +75,7 @@ public:
QString name = misc::toQStringU(f.path.filename()); QString name = misc::toQStringU(f.path.filename());
#endif #endif
// Do not display incomplete extensions // Do not display incomplete extensions
if(name.endsWith(".!qB")) if (name.endsWith(".!qB"))
name.chop(4); name.chop(4);
itemData << name; itemData << name;
//qDebug("Created a TreeItem file with name %s", qPrintable(getName())); //qDebug("Created a TreeItem file with name %s", qPrintable(getName()));
@ -84,7 +84,7 @@ public:
total_done = 0; total_done = 0;
itemData << 0.; // Progress; itemData << 0.; // Progress;
itemData << prio::NORMAL; // Priority itemData << prio::NORMAL; // Priority
if(parent) { if (parent) {
parent->appendChild(this); parent->appendChild(this);
parent->updateSize(); parent->updateSize();
} }
@ -95,14 +95,14 @@ public:
parentItem = parent; parentItem = parent;
m_type = FOLDER; m_type = FOLDER;
// Do not display incomplete extensions // Do not display incomplete extensions
if(name.endsWith(".!qB")) if (name.endsWith(".!qB"))
name.chop(4); name.chop(4);
itemData << name; itemData << name;
itemData << 0.; // Size itemData << 0.; // Size
itemData << 0.; // Progress; itemData << 0.; // Progress;
total_done = 0; total_done = 0;
itemData << prio::NORMAL; // Priority itemData << prio::NORMAL; // Priority
if(parent) { if (parent) {
parent->appendChild(this); parent->appendChild(this);
} }
} }
@ -155,36 +155,36 @@ public:
} }
void setSize(qulonglong size) { void setSize(qulonglong size) {
if(getSize() == size) return; if (getSize() == size) return;
itemData.replace(COL_SIZE, (qulonglong)size); itemData.replace(COL_SIZE, (qulonglong)size);
if(parentItem) if (parentItem)
parentItem->updateSize(); parentItem->updateSize();
} }
void updateSize() { void updateSize() {
if(m_type == ROOT) return; if (m_type == ROOT) return;
Q_ASSERT(m_type == FOLDER); Q_ASSERT(m_type == FOLDER);
qulonglong size = 0; qulonglong size = 0;
foreach(TorrentFileItem* child, childItems) { foreach (TorrentFileItem* child, childItems) {
if(child->getPriority() != prio::IGNORED) if (child->getPriority() != prio::IGNORED)
size += child->getSize(); size += child->getSize();
} }
setSize(size); setSize(size);
} }
void setProgress(qulonglong done) { void setProgress(qulonglong done) {
if(getPriority() == 0) return; if (getPriority() == 0) return;
total_done = done; total_done = done;
qulonglong size = getSize(); qulonglong size = getSize();
Q_ASSERT(total_done <= size); Q_ASSERT(total_done <= size);
qreal progress; qreal progress;
if(size > 0) if (size > 0)
progress = total_done/(float)size; progress = total_done/(float)size;
else else
progress = 1.; progress = 1.;
Q_ASSERT(progress >= 0. && progress <= 1.); Q_ASSERT(progress >= 0. && progress <= 1.);
itemData.replace(COL_PROGRESS, progress); itemData.replace(COL_PROGRESS, progress);
if(parentItem) if (parentItem)
parentItem->updateProgress(); parentItem->updateProgress();
} }
@ -193,20 +193,20 @@ public:
} }
qreal getProgress() const { qreal getProgress() const {
if(getPriority() == 0) if (getPriority() == 0)
return -1; return -1;
qulonglong size = getSize(); qulonglong size = getSize();
if(size > 0) if (size > 0)
return total_done/(float)getSize(); return total_done/(float)getSize();
return 1.; return 1.;
} }
void updateProgress() { void updateProgress() {
if(m_type == ROOT) return; if (m_type == ROOT) return;
Q_ASSERT(m_type == FOLDER); Q_ASSERT(m_type == FOLDER);
total_done = 0; total_done = 0;
foreach(TorrentFileItem* child, childItems) { foreach (TorrentFileItem* child, childItems) {
if(child->getPriority() > 0) if (child->getPriority() > 0)
total_done += child->getTotalDone(); total_done += child->getTotalDone();
} }
//qDebug("Folder: total_done: %llu/%llu", total_done, getSize()); //qDebug("Folder: total_done: %llu/%llu", total_done, getSize());
@ -221,17 +221,17 @@ public:
void setPriority(int new_prio, bool update_parent=true) { void setPriority(int new_prio, bool update_parent=true) {
Q_ASSERT(new_prio != prio::PARTIAL || m_type == FOLDER); // PARTIAL only applies to folders Q_ASSERT(new_prio != prio::PARTIAL || m_type == FOLDER); // PARTIAL only applies to folders
const int old_prio = getPriority(); 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); qDebug("setPriority(%s, %d)", qPrintable(getName()), new_prio);
// Reset progress if priority is 0 // Reset progress if priority is 0
if(new_prio == 0) { if (new_prio == 0) {
setProgress(0); setProgress(0);
} }
itemData.replace(COL_PRIO, new_prio); itemData.replace(COL_PRIO, new_prio);
// Update parent // Update parent
if(update_parent && parentItem) { if (update_parent && parentItem) {
qDebug("Updating parent item"); qDebug("Updating parent item");
parentItem->updateSize(); parentItem->updateSize();
parentItem->updateProgress(); parentItem->updateProgress();
@ -239,15 +239,15 @@ public:
} }
// Update children // Update children
if(new_prio != prio::PARTIAL && !childItems.empty()) { if (new_prio != prio::PARTIAL && !childItems.empty()) {
qDebug("Updating children items"); qDebug("Updating children items");
foreach(TorrentFileItem* child, childItems) { foreach (TorrentFileItem* child, childItems) {
// Do not update the parent since // Do not update the parent since
// the parent is causing the update // the parent is causing the update
child->setPriority(new_prio, false); child->setPriority(new_prio, false);
} }
} }
if(m_type == FOLDER) { if (m_type == FOLDER) {
updateSize(); updateSize();
updateProgress(); updateProgress();
} }
@ -255,28 +255,28 @@ public:
// Only non-root folders use this function // Only non-root folders use this function
void updatePriority() { void updatePriority() {
if(m_type == ROOT) return; if (m_type == ROOT) return;
Q_ASSERT(m_type == FOLDER); Q_ASSERT(m_type == FOLDER);
if(childItems.isEmpty()) return; if (childItems.isEmpty()) return;
// If all children have the same priority // If all children have the same priority
// then the folder should have the same // then the folder should have the same
// priority // priority
const int prio = childItems.first()->getPriority(); const int prio = childItems.first()->getPriority();
for(int i=1; i<childItems.size(); ++i) { for (int i=1; i<childItems.size(); ++i) {
if(childItems.at(i)->getPriority() != prio) { if (childItems.at(i)->getPriority() != prio) {
setPriority(prio::PARTIAL); setPriority(prio::PARTIAL);
return; return;
} }
} }
// All child items have the same priorrity // All child items have the same priorrity
// Update mine if necessary // Update mine if necessary
if(prio != getPriority()) if (prio != getPriority())
setPriority(prio); setPriority(prio);
} }
TorrentFileItem* childWithName(QString name) const { TorrentFileItem* childWithName(QString name) const {
foreach(TorrentFileItem *child, childItems) { foreach (TorrentFileItem *child, childItems) {
if(child->getName() == name) return child; if (child->getName() == name) return child;
} }
return 0; return 0;
} }
@ -290,9 +290,9 @@ public:
//Q_ASSERT(!childWithName(item->getName())); //Q_ASSERT(!childWithName(item->getName()));
Q_ASSERT(m_type != TFILE); Q_ASSERT(m_type != TFILE);
int i=0; int i=0;
for(i=0; i<childItems.size(); ++i) { for (i=0; i<childItems.size(); ++i) {
QString newchild_name = item->getName(); QString newchild_name = item->getName();
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.insert(i, item);
//childItems.append(item); //childItems.append(item);
@ -313,7 +313,7 @@ public:
} }
QVariant data(int column) const { QVariant data(int column) const {
if(column == COL_PROGRESS) if (column == COL_PROGRESS)
return getProgress(); return getProgress();
return itemData.value(column); return itemData.value(column);
} }
@ -355,7 +355,7 @@ public:
void updateFilesProgress(std::vector<libtorrent::size_type> fp) { void updateFilesProgress(std::vector<libtorrent::size_type> fp) {
emit layoutAboutToBeChanged(); emit layoutAboutToBeChanged();
for(unsigned int i=0; i<fp.size(); ++i) { for (unsigned int i=0; i<fp.size(); ++i) {
Q_ASSERT(fp[i] >= 0); Q_ASSERT(fp[i] >= 0);
files_index[i]->setProgress(fp[i]); files_index[i]->setProgress(fp[i]);
} }
@ -364,7 +364,7 @@ public:
void updateFilesPriorities(const std::vector<int> &fprio) { void updateFilesPriorities(const std::vector<int> &fprio) {
emit layoutAboutToBeChanged(); emit layoutAboutToBeChanged();
for(unsigned int i=0; i<fprio.size(); ++i) { for (unsigned int i=0; i<fprio.size(); ++i) {
//qDebug("Called updateFilesPriorities with %d", fprio[i]); //qDebug("Called updateFilesPriorities with %d", fprio[i]);
files_index[i]->setPriority(fprio[i]); files_index[i]->setPriority(fprio[i]);
} }
@ -373,7 +373,7 @@ public:
std::vector<int> getFilesPriorities(unsigned int nbFiles) const { std::vector<int> getFilesPriorities(unsigned int nbFiles) const {
std::vector<int> prio; std::vector<int> prio;
for(unsigned int i=0; i<nbFiles; ++i) { for (unsigned int i=0; i<nbFiles; ++i) {
//qDebug("Called getFilesPriorities: %d", files_index[i]->getPriority()); //qDebug("Called getFilesPriorities: %d", files_index[i]->getPriority());
prio.push_back(files_index[i]->getPriority()); prio.push_back(files_index[i]->getPriority());
} }
@ -381,8 +381,8 @@ public:
} }
bool allFiltered() const { bool allFiltered() const {
for(int i=0; i<rootItem->childCount(); ++i) { for (int i=0; i<rootItem->childCount(); ++i) {
if(rootItem->child(i)->getPriority() != prio::IGNORED) if (rootItem->child(i)->getPriority() != prio::IGNORED)
return false; return false;
} }
return true; return true;
@ -396,12 +396,12 @@ public:
} }
bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) { 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) { if (index.column() == 0 && role == Qt::CheckStateRole) {
TorrentFileItem *item = static_cast<TorrentFileItem*>(index.internalPointer()); TorrentFileItem *item = static_cast<TorrentFileItem*>(index.internalPointer());
qDebug("setData(%s, %d", qPrintable(item->getName()), value.toInt()); qDebug("setData(%s, %d", qPrintable(item->getName()), value.toInt());
if(item->getPriority() != value.toInt()) { if (item->getPriority() != value.toInt()) {
if(value.toInt() == Qt::PartiallyChecked) if (value.toInt() == Qt::PartiallyChecked)
item->setPriority(prio::PARTIAL); item->setPriority(prio::PARTIAL);
else if (value.toInt() == Qt::Unchecked) else if (value.toInt() == Qt::Unchecked)
item->setPriority(prio::IGNORED); item->setPriority(prio::IGNORED);
@ -450,16 +450,16 @@ public:
if (!index.isValid()) if (!index.isValid())
return QVariant(); return QVariant();
TorrentFileItem *item = static_cast<TorrentFileItem*>(index.internalPointer()); TorrentFileItem *item = static_cast<TorrentFileItem*>(index.internalPointer());
if(index.column() == 0 && role == Qt::DecorationRole) { if (index.column() == 0 && role == Qt::DecorationRole) {
if(item->isFolder()) if (item->isFolder())
return IconProvider::instance()->getIcon("inode-directory"); return IconProvider::instance()->getIcon("inode-directory");
else else
return IconProvider::instance()->getIcon("text-plain"); return IconProvider::instance()->getIcon("text-plain");
} }
if(index.column() == 0 && role == Qt::CheckStateRole) { if (index.column() == 0 && role == Qt::CheckStateRole) {
if(item->data(TorrentFileItem::COL_PRIO).toInt() == prio::IGNORED) if (item->data(TorrentFileItem::COL_PRIO).toInt() == prio::IGNORED)
return Qt::Unchecked; 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::PartiallyChecked;
return Qt::Checked; return Qt::Checked;
} }
@ -472,7 +472,7 @@ public:
Qt::ItemFlags flags(const QModelIndex &index) const { Qt::ItemFlags flags(const QModelIndex &index) const {
if (!index.isValid()) if (!index.isValid())
return 0; 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 | Qt::ItemIsTristate;
return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable; 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 { QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const {
if (parent.isValid() && parent.column() != 0) if (parent.isValid() && parent.column() != 0)
return QModelIndex(); return QModelIndex();
if(column >= TorrentFileItem::NB_COL) if (column >= TorrentFileItem::NB_COL)
return QModelIndex(); return QModelIndex();
TorrentFileItem *parentItem; TorrentFileItem *parentItem;
@ -497,7 +497,7 @@ public:
else else
parentItem = static_cast<TorrentFileItem*>(parent.internalPointer()); parentItem = static_cast<TorrentFileItem*>(parent.internalPointer());
Q_ASSERT(parentItem); Q_ASSERT(parentItem);
if(row >= parentItem->childCount()) if (row >= parentItem->childCount())
return QModelIndex(); return QModelIndex();
TorrentFileItem *childItem = parentItem->child(row); TorrentFileItem *childItem = parentItem->child(row);
@ -513,7 +513,7 @@ public:
return QModelIndex(); return QModelIndex();
TorrentFileItem *childItem = static_cast<TorrentFileItem*>(index.internalPointer()); TorrentFileItem *childItem = static_cast<TorrentFileItem*>(index.internalPointer());
if(!childItem) return QModelIndex(); if (!childItem) return QModelIndex();
TorrentFileItem *parentItem = childItem->parent(); TorrentFileItem *parentItem = childItem->parent();
if (parentItem == rootItem) if (parentItem == rootItem)
@ -539,7 +539,7 @@ public:
void clear() { void clear() {
qDebug("clear called"); qDebug("clear called");
beginResetModel(); beginResetModel();
if(files_index) { if (files_index) {
delete [] files_index; delete [] files_index;
files_index = 0; files_index = 0;
} }
@ -549,7 +549,7 @@ public:
void setupModelData(const libtorrent::torrent_info &t) { void setupModelData(const libtorrent::torrent_info &t) {
qDebug("setup model data called"); qDebug("setup model data called");
if(t.num_files() == 0) return; if (t.num_files() == 0) return;
emit layoutAboutToBeChanged(); emit layoutAboutToBeChanged();
// Initialize files_index array // Initialize files_index array
qDebug("Torrent contains %d files", t.num_files()); qDebug("Torrent contains %d files", t.num_files());
@ -560,7 +560,7 @@ public:
TorrentFileItem *current_parent; TorrentFileItem *current_parent;
// Iterate over files // Iterate over files
for(int i=0; i<t.num_files(); ++i) { for (int i=0; i<t.num_files(); ++i) {
libtorrent::file_entry fentry = t.file_at(i); libtorrent::file_entry fentry = t.file_at(i);
current_parent = root_folder; current_parent = root_folder;
#if LIBTORRENT_VERSION_MINOR >= 16 #if LIBTORRENT_VERSION_MINOR >= 16
@ -572,9 +572,9 @@ public:
QStringList pathFolders = path.split("/"); QStringList pathFolders = path.split("/");
pathFolders.removeAll(".unwanted"); pathFolders.removeAll(".unwanted");
pathFolders.takeLast(); pathFolders.takeLast();
foreach(const QString &pathPart, pathFolders) { foreach (const QString &pathPart, pathFolders) {
TorrentFileItem *new_parent = current_parent->childWithName(pathPart); TorrentFileItem *new_parent = current_parent->childWithName(pathPart);
if(!new_parent) { if (!new_parent) {
new_parent = new TorrentFileItem(pathPart, current_parent); new_parent = new TorrentFileItem(pathPart, current_parent);
} }
current_parent = new_parent; current_parent = new_parent;
@ -588,16 +588,16 @@ public:
public slots: public slots:
void selectAll() { void selectAll() {
for(int i=0; i<rootItem->childCount(); ++i) { for (int i=0; i<rootItem->childCount(); ++i) {
TorrentFileItem *child = rootItem->child(i); TorrentFileItem *child = rootItem->child(i);
if(child->getPriority() == prio::IGNORED) if (child->getPriority() == prio::IGNORED)
child->setPriority(prio::NORMAL); child->setPriority(prio::NORMAL);
} }
emit dataChanged(index(0,0), index(rowCount(), columnCount())); emit dataChanged(index(0,0), index(rowCount(), columnCount()));
} }
void selectNone() { void selectNone() {
for(int i=0; i<rootItem->childCount(); ++i) { for (int i=0; i<rootItem->childCount(); ++i) {
rootItem->child(i)->setPriority(prio::IGNORED); rootItem->child(i)->setPriority(prio::IGNORED);
} }
emit dataChanged(index(0,0), index(rowCount(), columnCount())); emit dataChanged(index(0,0), index(rowCount(), columnCount()));
@ -642,9 +642,9 @@ public:
} }
QModelIndex parent(const QModelIndex & child) const { QModelIndex parent(const QModelIndex & child) const {
if(!child.isValid()) return QModelIndex(); if (!child.isValid()) return QModelIndex();
QModelIndex sourceParent = m_model->parent(mapToSource(child)); QModelIndex sourceParent = m_model->parent(mapToSource(child));
if(!sourceParent.isValid()) return QModelIndex(); if (!sourceParent.isValid()) return QModelIndex();
return mapFromSource(sourceParent); return mapFromSource(sourceParent);
} }
@ -662,14 +662,14 @@ protected:
public slots: public slots:
void selectAll() { void selectAll() {
for(int i=0; i<rowCount(); ++i) { for (int i=0; i<rowCount(); ++i) {
setData(index(i, 0), Qt::Checked, Qt::CheckStateRole); setData(index(i, 0), Qt::Checked, Qt::CheckStateRole);
} }
emit dataChanged(index(0,0), index(rowCount(), columnCount())); emit dataChanged(index(0,0), index(rowCount(), columnCount()));
} }
void selectNone() { void selectNone() {
for(int i=0; i<rowCount(); ++i) { for (int i=0; i<rowCount(); ++i) {
setData(index(i, 0), Qt::Unchecked, Qt::CheckStateRole); setData(index(i, 0), Qt::Unchecked, Qt::CheckStateRole);
} }
emit dataChanged(index(0,0), index(rowCount(), columnCount())); emit dataChanged(index(0,0), index(rowCount(), columnCount()));

View file

@ -65,7 +65,7 @@ void TorrentImportDlg::on_browseTorrentBtn_clicked()
const QString default_dir = settings.value(QString::fromUtf8("MainWindowLastDir"), QDir::homePath()).toString(); const QString default_dir = settings.value(QString::fromUtf8("MainWindowLastDir"), QDir::homePath()).toString();
// Ask for a torrent file // Ask for a torrent file
m_torrentPath = QFileDialog::getOpenFileName(this, tr("Torrent file to import"), default_dir, tr("Torrent files (*.torrent)")); m_torrentPath = QFileDialog::getOpenFileName(this, tr("Torrent file to import"), default_dir, tr("Torrent files (*.torrent)"));
if(!m_torrentPath.isEmpty()) { if (!m_torrentPath.isEmpty()) {
loadTorrent(m_torrentPath); loadTorrent(m_torrentPath);
} else { } else {
ui->lineTorrent->clear(); ui->lineTorrent->clear();
@ -76,7 +76,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
{ {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
const QString default_dir = settings.value(QString::fromUtf8("TorrentImport/LastContentDir"), QDir::homePath()).toString(); 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 // Single file torrent
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
const QString file_name = misc::fileName(misc::toQStringU(t->file_at(0).path)); 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); QString extension = misc::file_extension(file_name);
qDebug("File extension is : %s", qPrintable(extension)); qDebug("File extension is : %s", qPrintable(extension));
QString filter; QString filter;
if(!extension.isEmpty()) { if (!extension.isEmpty()) {
extension = extension.toUpper(); extension = extension.toUpper();
filter = tr("%1 Files", "%1 is a file extension (e.g. PDF)").arg(extension)+" (*."+extension+")"; 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); 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; m_contentPath = QString::null;
ui->importBtn->setEnabled(false); ui->importBtn->setEnabled(false);
ui->checkSkipCheck->setEnabled(false); ui->checkSkipCheck->setEnabled(false);
@ -106,7 +106,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
#endif #endif
// Check file size // Check file size
const qint64 file_size = QFile(m_contentPath).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..."); qDebug("The file size matches, allowing fast seeding...");
ui->checkSkipCheck->setEnabled(true); ui->checkSkipCheck->setEnabled(true);
} else { } else {
@ -117,7 +117,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
// Handle file renaming // Handle file renaming
QStringList parts = m_contentPath.replace("\\", "/").split("/"); QStringList parts = m_contentPath.replace("\\", "/").split("/");
QString new_file_name = parts.takeLast(); QString new_file_name = parts.takeLast();
if(new_file_name != file_name) { if (new_file_name != file_name) {
qDebug("The file has been renamed"); qDebug("The file has been renamed");
QStringList new_parts = m_filesPath.first().split("/"); QStringList new_parts = m_filesPath.first().split("/");
new_parts.replace(new_parts.count()-1, new_file_name); new_parts.replace(new_parts.count()-1, new_file_name);
@ -128,7 +128,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
// multiple files torrent // multiple files torrent
m_contentPath = QFileDialog::getExistingDirectory(this, tr("Please point to the location of the torrent: %1").arg(misc::toQStringU(t->name())), m_contentPath = QFileDialog::getExistingDirectory(this, tr("Please point to the location of the torrent: %1").arg(misc::toQStringU(t->name())),
default_dir); default_dir);
if(m_contentPath.isEmpty() || !QDir(m_contentPath).exists()) { if (m_contentPath.isEmpty() || !QDir(m_contentPath).exists()) {
m_contentPath = QString::null; m_contentPath = QString::null;
ui->importBtn->setEnabled(false); ui->importBtn->setEnabled(false);
ui->checkSkipCheck->setEnabled(false); ui->checkSkipCheck->setEnabled(false);
@ -143,13 +143,13 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
bool size_mismatch = false; bool size_mismatch = false;
QDir content_dir(m_contentPath); QDir content_dir(m_contentPath);
// Check file sizes // Check file sizes
for(int i=0; i<t->num_files(); ++i) { for (int i=0; i<t->num_files(); ++i) {
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
const QString rel_path = misc::toQStringU(t->file_at(i).path); const QString rel_path = misc::toQStringU(t->file_at(i).path);
#else #else
const QString rel_path = misc::toQStringU(t->file_at(i).path.string()); const QString rel_path = misc::toQStringU(t->file_at(i).path.string());
#endif #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", qDebug("%s is %lld",
qPrintable(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))), (long long int) QFile(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))).size()); qPrintable(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))), (long long int) QFile(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))).size());
qDebug("%s is %lld", qDebug("%s is %lld",
@ -158,7 +158,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
break; break;
} }
} }
if(size_mismatch) { if (size_mismatch) {
qDebug("The file size does not match, forbidding fast seeding..."); qDebug("The file size does not match, forbidding fast seeding...");
ui->checkSkipCheck->setChecked(false); ui->checkSkipCheck->setChecked(false);
ui->checkSkipCheck->setEnabled(false); ui->checkSkipCheck->setEnabled(false);
@ -193,14 +193,14 @@ void TorrentImportDlg::importTorrent()
{ {
qDebug() << Q_FUNC_INFO << "ENTER"; qDebug() << Q_FUNC_INFO << "ENTER";
TorrentImportDlg dlg; TorrentImportDlg dlg;
if(dlg.exec()) { if (dlg.exec()) {
qDebug() << "Loading the torrent file..."; qDebug() << "Loading the torrent file...";
boost::intrusive_ptr<libtorrent::torrent_info> t = dlg.torrent(); boost::intrusive_ptr<libtorrent::torrent_info> t = dlg.torrent();
if(!t->is_valid()) if (!t->is_valid())
return; return;
QString torrent_path = dlg.getTorrentPath(); QString torrent_path = dlg.getTorrentPath();
QString content_path = dlg.getContentPath(); 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; qWarning() << "Incorrect input, aborting." << torrent_path << content_path;
return; return;
} }
@ -225,7 +225,7 @@ void TorrentImportDlg::loadTorrent(const QString &torrent_path)
// Load the torrent file // Load the torrent file
try { try {
t = new torrent_info(torrent_path.toUtf8().constData()); 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(); throw std::exception();
} catch(std::exception&) { } catch(std::exception&) {
ui->browseContentBtn->setEnabled(false); ui->browseContentBtn->setEnabled(false);
@ -251,7 +251,7 @@ void TorrentImportDlg::initializeFilesPath()
{ {
m_filesPath.clear(); m_filesPath.clear();
// Loads files path in the torrent // Loads files path in the torrent
for(int i=0; i<t->num_files(); ++i) { for (int i=0; i<t->num_files(); ++i) {
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
m_filesPath << misc::toQStringU(t->file_at(i).path).replace("\\", "/"); m_filesPath << misc::toQStringU(t->file_at(i).path).replace("\\", "/");
#else #else

View file

@ -53,7 +53,7 @@ public:
static void deleteTempData(QString hash) { static void deleteTempData(QString hash) {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume"));
QHash<QString, QVariant> all_data = settings.value("torrents-tmp").toHash(); QHash<QString, QVariant> all_data = settings.value("torrents-tmp").toHash();
if(all_data.contains(hash)) { if (all_data.contains(hash)) {
all_data.remove(hash); all_data.remove(hash);
settings.setValue("torrents-tmp", all_data); settings.setValue("torrents-tmp", all_data);
} }
@ -161,7 +161,7 @@ public:
const QHash<QString, QVariant> all_data = settings.value("torrents-tmp").toHash(); const QHash<QString, QVariant> all_data = settings.value("torrents-tmp").toHash();
const QHash<QString, QVariant> data = all_data.value(hash).toHash(); const QHash<QString, QVariant> data = all_data.value(hash).toHash();
const QList<int> list_var = misc::intListfromStringList(data.value("files_priority").toStringList()); const QList<int> 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); fp.push_back(var);
} }
} }
@ -207,8 +207,8 @@ public:
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume"));
const QHash<QString, QVariant> all_data = settings.value("torrents").toHash(); const QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
QHash<QString, QVariant>::ConstIterator it; QHash<QString, QVariant>::ConstIterator it;
for(it = all_data.constBegin(); it != all_data.constEnd(); it++) { for (it = all_data.constBegin(); it != all_data.constEnd(); it++) {
if(it.value().toHash().value("max_ratio", USE_GLOBAL_RATIO).toReal() >= 0) { if (it.value().toHash().value("max_ratio", USE_GLOBAL_RATIO).toReal() >= 0) {
return true; return true;
} }
} }
@ -219,7 +219,7 @@ public:
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume"));
QHash<QString, QVariant> all_data = settings.value("torrents").toHash(); QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
QHash<QString, QVariant> data = all_data.value(hash).toHash(); QHash<QString, QVariant> data = all_data.value(hash).toHash();
if(!data.contains("add_date")) { if (!data.contains("add_date")) {
data["add_date"] = QDateTime::currentDateTime(); data["add_date"] = QDateTime::currentDateTime();
all_data[hash] = data; all_data[hash] = data;
settings.setValue("torrents", all_data); settings.setValue("torrents", all_data);
@ -231,7 +231,7 @@ public:
const QHash<QString, QVariant> all_data = settings.value("torrents").toHash(); const QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
const QHash<QString, QVariant> data = all_data.value(hash).toHash(); const QHash<QString, QVariant> data = all_data.value(hash).toHash();
QDateTime dt = data.value("add_date").toDateTime(); QDateTime dt = data.value("add_date").toDateTime();
if(!dt.isValid()) { if (!dt.isValid()) {
setAddedDate(hash); setAddedDate(hash);
dt = QDateTime::currentDateTime(); dt = QDateTime::currentDateTime();
} }
@ -290,7 +290,7 @@ public:
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume"));
QHash<QString, QVariant> all_data = settings.value("torrents").toHash(); QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
QHash<QString, QVariant> data = all_data[h.hash()].toHash(); QHash<QString, QVariant> data = all_data[h.hash()].toHash();
if(h.is_seed()) if (h.is_seed())
data["seed_date"] = QDateTime::currentDateTime(); data["seed_date"] = QDateTime::currentDateTime();
else else
data.remove("seed_date"); data.remove("seed_date");
@ -308,7 +308,7 @@ public:
static void deletePersistentData(QString hash) { static void deletePersistentData(QString hash) {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume"));
QHash<QString, QVariant> all_data = settings.value("torrents").toHash(); QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
if(all_data.contains(hash)) { if (all_data.contains(hash)) {
all_data.remove(hash); all_data.remove(hash);
settings.setValue("torrents", all_data); settings.setValue("torrents", all_data);
} }
@ -322,12 +322,12 @@ public:
QHash<QString, QVariant> all_data = settings.value("torrents").toHash(); QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
QHash<QString, QVariant> data = all_data.value(h.hash()).toHash(); QHash<QString, QVariant> data = all_data.value(h.hash()).toHash();
data["is_magnet"] = is_magnet; data["is_magnet"] = is_magnet;
if(is_magnet) { if (is_magnet) {
data["magnet_uri"] = misc::toQString(make_magnet_uri(h)); data["magnet_uri"] = misc::toQString(make_magnet_uri(h));
} }
data["seed"] = h.is_seed(); data["seed"] = h.is_seed();
data["priority"] = h.queue_position(); data["priority"] = h.queue_position();
if(save_path.isEmpty()) { if (save_path.isEmpty()) {
qDebug("TorrentPersistantData: save path is %s", qPrintable(h.save_path())); qDebug("TorrentPersistantData: save path is %s", qPrintable(h.save_path()));
data["save_path"] = h.save_path(); data["save_path"] = h.save_path();
} else { } else {
@ -394,11 +394,11 @@ public:
QHash<QString, QVariant> all_data = settings.value("torrents").toHash(); QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
QHash<QString, QVariant> data = all_data[h.hash()].toHash(); QHash<QString, QVariant> data = all_data[h.hash()].toHash();
bool was_seed = data.value("seed", false).toBool(); bool was_seed = data.value("seed", false).toBool();
if(was_seed != h.is_seed()) { if (was_seed != h.is_seed()) {
data["seed"] = !was_seed; data["seed"] = !was_seed;
all_data[h.hash()] = data; all_data[h.hash()] = data;
settings.setValue("torrents", all_data); settings.setValue("torrents", all_data);
if(!was_seed) { if (!was_seed) {
// Save completion date // Save completion date
saveSeedDate(h); saveSeedDate(h);
} }

View file

@ -20,7 +20,7 @@ struct QPeer {
libtorrent::entry toEntry(bool no_peer_id) const { libtorrent::entry toEntry(bool no_peer_id) const {
libtorrent::entry::dictionary_type peer_map; libtorrent::entry::dictionary_type peer_map;
if(!no_peer_id) if (!no_peer_id)
peer_map["id"] = libtorrent::entry(peer_id.toStdString()); peer_map["id"] = libtorrent::entry(peer_id.toStdString());
peer_map["ip"] = libtorrent::entry(ip.toStdString()); peer_map["ip"] = libtorrent::entry(ip.toStdString());
peer_map["port"] = libtorrent::entry(port); peer_map["port"] = libtorrent::entry(port);

View file

@ -48,7 +48,7 @@ QTracker::QTracker(QObject *parent) :
} }
QTracker::~QTracker() { QTracker::~QTracker() {
if(isListening()) { if (isListening()) {
qDebug("Shutting down the embedded tracker..."); qDebug("Shutting down the embedded tracker...");
close(); close();
} }
@ -69,8 +69,8 @@ bool QTracker::start()
{ {
const int listen_port = Preferences().getTrackerPort(); const int listen_port = Preferences().getTrackerPort();
// //
if(isListening()) { if (isListening()) {
if(serverPort() == listen_port) { if (serverPort() == listen_port) {
// Already listening on the right port, just return // Already listening on the right port, just return
return true; return true;
} }
@ -88,19 +88,19 @@ void QTracker::readRequest()
QByteArray input = socket->readAll(); QByteArray input = socket->readAll();
//qDebug("QTracker: Raw request:\n%s", input.data()); //qDebug("QTracker: Raw request:\n%s", input.data());
QHttpRequestHeader http_request(input); QHttpRequestHeader http_request(input);
if(!http_request.isValid()) { if (!http_request.isValid()) {
qDebug("QTracker: Invalid HTTP Request:\n %s", qPrintable(http_request.toString())); qDebug("QTracker: Invalid HTTP Request:\n %s", qPrintable(http_request.toString()));
respondInvalidRequest(socket, 100, "Invalid request type"); respondInvalidRequest(socket, 100, "Invalid request type");
return; return;
} }
//qDebug("QTracker received the following request:\n%s", qPrintable(parser.toString())); //qDebug("QTracker received the following request:\n%s", qPrintable(parser.toString()));
// Request is correct, is it a GET request? // 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())); qDebug("QTracker: Unsupported HTTP request: %s", qPrintable(http_request.method()));
respondInvalidRequest(socket, 100, "Invalid request type"); respondInvalidRequest(socket, 100, "Invalid request type");
return; 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())); qDebug("QTracker: Unrecognized path: %s", qPrintable(http_request.path()));
respondInvalidRequest(socket, 100, "Invalid request type"); respondInvalidRequest(socket, 100, "Invalid request type");
return; return;
@ -134,82 +134,82 @@ void QTracker::respondToAnnounceRequest(QTcpSocket *socket,
// IP // IP
annonce_req.peer.ip = socket->peerAddress().toString(); annonce_req.peer.ip = socket->peerAddress().toString();
// 1. Get info_hash // 1. Get info_hash
if(!get_parameters.contains("info_hash")) { if (!get_parameters.contains("info_hash")) {
qDebug("QTracker: Missing info_hash"); qDebug("QTracker: Missing info_hash");
respondInvalidRequest(socket, 101, "Missing info_hash"); respondInvalidRequest(socket, 101, "Missing info_hash");
return; return;
} }
annonce_req.info_hash = get_parameters.value("info_hash"); annonce_req.info_hash = get_parameters.value("info_hash");
// info_hash cannot be longer than 20 bytes // 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()); 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"); respondInvalidRequest(socket, 150, "Invalid infohash");
return; return;
}*/ }*/
// 2. Get peer ID // 2. Get peer ID
if(!get_parameters.contains("peer_id")) { if (!get_parameters.contains("peer_id")) {
qDebug("QTracker: Missing peer_id"); qDebug("QTracker: Missing peer_id");
respondInvalidRequest(socket, 102, "Missing peer_id"); respondInvalidRequest(socket, 102, "Missing peer_id");
return; return;
} }
annonce_req.peer.peer_id = get_parameters.value("peer_id"); annonce_req.peer.peer_id = get_parameters.value("peer_id");
// peer_id cannot be longer than 20 bytes // 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)); qDebug("QTracker: peer_id is not 20 byte long: %s", qPrintable(annonce_req.peer.peer_id));
respondInvalidRequest(socket, 151, "Invalid peerid"); respondInvalidRequest(socket, 151, "Invalid peerid");
return; return;
}*/ }*/
// 3. Get port // 3. Get port
if(!get_parameters.contains("port")) { if (!get_parameters.contains("port")) {
qDebug("QTracker: Missing port"); qDebug("QTracker: Missing port");
respondInvalidRequest(socket, 103, "Missing port"); respondInvalidRequest(socket, 103, "Missing port");
return; return;
} }
bool ok = false; bool ok = false;
annonce_req.peer.port = get_parameters.value("port").toInt(&ok); 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); qDebug("QTracker: Invalid port number (%d)", annonce_req.peer.port);
respondInvalidRequest(socket, 103, "Missing port"); respondInvalidRequest(socket, 103, "Missing port");
return; return;
} }
// 4. Get event // 4. Get event
annonce_req.event = ""; annonce_req.event = "";
if(get_parameters.contains("event")) { if (get_parameters.contains("event")) {
annonce_req.event = get_parameters.value("event"); annonce_req.event = get_parameters.value("event");
qDebug("QTracker: event is %s", qPrintable(annonce_req.event)); qDebug("QTracker: event is %s", qPrintable(annonce_req.event));
} }
// 5. Get numwant // 5. Get numwant
annonce_req.numwant = 50; annonce_req.numwant = 50;
if(get_parameters.contains("numwant")) { if (get_parameters.contains("numwant")) {
int tmp = get_parameters.value("numwant").toInt(); int tmp = get_parameters.value("numwant").toInt();
if(tmp > 0) { if (tmp > 0) {
qDebug("QTracker: numwant=%d", tmp); qDebug("QTracker: numwant=%d", tmp);
annonce_req.numwant = tmp; annonce_req.numwant = tmp;
} }
} }
// 6. no_peer_id (extension) // 6. no_peer_id (extension)
annonce_req.no_peer_id = false; 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; annonce_req.no_peer_id = true;
} }
// 7. TODO: support "compact" extension // 7. TODO: support "compact" extension
// Done parsing, now let's reply // Done parsing, now let's reply
if(m_torrents.contains(annonce_req.info_hash)) { if (m_torrents.contains(annonce_req.info_hash)) {
if(annonce_req.event == "stopped") { if (annonce_req.event == "stopped") {
qDebug("QTracker: Peer stopped downloading, deleting it from the list"); qDebug("QTracker: Peer stopped downloading, deleting it from the list");
m_torrents[annonce_req.info_hash].remove(annonce_req.peer.qhash()); m_torrents[annonce_req.info_hash].remove(annonce_req.peer.qhash());
return; return;
} }
} else { } else {
// Unknown torrent // Unknown torrent
if(m_torrents.size() == MAX_TORRENTS) { if (m_torrents.size() == MAX_TORRENTS) {
// Reached max size, remove a random torrent // Reached max size, remove a random torrent
m_torrents.erase(m_torrents.begin()); m_torrents.erase(m_torrents.begin());
} }
} }
// Register the user // Register the user
PeerList peers = m_torrents.value(annonce_req.info_hash); 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 // Too many peers, remove a random one
peers.erase(peers.begin()); peers.erase(peers.begin());
} }
@ -226,8 +226,8 @@ void QTracker::ReplyWithPeerList(QTcpSocket *socket, const TrackerAnnounceReques
reply_dict["interval"] = entry(ANNOUNCE_INTERVAL); reply_dict["interval"] = entry(ANNOUNCE_INTERVAL);
QList<QPeer> peers = m_torrents.value(annonce_req.info_hash).values(); QList<QPeer> peers = m_torrents.value(annonce_req.info_hash).values();
entry::list_type peer_list; entry::list_type peer_list;
foreach(const QPeer & p, peers) { foreach (const QPeer & p, peers) {
//if(p != annonce_req.peer) //if (p != annonce_req.peer)
peer_list.push_back(p.toEntry(annonce_req.no_peer_id)); peer_list.push_back(p.toEntry(annonce_req.no_peer_id));
} }
reply_dict["peers"] = entry(peer_list); reply_dict["peers"] = entry(peer_list);

View file

@ -77,7 +77,7 @@ public:
case TorrentModelItem::TR_SEEDS: case TorrentModelItem::TR_SEEDS:
case TorrentModelItem::TR_PEERS: { case TorrentModelItem::TR_PEERS: {
QString display = QString::number(index.data().toLongLong()); 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 // Scrape was successful, we have total values
display += " ("+QString::number(index.data(Qt::UserRole).toLongLong())+")"; display += " ("+QString::number(index.data(Qt::UserRole).toLongLong())+")";
} }
@ -132,7 +132,7 @@ public:
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
const qlonglong limit = index.data().toLongLong(); const qlonglong limit = index.data().toLongLong();
opt.displayAlignment = Qt::AlignRight; 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)")); QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::number(limit/1024., 'f', 1) + " " + tr("KiB/s", "KiB/second (.i.e per second)"));
else else
QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8("")); QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8(""));
@ -142,7 +142,7 @@ public:
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
QString txt = misc::userFriendlyDuration(index.data().toLongLong()); QString txt = misc::userFriendlyDuration(index.data().toLongLong());
qlonglong seeding_time = index.data(Qt::UserRole).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))+")"; txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(misc::userFriendlyDuration(seeding_time))+")";
QItemDelegate::drawDisplay(painter, opt, opt.rect, txt); QItemDelegate::drawDisplay(painter, opt, opt.rect, txt);
break; break;
@ -156,7 +156,7 @@ public:
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
opt.displayAlignment = Qt::AlignRight; opt.displayAlignment = Qt::AlignRight;
const qreal ratio = index.data().toDouble(); const qreal ratio = index.data().toDouble();
if(ratio > QBtSession::MAX_RATIO) if (ratio > QBtSession::MAX_RATIO)
QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8("")); QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8(""));
else else
QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::number(ratio, 'f', 2)); QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::number(ratio, 'f', 2));
@ -164,7 +164,7 @@ public:
} }
case TorrentModelItem::TR_PRIORITY: { case TorrentModelItem::TR_PRIORITY: {
const int priority = index.data().toInt(); const int priority = index.data().toInt();
if(priority >= 0) { if (priority >= 0) {
opt.displayAlignment = Qt::AlignRight; opt.displayAlignment = Qt::AlignRight;
QItemDelegate::paint(painter, opt, index); QItemDelegate::paint(painter, opt, index);
} else { } else {
@ -179,7 +179,7 @@ public:
qreal progress = index.data().toDouble()*100.; qreal progress = index.data().toDouble()*100.;
// We don't want to display 100% unless // We don't want to display 100% unless
// the torrent is really complete // the torrent is really complete
if(progress > 99.94 && progress < 100.) if (progress > 99.94 && progress < 100.)
progress = 99.9; progress = 99.9;
newopt.rect = opt.rect; newopt.rect = opt.rect;
newopt.text = QString::number(progress, 'f', 1)+"%"; newopt.text = QString::number(progress, 'f', 1)+"%";

View file

@ -67,8 +67,8 @@ public:
// Redefine addItem() to make sure the list stays sorted // Redefine addItem() to make sure the list stays sorted
void addItem(QListWidgetItem *it) { void addItem(QListWidgetItem *it) {
Q_ASSERT(count() >= 2); Q_ASSERT(count() >= 2);
for(int i=2; i<count(); ++i) { for (int i=2; i<count(); ++i) {
if(item(i)->text().localeAwareCompare(it->text()) >= 0) { if (item(i)->text().localeAwareCompare(it->text()) >= 0) {
insertItem(i, it); insertItem(i, it);
return; return;
} }
@ -87,8 +87,8 @@ public:
int rowFromLabel(QString label) const { int rowFromLabel(QString label) const {
Q_ASSERT(!label.isEmpty()); Q_ASSERT(!label.isEmpty());
for(int i=2; i<count(); ++i) { for (int i=2; i<count(); ++i) {
if(label == labelFromRow(i)) return i; if (label == labelFromRow(i)) return i;
} }
return -1; return -1;
} }
@ -98,9 +98,9 @@ signals:
protected: protected:
void dragMoveEvent(QDragMoveEvent *event) { void dragMoveEvent(QDragMoveEvent *event) {
if(itemAt(event->pos()) && row(itemAt(event->pos())) > 0) { if (itemAt(event->pos()) && row(itemAt(event->pos())) > 0) {
if(itemHover) { if (itemHover) {
if(itemHover != itemAt(event->pos())) { if (itemHover != itemAt(event->pos())) {
setItemHover(false); setItemHover(false);
itemHover = itemAt(event->pos()); itemHover = itemAt(event->pos());
setItemHover(true); setItemHover(true);
@ -111,7 +111,7 @@ protected:
} }
event->acceptProposedAction(); event->acceptProposedAction();
} else { } else {
if(itemHover) if (itemHover)
setItemHover(false); setItemHover(false);
event->ignore(); event->ignore();
} }
@ -119,7 +119,7 @@ protected:
void dropEvent(QDropEvent *event) { void dropEvent(QDropEvent *event) {
qDebug("Drop Event in labels list"); qDebug("Drop Event in labels list");
if(itemAt(event->pos())) { if (itemAt(event->pos())) {
emit torrentDropped(row(itemAt(event->pos()))); emit torrentDropped(row(itemAt(event->pos())));
} }
event->ignore(); event->ignore();
@ -129,7 +129,7 @@ protected:
} }
void dragLeaveEvent(QDragLeaveEvent*) { void dragLeaveEvent(QDragLeaveEvent*) {
if(itemHover) if (itemHover)
setItemHover(false); setItemHover(false);
// Select current item again // Select current item again
currentItem()->setSelected(true); currentItem()->setSelected(true);
@ -137,7 +137,7 @@ protected:
void setItemHover(bool hover) { void setItemHover(bool hover) {
Q_ASSERT(itemHover); Q_ASSERT(itemHover);
if(hover) { if (hover) {
itemHover->setData(Qt::DecorationRole, IconProvider::instance()->getIcon("folder-documents.png")); itemHover->setData(Qt::DecorationRole, IconProvider::instance()->getIcon("folder-documents.png"));
itemHover->setSelected(true); itemHover->setSelected(true);
//setCurrentItem(itemHover); //setCurrentItem(itemHover);
@ -271,7 +271,7 @@ public:
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
statusFilters->setCurrentRow(settings.value("TransferListFilters/selectedFilterIndex", 0).toInt()); statusFilters->setCurrentRow(settings.value("TransferListFilters/selectedFilterIndex", 0).toInt());
const QStringList label_list = Preferences().getTorrentLabels(); const QStringList label_list = Preferences().getTorrentLabels();
foreach(const QString &label, label_list) { foreach (const QString &label, label_list) {
customLabels.insert(label, 0); customLabels.insert(label, 0);
qDebug("Creating label QListWidgetItem: %s", qPrintable(label)); qDebug("Creating label QListWidgetItem: %s", qPrintable(label));
QListWidgetItem *newLabel = new QListWidgetItem(); QListWidgetItem *newLabel = new QListWidgetItem();
@ -294,7 +294,7 @@ protected slots:
void torrentDropped(int row) { void torrentDropped(int row) {
Q_ASSERT(row > 0); Q_ASSERT(row > 0);
if(row == 1) { if (row == 1) {
transferList->setSelectionLabel(""); transferList->setSelectionLabel("");
} else { } else {
transferList->setSelectionLabel(labelFilters->labelFromRow(row)); transferList->setSelectionLabel(labelFilters->labelFromRow(row));
@ -303,7 +303,7 @@ protected slots:
void addLabel(QString label) { void addLabel(QString label) {
label = misc::toValidFileSystemName(label.trimmed()); label = misc::toValidFileSystemName(label.trimmed());
if(label.isEmpty() || customLabels.contains(label)) return; if (label.isEmpty() || customLabels.contains(label)) return;
QListWidgetItem *newLabel = new QListWidgetItem(); QListWidgetItem *newLabel = new QListWidgetItem();
newLabel->setText(label + " (0)"); newLabel->setText(label + " (0)");
newLabel->setData(Qt::DecorationRole, IconProvider::instance()->getIcon("inode-directory")); newLabel->setData(Qt::DecorationRole, IconProvider::instance()->getIcon("inode-directory"));
@ -315,7 +315,7 @@ protected slots:
void showLabelMenu(QPoint) { void showLabelMenu(QPoint) {
QMenu labelMenu(labelFilters); QMenu labelMenu(labelFilters);
QAction *removeAct = 0; 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")); removeAct = labelMenu.addAction(IconProvider::instance()->getIcon("list-remove"), tr("Remove label"));
QAction *addAct = labelMenu.addAction(IconProvider::instance()->getIcon("list-add"), tr("Add label...")); QAction *addAct = labelMenu.addAction(IconProvider::instance()->getIcon("list-add"), tr("Add label..."));
labelMenu.addSeparator(); labelMenu.addSeparator();
@ -324,24 +324,24 @@ protected slots:
QAction *deleteTorrentsAct = labelMenu.addAction(IconProvider::instance()->getIcon("edit-delete"), tr("Delete torrents")); QAction *deleteTorrentsAct = labelMenu.addAction(IconProvider::instance()->getIcon("edit-delete"), tr("Delete torrents"));
QAction *act = 0; QAction *act = 0;
act = labelMenu.exec(QCursor::pos()); act = labelMenu.exec(QCursor::pos());
if(act) { if (act) {
if(act == removeAct) { if (act == removeAct) {
removeSelectedLabel(); removeSelectedLabel();
return; return;
} }
if(act == deleteTorrentsAct) { if (act == deleteTorrentsAct) {
transferList->deleteVisibleTorrents(); transferList->deleteVisibleTorrents();
return; return;
} }
if(act == startAct) { if (act == startAct) {
transferList->startVisibleTorrents(); transferList->startVisibleTorrents();
return; return;
} }
if(act == pauseAct) { if (act == pauseAct) {
transferList->pauseVisibleTorrents(); transferList->pauseVisibleTorrents();
return; return;
} }
if(act == addAct) { if (act == addAct) {
bool ok; bool ok;
QString label = ""; QString label = "";
bool invalid; bool invalid;
@ -349,7 +349,7 @@ protected slots:
invalid = false; invalid = false;
label = QInputDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, label, &ok); label = QInputDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, label, &ok);
if (ok && !label.isEmpty()) { if (ok && !label.isEmpty()) {
if(misc::isValidFileSystemName(label)) { if (misc::isValidFileSystemName(label)) {
addLabel(label); addLabel(label);
} else { } else {
QMessageBox::warning(this, tr("Invalid label name"), tr("Please don't use any special characters in the label name.")); 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) { void torrentChangedLabel(TorrentModelItem *torrentItem, QString old_label, QString new_label) {
Q_UNUSED(torrentItem); Q_UNUSED(torrentItem);
qDebug("Torrent label changed from %s to %s", qPrintable(old_label), qPrintable(new_label)); qDebug("Torrent label changed from %s to %s", qPrintable(old_label), qPrintable(new_label));
if(!old_label.isEmpty()) { if (!old_label.isEmpty()) {
if(customLabels.contains(old_label)) { if (customLabels.contains(old_label)) {
const int new_count = customLabels.value(old_label, 0) - 1; const int new_count = customLabels.value(old_label, 0) - 1;
Q_ASSERT(new_count >= 0); Q_ASSERT(new_count >= 0);
customLabels.insert(old_label, new_count); customLabels.insert(old_label, new_count);
@ -406,8 +406,8 @@ protected slots:
} }
--nb_labeled; --nb_labeled;
} }
if(!new_label.isEmpty()) { if (!new_label.isEmpty()) {
if(!customLabels.contains(new_label)) if (!customLabels.contains(new_label))
addLabel(new_label); addLabel(new_label);
const int new_count = customLabels.value(new_label, 0) + 1; const int new_count = customLabels.value(new_label, 0) + 1;
Q_ASSERT(new_count >= 1); Q_ASSERT(new_count >= 1);
@ -423,8 +423,8 @@ protected slots:
void handleNewTorrent(TorrentModelItem* torrentItem) { void handleNewTorrent(TorrentModelItem* torrentItem) {
QString label = torrentItem->data(TorrentModelItem::TR_LABEL).toString(); QString label = torrentItem->data(TorrentModelItem::TR_LABEL).toString();
qDebug("New torrent was added with label: %s", qPrintable(label)); qDebug("New torrent was added with label: %s", qPrintable(label));
if(!label.isEmpty()) { if (!label.isEmpty()) {
if(!customLabels.contains(label)) { if (!customLabels.contains(label)) {
addLabel(label); addLabel(label);
} }
// Update label counter // Update label counter
@ -448,7 +448,7 @@ protected slots:
void torrentAboutToBeDeleted(TorrentModelItem* torrentItem) { void torrentAboutToBeDeleted(TorrentModelItem* torrentItem) {
Q_ASSERT(torrentItem); Q_ASSERT(torrentItem);
QString label = torrentItem->data(TorrentModelItem::TR_LABEL).toString(); QString label = torrentItem->data(TorrentModelItem::TR_LABEL).toString();
if(!label.isEmpty()) { if (!label.isEmpty()) {
// Update label counter // Update label counter
const int new_count = customLabels.value(label, 0) - 1; const int new_count = customLabels.value(label, 0) - 1;
customLabels.insert(label, new_count); customLabels.insert(label, new_count);

View file

@ -108,7 +108,7 @@ TransferListWidget::TransferListWidget(QWidget *parent, MainWindow *main_window,
setDragDropMode(QAbstractItemView::DragOnly); setDragDropMode(QAbstractItemView::DragOnly);
// Default hidden columns // Default hidden columns
if(!column_loaded) { if (!column_loaded) {
setColumnHidden(TorrentModelItem::TR_PRIORITY, true); setColumnHidden(TorrentModelItem::TR_PRIORITY, true);
setColumnHidden(TorrentModelItem::TR_ADD_DATE, true); setColumnHidden(TorrentModelItem::TR_ADD_DATE, true);
setColumnHidden(TorrentModelItem::TR_SEED_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 { inline QModelIndex TransferListWidget::mapToSource(const QModelIndex &index) const {
Q_ASSERT(index.isValid()); Q_ASSERT(index.isValid());
if(index.model() == nameFilterModel) if (index.model() == nameFilterModel)
return labelFilterModel->mapToSource(statusFilterModel->mapToSource(nameFilterModel->mapToSource(index))); 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(statusFilterModel->mapToSource(index));
return labelFilterModel->mapToSource(index); return labelFilterModel->mapToSource(index);
} }
@ -188,9 +188,9 @@ void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) {
const int row = mapToSource(index).row(); const int row = mapToSource(index).row();
const QString hash = getHashFromRow(row); const QString hash = getHashFromRow(row);
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(!h.is_valid()) return; if (!h.is_valid()) return;
int action; int action;
if(h.is_seed()) { if (h.is_seed()) {
action = Preferences().getActionOnDblClOnTorrentFn(); action = Preferences().getActionOnDblClOnTorrentFn();
} else { } else {
action = Preferences().getActionOnDblClOnTorrentDl(); action = Preferences().getActionOnDblClOnTorrentDl();
@ -198,7 +198,7 @@ void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) {
switch(action) { switch(action) {
case TOGGLE_PAUSE: case TOGGLE_PAUSE:
if(h.is_paused()) { if (h.is_paused()) {
h.resume(); h.resume();
} else { } else {
h.pause(); h.pause();
@ -213,7 +213,7 @@ void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) {
QStringList TransferListWidget::getSelectedTorrentsHashes() const { QStringList TransferListWidget::getSelectedTorrentsHashes() const {
QStringList hashes; QStringList hashes;
const QModelIndexList selectedIndexes = selectionModel()->selectedRows(); const QModelIndexList selectedIndexes = selectionModel()->selectedRows();
foreach(const QModelIndex &index, selectedIndexes) { foreach (const QModelIndex &index, selectedIndexes) {
hashes << getHashFromRow(mapToSource(index).row()); hashes << getHashFromRow(mapToSource(index).row());
} }
return hashes; return hashes;
@ -221,22 +221,22 @@ QStringList TransferListWidget::getSelectedTorrentsHashes() const {
void TransferListWidget::setSelectedTorrentsLocation() { void TransferListWidget::setSelectedTorrentsLocation() {
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
if(hashes.isEmpty()) return; if (hashes.isEmpty()) return;
QString dir; QString dir;
const QDir saveDir(TorrentPersistentData::getSavePath(hashes.first())); const QDir saveDir(TorrentPersistentData::getSavePath(hashes.first()));
qDebug("Old save path is %s", qPrintable(saveDir.absolutePath())); qDebug("Old save path is %s", qPrintable(saveDir.absolutePath()));
dir = QFileDialog::getExistingDirectory(this, tr("Choose save path"), saveDir.absolutePath(), dir = QFileDialog::getExistingDirectory(this, tr("Choose save path"), saveDir.absolutePath(),
QFileDialog::DontConfirmOverwrite|QFileDialog::ShowDirsOnly|QFileDialog::HideNameFilterDetails); QFileDialog::DontConfirmOverwrite|QFileDialog::ShowDirsOnly|QFileDialog::HideNameFilterDetails);
if(!dir.isNull()) { if (!dir.isNull()) {
qDebug("New path is %s", qPrintable(dir)); qDebug("New path is %s", qPrintable(dir));
// Check if savePath exists // Check if savePath exists
QDir savePath(misc::expandPath(dir)); QDir savePath(misc::expandPath(dir));
qDebug("New path after clean up is %s", qPrintable(savePath.absolutePath())); qDebug("New path after clean up is %s", qPrintable(savePath.absolutePath()));
foreach(const QString & hash, hashes) { foreach (const QString & hash, hashes) {
// Actually move storage // Actually move storage
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(!BTSession->useTemporaryFolder() || h.is_seed()) { if (!BTSession->useTemporaryFolder() || h.is_seed()) {
if(!savePath.exists()) savePath.mkpath(savePath.absolutePath()); if (!savePath.exists()) savePath.mkpath(savePath.absolutePath());
h.move_storage(savePath.absolutePath()); h.move_storage(savePath.absolutePath());
} else { } else {
TorrentPersistentData::saveSavePath(h.hash(), savePath.absolutePath()); TorrentPersistentData::saveSavePath(h.hash(), savePath.absolutePath());
@ -248,79 +248,79 @@ void TransferListWidget::setSelectedTorrentsLocation() {
void TransferListWidget::startSelectedTorrents() { void TransferListWidget::startSelectedTorrents() {
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
BTSession->resumeTorrent(hash); BTSession->resumeTorrent(hash);
} }
} }
void TransferListWidget::startVisibleTorrents() { void TransferListWidget::startVisibleTorrents() {
QStringList hashes; QStringList hashes;
for(int i=0; i<nameFilterModel->rowCount(); ++i) { for (int i=0; i<nameFilterModel->rowCount(); ++i) {
const int row = mapToSource(nameFilterModel->index(i, 0)).row(); const int row = mapToSource(nameFilterModel->index(i, 0)).row();
hashes << getHashFromRow(row); hashes << getHashFromRow(row);
} }
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
BTSession->resumeTorrent(hash); BTSession->resumeTorrent(hash);
} }
} }
void TransferListWidget::pauseSelectedTorrents() { void TransferListWidget::pauseSelectedTorrents() {
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
BTSession->pauseTorrent(hash); BTSession->pauseTorrent(hash);
} }
} }
void TransferListWidget::pauseVisibleTorrents() { void TransferListWidget::pauseVisibleTorrents() {
QStringList hashes; QStringList hashes;
for(int i=0; i<nameFilterModel->rowCount(); ++i) { for (int i=0; i<nameFilterModel->rowCount(); ++i) {
const int row = mapToSource(nameFilterModel->index(i, 0)).row(); const int row = mapToSource(nameFilterModel->index(i, 0)).row();
hashes << getHashFromRow(row); hashes << getHashFromRow(row);
} }
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
BTSession->pauseTorrent(hash); BTSession->pauseTorrent(hash);
} }
} }
void TransferListWidget::deleteSelectedTorrents() { void TransferListWidget::deleteSelectedTorrents() {
if(main_window->getCurrentTabWidget() != this) return; if (main_window->getCurrentTabWidget() != this) return;
const QStringList& hashes = getSelectedTorrentsHashes(); const QStringList& hashes = getSelectedTorrentsHashes();
if(hashes.empty()) return; if (hashes.empty()) return;
bool delete_local_files = false; bool delete_local_files = false;
if(Preferences().confirmTorrentDeletion() && if (Preferences().confirmTorrentDeletion() &&
!DeletionConfirmationDlg::askForDeletionConfirmation(&delete_local_files)) !DeletionConfirmationDlg::askForDeletionConfirmation(&delete_local_files))
return; return;
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
BTSession->deleteTorrent(hash, delete_local_files); BTSession->deleteTorrent(hash, delete_local_files);
} }
} }
void TransferListWidget::deleteVisibleTorrents() { void TransferListWidget::deleteVisibleTorrents() {
if(nameFilterModel->rowCount() <= 0) return; if (nameFilterModel->rowCount() <= 0) return;
bool delete_local_files = false; bool delete_local_files = false;
if(Preferences().confirmTorrentDeletion() && if (Preferences().confirmTorrentDeletion() &&
!DeletionConfirmationDlg::askForDeletionConfirmation(&delete_local_files)) !DeletionConfirmationDlg::askForDeletionConfirmation(&delete_local_files))
return; return;
QStringList hashes; QStringList hashes;
for(int i=0; i<nameFilterModel->rowCount(); ++i) { for (int i=0; i<nameFilterModel->rowCount(); ++i) {
const int row = mapToSource(nameFilterModel->index(i, 0)).row(); const int row = mapToSource(nameFilterModel->index(i, 0)).row();
hashes << getHashFromRow(row); hashes << getHashFromRow(row);
} }
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
BTSession->deleteTorrent(hash, delete_local_files); BTSession->deleteTorrent(hash, delete_local_files);
} }
} }
void TransferListWidget::increasePrioSelectedTorrents() { void TransferListWidget::increasePrioSelectedTorrents() {
qDebug() << Q_FUNC_INFO; qDebug() << Q_FUNC_INFO;
if(main_window->getCurrentTabWidget() != this) return; if (main_window->getCurrentTabWidget() != this) return;
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
std::priority_queue<QPair<int, QTorrentHandle>, std::vector<QPair<int, QTorrentHandle> >, std::greater<QPair<int, QTorrentHandle> > > torrent_queue; std::priority_queue<QPair<int, QTorrentHandle>, std::vector<QPair<int, QTorrentHandle> >, std::greater<QPair<int, QTorrentHandle> > > torrent_queue;
// Sort torrents by priority // Sort torrents by priority
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
try { try {
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(!h.is_seed()) { if (!h.is_seed()) {
torrent_queue.push(qMakePair(h.queue_position(), h)); torrent_queue.push(qMakePair(h.queue_position(), h));
} }
}catch(invalid_handle&){} }catch(invalid_handle&){}
@ -337,14 +337,14 @@ void TransferListWidget::increasePrioSelectedTorrents() {
void TransferListWidget::decreasePrioSelectedTorrents() { void TransferListWidget::decreasePrioSelectedTorrents() {
qDebug() << Q_FUNC_INFO; qDebug() << Q_FUNC_INFO;
if(main_window->getCurrentTabWidget() != this) return; if (main_window->getCurrentTabWidget() != this) return;
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
std::priority_queue<QPair<int, QTorrentHandle>, std::vector<QPair<int, QTorrentHandle> >, std::less<QPair<int, QTorrentHandle> > > torrent_queue; std::priority_queue<QPair<int, QTorrentHandle>, std::vector<QPair<int, QTorrentHandle> >, std::less<QPair<int, QTorrentHandle> > > torrent_queue;
// Sort torrents by priority // Sort torrents by priority
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
try { try {
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(!h.is_seed()) { if (!h.is_seed()) {
torrent_queue.push(qMakePair(h.queue_position(), h)); torrent_queue.push(qMakePair(h.queue_position(), h));
} }
}catch(invalid_handle&){} }catch(invalid_handle&){}
@ -360,22 +360,22 @@ void TransferListWidget::decreasePrioSelectedTorrents() {
} }
void TransferListWidget::topPrioSelectedTorrents() { void TransferListWidget::topPrioSelectedTorrents() {
if(main_window->getCurrentTabWidget() != this) return; if (main_window->getCurrentTabWidget() != this) return;
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(h.is_valid() && !h.is_seed()) { if (h.is_valid() && !h.is_seed()) {
h.queue_position_top(); h.queue_position_top();
} }
} }
} }
void TransferListWidget::bottomPrioSelectedTorrents() { void TransferListWidget::bottomPrioSelectedTorrents() {
if(main_window->getCurrentTabWidget() != this) return; if (main_window->getCurrentTabWidget() != this) return;
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(h.is_valid() && !h.is_seed()) { if (h.is_valid() && !h.is_seed()) {
h.queue_position_bottom(); h.queue_position_bottom();
} }
} }
@ -384,9 +384,9 @@ void TransferListWidget::bottomPrioSelectedTorrents() {
void TransferListWidget::copySelectedMagnetURIs() const { void TransferListWidget::copySelectedMagnetURIs() const {
QStringList magnet_uris; QStringList magnet_uris;
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
const QTorrentHandle h = BTSession->getTorrentHandle(hash); 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())); magnet_uris << misc::toQString(make_magnet_uri(h.get_torrent_info()));
} }
qApp->clipboard()->setText(magnet_uris.join("\n")); qApp->clipboard()->setText(magnet_uris.join("\n"));
@ -400,12 +400,12 @@ void TransferListWidget::hidePriorityColumn(bool hide) {
void TransferListWidget::openSelectedTorrentsFolder() const { void TransferListWidget::openSelectedTorrentsFolder() const {
QStringList pathsList; QStringList pathsList;
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
const QTorrentHandle h = BTSession->getTorrentHandle(hash); const QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(h.is_valid()) { if (h.is_valid()) {
const QString savePath = h.save_path(); const QString savePath = h.save_path();
qDebug("Opening path at %s", qPrintable(savePath)); qDebug("Opening path at %s", qPrintable(savePath));
if(!pathsList.contains(savePath)) { if (!pathsList.contains(savePath)) {
pathsList.append(savePath); pathsList.append(savePath);
QDesktopServices::openUrl(QUrl::fromLocalFile(savePath)); QDesktopServices::openUrl(QUrl::fromLocalFile(savePath));
} }
@ -415,9 +415,9 @@ void TransferListWidget::openSelectedTorrentsFolder() const {
void TransferListWidget::previewSelectedTorrents() { void TransferListWidget::previewSelectedTorrents() {
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
const QTorrentHandle h = BTSession->getTorrentHandle(hash); const QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(h.is_valid() && h.has_metadata()) { if (h.is_valid() && h.has_metadata()) {
new PreviewSelect(this, h); new PreviewSelect(this, h);
} }
} }
@ -428,28 +428,28 @@ void TransferListWidget::setDlLimitSelectedTorrents() {
bool first = true; bool first = true;
bool all_same_limit = true; bool all_same_limit = true;
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
const QTorrentHandle h = BTSession->getTorrentHandle(hash); const QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(h.is_valid() && !h.is_seed()) { if (h.is_valid() && !h.is_seed()) {
selected_torrents << h; selected_torrents << h;
// Determine current limit for selected torrents // Determine current limit for selected torrents
if(first) { if (first) {
first = false; first = false;
} else { } 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; all_same_limit = false;
} }
} }
} }
if(selected_torrents.empty()) return; if (selected_torrents.empty()) return;
bool ok=false; bool ok=false;
int default_limit = -1; int default_limit = -1;
if(all_same_limit) if (all_same_limit)
default_limit = selected_torrents.first().download_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.); const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Download Speed Limiting"), default_limit, Preferences().getGlobalDownloadLimit()*1024.);
if(ok) { if (ok) {
foreach(const QTorrentHandle &h, selected_torrents) { 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())); 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); BTSession->setDownloadLimit(h.hash(), new_limit);
} }
@ -461,28 +461,28 @@ void TransferListWidget::setUpLimitSelectedTorrents() {
bool first = true; bool first = true;
bool all_same_limit = true; bool all_same_limit = true;
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
const QTorrentHandle h = BTSession->getTorrentHandle(hash); const QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(h.is_valid()) { if (h.is_valid()) {
selected_torrents << h; selected_torrents << h;
// Determine current limit for selected torrents // Determine current limit for selected torrents
if(first) { if (first) {
first = false; first = false;
} else { } 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; all_same_limit = false;
} }
} }
} }
if(selected_torrents.empty()) return; if (selected_torrents.empty()) return;
bool ok=false; bool ok=false;
int default_limit = -1; int default_limit = -1;
if(all_same_limit) if (all_same_limit)
default_limit = selected_torrents.first().upload_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.); const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Upload Speed Limiting"), default_limit, Preferences().getGlobalUploadLimit()*1024.);
if(ok) { if (ok) {
foreach(const QTorrentHandle &h, selected_torrents) { 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())); 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); BTSession->setUploadLimit(h.hash(), new_limit);
} }
@ -514,7 +514,7 @@ void TransferListWidget::setMaxRatioSelectedTorrents() {
void TransferListWidget::recheckSelectedTorrents() { void TransferListWidget::recheckSelectedTorrents() {
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
BTSession->recheckTorrent(hash); BTSession->recheckTorrent(hash);
} }
} }
@ -524,8 +524,8 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&){
QMenu hideshowColumn(this); QMenu hideshowColumn(this);
hideshowColumn.setTitle(tr("Column visibility")); hideshowColumn.setTitle(tr("Column visibility"));
QList<QAction*> actions; QList<QAction*> actions;
for(int i=0; i < listModel->columnCount(); ++i) { for (int i=0; i < listModel->columnCount(); ++i) {
if(!BTSession->isQueueingEnabled() && i == TorrentModelItem::TR_PRIORITY) { if (!BTSession->isQueueingEnabled() && i == TorrentModelItem::TR_PRIORITY) {
actions.append(0); actions.append(0);
continue; continue;
} }
@ -536,21 +536,21 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&){
} }
// Call menu // Call menu
QAction *act = hideshowColumn.exec(QCursor::pos()); QAction *act = hideshowColumn.exec(QCursor::pos());
if(act) { if (act) {
int col = actions.indexOf(act); int col = actions.indexOf(act);
Q_ASSERT(col >= 0); Q_ASSERT(col >= 0);
qDebug("Toggling column %d visibility", col); qDebug("Toggling column %d visibility", col);
setColumnHidden(col, !isColumnHidden(col)); setColumnHidden(col, !isColumnHidden(col));
if(!isColumnHidden(col) && columnWidth(col) <= 5) if (!isColumnHidden(col) && columnWidth(col) <= 5)
setColumnWidth(col, 100); setColumnWidth(col, 100);
} }
} }
void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const { void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const {
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
QTorrentHandle h = BTSession->getTorrentHandle(hash); 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()); h.super_seeding(!h.super_seeding());
} }
} }
@ -558,12 +558,12 @@ void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const {
void TransferListWidget::toggleSelectedTorrentsSequentialDownload() const { void TransferListWidget::toggleSelectedTorrentsSequentialDownload() const {
const QStringList hashes = getSelectedTorrentsHashes(); const QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
QTorrentHandle h = BTSession->getTorrentHandle(hash); 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(); bool was_sequential = h.is_sequential_download();
h.set_sequential_download(!was_sequential); h.set_sequential_download(!was_sequential);
if(!was_sequential) if (!was_sequential)
h.prioritize_first_last_piece(true); h.prioritize_first_last_piece(true);
} }
} }
@ -571,9 +571,9 @@ void TransferListWidget::toggleSelectedTorrentsSequentialDownload() const {
void TransferListWidget::toggleSelectedFirstLastPiecePrio() const { void TransferListWidget::toggleSelectedFirstLastPiecePrio() const {
QStringList hashes = getSelectedTorrentsHashes(); QStringList hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
QTorrentHandle h = BTSession->getTorrentHandle(hash); 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()); h.prioritize_first_last_piece(!h.first_last_piece_first());
} }
} }
@ -587,7 +587,7 @@ void TransferListWidget::askNewLabelForSelection() {
invalid = false; invalid = false;
const QString label = QInputDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, "", &ok); const QString label = QInputDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, "", &ok);
if (ok && !label.isEmpty()) { if (ok && !label.isEmpty()) {
if(misc::isValidFileSystemName(label)) { if (misc::isValidFileSystemName(label)) {
setSelectionLabel(label); setSelectionLabel(label);
} else { } else {
QMessageBox::warning(this, tr("Invalid label name"), tr("Please don't use any special characters in the label name.")); 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() { void TransferListWidget::renameSelectedTorrent() {
const QModelIndexList selectedIndexes = selectionModel()->selectedRows(); const QModelIndexList selectedIndexes = selectionModel()->selectedRows();
if(selectedIndexes.size() != 1) return; if (selectedIndexes.size() != 1) return;
if(!selectedIndexes.first().isValid()) return; if (!selectedIndexes.first().isValid()) return;
const QString hash = getHashFromRow(mapToSource(selectedIndexes.first()).row()); const QString hash = getHashFromRow(mapToSource(selectedIndexes.first()).row());
const QTorrentHandle h = BTSession->getTorrentHandle(hash); const QTorrentHandle h = BTSession->getTorrentHandle(hash);
if(!h.is_valid()) return; if (!h.is_valid()) return;
// Ask for a new Name // Ask for a new Name
bool ok; bool ok;
const QString name = QInputDialog::getText(this, tr("Rename"), tr("New name:"), QLineEdit::Normal, h.name(), &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) { void TransferListWidget::setSelectionLabel(QString label) {
const QStringList& hashes = getSelectedTorrentsHashes(); const QStringList& hashes = getSelectedTorrentsHashes();
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
Q_ASSERT(!hash.isEmpty()); Q_ASSERT(!hash.isEmpty());
const int row = getRowFromHash(hash); const int row = getRowFromHash(hash);
const QString old_label = listModel->data(listModel->index(row, TorrentModelItem::TR_LABEL)).toString(); 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) { void TransferListWidget::removeLabelFromRows(QString label) {
for(int i=0; i<listModel->rowCount(); ++i) { for (int i=0; i<listModel->rowCount(); ++i) {
if(listModel->data(listModel->index(i, TorrentModelItem::TR_LABEL)) == label) { if (listModel->data(listModel->index(i, TorrentModelItem::TR_LABEL)) == label) {
const QString hash = getHashFromRow(i); const QString hash = getHashFromRow(i);
listModel->setData(listModel->index(i, TorrentModelItem::TR_LABEL), "", Qt::DisplayRole); listModel->setData(listModel->index(i, TorrentModelItem::TR_LABEL), "", Qt::DisplayRole);
// Update save path if necessary // Update save path if necessary
@ -694,63 +694,63 @@ void TransferListWidget::displayListMenu(const QPoint&) {
bool first = true; bool first = true;
QTorrentHandle h; QTorrentHandle h;
qDebug("Displaying menu"); qDebug("Displaying menu");
foreach(const QModelIndex &index, selectedIndexes) { foreach (const QModelIndex &index, selectedIndexes) {
// Get the file name // Get the file name
QString hash = getHashFromRow(mapToSource(index).row()); QString hash = getHashFromRow(mapToSource(index).row());
// Get handle and pause the torrent // Get handle and pause the torrent
h = BTSession->getTorrentHandle(hash); h = BTSession->getTorrentHandle(hash);
if(!h.is_valid()) continue; if (!h.is_valid()) continue;
if(h.has_metadata()) if (h.has_metadata())
one_has_metadata = true; one_has_metadata = true;
if(!h.is_seed()) { if (!h.is_seed()) {
one_not_seed = true; one_not_seed = true;
if(h.has_metadata()) { if (h.has_metadata()) {
if(first) { if (first) {
sequential_download_mode = h.is_sequential_download(); sequential_download_mode = h.is_sequential_download();
prioritize_first_last = h.first_last_piece_first(); prioritize_first_last = h.first_last_piece_first();
} else { } else {
if(sequential_download_mode != h.is_sequential_download()) { if (sequential_download_mode != h.is_sequential_download()) {
all_same_sequential_download_mode = false; 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; all_same_prio_firstlast = false;
} }
} }
} }
} }
else { else {
if(!one_not_seed && all_same_super_seeding && h.has_metadata()) { if (!one_not_seed && all_same_super_seeding && h.has_metadata()) {
if(first) { if (first) {
super_seeding_mode = h.super_seeding(); super_seeding_mode = h.super_seeding();
} else { } else {
if(super_seeding_mode != h.super_seeding()) { if (super_seeding_mode != h.super_seeding()) {
all_same_super_seeding = false; all_same_super_seeding = false;
} }
} }
} }
} }
if(h.is_paused()) { if (h.is_paused()) {
if(!has_start) { if (!has_start) {
listMenu.addAction(&actionStart); listMenu.addAction(&actionStart);
has_start = true; has_start = true;
} }
}else{ }else{
if(!has_pause) { if (!has_pause) {
listMenu.addAction(&actionPause); listMenu.addAction(&actionPause);
has_pause = true; has_pause = true;
} }
} }
if(h.has_metadata() && BTSession->isFilePreviewPossible(hash) && !has_preview) { if (h.has_metadata() && BTSession->isFilePreviewPossible(hash) && !has_preview) {
has_preview = true; has_preview = true;
} }
first = false; 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.addSeparator();
listMenu.addAction(&actionDelete); listMenu.addAction(&actionDelete);
listMenu.addSeparator(); listMenu.addSeparator();
listMenu.addAction(&actionSetTorrentPath); listMenu.addAction(&actionSetTorrentPath);
if(selectedIndexes.size() == 1) if (selectedIndexes.size() == 1)
listMenu.addAction(&actionRename); listMenu.addAction(&actionRename);
// Label Menu // Label Menu
QStringList customLabels = getCustomLabels(); 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("list-add"), tr("New...", "New label..."));
labelActions << labelMenu->addAction(IconProvider::instance()->getIcon("edit-clear"), tr("Reset", "Reset label")); labelActions << labelMenu->addAction(IconProvider::instance()->getIcon("edit-clear"), tr("Reset", "Reset label"));
labelMenu->addSeparator(); labelMenu->addSeparator();
foreach(const QString &label, customLabels) { foreach (const QString &label, customLabels) {
labelActions << labelMenu->addAction(IconProvider::instance()->getIcon("inode-directory"), label); labelActions << labelMenu->addAction(IconProvider::instance()->getIcon("inode-directory"), label);
} }
listMenu.addSeparator(); listMenu.addSeparator();
if(one_not_seed) if (one_not_seed)
listMenu.addAction(&actionSet_download_limit); listMenu.addAction(&actionSet_download_limit);
listMenu.addAction(&actionSet_max_ratio); listMenu.addAction(&actionSet_max_ratio);
listMenu.addAction(&actionSet_upload_limit); 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); actionSuper_seeding_mode.setChecked(super_seeding_mode);
listMenu.addAction(&actionSuper_seeding_mode); listMenu.addAction(&actionSuper_seeding_mode);
} }
listMenu.addSeparator(); listMenu.addSeparator();
bool added_preview_action = false; bool added_preview_action = false;
if(has_preview) { if (has_preview) {
listMenu.addAction(&actionPreview_file); listMenu.addAction(&actionPreview_file);
added_preview_action = true; added_preview_action = true;
} }
if(one_not_seed && one_has_metadata) { if (one_not_seed && one_has_metadata) {
if(all_same_sequential_download_mode) { if (all_same_sequential_download_mode) {
actionSequential_download.setChecked(sequential_download_mode); actionSequential_download.setChecked(sequential_download_mode);
listMenu.addAction(&actionSequential_download); listMenu.addAction(&actionSequential_download);
added_preview_action = true; added_preview_action = true;
} }
if(all_same_prio_firstlast) { if (all_same_prio_firstlast) {
actionFirstLastPiece_prio.setChecked(prioritize_first_last); actionFirstLastPiece_prio.setChecked(prioritize_first_last);
listMenu.addAction(&actionFirstLastPiece_prio); listMenu.addAction(&actionFirstLastPiece_prio);
added_preview_action = true; added_preview_action = true;
} }
} }
if(added_preview_action) if (added_preview_action)
listMenu.addSeparator(); listMenu.addSeparator();
if(one_has_metadata) { if (one_has_metadata) {
listMenu.addAction(&actionForce_recheck); listMenu.addAction(&actionForce_recheck);
listMenu.addSeparator(); listMenu.addSeparator();
} }
listMenu.addAction(&actionOpen_destination_folder); listMenu.addAction(&actionOpen_destination_folder);
if(BTSession->isQueueingEnabled() && one_not_seed) { if (BTSession->isQueueingEnabled() && one_not_seed) {
listMenu.addSeparator(); listMenu.addSeparator();
QMenu *prioMenu = listMenu.addMenu(tr("Priority")); QMenu *prioMenu = listMenu.addMenu(tr("Priority"));
prioMenu->addAction(&actionTopPriority); prioMenu->addAction(&actionTopPriority);
@ -806,22 +806,22 @@ void TransferListWidget::displayListMenu(const QPoint&) {
prioMenu->addAction(&actionBottomPriority); prioMenu->addAction(&actionBottomPriority);
} }
listMenu.addSeparator(); listMenu.addSeparator();
if(one_has_metadata) if (one_has_metadata)
listMenu.addAction(&actionCopy_magnet_link); listMenu.addAction(&actionCopy_magnet_link);
// Call menu // Call menu
QAction *act = 0; QAction *act = 0;
act = listMenu.exec(QCursor::pos()); act = listMenu.exec(QCursor::pos());
if(act) { if (act) {
// Parse label actions only (others have slots assigned) // Parse label actions only (others have slots assigned)
int i = labelActions.indexOf(act); int i = labelActions.indexOf(act);
if(i >= 0) { if (i >= 0) {
// Label action // Label action
if(i == 0) { if (i == 0) {
// New Label // New Label
askNewLabelForSelection(); askNewLabelForSelection();
} else { } else {
QString label = ""; QString label = "";
if(i > 1) if (i > 1)
label = customLabels.at(i-2); label = customLabels.at(i-2);
// Update Label // Update Label
setSelectionLabel(label); setSelectionLabel(label);
@ -833,7 +833,7 @@ void TransferListWidget::displayListMenu(const QPoint&) {
void TransferListWidget::currentChanged(const QModelIndex& current, const QModelIndex&) { void TransferListWidget::currentChanged(const QModelIndex& current, const QModelIndex&) {
qDebug("CURRENT CHANGED"); qDebug("CURRENT CHANGED");
QTorrentHandle h; QTorrentHandle h;
if(current.isValid()) { if (current.isValid()) {
const int row = mapToSource(current).row(); const int row = mapToSource(current).row();
h = BTSession->getTorrentHandle(getHashFromRow(row)); h = BTSession->getTorrentHandle(getHashFromRow(row));
// Scroll Fix // Scroll Fix
@ -843,11 +843,11 @@ void TransferListWidget::currentChanged(const QModelIndex& current, const QModel
} }
void TransferListWidget::applyLabelFilter(QString label) { void TransferListWidget::applyLabelFilter(QString label) {
if(label == "all") { if (label == "all") {
labelFilterModel->setFilterRegExp(QRegExp()); labelFilterModel->setFilterRegExp(QRegExp());
return; return;
} }
if(label == "none") { if (label == "none") {
labelFilterModel->setFilterRegExp(QRegExp("^$")); labelFilterModel->setFilterRegExp(QRegExp("^$"));
return; return;
} }
@ -884,7 +884,7 @@ void TransferListWidget::applyStatusFilter(int f) {
statusFilterModel->setFilterRegExp(QRegExp()); statusFilterModel->setFilterRegExp(QRegExp());
} }
// Select first item if nothing is selected // 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())); 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); selectionModel()->setCurrentIndex(nameFilterModel->index(0, TorrentModelItem::TR_NAME), QItemSelectionModel::SelectCurrent|QItemSelectionModel::Rows);
} }
@ -900,7 +900,7 @@ bool TransferListWidget::loadSettings()
{ {
QIniSettings settings("qBittorrent", "qBittorrent"); QIniSettings settings("qBittorrent", "qBittorrent");
bool ok = header()->restoreState(settings.value("TransferList/HeaderState").toByteArray()); bool ok = header()->restoreState(settings.value("TransferList/HeaderState").toByteArray());
if(!ok) { if (!ok) {
header()->resizeSection(0, 200); // Default header()->resizeSection(0, 200); // Default
} }
return ok; return ok;

View file

@ -58,23 +58,23 @@ QList<QVariantMap> EventManager::getEventList() const {
QList<QVariantMap> EventManager::getPropTrackersInfo(QString hash) const { QList<QVariantMap> EventManager::getPropTrackersInfo(QString hash) const {
QList<QVariantMap> trackersInfo; QList<QVariantMap> trackersInfo;
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if (h.is_valid()) {
QHash<QString, TrackerInfos> trackers_data = QBtSession::instance()->getTrackersInfo(hash); QHash<QString, TrackerInfos> trackers_data = QBtSession::instance()->getTrackersInfo(hash);
std::vector<announce_entry> vect_trackers = h.trackers(); std::vector<announce_entry> vect_trackers = h.trackers();
std::vector<announce_entry>::iterator it; std::vector<announce_entry>::iterator it;
for(it = vect_trackers.begin(); it != vect_trackers.end(); it++) { for (it = vect_trackers.begin(); it != vect_trackers.end(); it++) {
QVariantMap tracker; QVariantMap tracker;
QString tracker_url = misc::toQString(it->url); QString tracker_url = misc::toQString(it->url);
tracker["url"] = tracker_url; tracker["url"] = tracker_url;
TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url)); TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url));
QString error_message = data.last_message.trimmed(); QString error_message = data.last_message.trimmed();
if(it->verified) { if (it->verified) {
tracker["status"] = tr("Working"); tracker["status"] = tr("Working");
} else { } else {
if(it->updating && it->fails == 0) { if (it->updating && it->fails == 0) {
tracker["status"] = tr("Updating..."); tracker["status"] = tr("Updating...");
} else { } else {
if(it->fails > 0) { if (it->fails > 0) {
tracker["status"] = tr("Not working"); tracker["status"] = tr("Not working");
} else { } else {
tracker["status"] = tr("Not contacted yet"); tracker["status"] = tr("Not contacted yet");
@ -92,21 +92,21 @@ QList<QVariantMap> EventManager::getPropTrackersInfo(QString hash) const {
QList<QVariantMap> EventManager::getPropFilesInfo(QString hash) const { QList<QVariantMap> EventManager::getPropFilesInfo(QString hash) const {
QList<QVariantMap> files; QList<QVariantMap> files;
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); 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<int> priorities = h.file_priorities(); std::vector<int> priorities = h.file_priorities();
std::vector<size_type> fp; std::vector<size_type> fp;
h.file_progress(fp); h.file_progress(fp);
for(int i=0; i<h.num_files(); ++i) { for (int i=0; i<h.num_files(); ++i) {
QVariantMap file; QVariantMap file;
file["name"] = h.filename_at(i); file["name"] = h.filename_at(i);
libtorrent::size_type size = h.filesize_at(i); libtorrent::size_type size = h.filesize_at(i);
file["size"] = misc::friendlyUnit((double)size); file["size"] = misc::friendlyUnit((double)size);
if(size > 0) if (size > 0)
file["progress"] = fp[i]/(double)size; file["progress"] = fp[i]/(double)size;
else else
file["progress"] = 1.; // Empty file... file["progress"] = 1.; // Empty file...
file["priority"] = priorities[i]; file["priority"] = priorities[i];
if(i == 0) if (i == 0)
file["is_seed"] = h.is_seed(); file["is_seed"] = h.is_seed();
files << file; files << file;
} }
@ -116,11 +116,11 @@ QList<QVariantMap> EventManager::getPropFilesInfo(QString hash) const {
void EventManager::setGlobalPreferences(QVariantMap m) { void EventManager::setGlobalPreferences(QVariantMap m) {
// UI // UI
Preferences pref; Preferences pref;
if(m.contains("locale")) { if (m.contains("locale")) {
QString locale = m["locale"].toString(); QString locale = m["locale"].toString();
if(pref.getLocale() != locale) { if (pref.getLocale() != locale) {
QTranslator *translator = new QTranslator; 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)); qDebug("%s locale recognized, using translation.", qPrintable(locale));
}else{ }else{
qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale)); qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale));
@ -132,184 +132,184 @@ void EventManager::setGlobalPreferences(QVariantMap m) {
} }
} }
// Downloads // Downloads
if(m.contains("save_path")) if (m.contains("save_path"))
pref.setSavePath(m["save_path"].toString()); 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()); pref.setTempPathEnabled(m["temp_path_enabled"].toBool());
if(m.contains("temp_path")) if (m.contains("temp_path"))
pref.setTempPath(m["temp_path"].toString()); 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(); QVariantList download_at_path_tmp = m["download_in_scan_dirs"].toList();
QList<bool> download_at_path; QList<bool> download_at_path;
foreach(QVariant var, download_at_path_tmp) { foreach (QVariant var, download_at_path_tmp) {
download_at_path << var.toBool(); download_at_path << var.toBool();
} }
QStringList old_folders = pref.getScanDirs(); QStringList old_folders = pref.getScanDirs();
QStringList new_folders = m["scan_dirs"].toStringList(); 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.setScanDirs(new_folders);
pref.setDownloadInScanDirs(download_at_path); pref.setDownloadInScanDirs(download_at_path);
foreach(const QString &old_folder, old_folders) { foreach (const QString &old_folder, old_folders) {
// Update deleted folders // Update deleted folders
if(!new_folders.contains(old_folder)) { if (!new_folders.contains(old_folder)) {
QBtSession::instance()->getScanFoldersModel()->removePath(old_folder); QBtSession::instance()->getScanFoldersModel()->removePath(old_folder);
} }
} }
int i = 0; 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)); qDebug("New watched folder: %s", qPrintable(new_folder));
// Update new folders // 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)); QBtSession::instance()->getScanFoldersModel()->addPath(new_folder, download_at_path.at(i));
} }
++i; ++i;
} }
} }
} }
if(m.contains("export_dir")) if (m.contains("export_dir"))
pref.setExportDir(m["export_dir"].toString()); 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()); 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()); 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()); 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()); 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()); 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()); 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()); pref.setMailNotificationSMTPPassword(m["mail_notification_password"].toString());
if(m.contains("autorun_enabled")) if (m.contains("autorun_enabled"))
pref.setAutoRunEnabled(m["autorun_enabled"].toBool()); pref.setAutoRunEnabled(m["autorun_enabled"].toBool());
if(m.contains("autorun_program")) if (m.contains("autorun_program"))
pref.setAutoRunProgram(m["autorun_program"].toString()); pref.setAutoRunProgram(m["autorun_program"].toString());
if(m.contains("preallocate_all")) if (m.contains("preallocate_all"))
pref.preAllocateAllFiles(m["preallocate_all"].toBool()); pref.preAllocateAllFiles(m["preallocate_all"].toBool());
if(m.contains("queueing_enabled")) if (m.contains("queueing_enabled"))
pref.setQueueingSystemEnabled(m["queueing_enabled"].toBool()); 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()); 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()); 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()); 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()); 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()); pref.useIncompleteFilesExtension(m["incomplete_files_ext"].toBool());
// Connection // Connection
if(m.contains("listen_port")) if (m.contains("listen_port"))
pref.setSessionPort(m["listen_port"].toInt()); pref.setSessionPort(m["listen_port"].toInt());
if(m.contains("upnp")) if (m.contains("upnp"))
pref.setUPnPEnabled(m["upnp"].toBool()); pref.setUPnPEnabled(m["upnp"].toBool());
if(m.contains("dl_limit")) if (m.contains("dl_limit"))
pref.setGlobalDownloadLimit(m["dl_limit"].toInt()); pref.setGlobalDownloadLimit(m["dl_limit"].toInt());
if(m.contains("up_limit")) if (m.contains("up_limit"))
pref.setGlobalUploadLimit(m["up_limit"].toInt()); pref.setGlobalUploadLimit(m["up_limit"].toInt());
if(m.contains("max_connec")) if (m.contains("max_connec"))
pref.setMaxConnecs(m["max_connec"].toInt()); 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()); 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()); pref.setMaxUploadsPerTorrent(m["max_uploads_per_torrent"].toInt());
#if LIBTORRENT_VERSION_MINOR >= 16 #if LIBTORRENT_VERSION_MINOR >= 16
if(m.contains("enable_utp")) if (m.contains("enable_utp"))
pref.setuTPEnabled(m["enable_utp"].toBool()); 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()); pref.setuTPRateLimited(m["limit_utp_rate"].toBool());
#endif #endif
if(m.contains("limit_tcp_overhead")) if (m.contains("limit_tcp_overhead"))
pref.includeOverheadInLimits(m["limit_tcp_overhead"].toBool()); 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()); 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()); pref.setAltGlobalUploadLimit(m["alt_up_limit"].toInt());
if(m.contains("scheduler_enabled")) if (m.contains("scheduler_enabled"))
pref.setSchedulerEnabled(m["scheduler_enabled"].toBool()); 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(), pref.setSchedulerStartTime(QTime(m["schedule_from_hour"].toInt(),
m["schedule_from_min"].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(), pref.setSchedulerEndTime(QTime(m["schedule_to_hour"].toInt(),
m["schedule_to_min"].toInt())); m["schedule_to_min"].toInt()));
} }
if(m.contains("scheduler_days")) if (m.contains("scheduler_days"))
pref.setSchedulerDays(scheduler_days(m["scheduler_days"].toInt())); pref.setSchedulerDays(scheduler_days(m["scheduler_days"].toInt()));
// Bittorrent // Bittorrent
if(m.contains("dht")) if (m.contains("dht"))
pref.setDHTEnabled(m["dht"].toBool()); pref.setDHTEnabled(m["dht"].toBool());
if(m.contains("dhtSameAsBT")) if (m.contains("dhtSameAsBT"))
pref.setDHTPortSameAsBT(m["dhtSameAsBT"].toBool()); pref.setDHTPortSameAsBT(m["dhtSameAsBT"].toBool());
if(m.contains("dht_port")) if (m.contains("dht_port"))
pref.setDHTPort(m["dht_port"].toInt()); pref.setDHTPort(m["dht_port"].toInt());
if(m.contains("pex")) if (m.contains("pex"))
pref.setPeXEnabled(m["pex"].toBool()); pref.setPeXEnabled(m["pex"].toBool());
qDebug("Pex support: %d", (int)m["pex"].toBool()); qDebug("Pex support: %d", (int)m["pex"].toBool());
if(m.contains("lsd")) if (m.contains("lsd"))
pref.setLSDEnabled(m["lsd"].toBool()); pref.setLSDEnabled(m["lsd"].toBool());
if(m.contains("encryption")) if (m.contains("encryption"))
pref.setEncryptionSetting(m["encryption"].toInt()); pref.setEncryptionSetting(m["encryption"].toInt());
#if LIBTORRENT_VERSION_MINOR >= 16 #if LIBTORRENT_VERSION_MINOR >= 16
if(m.contains("anonymous_mode")) if (m.contains("anonymous_mode"))
pref.enableAnonymousMode(m["anonymous_mode"].toBool()); pref.enableAnonymousMode(m["anonymous_mode"].toBool());
#endif #endif
// Proxy // Proxy
if(m.contains("proxy_type")) if (m.contains("proxy_type"))
pref.setProxyType(m["proxy_type"].toInt()); pref.setProxyType(m["proxy_type"].toInt());
if(m.contains("proxy_ip")) if (m.contains("proxy_ip"))
pref.setProxyIp(m["proxy_ip"].toString()); pref.setProxyIp(m["proxy_ip"].toString());
if(m.contains("proxy_port")) if (m.contains("proxy_port"))
pref.setProxyPort(m["proxy_port"].toUInt()); 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()); 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()); pref.setProxyAuthEnabled(m["proxy_auth_enabled"].toBool());
if(m.contains("proxy_username")) if (m.contains("proxy_username"))
pref.setProxyUsername(m["proxy_username"].toString()); pref.setProxyUsername(m["proxy_username"].toString());
if(m.contains("proxy_password")) if (m.contains("proxy_password"))
pref.setProxyPassword(m["proxy_password"].toString()); pref.setProxyPassword(m["proxy_password"].toString());
// IP Filter // IP Filter
if(m.contains("ip_filter_enabled")) if (m.contains("ip_filter_enabled"))
pref.setFilteringEnabled(m["ip_filter_enabled"].toBool()); 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()); pref.setFilter(m["ip_filter_path"].toString());
// Web UI // Web UI
if(m.contains("web_ui_port")) if (m.contains("web_ui_port"))
pref.setWebUiPort(m["web_ui_port"].toUInt()); 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()); 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()); 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()); pref.setWebUiLocalAuthEnabled(!m["bypass_local_auth"].toBool());
if(m.contains("use_https")) if (m.contains("use_https"))
pref.setWebUiHttpsEnabled(m["use_https"].toBool()); pref.setWebUiHttpsEnabled(m["use_https"].toBool());
#ifndef QT_NO_OPENSSL #ifndef QT_NO_OPENSSL
if(m.contains("ssl_key")) { if (m.contains("ssl_key")) {
QByteArray raw_key = m["ssl_key"].toString().toAscii(); QByteArray raw_key = m["ssl_key"].toString().toAscii();
if (!QSslKey(raw_key, QSsl::Rsa).isNull()) if (!QSslKey(raw_key, QSsl::Rsa).isNull())
pref.setWebUiHttpsKey(raw_key); pref.setWebUiHttpsKey(raw_key);
} }
if(m.contains("ssl_cert")) { if (m.contains("ssl_cert")) {
QByteArray raw_cert = m["ssl_cert"].toString().toAscii(); QByteArray raw_cert = m["ssl_cert"].toString().toAscii();
if (!QSslCertificate(raw_cert).isNull()) if (!QSslCertificate(raw_cert).isNull())
pref.setWebUiHttpsCertificate(raw_cert); pref.setWebUiHttpsCertificate(raw_cert);
} }
#endif #endif
// Dyndns // Dyndns
if(m.contains("dyndns_enabled")) if (m.contains("dyndns_enabled"))
pref.setDynDNSEnabled(m["dyndns_enabled"].toBool()); pref.setDynDNSEnabled(m["dyndns_enabled"].toBool());
if(m.contains("dyndns_service")) if (m.contains("dyndns_service"))
pref.setDynDNSService(m["dyndns_service"].toInt()); pref.setDynDNSService(m["dyndns_service"].toInt());
if(m.contains("dyndns_username")) if (m.contains("dyndns_username"))
pref.setDynDNSUsername(m["dyndns_username"].toString()); pref.setDynDNSUsername(m["dyndns_username"].toString());
if(m.contains("dyndns_password")) if (m.contains("dyndns_password"))
pref.setDynDNSPassword(m["dyndns_password"].toString()); pref.setDynDNSPassword(m["dyndns_password"].toString());
if(m.contains("dyndns_domain")) if (m.contains("dyndns_domain"))
pref.setDynDomainName(m["dyndns_domain"].toString()); pref.setDynDomainName(m["dyndns_domain"].toString());
// Reload preferences // Reload preferences
QBtSession::instance()->configureSession(); QBtSession::instance()->configureSession();
@ -326,7 +326,7 @@ QVariantMap EventManager::getGlobalPreferences() const {
data["temp_path"] = pref.getTempPath(); data["temp_path"] = pref.getTempPath();
data["scan_dirs"] = pref.getScanDirs(); data["scan_dirs"] = pref.getScanDirs();
QVariantList var_list; QVariantList var_list;
foreach(bool b, pref.getDownloadInScanDirs()) { foreach (bool b, pref.getDownloadInScanDirs()) {
var_list << b; var_list << b;
} }
data["download_in_scan_dirs"] = var_list; data["download_in_scan_dirs"] = var_list;
@ -412,10 +412,10 @@ QVariantMap EventManager::getGlobalPreferences() const {
QVariantMap EventManager::getPropGeneralInfo(QString hash) const { QVariantMap EventManager::getPropGeneralInfo(QString hash) const {
QVariantMap data; QVariantMap data;
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid() && h.has_metadata()) { if (h.is_valid() && h.has_metadata()) {
// Save path // Save path
QString p = TorrentPersistentData::getSavePath(hash); QString p = TorrentPersistentData::getSavePath(hash);
if(p.isEmpty()) p = h.save_path(); if (p.isEmpty()) p = h.save_path();
data["save_path"] = p; data["save_path"] = p;
// Creation date // Creation date
data["creation_date"] = h.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_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_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")+")"); 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(""); data["up_limit"] = QString::fromUtf8("");
else else
data["up_limit"] = QVariant(misc::friendlyUnit(h.upload_limit())+tr("/s", "/second (i.e. per second)")); 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(""); data["dl_limit"] = QString::fromUtf8("");
else else
data["dl_limit"] = QVariant(misc::friendlyUnit(h.download_limit())+tr("/s", "/second (i.e. per second)")); data["dl_limit"] = QVariant(misc::friendlyUnit(h.download_limit())+tr("/s", "/second (i.e. per second)"));
QString elapsed_txt = misc::userFriendlyDuration(h.active_time()); 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()))+")"; elapsed_txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(misc::userFriendlyDuration(h.seeding_time()))+")";
} }
data["time_elapsed"] = elapsed_txt; 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()))+")"); 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 // Update ratio info
qreal ratio = QBtSession::instance()->getRealRatio(h.hash()); qreal ratio = QBtSession::instance()->getRealRatio(h.hash());
if(ratio > 100.) if (ratio > 100.)
data["share_ratio"] = QString::fromUtf8(""); data["share_ratio"] = QString::fromUtf8("");
else else
data["share_ratio"] = QString(QByteArray::number(ratio, 'f', 1)); data["share_ratio"] = QString(QByteArray::number(ratio, 'f', 1));
@ -465,18 +465,18 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h)
QString hash = h.hash(); QString hash = h.hash();
QVariantMap event; QVariantMap event;
event["eta"] = QVariant(QString::fromUtf8("")); event["eta"] = QVariant(QString::fromUtf8(""));
if(h.is_paused()) { if (h.is_paused()) {
if(h.has_error()) { if (h.has_error()) {
event["state"] = QVariant("error"); event["state"] = QVariant("error");
} else { } else {
if(h.is_seed()) if (h.is_seed())
event["state"] = QVariant("pausedUP"); event["state"] = QVariant("pausedUP");
else else
event["state"] = QVariant("pausedDL"); event["state"] = QVariant("pausedDL");
} }
} else { } else {
if(QBtSession::instance()->isQueueingEnabled() && h.is_queued()) { if (QBtSession::instance()->isQueueingEnabled() && h.is_queued()) {
if(h.is_seed()) if (h.is_seed())
event["state"] = QVariant("queuedUP"); event["state"] = QVariant("queuedUP");
else else
event["state"] = QVariant("queuedDL"); event["state"] = QVariant("queuedDL");
@ -485,7 +485,7 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h)
{ {
case torrent_status::finished: case torrent_status::finished:
case torrent_status::seeding: case torrent_status::seeding:
if(h.upload_payload_rate() > 0) { if (h.upload_payload_rate() > 0) {
event["state"] = QVariant("uploading"); event["state"] = QVariant("uploading");
} else { } else {
event["state"] = QVariant("stalledUP"); event["state"] = QVariant("stalledUP");
@ -495,7 +495,7 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h)
case torrent_status::checking_files: case torrent_status::checking_files:
case torrent_status::queued_for_checking: case torrent_status::queued_for_checking:
case torrent_status::checking_resume_data: case torrent_status::checking_resume_data:
if(h.is_seed()) { if (h.is_seed()) {
event["state"] = QVariant("checkingUP"); event["state"] = QVariant("checkingUP");
} else { } else {
event["state"] = QVariant("checkingDL"); event["state"] = QVariant("checkingDL");
@ -503,7 +503,7 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h)
break; break;
case torrent_status::downloading: case torrent_status::downloading:
case torrent_status::downloading_metadata: case torrent_status::downloading_metadata:
if(h.download_payload_rate() > 0) if (h.download_payload_rate() > 0)
event["state"] = QVariant("downloading"); event["state"] = QVariant("downloading");
else else
event["state"] = QVariant("stalledDL"); event["state"] = QVariant("stalledDL");
@ -519,8 +519,8 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h)
event["size"] = QVariant(misc::friendlyUnit(h.actual_size())); event["size"] = QVariant(misc::friendlyUnit(h.actual_size()));
event["progress"] = QVariant((double)h.progress()); event["progress"] = QVariant((double)h.progress());
event["dlspeed"] = QVariant(tr("%1/s", "e.g. 120 KiB/s").arg(misc::friendlyUnit(h.download_payload_rate()))); event["dlspeed"] = QVariant(tr("%1/s", "e.g. 120 KiB/s").arg(misc::friendlyUnit(h.download_payload_rate())));
if(QBtSession::instance()->isQueueingEnabled()) { if (QBtSession::instance()->isQueueingEnabled()) {
if(h.queue_position() >= 0) if (h.queue_position() >= 0)
event["priority"] = QVariant(QString::number(h.queue_position())); event["priority"] = QVariant(QString::number(h.queue_position()));
else else
event["priority"] = "*"; 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()))); 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()); QString seeds = QString::number(h.num_seeds());
if(h.num_complete() > 0) if (h.num_complete() > 0)
seeds += " ("+QString::number(h.num_complete())+")"; seeds += " ("+QString::number(h.num_complete())+")";
event["num_seeds"] = QVariant(seeds); event["num_seeds"] = QVariant(seeds);
QString leechs = QString::number(h.num_peers()-h.num_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())+")"; leechs += " ("+QString::number(h.num_incomplete())+")";
event["num_leechs"] = QVariant(leechs); event["num_leechs"] = QVariant(leechs);
event["seed"] = QVariant(h.is_seed()); event["seed"] = QVariant(h.is_seed());
qreal ratio = QBtSession::instance()->getRealRatio(hash); qreal ratio = QBtSession::instance()->getRealRatio(hash);
if(ratio > 100.) if (ratio > 100.)
event["ratio"] = QString::fromUtf8(""); event["ratio"] = QString::fromUtf8("");
else else
event["ratio"] = QVariant(QString::number(ratio, 'f', 1)); event["ratio"] = QVariant(QString::number(ratio, 'f', 1));

View file

@ -120,7 +120,7 @@ void HttpConnection::read() {
m_parser.writeMessage(message); m_parser.writeMessage(message);
} }
if(m_parser.isError()) { if (m_parser.isError()) {
qDebug() << Q_FUNC_INFO << "message parsing error"; qDebug() << Q_FUNC_INFO << "message parsing error";
m_generator.setStatusLine(400, "Bad Request"); m_generator.setStatusLine(400, "Bad Request");
write(); write();
@ -150,7 +150,7 @@ void HttpConnection::translateDocument(QString& data) {
found = false; found = false;
i = regex.indexIn(data, i); i = regex.indexIn(data, i);
if(i >= 0) { if (i >= 0) {
//qDebug("Found translatable string: %s", regex.cap(1).toUtf8().data()); //qDebug("Found translatable string: %s", regex.cap(1).toUtf8().data());
QByteArray word = regex.cap(1).toLocal8Bit(); QByteArray word = regex.cap(1).toLocal8Bit();
@ -173,20 +173,20 @@ void HttpConnection::translateDocument(QString& data) {
} }
void HttpConnection::respond() { void HttpConnection::respond() {
if((m_socket->peerAddress() != QHostAddress::LocalHost if ((m_socket->peerAddress() != QHostAddress::LocalHost
&& m_socket->peerAddress() != QHostAddress::LocalHostIPv6) && m_socket->peerAddress() != QHostAddress::LocalHostIPv6)
|| m_httpserver->isLocalAuthEnabled()) { || m_httpserver->isLocalAuthEnabled()) {
// Authentication // Authentication
const QString peer_ip = m_socket->peerAddress().toString(); const QString peer_ip = m_socket->peerAddress().toString();
const int nb_fail = m_httpserver->NbFailedAttemptsForIp(peer_ip); 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.setStatusLine(403, "Forbidden");
m_generator.setMessage(tr("Your IP address has been banned after too many failed authentication attempts.")); m_generator.setMessage(tr("Your IP address has been banned after too many failed authentication attempts."));
write(); write();
return; return;
} }
QString auth = m_parser.header().value("Authorization"); QString auth = m_parser.header().value("Authorization");
if(auth.isEmpty()) { if (auth.isEmpty()) {
// Return unauthorized header // Return unauthorized header
qDebug("Auth is Empty..."); qDebug("Auth is Empty...");
m_generator.setStatusLine(401, "Unauthorized"); m_generator.setStatusLine(401, "Unauthorized");
@ -211,10 +211,10 @@ void HttpConnection::respond() {
} }
QString url = m_parser.url(); QString url = m_parser.url();
// Favicon // Favicon
if(url.endsWith("favicon.ico")) { if (url.endsWith("favicon.ico")) {
qDebug("Returning favicon"); qDebug("Returning favicon");
QFile favicon(":/Icons/skin/qbittorrent16.png"); QFile favicon(":/Icons/skin/qbittorrent16.png");
if(favicon.open(QIODevice::ReadOnly)) { if (favicon.open(QIODevice::ReadOnly)) {
QByteArray data = favicon.readAll(); QByteArray data = favicon.readAll();
favicon.close(); favicon.close();
m_generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
@ -242,28 +242,28 @@ void HttpConnection::respond() {
respondJson(); respondJson();
return; return;
} }
if(list.size() > 2) { if (list.size() > 2) {
if(list[1] == "propertiesGeneral") { if (list[1] == "propertiesGeneral") {
const QString& hash = list[2]; const QString& hash = list[2];
respondGenPropertiesJson(hash); respondGenPropertiesJson(hash);
return; return;
} }
if(list[1] == "propertiesTrackers") { if (list[1] == "propertiesTrackers") {
const QString& hash = list[2]; const QString& hash = list[2];
respondTrackersPropertiesJson(hash); respondTrackersPropertiesJson(hash);
return; return;
} }
if(list[1] == "propertiesFiles") { if (list[1] == "propertiesFiles") {
const QString& hash = list[2]; const QString& hash = list[2];
respondFilesPropertiesJson(hash); respondFilesPropertiesJson(hash);
return; return;
} }
} else { } else {
if(list[1] == "preferences") { if (list[1] == "preferences") {
respondPreferencesJson(); respondPreferencesJson();
return; return;
} else { } else {
if(list[1] == "transferInfo") { if (list[1] == "transferInfo") {
respondGlobalTransferInfoJson(); respondGlobalTransferInfoJson();
return; return;
} }
@ -281,7 +281,7 @@ void HttpConnection::respond() {
// Icons from theme // Icons from theme
qDebug() << "list[0]" << list[0]; qDebug() << "list[0]" << list[0];
if(list[0] == "theme" && list.size() == 2) { if (list[0] == "theme" && list.size() == 2) {
#ifdef DISABLE_GUI #ifdef DISABLE_GUI
url = ":/Icons/oxygen/"+list[1]+".png"; url = ":/Icons/oxygen/"+list[1]+".png";
#else #else
@ -292,14 +292,14 @@ void HttpConnection::respond() {
if (list[0] == "images") { if (list[0] == "images") {
list[0] = "Icons"; list[0] = "Icons";
} else { } else {
if(list.last().endsWith(".html")) if (list.last().endsWith(".html"))
list.prepend("html"); list.prepend("html");
list.prepend("webui"); list.prepend("webui");
} }
url = ":/" + list.join("/"); url = ":/" + list.join("/");
} }
QFile file(url); QFile file(url);
if(!file.open(QIODevice::ReadOnly)) { if (!file.open(QIODevice::ReadOnly)) {
qDebug("File %s was not found!", qPrintable(url)); qDebug("File %s was not found!", qPrintable(url));
respondNotFound(); respondNotFound();
return; return;
@ -314,7 +314,7 @@ void HttpConnection::respond() {
file.close(); file.close();
// Translate the page // 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()); QString dataStr = QString::fromUtf8(data.constData());
translateDocument(dataStr); translateDocument(dataStr);
if (url.endsWith("about.html")) { if (url.endsWith("about.html")) {
@ -391,17 +391,17 @@ void HttpConnection::respondGlobalTransferInfoJson() {
} }
void HttpConnection::respondCommand(const QString& command) { void HttpConnection::respondCommand(const QString& command) {
if(command == "download") { if (command == "download") {
QString urls = m_parser.post("urls"); QString urls = m_parser.post("urls");
QStringList list = urls.split('\n'); QStringList list = urls.split('\n');
foreach(QString url, list){ foreach (QString url, list){
url = url.trimmed(); url = url.trimmed();
if(!url.isEmpty()){ if (!url.isEmpty()){
if(url.startsWith("bc://bt/", Qt::CaseInsensitive)) { if (url.startsWith("bc://bt/", Qt::CaseInsensitive)) {
qDebug("Converting bc link to magnet link"); qDebug("Converting bc link to magnet link");
url = misc::bcLinkToMagnet(url); url = misc::bcLinkToMagnet(url);
} }
if(url.startsWith("magnet:", Qt::CaseInsensitive)) { if (url.startsWith("magnet:", Qt::CaseInsensitive)) {
emit MagnetReadyToBeDownloaded(url); emit MagnetReadyToBeDownloaded(url);
} else { } else {
qDebug("Downloading url: %s", (const char*)url.toLocal8Bit()); qDebug("Downloading url: %s", (const char*)url.toLocal8Bit());
@ -412,14 +412,14 @@ void HttpConnection::respondCommand(const QString& command) {
return; return;
} }
if(command == "addTrackers") { if (command == "addTrackers") {
QString hash = m_parser.post("hash"); QString hash = m_parser.post("hash");
if(!hash.isEmpty()) { if (!hash.isEmpty()) {
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); 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"); QString urls = m_parser.post("urls");
QStringList list = urls.split('\n'); QStringList list = urls.split('\n');
foreach(const QString& url, list) { foreach (const QString& url, list) {
announce_entry e(url.toStdString()); announce_entry e(url.toStdString());
h.add_tracker(e); h.add_tracker(e);
} }
@ -427,7 +427,7 @@ void HttpConnection::respondCommand(const QString& command) {
} }
return; return;
} }
if(command == "upload") { if (command == "upload") {
qDebug() << Q_FUNC_INFO << "upload"; qDebug() << Q_FUNC_INFO << "upload";
// Get a unique filename // Get a unique filename
QTemporaryFile *tmpfile = new QTemporaryFile (QDir::temp().absoluteFilePath("qBT-XXXXXX.torrent")); QTemporaryFile *tmpfile = new QTemporaryFile (QDir::temp().absoluteFilePath("qBT-XXXXXX.torrent"));
@ -454,35 +454,35 @@ void HttpConnection::respondCommand(const QString& command) {
write(); write();
return; return;
} }
if(command == "resumeall") { if (command == "resumeall") {
emit resumeAllTorrents(); emit resumeAllTorrents();
return; return;
} }
if(command == "pauseall") { if (command == "pauseall") {
emit pauseAllTorrents(); emit pauseAllTorrents();
return; return;
} }
if(command == "resume") { if (command == "resume") {
emit resumeTorrent(m_parser.post("hash")); emit resumeTorrent(m_parser.post("hash"));
return; return;
} }
if(command == "setPreferences") { if (command == "setPreferences") {
QString json_str = m_parser.post("json"); QString json_str = m_parser.post("json");
EventManager* manager = m_httpserver->eventManager(); EventManager* manager = m_httpserver->eventManager();
manager->setGlobalPreferences(json::fromJson(json_str)); manager->setGlobalPreferences(json::fromJson(json_str));
return; return;
} }
if(command == "setFilePrio") { if (command == "setFilePrio") {
QString hash = m_parser.post("hash"); QString hash = m_parser.post("hash");
int file_id = m_parser.post("id").toInt(); int file_id = m_parser.post("id").toInt();
int priority = m_parser.post("priority").toInt(); int priority = m_parser.post("priority").toInt();
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); 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); h.file_priority(file_id, priority);
} }
return; return;
} }
if(command == "getGlobalUpLimit") { if (command == "getGlobalUpLimit") {
m_generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
m_generator.setContentTypeByExt("html"); m_generator.setContentTypeByExt("html");
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
@ -493,7 +493,7 @@ void HttpConnection::respondCommand(const QString& command) {
write(); write();
return; return;
} }
if(command == "getGlobalDlLimit") { if (command == "getGlobalDlLimit") {
m_generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
m_generator.setContentTypeByExt("html"); m_generator.setContentTypeByExt("html");
#if LIBTORRENT_VERSION_MINOR > 15 #if LIBTORRENT_VERSION_MINOR > 15
@ -504,10 +504,10 @@ void HttpConnection::respondCommand(const QString& command) {
write(); write();
return; return;
} }
if(command == "getTorrentUpLimit") { if (command == "getTorrentUpLimit") {
QString hash = m_parser.post("hash"); QString hash = m_parser.post("hash");
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if (h.is_valid()) {
m_generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
m_generator.setContentTypeByExt("html"); m_generator.setContentTypeByExt("html");
m_generator.setMessage(QString::number(h.upload_limit())); m_generator.setMessage(QString::number(h.upload_limit()));
@ -515,10 +515,10 @@ void HttpConnection::respondCommand(const QString& command) {
} }
return; return;
} }
if(command == "getTorrentDlLimit") { if (command == "getTorrentDlLimit") {
QString hash = m_parser.post("hash"); QString hash = m_parser.post("hash");
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if (h.is_valid()) {
m_generator.setStatusLine(200, "OK"); m_generator.setStatusLine(200, "OK");
m_generator.setContentTypeByExt("html"); m_generator.setContentTypeByExt("html");
m_generator.setMessage(QString::number(h.download_limit())); m_generator.setMessage(QString::number(h.download_limit()));
@ -526,81 +526,81 @@ void HttpConnection::respondCommand(const QString& command) {
} }
return; return;
} }
if(command == "setTorrentUpLimit") { if (command == "setTorrentUpLimit") {
QString hash = m_parser.post("hash"); QString hash = m_parser.post("hash");
qlonglong limit = m_parser.post("limit").toLongLong(); qlonglong limit = m_parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if (limit == 0) limit = -1;
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if (h.is_valid()) {
h.set_upload_limit(limit); h.set_upload_limit(limit);
} }
return; return;
} }
if(command == "setTorrentDlLimit") { if (command == "setTorrentDlLimit") {
QString hash = m_parser.post("hash"); QString hash = m_parser.post("hash");
qlonglong limit = m_parser.post("limit").toLongLong(); qlonglong limit = m_parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if (limit == 0) limit = -1;
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if (h.is_valid()) {
h.set_download_limit(limit); h.set_download_limit(limit);
} }
return; return;
} }
if(command == "setGlobalUpLimit") { if (command == "setGlobalUpLimit") {
qlonglong limit = m_parser.post("limit").toLongLong(); qlonglong limit = m_parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if (limit == 0) limit = -1;
QBtSession::instance()->setUploadRateLimit(limit); QBtSession::instance()->setUploadRateLimit(limit);
Preferences().setGlobalUploadLimit(limit/1024.); Preferences().setGlobalUploadLimit(limit/1024.);
return; return;
} }
if(command == "setGlobalDlLimit") { if (command == "setGlobalDlLimit") {
qlonglong limit = m_parser.post("limit").toLongLong(); qlonglong limit = m_parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if (limit == 0) limit = -1;
QBtSession::instance()->setDownloadRateLimit(limit); QBtSession::instance()->setDownloadRateLimit(limit);
Preferences().setGlobalDownloadLimit(limit/1024.); Preferences().setGlobalDownloadLimit(limit/1024.);
return; return;
} }
if(command == "pause") { if (command == "pause") {
emit pauseTorrent(m_parser.post("hash")); emit pauseTorrent(m_parser.post("hash"));
return; return;
} }
if(command == "delete") { if (command == "delete") {
QStringList hashes = m_parser.post("hashes").split("|"); QStringList hashes = m_parser.post("hashes").split("|");
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
emit deleteTorrent(hash, false); emit deleteTorrent(hash, false);
} }
return; return;
} }
if(command == "deletePerm") { if (command == "deletePerm") {
QStringList hashes = m_parser.post("hashes").split("|"); QStringList hashes = m_parser.post("hashes").split("|");
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
emit deleteTorrent(hash, true); emit deleteTorrent(hash, true);
} }
return; return;
} }
if(command == "increasePrio") { if (command == "increasePrio") {
increaseTorrentsPriority(m_parser.post("hashes").split("|")); increaseTorrentsPriority(m_parser.post("hashes").split("|"));
return; return;
} }
if(command == "decreasePrio") { if (command == "decreasePrio") {
decreaseTorrentsPriority(m_parser.post("hashes").split("|")); decreaseTorrentsPriority(m_parser.post("hashes").split("|"));
return; return;
} }
if(command == "topPrio") { if (command == "topPrio") {
foreach(const QString &hash, m_parser.post("hashes").split("|")) { foreach (const QString &hash, m_parser.post("hashes").split("|")) {
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) h.queue_position_top(); if (h.is_valid()) h.queue_position_top();
} }
return; return;
} }
if(command == "bottomPrio") { if (command == "bottomPrio") {
foreach(const QString &hash, m_parser.post("hashes").split("|")) { foreach (const QString &hash, m_parser.post("hashes").split("|")) {
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) h.queue_position_bottom(); if (h.is_valid()) h.queue_position_bottom();
} }
return; return;
} }
if(command == "recheck"){ if (command == "recheck"){
QBtSession::instance()->recheckTorrent(m_parser.post("hash")); QBtSession::instance()->recheckTorrent(m_parser.post("hash"));
return; return;
} }
@ -612,10 +612,10 @@ void HttpConnection::decreaseTorrentsPriority(const QStringList &hashes) {
std::vector<QPair<int, QTorrentHandle> >, std::vector<QPair<int, QTorrentHandle> >,
std::less<QPair<int, QTorrentHandle> > > torrent_queue; std::less<QPair<int, QTorrentHandle> > > torrent_queue;
// Sort torrents by priority // Sort torrents by priority
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
try { try {
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(!h.is_seed()) { if (!h.is_seed()) {
torrent_queue.push(qMakePair(h.queue_position(), h)); torrent_queue.push(qMakePair(h.queue_position(), h));
} }
}catch(invalid_handle&){} }catch(invalid_handle&){}
@ -637,10 +637,10 @@ void HttpConnection::increaseTorrentsPriority(const QStringList &hashes)
std::vector<QPair<int, QTorrentHandle> >, std::vector<QPair<int, QTorrentHandle> >,
std::greater<QPair<int, QTorrentHandle> > > torrent_queue; std::greater<QPair<int, QTorrentHandle> > > torrent_queue;
// Sort torrents by priority // Sort torrents by priority
foreach(const QString &hash, hashes) { foreach (const QString &hash, hashes) {
try { try {
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(!h.is_seed()) { if (!h.is_seed()) {
torrent_queue.push(qMakePair(h.queue_position(), h)); torrent_queue.push(qMakePair(h.queue_position(), h));
} }
}catch(invalid_handle&){} }catch(invalid_handle&){}

View file

@ -87,7 +87,7 @@ void HttpRequestParser::writeMessage(const QByteArray& ba) {
qDebug() << Q_FUNC_INFO << "m_data.size(): " << m_data.size(); qDebug() << Q_FUNC_INFO << "m_data.size(): " << m_data.size();
// Parse POST data // Parse POST data
if(m_header.contentType() == "application/x-www-form-urlencoded") { if (m_header.contentType() == "application/x-www-form-urlencoded") {
QUrl url; QUrl url;
url.setEncodedQuery(m_data); url.setEncodedQuery(m_data);
QListIterator<QPair<QString, QString> > i(url.queryItems()); QListIterator<QPair<QString, QString> > i(url.queryItems());

View file

@ -42,23 +42,23 @@ void HttpResponseGenerator::setMessage(const QString& message) {
} }
void HttpResponseGenerator::setContentTypeByExt(const QString& ext) { void HttpResponseGenerator::setContentTypeByExt(const QString& ext) {
if(ext == "css") { if (ext == "css") {
setContentType("text/css"); setContentType("text/css");
return; return;
} }
if(ext == "gif") { if (ext == "gif") {
setContentType("image/gif"); setContentType("image/gif");
return; return;
} }
if(ext == "htm" || ext == "html") { if (ext == "htm" || ext == "html") {
setContentType("text/html"); setContentType("text/html");
return; return;
} }
if(ext == "js") { if (ext == "js") {
setContentType("text/javascript"); setContentType("text/javascript");
return; return;
} }
if(ext == "png") { if (ext == "png") {
setContentType("image/x-png"); setContentType("image/x-png");
return; return;
} }

View file

@ -76,7 +76,7 @@ int HttpServer::NbFailedAttemptsForIp(const QString& ip) const {
void HttpServer::increaseNbFailedAttemptsForIp(const QString& ip) { void HttpServer::increaseNbFailedAttemptsForIp(const QString& ip) {
const int nb_fail = m_clientFailedAttempts.value(ip, 0) + 1; const int nb_fail = m_clientFailedAttempts.value(ip, 0) + 1;
m_clientFailedAttempts.insert(ip, nb_fail); 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 // Max number of failed attempts reached
// Start ban period // Start ban period
UnbanTimer* ubantimer = new UnbanTimer(ip, this); UnbanTimer* ubantimer = new UnbanTimer(ip, this);
@ -112,9 +112,9 @@ HttpServer::HttpServer(int msec, QObject* parent) : QTcpServer(parent),
// Add torrents // Add torrents
std::vector<torrent_handle> torrents = QBtSession::instance()->getTorrents(); std::vector<torrent_handle> torrents = QBtSession::instance()->getTorrents();
std::vector<torrent_handle>::iterator torrentIT; std::vector<torrent_handle>::iterator torrentIT;
for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) {
QTorrentHandle h = QTorrentHandle(*torrentIT); QTorrentHandle h = QTorrentHandle(*torrentIT);
if(h.is_valid()) if (h.is_valid())
m_eventManager->addedTorrent(h); m_eventManager->addedTorrent(h);
} }
@ -217,9 +217,9 @@ void HttpServer::handleNewConnection(QTcpSocket *socket)
void HttpServer::onTimer() { void HttpServer::onTimer() {
std::vector<torrent_handle> torrents = QBtSession::instance()->getTorrents(); std::vector<torrent_handle> torrents = QBtSession::instance()->getTorrents();
std::vector<torrent_handle>::iterator torrentIT; std::vector<torrent_handle>::iterator torrentIT;
for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { for (torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) {
QTorrentHandle h = QTorrentHandle(*torrentIT); QTorrentHandle h = QTorrentHandle(*torrentIT);
if(h.is_valid()) if (h.is_valid())
m_eventManager->modifiedTorrent(h); m_eventManager->modifiedTorrent(h);
} }
} }
@ -245,28 +245,28 @@ bool HttpServer::isAuthorized(const QByteArray& auth,
//qDebug("AUTH string is %s", auth.data()); //qDebug("AUTH string is %s", auth.data());
// Get user name // Get user name
QRegExp regex_user(".*username=\"([^\"]+)\".*"); // Must be a quoted string 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); QString prop_user = regex_user.cap(1);
//qDebug("AUTH: Proposed username is %s, real username is %s", prop_user.toLocal8Bit().data(), username.data()); //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 // User name is invalid, we can reject already
qDebug("AUTH-PROB: Username is invalid"); qDebug("AUTH-PROB: Username is invalid");
return false; return false;
} }
// Get realm // Get realm
QRegExp regex_realm(".*realm=\"([^\"]+)\".*"); // Must be a quoted string 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"); qDebug("AUTH-PROB: Missing realm");
return false; return false;
} }
QByteArray prop_realm = regex_realm.cap(1).toLocal8Bit(); QByteArray prop_realm = regex_realm.cap(1).toLocal8Bit();
if(prop_realm != QBT_REALM) { if (prop_realm != QBT_REALM) {
qDebug("AUTH-PROB: Wrong realm"); qDebug("AUTH-PROB: Wrong realm");
return false; return false;
} }
// get nonce // get nonce
QRegExp regex_nonce(".*nonce=[\"]?([\\w=]+)[\"]?.*"); QRegExp regex_nonce(".*nonce=[\"]?([\\w=]+)[\"]?.*");
if(regex_nonce.indexIn(auth) < 0) { if (regex_nonce.indexIn(auth) < 0) {
qDebug("AUTH-PROB: missing nonce"); qDebug("AUTH-PROB: missing nonce");
return false; return false;
} }
@ -274,7 +274,7 @@ bool HttpServer::isAuthorized(const QByteArray& auth,
//qDebug("prop nonce is: %s", prop_nonce.data()); //qDebug("prop nonce is: %s", prop_nonce.data());
// get uri // get uri
QRegExp regex_uri(".*uri=\"([^\"]+)\".*"); QRegExp regex_uri(".*uri=\"([^\"]+)\".*");
if(regex_uri.indexIn(auth) < 0) { if (regex_uri.indexIn(auth) < 0) {
qDebug("AUTH-PROB: Missing uri"); qDebug("AUTH-PROB: Missing uri");
return false; return false;
} }
@ -282,7 +282,7 @@ bool HttpServer::isAuthorized(const QByteArray& auth,
//qDebug("prop uri is: %s", prop_uri.data()); //qDebug("prop uri is: %s", prop_uri.data());
// get response // get response
QRegExp regex_response(".*response=[\"]?([\\w=]+)[\"]?.*"); QRegExp regex_response(".*response=[\"]?([\\w=]+)[\"]?.*");
if(regex_response.indexIn(auth) < 0) { if (regex_response.indexIn(auth) < 0) {
qDebug("AUTH-PROB: Missing response"); qDebug("AUTH-PROB: Missing response");
return false; return false;
} }
@ -293,25 +293,25 @@ bool HttpServer::isAuthorized(const QByteArray& auth,
md5_ha2.addData(method.toLocal8Bit() + ":" + prop_uri); md5_ha2.addData(method.toLocal8Bit() + ":" + prop_uri);
QByteArray ha2 = md5_ha2.result().toHex(); QByteArray ha2 = md5_ha2.result().toHex();
QByteArray response = ""; QByteArray response = "";
if(auth.contains("qop=")) { if (auth.contains("qop=")) {
QCryptographicHash md5_ha(QCryptographicHash::Md5); QCryptographicHash md5_ha(QCryptographicHash::Md5);
// Get nc // Get nc
QRegExp regex_nc(".*nc=[\"]?([\\w=]+)[\"]?.*"); QRegExp regex_nc(".*nc=[\"]?([\\w=]+)[\"]?.*");
if(regex_nc.indexIn(auth) < 0) { if (regex_nc.indexIn(auth) < 0) {
qDebug("AUTH-PROB: qop but missing nc"); qDebug("AUTH-PROB: qop but missing nc");
return false; return false;
} }
QByteArray prop_nc = regex_nc.cap(1).toLocal8Bit(); QByteArray prop_nc = regex_nc.cap(1).toLocal8Bit();
//qDebug("prop nc is: %s", prop_nc.data()); //qDebug("prop nc is: %s", prop_nc.data());
QRegExp regex_cnonce(".*cnonce=[\"]?([\\w=]+)[\"]?.*"); QRegExp regex_cnonce(".*cnonce=[\"]?([\\w=]+)[\"]?.*");
if(regex_cnonce.indexIn(auth) < 0) { if (regex_cnonce.indexIn(auth) < 0) {
qDebug("AUTH-PROB: qop but missing cnonce"); qDebug("AUTH-PROB: qop but missing cnonce");
return false; return false;
} }
QByteArray prop_cnonce = regex_cnonce.cap(1).toLocal8Bit(); QByteArray prop_cnonce = regex_cnonce.cap(1).toLocal8Bit();
//qDebug("prop cnonce is: %s", prop_cnonce.data()); //qDebug("prop cnonce is: %s", prop_cnonce.data());
QRegExp regex_qop(".*qop=[\"]?(\\w+)[\"]?.*"); QRegExp regex_qop(".*qop=[\"]?(\\w+)[\"]?.*");
if(regex_qop.indexIn(auth) < 0) { if (regex_qop.indexIn(auth) < 0) {
qDebug("AUTH-PROB: missing qop"); qDebug("AUTH-PROB: missing qop");
return false; return false;
} }

View file

@ -51,7 +51,7 @@ namespace json {
case QVariant::StringList: case QVariant::StringList:
case QVariant::List: { case QVariant::List: {
QStringList strList; QStringList strList;
foreach(const QVariant &var, v.toList()) { foreach (const QVariant &var, v.toList()) {
strList << toJson(var); strList << toJson(var);
} }
return "["+strList.join(",")+"]"; return "["+strList.join(",")+"]";
@ -59,7 +59,7 @@ namespace json {
case QVariant::String: { case QVariant::String: {
QString s = v.value<QString>(); QString s = v.value<QString>();
QString result = "\""; QString result = "\"";
for(int i=0; i<s.size(); ++i) { for (int i=0; i<s.size(); ++i) {
const QChar ch = s[i]; const QChar ch = s[i];
switch(ch.toAscii()) switch(ch.toAscii())
{ {
@ -109,39 +109,39 @@ namespace json {
QVariantMap fromJson(const QString& json) { QVariantMap fromJson(const QString& json) {
qDebug("JSON is %s", qPrintable(json)); qDebug("JSON is %s", qPrintable(json));
QVariantMap m; QVariantMap m;
if(json.startsWith("{") && json.endsWith("}")) { if (json.startsWith("{") && json.endsWith("}")) {
QStringList couples; QStringList couples;
QString tmp = ""; QString tmp = "";
bool in_list = false; bool in_list = false;
foreach(const QChar &c, json.mid(1, json.length()-2)) { foreach (const QChar &c, json.mid(1, json.length()-2)) {
if(c == ',' && !in_list) { if (c == ',' && !in_list) {
couples << tmp; couples << tmp;
tmp = ""; tmp = "";
} else { } else {
if(c == '[') if (c == '[')
in_list = true; in_list = true;
else if(c == ']') else if (c == ']')
in_list = false; in_list = false;
tmp += c; tmp += c;
} }
} }
if(!tmp.isEmpty()) couples << tmp; if (!tmp.isEmpty()) couples << tmp;
foreach(const QString &couple, couples) { foreach (const QString &couple, couples) {
QStringList parts = couple.split(":"); QStringList parts = couple.split(":");
if(parts.size() != 2) continue; if (parts.size() != 2) continue;
QString key = parts.first(); QString key = parts.first();
if(key.startsWith("\"") && key.endsWith("\"")) { if (key.startsWith("\"") && key.endsWith("\"")) {
key = key.mid(1, key.length()-2); key = key.mid(1, key.length()-2);
} }
QString value_str = parts.last(); QString value_str = parts.last();
QVariant value; QVariant value;
if(value_str.startsWith("[") && value_str.endsWith("]")) { if (value_str.startsWith("[") && value_str.endsWith("]")) {
value_str = value_str.mid(1, value_str.length()-2); value_str = value_str.mid(1, value_str.length()-2);
QStringList list_elems = value_str.split(",", QString::SkipEmptyParts); QStringList list_elems = value_str.split(",", QString::SkipEmptyParts);
QVariantList varlist; QVariantList varlist;
foreach(const QString &list_val, list_elems) { foreach (const QString &list_val, list_elems) {
if(list_val.startsWith("\"") && list_val.endsWith("\"")) { if (list_val.startsWith("\"") && list_val.endsWith("\"")) {
varlist << list_val.mid(1, list_val.length()-2).replace("\\n", "\n"); varlist << list_val.mid(1, list_val.length()-2).replace("\\n", "\n");
} else { } else {
varlist << list_val.toInt(); varlist << list_val.toInt();
@ -149,7 +149,7 @@ namespace json {
} }
value = varlist; value = varlist;
} else { } else {
if(value_str.startsWith("\"") && value_str.endsWith("\"")) { if (value_str.startsWith("\"") && value_str.endsWith("\"")) {
value_str = value_str.mid(1, value_str.length()-2).replace("\\n", "\n"); value_str = value_str.mid(1, value_str.length()-2).replace("\\n", "\n");
value = value_str; value = value_str;
} else { } else {
@ -170,10 +170,10 @@ namespace json {
QString toJson(const QList<QVariantMap>& v) { QString toJson(const QList<QVariantMap>& v) {
QStringList res; QStringList res;
foreach(QVariantMap m, v) { foreach (QVariantMap m, v) {
QStringList vlist; QStringList vlist;
QVariantMap::ConstIterator it; 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()); vlist << toJson(it.key())+":"+toJson(it.value());
} }
res << "{"+vlist.join(",")+"}"; res << "{"+vlist.join(",")+"}";