mirror of
https://github.com/qbittorrent/qBittorrent.git
synced 2025-12-18 22:47:21 -06:00
Coding style clean up
This commit is contained in:
@@ -100,7 +100,7 @@ class about : public QDialog, private Ui::AboutDlg{
|
||||
// License
|
||||
te_license->append(QString::fromUtf8("<a name='top'></a>"));
|
||||
QFile licensefile(":/gpl.html");
|
||||
if(licensefile.open(QIODevice::ReadOnly|QIODevice::Text)) {
|
||||
if (licensefile.open(QIODevice::ReadOnly|QIODevice::Text)) {
|
||||
te_license->setHtml(licensefile.readAll());
|
||||
licensefile.close();
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ class DeletionConfirmationDlg : public QDialog, private Ui::confirmDeletionDlg {
|
||||
|
||||
static bool askForDeletionConfirmation(bool *delete_local_files) {
|
||||
DeletionConfirmationDlg dlg;
|
||||
if(dlg.exec() == QDialog::Accepted) {
|
||||
if (dlg.exec() == QDialog::Accepted) {
|
||||
*delete_local_files = dlg.shouldDeleteLocalFiles();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ DNSUpdater::DNSUpdater(QObject *parent) :
|
||||
m_ipCheckTimer.start();
|
||||
|
||||
// Check lastUpdate to avoid flooding
|
||||
if(!m_lastIPCheckTime.isValid() ||
|
||||
if (!m_lastIPCheckTime.isValid() ||
|
||||
m_lastIPCheckTime.secsTo(QDateTime::currentDateTime())*1000 > IP_CHECK_INTERVAL_MS) {
|
||||
checkPublicIP();
|
||||
}
|
||||
@@ -79,19 +79,19 @@ void DNSUpdater::checkPublicIP()
|
||||
void DNSUpdater::ipRequestFinished(QNetworkReply *reply)
|
||||
{
|
||||
qDebug() << Q_FUNC_INFO;
|
||||
if(reply->error()) {
|
||||
if (reply->error()) {
|
||||
// Error
|
||||
qWarning() << Q_FUNC_INFO << "Error:" << reply->errorString();
|
||||
} else {
|
||||
// Parse response
|
||||
QRegExp ipregex("Current IP Address:\\s+([^<]+)</body>");
|
||||
QString ret = reply->readAll();
|
||||
if(ipregex.indexIn(ret) >= 0) {
|
||||
if (ipregex.indexIn(ret) >= 0) {
|
||||
QString ip_str = ipregex.cap(1);
|
||||
qDebug() << Q_FUNC_INFO << "Regular expression captured the following IP:" << ip_str;
|
||||
QHostAddress new_ip(ip_str);
|
||||
if(!new_ip.isNull()) {
|
||||
if(m_lastIP != new_ip) {
|
||||
if (!new_ip.isNull()) {
|
||||
if (m_lastIP != new_ip) {
|
||||
qDebug() << Q_FUNC_INFO << "The IP address changed, report the change to DynDNS...";
|
||||
qDebug() << m_lastIP.toString() << "->" << new_ip.toString();
|
||||
m_lastIP = new_ip;
|
||||
@@ -157,7 +157,7 @@ QUrl DNSUpdater::getUpdateUrl() const
|
||||
|
||||
void DNSUpdater::ipUpdateFinished(QNetworkReply *reply)
|
||||
{
|
||||
if(reply->error()) {
|
||||
if (reply->error()) {
|
||||
// Error
|
||||
qWarning() << Q_FUNC_INFO << "Error:" << reply->errorString();
|
||||
} else {
|
||||
@@ -174,11 +174,11 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
|
||||
qDebug() << Q_FUNC_INFO << reply;
|
||||
QString code = reply.split(" ").first();
|
||||
qDebug() << Q_FUNC_INFO << "Code:" << code;
|
||||
if(code == "good" || code == "nochg") {
|
||||
if (code == "good" || code == "nochg") {
|
||||
QBtSession::instance()->addConsoleMessage(tr("Your dynamic DNS was successfuly updated."), "green");
|
||||
return;
|
||||
}
|
||||
if(code == "911" || code == "dnserr") {
|
||||
if (code == "911" || code == "dnserr") {
|
||||
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: The service is temporarily unavailable, it will be retried in 30 minutes."),
|
||||
"red");
|
||||
m_lastIP.clear();
|
||||
@@ -188,30 +188,30 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
|
||||
// Everything bellow is an error, stop updating until the user updates something
|
||||
m_ipCheckTimer.stop();
|
||||
m_lastIP.clear();
|
||||
if(code == "nohost") {
|
||||
if (code == "nohost") {
|
||||
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: hostname supplied does not exist under specified account."),
|
||||
"red");
|
||||
m_state = INVALID_CREDS;
|
||||
return;
|
||||
}
|
||||
if(code == "badauth") {
|
||||
if (code == "badauth") {
|
||||
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: Invalid username/password."), "red");
|
||||
m_state = INVALID_CREDS;
|
||||
return;
|
||||
}
|
||||
if(code == "badagent") {
|
||||
if (code == "badagent") {
|
||||
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: qBittorrent was blacklisted by the service, please report a bug at http://bugs.qbittorrent.org."),
|
||||
"red");
|
||||
m_state = FATAL;
|
||||
return;
|
||||
}
|
||||
if(code == "!donator") {
|
||||
if (code == "!donator") {
|
||||
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: %1 was returned by the service, please report a bug at http://bugs.qbittorrent.org.").arg("!donator"),
|
||||
"red");
|
||||
m_state = FATAL;
|
||||
return;
|
||||
}
|
||||
if(code == "abuse") {
|
||||
if (code == "abuse") {
|
||||
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: Your username was blocked due to abuse."),
|
||||
"red");
|
||||
m_state = FATAL;
|
||||
@@ -221,18 +221,18 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
|
||||
|
||||
void DNSUpdater::updateCredentials()
|
||||
{
|
||||
if(m_state == FATAL) return;
|
||||
if (m_state == FATAL) return;
|
||||
Preferences pref;
|
||||
bool change = false;
|
||||
// Get DNS service information
|
||||
if(m_service != pref.getDynDNSService()) {
|
||||
if (m_service != pref.getDynDNSService()) {
|
||||
m_service = pref.getDynDNSService();
|
||||
change = true;
|
||||
}
|
||||
if(m_domain != pref.getDynDomainName()) {
|
||||
if (m_domain != pref.getDynDomainName()) {
|
||||
m_domain = pref.getDynDomainName();
|
||||
QRegExp domain_regex("^(?:(?!\\d|-)[a-zA-Z0-9\\-]{1,63}\\.)+[a-zA-Z]{2,}$");
|
||||
if(domain_regex.indexIn(m_domain) < 0) {
|
||||
if (domain_regex.indexIn(m_domain) < 0) {
|
||||
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied domain name is invalid."),
|
||||
"red");
|
||||
m_lastIP.clear();
|
||||
@@ -242,9 +242,9 @@ void DNSUpdater::updateCredentials()
|
||||
}
|
||||
change = true;
|
||||
}
|
||||
if(m_username != pref.getDynDNSUsername()) {
|
||||
if (m_username != pref.getDynDNSUsername()) {
|
||||
m_username = pref.getDynDNSUsername();
|
||||
if(m_username.length() < 4) {
|
||||
if (m_username.length() < 4) {
|
||||
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied username is too short."),
|
||||
"red");
|
||||
m_lastIP.clear();
|
||||
@@ -254,9 +254,9 @@ void DNSUpdater::updateCredentials()
|
||||
}
|
||||
change = true;
|
||||
}
|
||||
if(m_password != pref.getDynDNSPassword()) {
|
||||
if (m_password != pref.getDynDNSPassword()) {
|
||||
m_password = pref.getDynDNSPassword();
|
||||
if(m_password.length() < 4) {
|
||||
if (m_password.length() < 4) {
|
||||
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied password is too short."),
|
||||
"red");
|
||||
m_lastIP.clear();
|
||||
@@ -267,7 +267,7 @@ void DNSUpdater::updateCredentials()
|
||||
change = true;
|
||||
}
|
||||
|
||||
if(m_state == INVALID_CREDS && change) {
|
||||
if (m_state == INVALID_CREDS && change) {
|
||||
m_state = OK; // Try again
|
||||
m_ipCheckTimer.start();
|
||||
checkPublicIP();
|
||||
|
||||
@@ -50,7 +50,7 @@ class downloadFromURL : public QDialog, private Ui::downloadFromURL{
|
||||
show();
|
||||
// Paste clipboard if there is an URL in it
|
||||
QString clip_txt = qApp->clipboard()->text();
|
||||
if(clip_txt.startsWith("http://", Qt::CaseInsensitive) || clip_txt.startsWith("https://", Qt::CaseInsensitive) || clip_txt.startsWith("ftp://", Qt::CaseInsensitive) || clip_txt.startsWith("magnet:", Qt::CaseInsensitive) || clip_txt.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
if (clip_txt.startsWith("http://", Qt::CaseInsensitive) || clip_txt.startsWith("https://", Qt::CaseInsensitive) || clip_txt.startsWith("ftp://", Qt::CaseInsensitive) || clip_txt.startsWith("magnet:", Qt::CaseInsensitive) || clip_txt.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
textUrls->setText(clip_txt);
|
||||
}
|
||||
}
|
||||
@@ -66,15 +66,15 @@ class downloadFromURL : public QDialog, private Ui::downloadFromURL{
|
||||
QStringList url_list = urls.split(QString::fromUtf8("\n"));
|
||||
QString url;
|
||||
QStringList url_list_cleaned;
|
||||
foreach(url, url_list){
|
||||
foreach (url, url_list){
|
||||
url = url.trimmed();
|
||||
if(!url.isEmpty()){
|
||||
if(url_list_cleaned.indexOf(QRegExp(url, Qt::CaseInsensitive, QRegExp::FixedString)) < 0){
|
||||
if (!url.isEmpty()){
|
||||
if (url_list_cleaned.indexOf(QRegExp(url, Qt::CaseInsensitive, QRegExp::FixedString)) < 0){
|
||||
url_list_cleaned << url;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!url_list_cleaned.size()){
|
||||
if (!url_list_cleaned.size()){
|
||||
QMessageBox::critical(0, tr("No URL entered"), tr("Please type at least one URL."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ void DownloadThread::processDlFinished(QNetworkReply* reply) {
|
||||
QString url = reply->url().toString();
|
||||
qDebug("Download finished: %s", qPrintable(url));
|
||||
// Check if the request was successful
|
||||
if(reply->error() != QNetworkReply::NoError) {
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
// Failure
|
||||
qDebug("Download failure (%s), reason: %s", qPrintable(url), qPrintable(errorCodeToString(reply->error())));
|
||||
emit downloadFailure(url, errorCodeToString(reply->error()));
|
||||
@@ -64,7 +64,7 @@ void DownloadThread::processDlFinished(QNetworkReply* reply) {
|
||||
}
|
||||
// Check if the server ask us to redirect somewhere lese
|
||||
const QVariant redirection = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
|
||||
if(redirection.isValid()) {
|
||||
if (redirection.isValid()) {
|
||||
// We should redirect
|
||||
QUrl newUrl = redirection.toUrl();
|
||||
// Resolve relative urls
|
||||
@@ -78,7 +78,7 @@ void DownloadThread::processDlFinished(QNetworkReply* reply) {
|
||||
return;
|
||||
}
|
||||
// Checking if it was redirected, restoring initial URL
|
||||
if(m_redirectMapping.contains(url)) {
|
||||
if (m_redirectMapping.contains(url)) {
|
||||
url = m_redirectMapping.take(url);
|
||||
}
|
||||
// Success
|
||||
@@ -87,7 +87,7 @@ void DownloadThread::processDlFinished(QNetworkReply* reply) {
|
||||
if (tmpfile->open()) {
|
||||
QString filePath = tmpfile->fileName();
|
||||
qDebug("Temporary filename is: %s", qPrintable(filePath));
|
||||
if(reply->isOpen() || reply->open(QIODevice::ReadOnly)) {
|
||||
if (reply->isOpen() || reply->open(QIODevice::ReadOnly)) {
|
||||
// TODO: Support GZIP compression
|
||||
tmpfile->write(reply->readAll());
|
||||
tmpfile->close();
|
||||
@@ -115,9 +115,9 @@ void DownloadThread::loadCookies(const QString &host_name, QString url) {
|
||||
QNetworkCookieJar *cookie_jar = m_networkManager.cookieJar();
|
||||
QList<QNetworkCookie> cookies;
|
||||
qDebug("Loading cookies for host name: %s", qPrintable(host_name));
|
||||
foreach(const QByteArray& raw_cookie, raw_cookies) {
|
||||
foreach (const QByteArray& raw_cookie, raw_cookies) {
|
||||
QList<QByteArray> cookie_parts = raw_cookie.split('=');
|
||||
if(cookie_parts.size() == 2) {
|
||||
if (cookie_parts.size() == 2) {
|
||||
qDebug("Loading cookie: %s", raw_cookie.constData());
|
||||
cookies << QNetworkCookie(cookie_parts.first(), cookie_parts.last());
|
||||
}
|
||||
@@ -139,7 +139,7 @@ QNetworkReply* DownloadThread::downloadUrl(const QString &url){
|
||||
#ifndef DISABLE_GUI
|
||||
// Load cookies
|
||||
QString host_name = QUrl::fromEncoded(url.toUtf8()).host();
|
||||
if(!host_name.isEmpty())
|
||||
if (!host_name.isEmpty())
|
||||
loadCookies(host_name, url);
|
||||
#endif
|
||||
// Process download request
|
||||
@@ -151,7 +151,7 @@ QNetworkReply* DownloadThread::downloadUrl(const QString &url){
|
||||
request.setRawHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5");
|
||||
qDebug("Downloading %s...", request.url().toEncoded().data());
|
||||
qDebug("%d cookies for this URL", m_networkManager.cookieJar()->cookiesForUrl(url).size());
|
||||
for(int i=0; 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("Domain: %s, Path: %s", qPrintable(m_networkManager.cookieJar()->cookiesForUrl(url).at(i).domain()), qPrintable(m_networkManager.cookieJar()->cookiesForUrl(url).at(i).path()));
|
||||
}
|
||||
@@ -160,10 +160,10 @@ QNetworkReply* DownloadThread::downloadUrl(const QString &url){
|
||||
|
||||
void DownloadThread::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal) {
|
||||
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
|
||||
if(!reply) return;
|
||||
if(bytesTotal > 0) {
|
||||
if (!reply) return;
|
||||
if (bytesTotal > 0) {
|
||||
// Total number of bytes is available
|
||||
if(bytesTotal > 1048576) {
|
||||
if (bytesTotal > 1048576) {
|
||||
// More than 1MB, this is probably not a torrent file, aborting...
|
||||
reply->abort();
|
||||
reply->deleteLater();
|
||||
@@ -171,7 +171,7 @@ void DownloadThread::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal)
|
||||
disconnect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(checkDownloadSize(qint64,qint64)));
|
||||
}
|
||||
} else {
|
||||
if(bytesReceived > 1048576) {
|
||||
if (bytesReceived > 1048576) {
|
||||
// More than 1MB, this is probably not a torrent file, aborting...
|
||||
reply->abort();
|
||||
reply->deleteLater();
|
||||
@@ -182,13 +182,13 @@ void DownloadThread::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal)
|
||||
void DownloadThread::applyProxySettings() {
|
||||
QNetworkProxy proxy;
|
||||
const Preferences pref;
|
||||
if(pref.isProxyEnabled()) {
|
||||
if (pref.isProxyEnabled()) {
|
||||
// Proxy enabled
|
||||
proxy.setHostName(pref.getProxyIp());
|
||||
proxy.setPort(pref.getProxyPort());
|
||||
// Default proxy type is HTTP, we must change if it is SOCKS5
|
||||
const int proxy_type = pref.getProxyType();
|
||||
if(proxy_type == Proxy::SOCKS5 || proxy_type == Proxy::SOCKS5_PW) {
|
||||
if (proxy_type == Proxy::SOCKS5 || proxy_type == Proxy::SOCKS5_PW) {
|
||||
qDebug() << Q_FUNC_INFO << "using SOCKS proxy";
|
||||
proxy.setType(QNetworkProxy::Socks5Proxy);
|
||||
} else {
|
||||
@@ -196,7 +196,7 @@ void DownloadThread::applyProxySettings() {
|
||||
proxy.setType(QNetworkProxy::HttpProxy);
|
||||
}
|
||||
// Authentication?
|
||||
if(pref.isProxyAuthEnabled()) {
|
||||
if (pref.isProxyAuthEnabled()) {
|
||||
qDebug("Proxy requires authentication, authenticating");
|
||||
proxy.setUser(pref.getProxyUsername());
|
||||
proxy.setPassword(pref.getProxyPassword());
|
||||
|
||||
@@ -50,10 +50,10 @@ ExecutionLog::ExecutionLog(QWidget *parent) :
|
||||
ui->tabBan->layout()->addWidget(m_banList);
|
||||
|
||||
const QStringList log_msgs = QBtSession::instance()->getConsoleMessages();
|
||||
foreach(const QString& msg, log_msgs)
|
||||
foreach (const QString& msg, log_msgs)
|
||||
addLogMessage(msg);
|
||||
const QStringList ban_msgs = QBtSession::instance()->getPeerBanMessages();
|
||||
foreach(const QString& msg, ban_msgs)
|
||||
foreach (const QString& msg, ban_msgs)
|
||||
addBanMessage(msg);
|
||||
connect(QBtSession::instance(), SIGNAL(newConsoleMessage(QString)), SLOT(addLogMessage(QString)));
|
||||
connect(QBtSession::instance(), SIGNAL(newBanMessage(QString)), SLOT(addBanMessage(QString)));
|
||||
|
||||
@@ -59,11 +59,11 @@ private:
|
||||
private:
|
||||
static bool isNetworkFileSystem(QString path) {
|
||||
QString file = path;
|
||||
if(!file.endsWith(QDir::separator()))
|
||||
if (!file.endsWith(QDir::separator()))
|
||||
file += QDir::separator();
|
||||
file += ".";
|
||||
struct statfs buf;
|
||||
if(!statfs(file.toLocal8Bit().constData(), &buf)) {
|
||||
if (!statfs(file.toLocal8Bit().constData(), &buf)) {
|
||||
#ifdef Q_WS_MAC
|
||||
// XXX: should we make sure HAVE_STRUCT_FSSTAT_F_FSTYPENAME is defined?
|
||||
return (strcmp(buf.f_fstypename, "nfs") == 0 || strcmp(buf.f_fstypename, "cifs") == 0 || strcmp(buf.f_fstypename, "smbfs") == 0);
|
||||
@@ -124,17 +124,17 @@ public:
|
||||
|
||||
~FileSystemWatcher() {
|
||||
#ifndef Q_WS_WIN
|
||||
if(watch_timer)
|
||||
if (watch_timer)
|
||||
delete watch_timer;
|
||||
#endif
|
||||
if(m_partialTorrentTimer)
|
||||
if (m_partialTorrentTimer)
|
||||
delete m_partialTorrentTimer;
|
||||
}
|
||||
|
||||
QStringList directories() const {
|
||||
QStringList dirs;
|
||||
#ifndef Q_WS_WIN
|
||||
if(watch_timer) {
|
||||
if (watch_timer) {
|
||||
foreach (const QDir &dir, watched_folders)
|
||||
dirs << dir.canonicalPath();
|
||||
}
|
||||
@@ -149,7 +149,7 @@ public:
|
||||
if (!dir.exists())
|
||||
return;
|
||||
// Check if the path points to a network file system or not
|
||||
if(isNetworkFileSystem(path)) {
|
||||
if (isNetworkFileSystem(path)) {
|
||||
// Network mode
|
||||
qDebug("Network folder detected: %s", qPrintable(path));
|
||||
qDebug("Using file polling mode instead of inotify...");
|
||||
@@ -194,7 +194,7 @@ protected slots:
|
||||
// Local folders scan
|
||||
addTorrentsFromDir(QDir(path), torrents);
|
||||
// Report detected torrent files
|
||||
if(!torrents.empty()) {
|
||||
if (!torrents.empty()) {
|
||||
qDebug("The following files are being reported: %s", qPrintable(torrents.join("\n")));
|
||||
emit torrentsAdded(torrents);
|
||||
}
|
||||
@@ -210,7 +210,7 @@ protected slots:
|
||||
addTorrentsFromDir(dir, torrents);
|
||||
}
|
||||
// Report detected torrent files
|
||||
if(!torrents.empty()) {
|
||||
if (!torrents.empty()) {
|
||||
qDebug("The following files are being reported: %s", qPrintable(torrents.join("\n")));
|
||||
emit torrentsAdded(torrents);
|
||||
}
|
||||
@@ -221,16 +221,16 @@ protected slots:
|
||||
QStringList no_longer_partial;
|
||||
|
||||
// Check which torrents are still partial
|
||||
foreach(const QString& torrent_path, m_partialTorrents.keys()) {
|
||||
if(!QFile::exists(torrent_path)) {
|
||||
foreach (const QString& torrent_path, m_partialTorrents.keys()) {
|
||||
if (!QFile::exists(torrent_path)) {
|
||||
m_partialTorrents.remove(torrent_path);
|
||||
continue;
|
||||
}
|
||||
if(misc::isValidTorrentFile(torrent_path)) {
|
||||
if (misc::isValidTorrentFile(torrent_path)) {
|
||||
no_longer_partial << torrent_path;
|
||||
m_partialTorrents.remove(torrent_path);
|
||||
} else {
|
||||
if(m_partialTorrents[torrent_path] >= MAX_PARTIAL_RETRIES) {
|
||||
if (m_partialTorrents[torrent_path] >= MAX_PARTIAL_RETRIES) {
|
||||
m_partialTorrents.remove(torrent_path);
|
||||
QFile::rename(torrent_path, torrent_path+".invalid");
|
||||
} else {
|
||||
@@ -240,7 +240,7 @@ protected slots:
|
||||
}
|
||||
|
||||
// Stop the partial timer if necessary
|
||||
if(m_partialTorrents.empty()) {
|
||||
if (m_partialTorrents.empty()) {
|
||||
m_partialTorrentTimer->stop();
|
||||
m_partialTorrentTimer->deleteLater();
|
||||
qDebug("No longer any partial torrent.");
|
||||
@@ -249,7 +249,7 @@ protected slots:
|
||||
m_partialTorrentTimer->start(WATCH_INTERVAL);
|
||||
}
|
||||
// Notify of new torrents
|
||||
if(!no_longer_partial.isEmpty())
|
||||
if (!no_longer_partial.isEmpty())
|
||||
emit torrentsAdded(no_longer_partial);
|
||||
}
|
||||
|
||||
@@ -259,7 +259,7 @@ signals:
|
||||
private:
|
||||
void startPartialTorrentTimer() {
|
||||
Q_ASSERT(!m_partialTorrents.isEmpty());
|
||||
if(!m_partialTorrentTimer) {
|
||||
if (!m_partialTorrentTimer) {
|
||||
m_partialTorrentTimer = new QTimer();
|
||||
connect(m_partialTorrentTimer, SIGNAL(timeout()), SLOT(processPartialTorrents()));
|
||||
m_partialTorrentTimer->setSingleShot(true);
|
||||
@@ -269,19 +269,19 @@ private:
|
||||
|
||||
void addTorrentsFromDir(const QDir &dir, QStringList &torrents) {
|
||||
const QStringList files = dir.entryList(m_filters, QDir::Files, QDir::Unsorted);
|
||||
foreach(const QString &file, files) {
|
||||
foreach (const QString &file, files) {
|
||||
const QString file_abspath = dir.absoluteFilePath(file);
|
||||
if(misc::isValidTorrentFile(file_abspath)) {
|
||||
if (misc::isValidTorrentFile(file_abspath)) {
|
||||
torrents << file_abspath;
|
||||
} else {
|
||||
if(!m_partialTorrents.contains(file_abspath)) {
|
||||
if (!m_partialTorrents.contains(file_abspath)) {
|
||||
qDebug("Partial torrent detected at: %s", qPrintable(file_abspath));
|
||||
qDebug("Delay the file's processing...");
|
||||
m_partialTorrents.insert(file_abspath, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!m_partialTorrents.empty())
|
||||
if (!m_partialTorrents.empty())
|
||||
startPartialTorrentTimer();
|
||||
}
|
||||
|
||||
|
||||
@@ -70,14 +70,14 @@ using namespace libtorrent;
|
||||
|
||||
QString GeoIPManager::geoipFolder(bool embedded) {
|
||||
#ifdef WITH_GEOIP_EMBEDDED
|
||||
if(embedded)
|
||||
if (embedded)
|
||||
return ":/geoip/";
|
||||
return misc::QDesktopServicesDataLocation()+"geoip"+QDir::separator();
|
||||
#else
|
||||
Q_UNUSED(embedded);
|
||||
if(QFile::exists("/usr/local/share/GeoIP/GeoIP.dat"))
|
||||
if (QFile::exists("/usr/local/share/GeoIP/GeoIP.dat"))
|
||||
return "/usr/local/share/GeoIP/";
|
||||
if(QFile::exists("/var/lib/GeoIP/GeoIP.dat"))
|
||||
if (QFile::exists("/var/lib/GeoIP/GeoIP.dat"))
|
||||
return "/var/lib/GeoIP/";
|
||||
return "/usr/share/GeoIP/";
|
||||
#endif
|
||||
@@ -89,22 +89,22 @@ QString GeoIPManager::geoipDBpath(bool embedded) {
|
||||
|
||||
#ifdef WITH_GEOIP_EMBEDDED
|
||||
void GeoIPManager::exportEmbeddedDb() {
|
||||
if(!QFile::exists(geoipDBpath(false)) || QFile(geoipDBpath(false)).size() != QFile(geoipDBpath(true)).size()) { // Export is required
|
||||
if (!QFile::exists(geoipDBpath(false)) || QFile(geoipDBpath(false)).size() != QFile(geoipDBpath(true)).size()) { // Export is required
|
||||
qDebug("A local Geoip database update is required, proceeding...");
|
||||
// Create geoip folder is necessary
|
||||
QDir gfolder(geoipFolder(false));
|
||||
if(!gfolder.exists()) {
|
||||
if(!gfolder.mkpath(geoipFolder(false))) {
|
||||
if (!gfolder.exists()) {
|
||||
if (!gfolder.mkpath(geoipFolder(false))) {
|
||||
std::cerr << "Failed to create geoip folder at " << qPrintable(geoipFolder(false)) << std::endl;
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Remove destination files
|
||||
if(QFile::exists(geoipDBpath(false)))
|
||||
if (QFile::exists(geoipDBpath(false)))
|
||||
QFile::remove(geoipDBpath(false));
|
||||
// Copy from executable to hard disk
|
||||
qDebug("%s -> %s", qPrintable(geoipDBpath(true)), qPrintable(geoipDBpath(false)));
|
||||
if(!QFile::copy(geoipDBpath(true), geoipDBpath(false))) {
|
||||
if (!QFile::copy(geoipDBpath(true), geoipDBpath(false))) {
|
||||
std::cerr << "ERROR: Failed to copy geoip.dat from executable to hard disk" << std::endl;
|
||||
}
|
||||
qDebug("Local Geoip database was updated");
|
||||
@@ -116,7 +116,7 @@ void GeoIPManager::loadDatabase(session *s) {
|
||||
#ifdef WITH_GEOIP_EMBEDDED
|
||||
exportEmbeddedDb();
|
||||
#endif
|
||||
if(QFile::exists(geoipDBpath(false))) {
|
||||
if (QFile::exists(geoipDBpath(false))) {
|
||||
qDebug("Loading GeoIP database from %s...", qPrintable(geoipDBpath(false)));
|
||||
s->load_country_db(geoipDBpath(false).toLocal8Bit().constData());
|
||||
} else {
|
||||
@@ -183,9 +183,9 @@ const char * country_name[253] =
|
||||
"Saint Barthelemy","Saint Martin"};
|
||||
|
||||
QString GeoIPManager::CountryISOCodeToName(const char* iso) {
|
||||
if(iso[0] == 0) return "N/A";
|
||||
for(uint i = 0; i < num_countries; ++i) {
|
||||
if(iso[0] == country_code[i][0] && iso[1] == country_code[i][1]) {
|
||||
if (iso[0] == 0) return "N/A";
|
||||
for (uint i = 0; i < num_countries; ++i) {
|
||||
if (iso[0] == country_code[i][0] && iso[1] == country_code[i][1]) {
|
||||
return QLatin1String(country_name[i]);
|
||||
}
|
||||
}
|
||||
@@ -195,7 +195,7 @@ QString GeoIPManager::CountryISOCodeToName(const char* iso) {
|
||||
|
||||
// http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm
|
||||
QIcon GeoIPManager::CountryISOCodeToIcon(const char* iso) {
|
||||
if(iso[0] == 0 || iso[0] == '!') return QIcon();
|
||||
if (iso[0] == 0 || iso[0] == '!') return QIcon();
|
||||
const QString isoStr = QString(QByteArray(iso, 2)).toLower();
|
||||
return QIcon(":/Icons/flags/"+isoStr+".png");
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ public:
|
||||
std::cout << qPrintable(tr("To control qBittorrent, access the Web UI at http://localhost:%1").arg(QString::number(pref.getWebUiPort()))) << std::endl;
|
||||
std::cout << qPrintable(tr("The Web UI administrator user name is: %1").arg(pref.getWebUiUsername())) << std::endl;
|
||||
qDebug() << "Password:" << pref.getWebUiPassword();
|
||||
if(pref.getWebUiPassword() == "32fe0bd2bb001911bb8bcfe23fc92b63") {
|
||||
if (pref.getWebUiPassword() == "32fe0bd2bb001911bb8bcfe23fc92b63") {
|
||||
std::cout << qPrintable(tr("The Web UI administrator password is still the default one: %1").arg("adminadmin")) << std::endl;
|
||||
std::cout << qPrintable(tr("This is a security risk, please consider changing your password from program preferences.")) << std::endl;
|
||||
}
|
||||
@@ -85,16 +85,16 @@ public slots:
|
||||
// the right addTorrent function, considering
|
||||
// the parameter type.
|
||||
void processParams(const QStringList& params) {
|
||||
foreach(QString param, params) {
|
||||
foreach (QString param, params) {
|
||||
param = param.trimmed();
|
||||
if(param.startsWith(QString::fromUtf8("http://"), Qt::CaseInsensitive) || param.startsWith(QString::fromUtf8("ftp://"), Qt::CaseInsensitive) || param.startsWith(QString::fromUtf8("https://"), Qt::CaseInsensitive)) {
|
||||
if (param.startsWith(QString::fromUtf8("http://"), Qt::CaseInsensitive) || param.startsWith(QString::fromUtf8("ftp://"), Qt::CaseInsensitive) || param.startsWith(QString::fromUtf8("https://"), Qt::CaseInsensitive)) {
|
||||
QBtSession::instance()->downloadFromUrl(param);
|
||||
}else{
|
||||
if(param.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
if (param.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
qDebug("Converting bc link to magnet link");
|
||||
param = misc::bcLinkToMagnet(param);
|
||||
}
|
||||
if(param.startsWith("magnet:", Qt::CaseInsensitive)) {
|
||||
if (param.startsWith("magnet:", Qt::CaseInsensitive)) {
|
||||
QBtSession::instance()->addMagnetUri(param);
|
||||
} else {
|
||||
QBtSession::instance()->addTorrent(param);
|
||||
|
||||
@@ -44,7 +44,7 @@ public:
|
||||
protected:
|
||||
void tabInserted(int index) {
|
||||
QTabWidget::tabInserted(index);
|
||||
if(count() == 1) {
|
||||
if (count() == 1) {
|
||||
showTabBar(false);
|
||||
} else {
|
||||
showTabBar(true);
|
||||
@@ -53,7 +53,7 @@ protected:
|
||||
|
||||
void tabRemoved(int index) {
|
||||
QTabWidget::tabInserted(index);
|
||||
if(count() == 1) {
|
||||
if (count() == 1) {
|
||||
showTabBar(false);
|
||||
} else {
|
||||
showTabBar(true);
|
||||
|
||||
@@ -42,14 +42,14 @@ IconProvider::IconProvider()
|
||||
|
||||
IconProvider * IconProvider::instance()
|
||||
{
|
||||
if(!m_instance)
|
||||
if (!m_instance)
|
||||
m_instance = new IconProvider;
|
||||
return m_instance;
|
||||
}
|
||||
|
||||
void IconProvider::drop()
|
||||
{
|
||||
if(m_instance) {
|
||||
if (m_instance) {
|
||||
delete m_instance;
|
||||
m_instance = 0;
|
||||
}
|
||||
@@ -58,7 +58,7 @@ void IconProvider::drop()
|
||||
QIcon IconProvider::getIcon(const QString &iconId)
|
||||
{
|
||||
#if defined(Q_WS_X11) && (QT_VERSION >= QT_VERSION_CHECK(4,6,0))
|
||||
if(m_useSystemTheme) {
|
||||
if (m_useSystemTheme) {
|
||||
QIcon icon = QIcon::fromTheme(iconId, QIcon(":/Icons/oxygen/"+iconId+".png"));
|
||||
icon = generateDifferentSizes(icon);
|
||||
return icon;
|
||||
@@ -84,14 +84,14 @@ QIcon IconProvider::generateDifferentSizes(const QIcon &icon)
|
||||
required_sizes << QSize(16, 16) << QSize(24, 24);
|
||||
QList<QIcon::Mode> modes;
|
||||
modes << QIcon::Normal << QIcon::Active << QIcon::Selected << QIcon::Disabled;
|
||||
foreach(const QSize& size, required_sizes) {
|
||||
foreach(QIcon::Mode mode, modes) {
|
||||
foreach (const QSize& size, required_sizes) {
|
||||
foreach (QIcon::Mode mode, modes) {
|
||||
QPixmap pixoff = icon.pixmap(size, mode, QIcon::Off);
|
||||
if(pixoff.height() > size.height())
|
||||
if (pixoff.height() > size.height())
|
||||
pixoff = pixoff.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
|
||||
new_icon.addPixmap(pixoff, mode, QIcon::Off);
|
||||
QPixmap pixon = icon.pixmap(size, mode, QIcon::On);
|
||||
if(pixon.height() > size.height())
|
||||
if (pixon.height() > size.height())
|
||||
pixon = pixoff.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
|
||||
new_icon.addPixmap(pixon, mode, QIcon::On);
|
||||
}
|
||||
@@ -103,11 +103,11 @@ QIcon IconProvider::generateDifferentSizes(const QIcon &icon)
|
||||
QString IconProvider::getIconPath(const QString &iconId)
|
||||
{
|
||||
#if defined(Q_WS_X11) && (QT_VERSION >= QT_VERSION_CHECK(4,6,0))
|
||||
if(m_useSystemTheme) {
|
||||
if (m_useSystemTheme) {
|
||||
QString path = QDir::temp().absoluteFilePath(iconId+".png");
|
||||
if(!QFile::exists(path)) {
|
||||
if (!QFile::exists(path)) {
|
||||
const QIcon icon = QIcon::fromTheme(iconId);
|
||||
if(icon.isNull()) return ":/Icons/oxygen/"+iconId+".png";
|
||||
if (icon.isNull()) return ":/Icons/oxygen/"+iconId+".png";
|
||||
QPixmap px = icon.pixmap(32);
|
||||
px.save(path);
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ void LogListWidget::appendLine(const QString &line)
|
||||
setItemWidget(item, lbl);
|
||||
const int nbLines = count();
|
||||
// Limit log size
|
||||
if(nbLines > m_maxLines)
|
||||
if (nbLines > m_maxLines)
|
||||
delete takeItem(nbLines - 1);
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ void LogListWidget::copySelection()
|
||||
static QRegExp html_tag("<[^>]+>");
|
||||
QList<QListWidgetItem*> items = selectedItems();
|
||||
QStringList strings;
|
||||
foreach(QListWidgetItem* it, items)
|
||||
foreach (QListWidgetItem* it, items)
|
||||
strings << static_cast<QLabel*>(itemWidget(it))->text().replace(html_tag, "");
|
||||
|
||||
QApplication::clipboard()->setText(strings.join("\n"));
|
||||
|
||||
44
src/main.cpp
44
src/main.cpp
@@ -87,14 +87,14 @@ class LegalNotice: public QObject {
|
||||
public:
|
||||
static bool userAgreesWithNotice() {
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
|
||||
if(settings.value(QString::fromUtf8("LegalNotice/Accepted"), false).toBool()) // Already accepted once
|
||||
if (settings.value(QString::fromUtf8("LegalNotice/Accepted"), false).toBool()) // Already accepted once
|
||||
return true;
|
||||
#ifdef DISABLE_GUI
|
||||
std::cout << std::endl << "*** " << qPrintable(tr("Legal Notice")) << " ***" << std::endl;
|
||||
std::cout << qPrintable(tr("qBittorrent is a file sharing program. When you run a torrent, its data will be made available to others by means of upload. Any content you share is your sole responsibility.\n\nNo further notices will be issued.")) << std::endl << std::endl;
|
||||
std::cout << qPrintable(tr("Press %1 key to accept and continue...").arg("'y'")) << std::endl;
|
||||
char ret = getchar(); // Read pressed key
|
||||
if(ret == 'y' || ret == 'Y') {
|
||||
if (ret == 'y' || ret == 'Y') {
|
||||
// Save the answer
|
||||
settings.setValue(QString::fromUtf8("LegalNotice/Accepted"), true);
|
||||
return true;
|
||||
@@ -109,7 +109,7 @@ public:
|
||||
msgBox.show(); // Need to be shown or to moveToCenter does not work
|
||||
msgBox.move(misc::screenCenter(&msgBox));
|
||||
msgBox.exec();
|
||||
if(msgBox.clickedButton() == agree_button) {
|
||||
if (msgBox.clickedButton() == agree_button) {
|
||||
// Save the answer
|
||||
settings.setValue(QString::fromUtf8("LegalNotice/Accepted"), true);
|
||||
return true;
|
||||
@@ -164,18 +164,18 @@ int main(int argc, char *argv[]){
|
||||
#endif
|
||||
|
||||
// Check if qBittorrent is already running for this user
|
||||
if(app.isRunning()) {
|
||||
if (app.isRunning()) {
|
||||
qDebug("qBittorrent is already running for this user.");
|
||||
//Pass program parameters if any
|
||||
QString message;
|
||||
for (int a = 1; a < argc; ++a) {
|
||||
QString p = QString::fromLocal8Bit(argv[a]);
|
||||
if(p.startsWith("--")) continue;
|
||||
if (p.startsWith("--")) continue;
|
||||
message += p;
|
||||
if (a < argc-1)
|
||||
message += "|";
|
||||
}
|
||||
if(!message.isEmpty()) {
|
||||
if (!message.isEmpty()) {
|
||||
qDebug("Passing program parameters to running instance...");
|
||||
qDebug("Message: %s", qPrintable(message));
|
||||
app.sendMessage(message);
|
||||
@@ -192,11 +192,11 @@ int main(int argc, char *argv[]){
|
||||
QString locale = pref.getLocale();
|
||||
QTranslator qtTranslator;
|
||||
QTranslator translator;
|
||||
if(locale.isEmpty()){
|
||||
if (locale.isEmpty()){
|
||||
locale = QLocale::system().name();
|
||||
pref.setLocale(locale);
|
||||
}
|
||||
if(qtTranslator.load(
|
||||
if (qtTranslator.load(
|
||||
QString::fromUtf8("qt_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)
|
||||
)){
|
||||
qDebug("Qt %s locale recognized, using translation.", qPrintable(locale));
|
||||
@@ -204,14 +204,14 @@ int main(int argc, char *argv[]){
|
||||
qDebug("Qt %s locale unrecognized, using default (en_GB).", qPrintable(locale));
|
||||
}
|
||||
app.installTranslator(&qtTranslator);
|
||||
if(translator.load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){
|
||||
if (translator.load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){
|
||||
qDebug("%s locale recognized, using translation.", qPrintable(locale));
|
||||
}else{
|
||||
qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale));
|
||||
}
|
||||
app.installTranslator(&translator);
|
||||
#ifndef DISABLE_GUI
|
||||
if(locale.startsWith("ar")) {
|
||||
if (locale.startsWith("ar")) {
|
||||
qDebug("Right to Left mode");
|
||||
app.setLayoutDirection(Qt::RightToLeft);
|
||||
} else {
|
||||
@@ -221,28 +221,28 @@ int main(int argc, char *argv[]){
|
||||
app.setApplicationName(QString::fromUtf8("qBittorrent"));
|
||||
|
||||
// Check for executable parameters
|
||||
if(argc > 1){
|
||||
if(QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--version")){
|
||||
if (argc > 1){
|
||||
if (QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--version")){
|
||||
std::cout << "qBittorrent " << VERSION << '\n';
|
||||
return 0;
|
||||
}
|
||||
if(QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--help")){
|
||||
if (QString::fromLocal8Bit(argv[1]) == QString::fromUtf8("--help")){
|
||||
UsageDisplay::displayUsage(argv[0]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
for(int i=1; i<argc; ++i) {
|
||||
for (int i=1; i<argc; ++i) {
|
||||
#ifndef DISABLE_GUI
|
||||
if(QString::fromLocal8Bit(argv[i]) == QString::fromUtf8("--no-splash")) {
|
||||
if (QString::fromLocal8Bit(argv[i]) == QString::fromUtf8("--no-splash")) {
|
||||
no_splash = true;
|
||||
} else {
|
||||
#endif
|
||||
if(QString::fromLocal8Bit(argv[i]).startsWith("--webui-port=")) {
|
||||
if (QString::fromLocal8Bit(argv[i]).startsWith("--webui-port=")) {
|
||||
QStringList parts = QString::fromLocal8Bit(argv[i]).split("=");
|
||||
if(parts.size() == 2) {
|
||||
if (parts.size() == 2) {
|
||||
bool ok = false;
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -254,11 +254,11 @@ int main(int argc, char *argv[]){
|
||||
}
|
||||
|
||||
#ifndef DISABLE_GUI
|
||||
if(pref.isSlashScreenDisabled()) {
|
||||
if (pref.isSlashScreenDisabled()) {
|
||||
no_splash = true;
|
||||
}
|
||||
QSplashScreen *splash = 0;
|
||||
if(!no_splash) {
|
||||
if (!no_splash) {
|
||||
QPixmap splash_img(":/Icons/skin/splash.png");
|
||||
QPainter painter(&splash_img);
|
||||
QString version = VERSION;
|
||||
@@ -280,7 +280,7 @@ int main(int argc, char *argv[]){
|
||||
app.setStyleSheet("QStatusBar::item { border-width: 0; }");
|
||||
#endif
|
||||
|
||||
if(!LegalNotice::userAgreesWithNotice()) {
|
||||
if (!LegalNotice::userAgreesWithNotice()) {
|
||||
return 0;
|
||||
}
|
||||
#ifndef DISABLE_GUI
|
||||
@@ -297,7 +297,7 @@ int main(int argc, char *argv[]){
|
||||
// Remove first argument (program name)
|
||||
torrentCmdLine.removeFirst();
|
||||
#ifndef QT_NO_DEBUG_OUTPUT
|
||||
foreach(const QString &argument, torrentCmdLine) {
|
||||
foreach (const QString &argument, torrentCmdLine) {
|
||||
qDebug() << "Command line argument:" << argument;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -247,14 +247,14 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo
|
||||
#endif
|
||||
actionAutoExit_qBittorrent->setChecked(pref.shutdownqBTWhenDownloadsComplete());
|
||||
|
||||
if(!autoShutdownGroup->checkedAction())
|
||||
if (!autoShutdownGroup->checkedAction())
|
||||
actionAutoShutdown_Disabled->setChecked(true);
|
||||
|
||||
// Load Window state and sizes
|
||||
readSettings();
|
||||
|
||||
if(!ui_locked) {
|
||||
if(pref.startMinimized() && systrayIcon)
|
||||
if (!ui_locked) {
|
||||
if (pref.startMinimized() && systrayIcon)
|
||||
showMinimized();
|
||||
else {
|
||||
show();
|
||||
@@ -285,8 +285,8 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo
|
||||
|
||||
qDebug("GUI Built");
|
||||
#ifdef Q_WS_WIN
|
||||
if(!pref.neverCheckFileAssoc() && (!Preferences::isTorrentFileAssocSet() || !Preferences::isMagnetLinkAssocSet())) {
|
||||
if(QMessageBox::question(0, tr("Torrent file association"),
|
||||
if (!pref.neverCheckFileAssoc() && (!Preferences::isTorrentFileAssocSet() || !Preferences::isMagnetLinkAssocSet())) {
|
||||
if (QMessageBox::question(0, tr("Torrent file association"),
|
||||
tr("qBittorrent is not the default application to open torrent files or Magnet links.\nDo you want to associate qBittorrent to torrent files and Magnet links?"),
|
||||
QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
|
||||
Preferences::setTorrentFileAssoc(true);
|
||||
@@ -301,7 +301,7 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo
|
||||
#endif
|
||||
#if defined(Q_WS_WIN) || defined(Q_WS_MAC)
|
||||
// Check for update
|
||||
if(pref.isUpdateCheckEnabled()) {
|
||||
if (pref.isUpdateCheckEnabled()) {
|
||||
ProgramUpdater *updater = new ProgramUpdater(this);
|
||||
connect(updater, SIGNAL(updateCheckFinished(bool, QString)), SLOT(handleUpdateCheckFinished(bool, QString)));
|
||||
updater->checkForUpdates();
|
||||
@@ -337,37 +337,37 @@ MainWindow::~MainWindow() {
|
||||
#endif
|
||||
disconnect(tabs, SIGNAL(currentChanged(int)), this, SLOT(tab_changed(int)));
|
||||
// Delete other GUI objects
|
||||
if(executable_watcher)
|
||||
if (executable_watcher)
|
||||
delete executable_watcher;
|
||||
delete status_bar;
|
||||
delete search_filter;
|
||||
delete transferList;
|
||||
delete guiUpdater;
|
||||
if(createTorrentDlg)
|
||||
if (createTorrentDlg)
|
||||
delete createTorrentDlg;
|
||||
if(m_executionLog)
|
||||
if (m_executionLog)
|
||||
delete m_executionLog;
|
||||
if(aboutDlg)
|
||||
if (aboutDlg)
|
||||
delete aboutDlg;
|
||||
if(options)
|
||||
if (options)
|
||||
delete options;
|
||||
if(downloadFromURLDialog)
|
||||
if (downloadFromURLDialog)
|
||||
delete downloadFromURLDialog;
|
||||
if(rssWidget)
|
||||
if (rssWidget)
|
||||
delete rssWidget;
|
||||
if(searchEngine)
|
||||
if (searchEngine)
|
||||
delete searchEngine;
|
||||
delete transferListFilters;
|
||||
delete properties;
|
||||
delete hSplitter;
|
||||
delete vSplitter;
|
||||
if(systrayCreator) {
|
||||
if (systrayCreator) {
|
||||
delete systrayCreator;
|
||||
}
|
||||
if(systrayIcon) {
|
||||
if (systrayIcon) {
|
||||
delete systrayIcon;
|
||||
}
|
||||
if(myTrayIconMenu) {
|
||||
if (myTrayIconMenu) {
|
||||
delete myTrayIconMenu;
|
||||
}
|
||||
delete tabs;
|
||||
@@ -386,16 +386,16 @@ MainWindow::~MainWindow() {
|
||||
|
||||
void MainWindow::defineUILockPassword() {
|
||||
QString old_pass_md5 = Preferences().getUILockPasswordMD5();
|
||||
if(old_pass_md5.isNull()) old_pass_md5 = "";
|
||||
if (old_pass_md5.isNull()) old_pass_md5 = "";
|
||||
bool ok = false;
|
||||
QString new_clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, old_pass_md5, &ok);
|
||||
if(ok) {
|
||||
if (ok) {
|
||||
new_clear_password = new_clear_password.trimmed();
|
||||
if(new_clear_password.size() < 3) {
|
||||
if (new_clear_password.size() < 3) {
|
||||
QMessageBox::warning(this, tr("Invalid password"), tr("The password should contain at least 3 characters"));
|
||||
return;
|
||||
}
|
||||
if(new_clear_password != old_pass_md5) {
|
||||
if (new_clear_password != old_pass_md5) {
|
||||
Preferences().setUILockPassword(new_clear_password);
|
||||
}
|
||||
QMessageBox::information(this, tr("Password update"), tr("The UI lock password has been successfully updated"));
|
||||
@@ -405,11 +405,11 @@ void MainWindow::defineUILockPassword() {
|
||||
void MainWindow::on_actionLock_qBittorrent_triggered() {
|
||||
Preferences pref;
|
||||
// Check if there is a password
|
||||
if(pref.getUILockPasswordMD5().isEmpty()) {
|
||||
if (pref.getUILockPasswordMD5().isEmpty()) {
|
||||
// Ask for a password
|
||||
bool ok = false;
|
||||
QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok);
|
||||
if(!ok) return;
|
||||
if (!ok) return;
|
||||
pref.setUILockPassword(clear_password);
|
||||
}
|
||||
// Lock the interface
|
||||
@@ -420,29 +420,29 @@ void MainWindow::on_actionLock_qBittorrent_triggered() {
|
||||
}
|
||||
|
||||
void MainWindow::displayRSSTab(bool enable) {
|
||||
if(enable) {
|
||||
if (enable) {
|
||||
// RSS tab
|
||||
if(!rssWidget) {
|
||||
if (!rssWidget) {
|
||||
rssWidget = new RSSImp(tabs);
|
||||
int index_tab = tabs->addTab(rssWidget, tr("RSS"));
|
||||
tabs->setTabIcon(index_tab, IconProvider::instance()->getIcon("application-rss+xml"));
|
||||
}
|
||||
} else {
|
||||
if(rssWidget) {
|
||||
if (rssWidget) {
|
||||
delete rssWidget;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::displaySearchTab(bool enable) {
|
||||
if(enable) {
|
||||
if (enable) {
|
||||
// RSS tab
|
||||
if(!searchEngine) {
|
||||
if (!searchEngine) {
|
||||
searchEngine = new SearchEngine(this);
|
||||
tabs->insertTab(1, searchEngine, IconProvider::instance()->getIcon("edit-find"), tr("Search"));
|
||||
}
|
||||
} else {
|
||||
if(searchEngine) {
|
||||
if (searchEngine) {
|
||||
delete searchEngine;
|
||||
}
|
||||
}
|
||||
@@ -468,12 +468,12 @@ void MainWindow::tab_changed(int new_tab) {
|
||||
Q_UNUSED(new_tab);
|
||||
// We cannot rely on the index new_tab
|
||||
// because the tab order is undetermined now
|
||||
if(tabs->currentWidget() == vSplitter) {
|
||||
if (tabs->currentWidget() == vSplitter) {
|
||||
qDebug("Changed tab to transfer list, refreshing the list");
|
||||
properties->loadDynamicData();
|
||||
return;
|
||||
}
|
||||
if(tabs->currentWidget() == searchEngine) {
|
||||
if (tabs->currentWidget() == searchEngine) {
|
||||
qDebug("Changed tab to search engine, giving focus to search input");
|
||||
searchEngine->giveFocusToSearchInput();
|
||||
}
|
||||
@@ -492,12 +492,12 @@ void MainWindow::writeSettings() {
|
||||
void MainWindow::readSettings() {
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
|
||||
settings.beginGroup(QString::fromUtf8("MainWindow"));
|
||||
if(settings.contains("geometry")) {
|
||||
if(restoreGeometry(settings.value("geometry").toByteArray()))
|
||||
if (settings.contains("geometry")) {
|
||||
if (restoreGeometry(settings.value("geometry").toByteArray()))
|
||||
m_posInitialized = true;
|
||||
}
|
||||
const QByteArray splitterState = settings.value("vsplitterState").toByteArray();
|
||||
if(splitterState.isEmpty()) {
|
||||
if (splitterState.isEmpty()) {
|
||||
// Default sizes
|
||||
vSplitter->setSizes(QList<int>() << 120 << vSplitter->width()-120);
|
||||
} else {
|
||||
@@ -507,9 +507,9 @@ void MainWindow::readSettings() {
|
||||
}
|
||||
|
||||
void MainWindow::balloonClicked() {
|
||||
if(isHidden()) {
|
||||
if (isHidden()) {
|
||||
show();
|
||||
if(isMinimized()) {
|
||||
if (isMinimized()) {
|
||||
showNormal();
|
||||
}
|
||||
raise();
|
||||
@@ -519,13 +519,13 @@ void MainWindow::balloonClicked() {
|
||||
|
||||
// called when a torrent has finished
|
||||
void MainWindow::finishedTorrent(const QTorrentHandle& h) const {
|
||||
if(!TorrentPersistentData::isSeed(h.hash()))
|
||||
if (!TorrentPersistentData::isSeed(h.hash()))
|
||||
showNotificationBaloon(tr("Download completion"), tr("%1 has finished downloading.", "e.g: xxx.avi has finished downloading.").arg(h.name()));
|
||||
}
|
||||
|
||||
// Notification when disk is full
|
||||
void MainWindow::fullDiskError(const QTorrentHandle& h, QString msg) const {
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
showNotificationBaloon(tr("I/O Error", "i.e: Input/Output Error"), tr("An I/O error occured for torrent %1.\n Reason: %2", "e.g: An error occured for torrent xxx.avi.\n Reason: disk is full.").arg(h.name()).arg(msg));
|
||||
}
|
||||
|
||||
@@ -566,12 +566,12 @@ void MainWindow::displayTransferTab() const {
|
||||
}
|
||||
|
||||
void MainWindow::displaySearchTab() const {
|
||||
if(searchEngine)
|
||||
if (searchEngine)
|
||||
tabs->setCurrentWidget(searchEngine);
|
||||
}
|
||||
|
||||
void MainWindow::displayRSSTab() const {
|
||||
if(rssWidget)
|
||||
if (rssWidget)
|
||||
tabs->setCurrentWidget(rssWidget);
|
||||
}
|
||||
|
||||
@@ -579,7 +579,7 @@ void MainWindow::displayRSSTab() const {
|
||||
|
||||
void MainWindow::askRecursiveTorrentDownloadConfirmation(const QTorrentHandle &h) {
|
||||
Preferences pref;
|
||||
if(pref.recursiveDownloadDisabled()) return;
|
||||
if (pref.recursiveDownloadDisabled()) return;
|
||||
// Get Torrent name
|
||||
QString torrent_name;
|
||||
try {
|
||||
@@ -592,12 +592,12 @@ void MainWindow::askRecursiveTorrentDownloadConfirmation(const QTorrentHandle &h
|
||||
/*QPushButton *no = */confirmBox.addButton(tr("No"), QMessageBox::NoRole);
|
||||
QPushButton *never = confirmBox.addButton(tr("Never"), QMessageBox::NoRole);
|
||||
confirmBox.exec();
|
||||
if(confirmBox.clickedButton() == 0) return;
|
||||
if(confirmBox.clickedButton() == yes) {
|
||||
if (confirmBox.clickedButton() == 0) return;
|
||||
if (confirmBox.clickedButton() == yes) {
|
||||
QBtSession::instance()->recursiveTorrentDownload(h);
|
||||
return;
|
||||
}
|
||||
if(confirmBox.clickedButton() == never) {
|
||||
if (confirmBox.clickedButton() == never) {
|
||||
pref.disableRecursiveDownload();
|
||||
}
|
||||
}
|
||||
@@ -616,10 +616,10 @@ void MainWindow::on_actionSet_global_upload_limit_triggered() {
|
||||
int cur_limit = QBtSession::instance()->getSession()->upload_rate_limit();
|
||||
#endif
|
||||
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), cur_limit);
|
||||
if(ok) {
|
||||
if (ok) {
|
||||
qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.);
|
||||
QBtSession::instance()->setUploadRateLimit(new_limit);
|
||||
if(new_limit <= 0)
|
||||
if (new_limit <= 0)
|
||||
Preferences().setGlobalUploadLimit(-1);
|
||||
else
|
||||
Preferences().setGlobalUploadLimit(new_limit/1024.);
|
||||
@@ -635,10 +635,10 @@ void MainWindow::on_actionSet_global_download_limit_triggered() {
|
||||
int cur_limit = QBtSession::instance()->getSession()->download_rate_limit();
|
||||
#endif
|
||||
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), cur_limit);
|
||||
if(ok) {
|
||||
if (ok) {
|
||||
qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.);
|
||||
QBtSession::instance()->setDownloadRateLimit(new_limit);
|
||||
if(new_limit <= 0)
|
||||
if (new_limit <= 0)
|
||||
Preferences().setGlobalDownloadLimit(-1);
|
||||
else
|
||||
Preferences().setGlobalDownloadLimit(new_limit/1024.);
|
||||
@@ -653,9 +653,9 @@ void MainWindow::on_actionExit_triggered() {
|
||||
}
|
||||
|
||||
QWidget* MainWindow::getCurrentTabWidget() const {
|
||||
if(isMinimized() || !isVisible())
|
||||
if (isMinimized() || !isVisible())
|
||||
return 0;
|
||||
if(tabs->currentIndex() == 0)
|
||||
if (tabs->currentIndex() == 0)
|
||||
return transferList;
|
||||
return tabs->currentWidget();
|
||||
}
|
||||
@@ -667,13 +667,13 @@ void MainWindow::setTabText(int index, QString text) const {
|
||||
bool MainWindow::unlockUI() {
|
||||
bool ok = false;
|
||||
QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok);
|
||||
if(!ok) return false;
|
||||
if (!ok) return false;
|
||||
Preferences pref;
|
||||
QString real_pass_md5 = pref.getUILockPasswordMD5();
|
||||
QCryptographicHash md5(QCryptographicHash::Md5);
|
||||
md5.addData(clear_password.toLocal8Bit());
|
||||
QString password_md5 = md5.result().toHex();
|
||||
if(real_pass_md5 == password_md5) {
|
||||
if (real_pass_md5 == password_md5) {
|
||||
ui_locked = false;
|
||||
pref.setUILocked(false);
|
||||
myTrayIconMenu->setEnabled(true);
|
||||
@@ -693,16 +693,16 @@ void MainWindow::notifyOfUpdate(QString) {
|
||||
|
||||
// Toggle Main window visibility
|
||||
void MainWindow::toggleVisibility(QSystemTrayIcon::ActivationReason e) {
|
||||
if(e == QSystemTrayIcon::Trigger || e == QSystemTrayIcon::DoubleClick) {
|
||||
if(isHidden()) {
|
||||
if(ui_locked) {
|
||||
if (e == QSystemTrayIcon::Trigger || e == QSystemTrayIcon::DoubleClick) {
|
||||
if (isHidden()) {
|
||||
if (ui_locked) {
|
||||
// Ask for UI lock password
|
||||
if(!unlockUI())
|
||||
if (!unlockUI())
|
||||
return;
|
||||
}
|
||||
show();
|
||||
if(isMinimized()) {
|
||||
if(isMaximized()) {
|
||||
if (isMinimized()) {
|
||||
if (isMaximized()) {
|
||||
showMaximized();
|
||||
}else{
|
||||
showNormal();
|
||||
@@ -720,7 +720,7 @@ void MainWindow::toggleVisibility(QSystemTrayIcon::ActivationReason e) {
|
||||
// Display About Dialog
|
||||
void MainWindow::on_actionAbout_triggered() {
|
||||
//About dialog
|
||||
if(aboutDlg) {
|
||||
if (aboutDlg) {
|
||||
aboutDlg->setFocus();
|
||||
} else {
|
||||
aboutDlg = new about(this);
|
||||
@@ -730,14 +730,14 @@ void MainWindow::on_actionAbout_triggered() {
|
||||
void MainWindow::showEvent(QShowEvent *e) {
|
||||
qDebug("** Show Event **");
|
||||
|
||||
if(getCurrentTabWidget() == transferList) {
|
||||
if (getCurrentTabWidget() == transferList) {
|
||||
properties->loadDynamicData();
|
||||
}
|
||||
|
||||
e->accept();
|
||||
|
||||
// Make sure the window is initially centered
|
||||
if(!m_posInitialized) {
|
||||
if (!m_posInitialized) {
|
||||
move(misc::screenCenter(this));
|
||||
m_posInitialized = true;
|
||||
}
|
||||
@@ -747,14 +747,14 @@ void MainWindow::showEvent(QShowEvent *e) {
|
||||
void MainWindow::closeEvent(QCloseEvent *e) {
|
||||
Preferences pref;
|
||||
const bool goToSystrayOnExit = pref.closeToTray();
|
||||
if(!force_exit && systrayIcon && goToSystrayOnExit && !this->isHidden()) {
|
||||
if (!force_exit && systrayIcon && goToSystrayOnExit && !this->isHidden()) {
|
||||
hide();
|
||||
e->accept();
|
||||
return;
|
||||
}
|
||||
if(pref.confirmOnExit() && QBtSession::instance()->hasActiveTorrents()) {
|
||||
if(e->spontaneous() || force_exit) {
|
||||
if(!isVisible())
|
||||
if (pref.confirmOnExit() && QBtSession::instance()->hasActiveTorrents()) {
|
||||
if (e->spontaneous() || force_exit) {
|
||||
if (!isVisible())
|
||||
show();
|
||||
QMessageBox confirmBox(QMessageBox::Question, tr("Exiting qBittorrent"),
|
||||
tr("Some files are currently transferring.\nAre you sure you want to quit qBittorrent?"),
|
||||
@@ -764,20 +764,20 @@ void MainWindow::closeEvent(QCloseEvent *e) {
|
||||
QPushButton *alwaysBtn = confirmBox.addButton(tr("Always"), QMessageBox::YesRole);
|
||||
confirmBox.setDefaultButton(yesBtn);
|
||||
confirmBox.exec();
|
||||
if(!confirmBox.clickedButton() || confirmBox.clickedButton() == noBtn) {
|
||||
if (!confirmBox.clickedButton() || confirmBox.clickedButton() == noBtn) {
|
||||
// Cancel exit
|
||||
e->ignore();
|
||||
force_exit = false;
|
||||
return;
|
||||
}
|
||||
if(confirmBox.clickedButton() == alwaysBtn) {
|
||||
if (confirmBox.clickedButton() == alwaysBtn) {
|
||||
// Remember choice
|
||||
Preferences().setConfirmOnExit(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
hide();
|
||||
if(systrayIcon) {
|
||||
if (systrayIcon) {
|
||||
// Hide tray icon
|
||||
systrayIcon->hide();
|
||||
}
|
||||
@@ -790,7 +790,7 @@ void MainWindow::closeEvent(QCloseEvent *e) {
|
||||
|
||||
// Display window to create a torrent
|
||||
void MainWindow::on_actionCreate_torrent_triggered() {
|
||||
if(createTorrentDlg) {
|
||||
if (createTorrentDlg) {
|
||||
createTorrentDlg->setFocus();
|
||||
} else {
|
||||
createTorrentDlg = new TorrentCreatorDlg(this);
|
||||
@@ -803,20 +803,20 @@ bool MainWindow::event(QEvent * e) {
|
||||
case QEvent::WindowStateChange: {
|
||||
qDebug("Window change event");
|
||||
//Now check to see if the window is minimised
|
||||
if(isMinimized()) {
|
||||
if (isMinimized()) {
|
||||
qDebug("minimisation");
|
||||
if(systrayIcon && Preferences().minimizeToTray()) {
|
||||
if (systrayIcon && Preferences().minimizeToTray()) {
|
||||
qDebug("Has active window: %d", (int)(qApp->activeWindow() != 0));
|
||||
// Check if there is a modal window
|
||||
bool has_modal_window = false;
|
||||
foreach (QWidget *widget, QApplication::allWidgets()) {
|
||||
if(widget->isModal()) {
|
||||
if (widget->isModal()) {
|
||||
has_modal_window = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Iconify if there is no modal window
|
||||
if(!has_modal_window) {
|
||||
if (!has_modal_window) {
|
||||
qDebug("Minimize to Tray enabled, hiding!");
|
||||
e->accept();
|
||||
QTimer::singleShot(0, this, SLOT(hide()));
|
||||
@@ -847,11 +847,11 @@ bool MainWindow::event(QEvent * e) {
|
||||
void MainWindow::dropEvent(QDropEvent *event) {
|
||||
event->acceptProposedAction();
|
||||
QStringList files;
|
||||
if(event->mimeData()->hasUrls()) {
|
||||
if (event->mimeData()->hasUrls()) {
|
||||
const QList<QUrl> urls = event->mimeData()->urls();
|
||||
foreach(const QUrl &url, urls) {
|
||||
if(!url.isEmpty()) {
|
||||
if(url.scheme().compare("file", Qt::CaseInsensitive) == 0)
|
||||
foreach (const QUrl &url, urls) {
|
||||
if (!url.isEmpty()) {
|
||||
if (url.scheme().compare("file", Qt::CaseInsensitive) == 0)
|
||||
files << url.toLocalFile();
|
||||
else
|
||||
files << url.toString();
|
||||
@@ -863,19 +863,19 @@ void MainWindow::dropEvent(QDropEvent *event) {
|
||||
// Add file to download list
|
||||
Preferences pref;
|
||||
const bool useTorrentAdditionDialog = pref.useAdditionDialog();
|
||||
foreach(QString file, files) {
|
||||
foreach (QString file, files) {
|
||||
qDebug("Dropped file %s on download list", qPrintable(file));
|
||||
if(misc::isUrl(file)) {
|
||||
if (misc::isUrl(file)) {
|
||||
QBtSession::instance()->downloadFromUrl(file);
|
||||
continue;
|
||||
}
|
||||
// Bitcomet or Magnet link
|
||||
if(file.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
if (file.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
qDebug("Converting bc link to magnet link");
|
||||
file = misc::bcLinkToMagnet(file);
|
||||
}
|
||||
if(file.startsWith("magnet:", Qt::CaseInsensitive)) {
|
||||
if(useTorrentAdditionDialog) {
|
||||
if (file.startsWith("magnet:", Qt::CaseInsensitive)) {
|
||||
if (useTorrentAdditionDialog) {
|
||||
torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
|
||||
dialog->showLoadMagnetURI(file);
|
||||
} else {
|
||||
@@ -884,9 +884,9 @@ void MainWindow::dropEvent(QDropEvent *event) {
|
||||
continue;
|
||||
}
|
||||
// Local file
|
||||
if(useTorrentAdditionDialog) {
|
||||
if (useTorrentAdditionDialog) {
|
||||
torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
|
||||
if(file.startsWith("file:", Qt::CaseInsensitive))
|
||||
if (file.startsWith("file:", Qt::CaseInsensitive))
|
||||
file = QUrl(file).toLocalFile();
|
||||
dialog->showLoad(file);
|
||||
}else{
|
||||
@@ -897,7 +897,7 @@ void MainWindow::dropEvent(QDropEvent *event) {
|
||||
|
||||
// Decode if we accept drag 'n drop or not
|
||||
void MainWindow::dragEnterEvent(QDragEnterEvent *event) {
|
||||
foreach(const QString &mime, event->mimeData()->formats()){
|
||||
foreach (const QString &mime, event->mimeData()->formats()){
|
||||
qDebug("mimeData: %s", mime.toLocal8Bit().data());
|
||||
}
|
||||
if (event->mimeData()->hasFormat(QString::fromUtf8("text/plain")) || event->mimeData()->hasFormat(QString::fromUtf8("text/uri-list"))) {
|
||||
@@ -921,11 +921,11 @@ void MainWindow::on_actionOpen_triggered() {
|
||||
const QStringList pathsList = QFileDialog::getOpenFileNames(0,
|
||||
tr("Open Torrent Files"), settings.value(QString::fromUtf8("MainWindowLastDir"), QDir::homePath()).toString(),
|
||||
tr("Torrent Files")+QString::fromUtf8(" (*.torrent)"));
|
||||
if(!pathsList.empty()) {
|
||||
if (!pathsList.empty()) {
|
||||
const bool useTorrentAdditionDialog = pref.useAdditionDialog();
|
||||
const uint listSize = pathsList.size();
|
||||
for(uint i=0; i<listSize; ++i) {
|
||||
if(useTorrentAdditionDialog) {
|
||||
for (uint i=0; i<listSize; ++i) {
|
||||
if (useTorrentAdditionDialog) {
|
||||
torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
|
||||
dialog->showLoad(pathsList.at(i));
|
||||
}else{
|
||||
@@ -950,24 +950,24 @@ void MainWindow::processParams(const QString& params_str) {
|
||||
void MainWindow::processParams(const QStringList& params) {
|
||||
Preferences pref;
|
||||
const bool useTorrentAdditionDialog = pref.useAdditionDialog();
|
||||
foreach(QString param, params) {
|
||||
foreach (QString param, params) {
|
||||
param = param.trimmed();
|
||||
if(misc::isUrl(param)) {
|
||||
if (misc::isUrl(param)) {
|
||||
QBtSession::instance()->downloadFromUrl(param);
|
||||
}else{
|
||||
if(param.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
if (param.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
qDebug("Converting bc link to magnet link");
|
||||
param = misc::bcLinkToMagnet(param);
|
||||
}
|
||||
if(param.startsWith("magnet:", Qt::CaseInsensitive)) {
|
||||
if(useTorrentAdditionDialog) {
|
||||
if (param.startsWith("magnet:", Qt::CaseInsensitive)) {
|
||||
if (useTorrentAdditionDialog) {
|
||||
torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
|
||||
dialog->showLoadMagnetURI(param);
|
||||
} else {
|
||||
QBtSession::instance()->addMagnetUri(param);
|
||||
}
|
||||
} else {
|
||||
if(useTorrentAdditionDialog) {
|
||||
if (useTorrentAdditionDialog) {
|
||||
torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
|
||||
dialog->showLoad(param);
|
||||
}else{
|
||||
@@ -985,7 +985,7 @@ void MainWindow::addTorrent(QString path) {
|
||||
void MainWindow::processDownloadedFiles(QString path, QString url) {
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
|
||||
const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool();
|
||||
if(useTorrentAdditionDialog) {
|
||||
if (useTorrentAdditionDialog) {
|
||||
torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
|
||||
dialog->showLoad(path, url);
|
||||
}else{
|
||||
@@ -1003,11 +1003,11 @@ void MainWindow::loadPreferences(bool configure_session) {
|
||||
const Preferences pref;
|
||||
const bool newSystrayIntegration = pref.systrayIntegration();
|
||||
actionLock_qBittorrent->setEnabled(newSystrayIntegration);
|
||||
if(newSystrayIntegration != (systrayIcon!=0)) {
|
||||
if(newSystrayIntegration) {
|
||||
if (newSystrayIntegration != (systrayIcon!=0)) {
|
||||
if (newSystrayIntegration) {
|
||||
// create the trayicon
|
||||
if(!QSystemTrayIcon::isSystemTrayAvailable()) {
|
||||
if(!configure_session) { // Program startup
|
||||
if (!QSystemTrayIcon::isSystemTrayAvailable()) {
|
||||
if (!configure_session) { // Program startup
|
||||
systrayCreator = new QTimer(this);
|
||||
connect(systrayCreator, SIGNAL(timeout()), this, SLOT(createSystrayDelayed()));
|
||||
systrayCreator->setSingleShot(true);
|
||||
@@ -1026,11 +1026,11 @@ void MainWindow::loadPreferences(bool configure_session) {
|
||||
}
|
||||
}
|
||||
// Reload systray icon
|
||||
if(newSystrayIntegration && systrayIcon) {
|
||||
if (newSystrayIntegration && systrayIcon) {
|
||||
systrayIcon->setIcon(getSystrayIcon());
|
||||
}
|
||||
// General
|
||||
if(pref.isToolbarDisplayed()) {
|
||||
if (pref.isToolbarDisplayed()) {
|
||||
toolBar->setVisible(true);
|
||||
} else {
|
||||
// Clear search filter before hiding the top toolbar
|
||||
@@ -1038,7 +1038,7 @@ void MainWindow::loadPreferences(bool configure_session) {
|
||||
toolBar->setVisible(false);
|
||||
}
|
||||
|
||||
if(pref.preventFromSuspend())
|
||||
if (pref.preventFromSuspend())
|
||||
{
|
||||
preventTimer->start(PREVENT_SUSPEND_INTERVAL);
|
||||
}
|
||||
@@ -1055,8 +1055,8 @@ void MainWindow::loadPreferences(bool configure_session) {
|
||||
properties->getTrackerList()->setAlternatingRowColors(pref.useAlternatingRowColors());
|
||||
properties->getPeerList()->setAlternatingRowColors(pref.useAlternatingRowColors());
|
||||
// Queueing System
|
||||
if(pref.isQueueingSystemEnabled()) {
|
||||
if(!actionDecreasePriority->isVisible()) {
|
||||
if (pref.isQueueingSystemEnabled()) {
|
||||
if (!actionDecreasePriority->isVisible()) {
|
||||
transferList->hidePriorityColumn(false);
|
||||
actionDecreasePriority->setVisible(true);
|
||||
actionIncreasePriority->setVisible(true);
|
||||
@@ -1064,7 +1064,7 @@ void MainWindow::loadPreferences(bool configure_session) {
|
||||
prioSeparatorMenu->setVisible(true);
|
||||
}
|
||||
} else {
|
||||
if(actionDecreasePriority->isVisible()) {
|
||||
if (actionDecreasePriority->isVisible()) {
|
||||
transferList->hidePriorityColumn(true);
|
||||
actionDecreasePriority->setVisible(false);
|
||||
actionIncreasePriority->setVisible(false);
|
||||
@@ -1081,7 +1081,7 @@ void MainWindow::loadPreferences(bool configure_session) {
|
||||
IconProvider::instance()->useSystemIconTheme(pref.useSystemIconTheme());
|
||||
#endif
|
||||
|
||||
if(configure_session)
|
||||
if (configure_session)
|
||||
QBtSession::instance()->configureSession();
|
||||
|
||||
qDebug("GUI settings loaded");
|
||||
@@ -1089,14 +1089,14 @@ void MainWindow::loadPreferences(bool configure_session) {
|
||||
|
||||
void MainWindow::addUnauthenticatedTracker(const QPair<QTorrentHandle,QString> &tracker) {
|
||||
// Trackers whose authentication was cancelled
|
||||
if(unauthenticated_trackers.indexOf(tracker) < 0) {
|
||||
if (unauthenticated_trackers.indexOf(tracker) < 0) {
|
||||
unauthenticated_trackers << tracker;
|
||||
}
|
||||
}
|
||||
|
||||
// Called when a tracker requires authentication
|
||||
void MainWindow::trackerAuthenticationRequired(const QTorrentHandle& h) {
|
||||
if(unauthenticated_trackers.indexOf(QPair<QTorrentHandle,QString>(h, h.current_tracker())) < 0) {
|
||||
if (unauthenticated_trackers.indexOf(QPair<QTorrentHandle,QString>(h, h.current_tracker())) < 0) {
|
||||
// Tracker login
|
||||
new trackerLogin(this, h);
|
||||
}
|
||||
@@ -1105,7 +1105,7 @@ void MainWindow::trackerAuthenticationRequired(const QTorrentHandle& h) {
|
||||
// Check connection status and display right icon
|
||||
void MainWindow::updateGUI() {
|
||||
// update global informations
|
||||
if(systrayIcon) {
|
||||
if (systrayIcon) {
|
||||
#if defined(Q_WS_X11) || defined(Q_WS_MAC)
|
||||
QString html = "<div style='background-color: #678db2; color: #fff;height: 18px; font-weight: bold; margin-bottom: 5px;'>";
|
||||
html += tr("qBittorrent");
|
||||
@@ -1124,28 +1124,28 @@ void MainWindow::updateGUI() {
|
||||
#endif
|
||||
systrayIcon->setToolTip(html); // tray icon
|
||||
}
|
||||
if(displaySpeedInTitle) {
|
||||
if (displaySpeedInTitle) {
|
||||
setWindowTitle(tr("[D: %1/s, U: %2/s] qBittorrent %3", "D = Download; U = Upload; %3 is qBittorrent version").arg(misc::friendlyUnit(QBtSession::instance()->getSessionStatus().payload_download_rate)).arg(misc::friendlyUnit(QBtSession::instance()->getSessionStatus().payload_upload_rate)).arg(QString::fromUtf8(VERSION)));
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::showNotificationBaloon(QString title, QString msg) const {
|
||||
if(!Preferences().useProgramNotification()) return;
|
||||
if (!Preferences().useProgramNotification()) return;
|
||||
#if defined(Q_WS_X11) && defined(QT_DBUS_LIB)
|
||||
org::freedesktop::Notifications notifications("org.freedesktop.Notifications",
|
||||
"/org/freedesktop/Notifications",
|
||||
QDBusConnection::sessionBus());
|
||||
if(notifications.isValid()) {
|
||||
if (notifications.isValid()) {
|
||||
QVariantMap hints;
|
||||
hints["desktop-entry"] = "qBittorrent";
|
||||
QDBusPendingReply<uint> reply = notifications.Notify("qBittorrent", 0, "qbittorrent", title,
|
||||
msg, QStringList(), hints, -1);
|
||||
reply.waitForFinished();
|
||||
if(!reply.isError())
|
||||
if (!reply.isError())
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if(systrayIcon && QSystemTrayIcon::supportsMessages())
|
||||
if (systrayIcon && QSystemTrayIcon::supportsMessages())
|
||||
systrayIcon->showMessage(title, msg, QSystemTrayIcon::Information, TIME_TRAY_BALLOON);
|
||||
}
|
||||
|
||||
@@ -1158,13 +1158,13 @@ void MainWindow::showNotificationBaloon(QString title, QString msg) const {
|
||||
void MainWindow::downloadFromURLList(const QStringList& url_list) {
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
|
||||
const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool();
|
||||
foreach(QString url, url_list) {
|
||||
if(url.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
foreach (QString url, url_list) {
|
||||
if (url.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
qDebug("Converting bc link to magnet link");
|
||||
url = misc::bcLinkToMagnet(url);
|
||||
}
|
||||
if(url.startsWith("magnet:", Qt::CaseInsensitive)) {
|
||||
if(useTorrentAdditionDialog) {
|
||||
if (url.startsWith("magnet:", Qt::CaseInsensitive)) {
|
||||
if (useTorrentAdditionDialog) {
|
||||
torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
|
||||
dialog->showLoadMagnetURI(url);
|
||||
} else {
|
||||
@@ -1184,13 +1184,13 @@ void MainWindow::downloadFromURLList(const QStringList& url_list) {
|
||||
|
||||
void MainWindow::createSystrayDelayed() {
|
||||
static int timeout = 20;
|
||||
if(QSystemTrayIcon::isSystemTrayAvailable()) {
|
||||
if (QSystemTrayIcon::isSystemTrayAvailable()) {
|
||||
// Ok, systray integration is now supported
|
||||
// Create systray icon
|
||||
createTrayIcon();
|
||||
delete systrayCreator;
|
||||
} else {
|
||||
if(timeout) {
|
||||
if (timeout) {
|
||||
// Retry a bit later
|
||||
systrayCreator->start(2000);
|
||||
--timeout;
|
||||
@@ -1210,7 +1210,7 @@ void MainWindow::updateAltSpeedsBtn(bool alternative) {
|
||||
}
|
||||
|
||||
QMenu* MainWindow::getTrayIconMenu() {
|
||||
if(myTrayIconMenu)
|
||||
if (myTrayIconMenu)
|
||||
return myTrayIconMenu;
|
||||
// Tray icon Menu
|
||||
myTrayIconMenu = new QMenu(this);
|
||||
@@ -1231,7 +1231,7 @@ QMenu* MainWindow::getTrayIconMenu() {
|
||||
myTrayIconMenu->addAction(actionPause_All);
|
||||
myTrayIconMenu->addSeparator();
|
||||
myTrayIconMenu->addAction(actionExit);
|
||||
if(ui_locked)
|
||||
if (ui_locked)
|
||||
myTrayIconMenu->setEnabled(false);
|
||||
return myTrayIconMenu;
|
||||
}
|
||||
@@ -1249,7 +1249,7 @@ void MainWindow::createTrayIcon() {
|
||||
|
||||
// Display Program Options
|
||||
void MainWindow::on_actionOptions_triggered() {
|
||||
if(options) {
|
||||
if (options) {
|
||||
// Get focus
|
||||
options->setFocus();
|
||||
} else {
|
||||
@@ -1267,7 +1267,7 @@ void MainWindow::on_actionTop_tool_bar_triggered() {
|
||||
void MainWindow::on_actionSpeed_in_title_bar_triggered() {
|
||||
displaySpeedInTitle = static_cast<QAction*>(sender())->isChecked();
|
||||
Preferences().showSpeedInTitleBar(displaySpeedInTitle);
|
||||
if(displaySpeedInTitle)
|
||||
if (displaySpeedInTitle)
|
||||
updateGUI();
|
||||
else
|
||||
setWindowTitle(tr("qBittorrent %1", "e.g: qBittorrent v0.x").arg(QString::fromUtf8(VERSION)));
|
||||
@@ -1297,7 +1297,7 @@ void MainWindow::on_action_Import_Torrent_triggered()
|
||||
// Display an input dialog to prompt user for
|
||||
// an url
|
||||
void MainWindow::on_actionDownload_from_URL_triggered() {
|
||||
if(!downloadFromURLDialog) {
|
||||
if (!downloadFromURLDialog) {
|
||||
downloadFromURLDialog = new downloadFromURL(this);
|
||||
connect(downloadFromURLDialog, SIGNAL(urlsReadyToBeDownloaded(QStringList)), this, SLOT(downloadFromURLList(QStringList)));
|
||||
}
|
||||
@@ -1307,8 +1307,8 @@ void MainWindow::on_actionDownload_from_URL_triggered() {
|
||||
|
||||
void MainWindow::handleUpdateCheckFinished(bool update_available, QString new_version)
|
||||
{
|
||||
if(update_available) {
|
||||
if(QMessageBox::question(this, tr("A newer version is available"),
|
||||
if (update_available) {
|
||||
if (QMessageBox::question(this, tr("A newer version is available"),
|
||||
tr("A newer version of qBittorrent is available on Sourceforge.\nWould you like to update qBittorrent to version %1?").arg(new_version),
|
||||
QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
|
||||
// The user want to update, let's download the update
|
||||
@@ -1323,7 +1323,7 @@ void MainWindow::handleUpdateCheckFinished(bool update_available, QString new_ve
|
||||
|
||||
void MainWindow::handleUpdateInstalled(QString error_msg)
|
||||
{
|
||||
if(!error_msg.isEmpty()) {
|
||||
if (!error_msg.isEmpty()) {
|
||||
QMessageBox::critical(this, tr("Impossible to update qBittorrent"), tr("qBittorrent failed to update, reason: %1").arg(error_msg));
|
||||
}
|
||||
}
|
||||
@@ -1348,13 +1348,13 @@ void MainWindow::minimizeWindow()
|
||||
|
||||
void MainWindow::on_actionExecution_Logs_triggered(bool checked)
|
||||
{
|
||||
if(checked) {
|
||||
if (checked) {
|
||||
Q_ASSERT(!m_executionLog);
|
||||
m_executionLog = new ExecutionLog(tabs);
|
||||
int index_tab = tabs->addTab(m_executionLog, tr("Execution Log"));
|
||||
tabs->setTabIcon(index_tab, IconProvider::instance()->getIcon("view-calendar-journal"));
|
||||
} else {
|
||||
if(m_executionLog)
|
||||
if (m_executionLog)
|
||||
delete m_executionLog;
|
||||
}
|
||||
Preferences().setExecutionLogEnabled(checked);
|
||||
@@ -1381,7 +1381,7 @@ void MainWindow::on_actionAutoShutdown_system_toggled(bool enabled)
|
||||
void MainWindow::checkForActiveTorrents()
|
||||
{
|
||||
const TorrentStatusReport report = transferList->getSourceModel()->getTorrentStatusReport();
|
||||
if(report.nb_active > 0) // Active torrents are present; prevent system from suspend
|
||||
if (report.nb_active > 0) // Active torrents are present; prevent system from suspend
|
||||
m_pwr->setActivityState(true);
|
||||
else
|
||||
m_pwr->setActivityState(false);
|
||||
|
||||
234
src/misc.cpp
234
src/misc.cpp
@@ -107,7 +107,7 @@ QString misc::QDesktopServicesDataLocation() {
|
||||
result = QString::fromWCharArray(path);
|
||||
if (!QCoreApplication::applicationName().isEmpty())
|
||||
result = result + QLatin1String("\\") + qApp->applicationName();
|
||||
if(!result.endsWith("\\"))
|
||||
if (!result.endsWith("\\"))
|
||||
result += "\\";
|
||||
return result;
|
||||
#else
|
||||
@@ -208,16 +208,16 @@ QString misc::QDesktopServicesDownloadLocation() {
|
||||
}
|
||||
|
||||
long long misc::freeDiskSpaceOnPath(QString path) {
|
||||
if(path.isEmpty()) return -1;
|
||||
if (path.isEmpty()) return -1;
|
||||
path.replace("\\", "/");
|
||||
QDir dir_path(path);
|
||||
if(!dir_path.exists()) {
|
||||
if (!dir_path.exists()) {
|
||||
QStringList parts = path.split("/");
|
||||
while (parts.size() > 1 && !QDir(parts.join("/")).exists()) {
|
||||
parts.removeLast();
|
||||
}
|
||||
dir_path = QDir(parts.join("/"));
|
||||
if(!dir_path.exists()) return -1;
|
||||
if (!dir_path.exists()) return -1;
|
||||
}
|
||||
Q_ASSERT(dir_path.exists());
|
||||
|
||||
@@ -226,7 +226,7 @@ long long misc::freeDiskSpaceOnPath(QString path) {
|
||||
struct statfs stats;
|
||||
const QString statfs_path = dir_path.path()+"/.";
|
||||
const int ret = statfs (qPrintable(statfs_path), &stats) ;
|
||||
if(ret == 0) {
|
||||
if (ret == 0) {
|
||||
available = ((unsigned long long)stats.f_bavail) *
|
||||
((unsigned long long)stats.f_bsize) ;
|
||||
return available;
|
||||
@@ -264,11 +264,11 @@ long long misc::freeDiskSpaceOnPath(QString path) {
|
||||
void misc::shutdownComputer(bool sleep) {
|
||||
#if defined(Q_WS_X11) && defined(QT_DBUS_LIB)
|
||||
// Use dbus to power off / suspend the system
|
||||
if(sleep) {
|
||||
if (sleep) {
|
||||
// Recent systems use UPower
|
||||
QDBusInterface upowerIface("org.freedesktop.UPower", "/org/freedesktop/UPower",
|
||||
"org.freedesktop.UPower", QDBusConnection::systemBus());
|
||||
if(upowerIface.isValid()) {
|
||||
if (upowerIface.isValid()) {
|
||||
upowerIface.call("Suspend");
|
||||
return;
|
||||
}
|
||||
@@ -281,7 +281,7 @@ void misc::shutdownComputer(bool sleep) {
|
||||
// Recent systems use ConsoleKit
|
||||
QDBusInterface consolekitIface("org.freedesktop.ConsoleKit", "/org/freedesktop/ConsoleKit/Manager",
|
||||
"org.freedesktop.ConsoleKit.Manager", QDBusConnection::systemBus());
|
||||
if(consolekitIface.isValid()) {
|
||||
if (consolekitIface.isValid()) {
|
||||
consolekitIface.call("Stop");
|
||||
return;
|
||||
}
|
||||
@@ -294,7 +294,7 @@ void misc::shutdownComputer(bool sleep) {
|
||||
#endif
|
||||
#ifdef Q_WS_MAC
|
||||
AEEventID EventToSend;
|
||||
if(sleep)
|
||||
if (sleep)
|
||||
EventToSend = kAESleep;
|
||||
else
|
||||
EventToSend = kAEShutDown;
|
||||
@@ -336,7 +336,7 @@ void misc::shutdownComputer(bool sleep) {
|
||||
#ifdef Q_WS_WIN
|
||||
HANDLE hToken; // handle to process token
|
||||
TOKEN_PRIVILEGES tkp; // pointer to token structure
|
||||
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
|
||||
return;
|
||||
// Get the LUID for shutdown privilege.
|
||||
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
|
||||
@@ -355,7 +355,7 @@ void misc::shutdownComputer(bool sleep) {
|
||||
if (GetLastError() != ERROR_SUCCESS)
|
||||
return;
|
||||
|
||||
if(sleep)
|
||||
if (sleep)
|
||||
SetSuspendState(false, false, false);
|
||||
else
|
||||
InitiateSystemShutdownA(0, tr("qBittorrent will shutdown the computer now because all downloads are complete.").toLocal8Bit().data(), 10, true, false);
|
||||
@@ -372,13 +372,13 @@ QString misc::fixFileNames(QString path) {
|
||||
//qDebug() << Q_FUNC_INFO << path;
|
||||
path.replace("\\", "/");
|
||||
QStringList parts = path.split("/", QString::SkipEmptyParts);
|
||||
if(parts.isEmpty()) return path;
|
||||
if (parts.isEmpty()) return path;
|
||||
QString last_part = parts.takeLast();
|
||||
QList<QString>::iterator it;
|
||||
for(it = parts.begin(); it != parts.end(); it++) {
|
||||
for (it = parts.begin(); it != parts.end(); it++) {
|
||||
QByteArray raw_filename = it->toLocal8Bit();
|
||||
// Make sure the filename is not too long
|
||||
if(raw_filename.size() > MAX_FILENAME_LENGTH) {
|
||||
if (raw_filename.size() > MAX_FILENAME_LENGTH) {
|
||||
qDebug() << "Folder" << *it << "was cut because it was too long";
|
||||
raw_filename.resize(MAX_FILENAME_LENGTH);
|
||||
*it = QString::fromLocal8Bit(raw_filename.constData());
|
||||
@@ -389,12 +389,12 @@ QString misc::fixFileNames(QString path) {
|
||||
// Fix the last part (file name)
|
||||
QByteArray raw_lastPart = last_part.toLocal8Bit();
|
||||
qDebug() << "Last part length:" << raw_lastPart.length();
|
||||
if(raw_lastPart.length() > MAX_FILENAME_LENGTH) {
|
||||
if (raw_lastPart.length() > MAX_FILENAME_LENGTH) {
|
||||
qDebug() << "Filename" << last_part << "was cut because it was too long";
|
||||
// Shorten the name, keep the file extension
|
||||
int point_index = raw_lastPart.lastIndexOf(".");
|
||||
QByteArray extension = "";
|
||||
if(point_index >= 0) {
|
||||
if (point_index >= 0) {
|
||||
extension = raw_lastPart.mid(point_index);
|
||||
raw_lastPart = raw_lastPart.left(point_index);
|
||||
}
|
||||
@@ -408,7 +408,7 @@ QString misc::fixFileNames(QString path) {
|
||||
}
|
||||
|
||||
QString misc::truncateRootFolder(boost::intrusive_ptr<torrent_info> t) {
|
||||
if(t->num_files() == 1) {
|
||||
if (t->num_files() == 1) {
|
||||
// Single file torrent
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
QString path = QString::fromUtf8(t->file_at(0).path.c_str());
|
||||
@@ -421,14 +421,14 @@ QString misc::truncateRootFolder(boost::intrusive_ptr<torrent_info> t) {
|
||||
return QString();
|
||||
}
|
||||
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
|
||||
QString path = QString::fromUtf8(t->file_at(i).path.c_str());
|
||||
#else
|
||||
QString path = QString::fromUtf8(t->file_at(i).path.string().c_str());
|
||||
#endif
|
||||
QStringList path_parts = path.split("/", QString::SkipEmptyParts);
|
||||
if(path_parts.size() > 1) {
|
||||
if (path_parts.size() > 1) {
|
||||
root_folder = path_parts.takeFirst();
|
||||
}
|
||||
path = fixFileNames(path_parts.join("/"));
|
||||
@@ -439,7 +439,7 @@ QString misc::truncateRootFolder(boost::intrusive_ptr<torrent_info> t) {
|
||||
|
||||
QString misc::truncateRootFolder(libtorrent::torrent_handle h) {
|
||||
torrent_info t = h.get_torrent_info();
|
||||
if(t.num_files() == 1) {
|
||||
if (t.num_files() == 1) {
|
||||
// Single file torrent
|
||||
// Remove possible subfolders
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
@@ -452,14 +452,14 @@ QString misc::truncateRootFolder(libtorrent::torrent_handle h) {
|
||||
return QString();
|
||||
}
|
||||
QString root_folder;
|
||||
for(int i=0; i<t.num_files(); ++i) {
|
||||
for (int i=0; i<t.num_files(); ++i) {
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
QString path = QString::fromUtf8(t.file_at(i).path.c_str());
|
||||
#else
|
||||
QString path = QString::fromUtf8(t.file_at(i).path.string().c_str());
|
||||
#endif
|
||||
QStringList path_parts = path.split("/", QString::SkipEmptyParts);
|
||||
if(path_parts.size() > 1) {
|
||||
if (path_parts.size() > 1) {
|
||||
root_folder = path_parts.takeFirst();
|
||||
}
|
||||
path = fixFileNames(path_parts.join("/"));
|
||||
@@ -470,16 +470,16 @@ QString misc::truncateRootFolder(libtorrent::torrent_handle h) {
|
||||
|
||||
bool misc::sameFiles(const QString &path1, const QString &path2) {
|
||||
QFile f1(path1), f2(path2);
|
||||
if(!f1.exists() || !f2.exists()) return false;
|
||||
if(f1.size() != f2.size()) return false;
|
||||
if(!f1.open(QIODevice::ReadOnly)) return false;
|
||||
if(!f2.open(QIODevice::ReadOnly)) {
|
||||
if (!f1.exists() || !f2.exists()) return false;
|
||||
if (f1.size() != f2.size()) return false;
|
||||
if (!f1.open(QIODevice::ReadOnly)) return false;
|
||||
if (!f2.open(QIODevice::ReadOnly)) {
|
||||
f1.close();
|
||||
return false;
|
||||
}
|
||||
bool same = true;
|
||||
while(!f1.atEnd() && !f2.atEnd()) {
|
||||
if(f1.read(5) != f2.read(5)) {
|
||||
if (f1.read(5) != f2.read(5)) {
|
||||
same = false;
|
||||
break;
|
||||
}
|
||||
@@ -489,34 +489,34 @@ bool misc::sameFiles(const QString &path1, const QString &path2) {
|
||||
}
|
||||
|
||||
QString misc::updateLabelInSavePath(QString defaultSavePath, QString save_path, const QString &old_label, const QString &new_label) {
|
||||
if(old_label == new_label) return save_path;
|
||||
if (old_label == new_label) return save_path;
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
defaultSavePath.replace("\\", "/");
|
||||
save_path.replace("\\", "/");
|
||||
#endif
|
||||
qDebug("UpdateLabelInSavePath(%s, %s, %s)", qPrintable(save_path), qPrintable(old_label), qPrintable(new_label));
|
||||
if(!save_path.startsWith(defaultSavePath)) return save_path;
|
||||
if (!save_path.startsWith(defaultSavePath)) return save_path;
|
||||
QString new_save_path = save_path;
|
||||
new_save_path.replace(defaultSavePath, "");
|
||||
QStringList path_parts = new_save_path.split("/", QString::SkipEmptyParts);
|
||||
if(path_parts.empty()) {
|
||||
if(!new_label.isEmpty())
|
||||
if (path_parts.empty()) {
|
||||
if (!new_label.isEmpty())
|
||||
path_parts << new_label;
|
||||
} else {
|
||||
if(old_label.isEmpty() || path_parts.first() != old_label) {
|
||||
if(path_parts.first() != new_label)
|
||||
if (old_label.isEmpty() || path_parts.first() != old_label) {
|
||||
if (path_parts.first() != new_label)
|
||||
path_parts.prepend(new_label);
|
||||
} else {
|
||||
if(new_label.isEmpty()) {
|
||||
if (new_label.isEmpty()) {
|
||||
path_parts.removeAt(0);
|
||||
} else {
|
||||
if(path_parts.first() != new_label)
|
||||
if (path_parts.first() != new_label)
|
||||
path_parts.replace(0, new_label);
|
||||
}
|
||||
}
|
||||
}
|
||||
new_save_path = defaultSavePath;
|
||||
if(!new_save_path.endsWith(QDir::separator())) new_save_path += QDir::separator();
|
||||
if (!new_save_path.endsWith(QDir::separator())) new_save_path += QDir::separator();
|
||||
new_save_path += path_parts.join(QDir::separator());
|
||||
qDebug("New save path is %s", qPrintable(new_save_path));
|
||||
return new_save_path;
|
||||
@@ -531,7 +531,7 @@ QString misc::toValidFileSystemName(QString filename) {
|
||||
}
|
||||
|
||||
bool misc::isValidFileSystemName(const QString& filename) {
|
||||
if(filename.isEmpty()) return false;
|
||||
if (filename.isEmpty()) return false;
|
||||
const QRegExp regex("[\\\\/:?\"*<>|]");
|
||||
return !filename.contains(regex);
|
||||
}
|
||||
@@ -542,9 +542,9 @@ QPoint misc::screenCenter(QWidget *win) {
|
||||
int scrn = 0;
|
||||
const QWidget *w = win->window();
|
||||
|
||||
if(w)
|
||||
if (w)
|
||||
scrn = QApplication::desktop()->screenNumber(w);
|
||||
else if(QApplication::desktop()->isVirtualDesktop())
|
||||
else if (QApplication::desktop()->isVirtualDesktop())
|
||||
scrn = QApplication::desktop()->screenNumber(QCursor::pos());
|
||||
else
|
||||
scrn = QApplication::desktop()->screenNumber(win);
|
||||
@@ -585,7 +585,7 @@ QString misc::searchEngineLocation() {
|
||||
const QString location = QDir::cleanPath(QDesktopServicesDataLocation()
|
||||
+ QDir::separator() + folder);
|
||||
QDir locationDir(location);
|
||||
if(!locationDir.exists())
|
||||
if (!locationDir.exists())
|
||||
locationDir.mkpath(locationDir.absolutePath());
|
||||
return location;
|
||||
}
|
||||
@@ -594,7 +594,7 @@ QString misc::BTBackupLocation() {
|
||||
const QString location = QDir::cleanPath(QDesktopServicesDataLocation()
|
||||
+ QDir::separator() + "BT_backup");
|
||||
QDir locationDir(location);
|
||||
if(!locationDir.exists())
|
||||
if (!locationDir.exists())
|
||||
locationDir.mkpath(locationDir.absolutePath());
|
||||
return location;
|
||||
}
|
||||
@@ -602,7 +602,7 @@ QString misc::BTBackupLocation() {
|
||||
QString misc::cacheLocation() {
|
||||
QString location = QDir::cleanPath(QDesktopServicesCacheLocation());
|
||||
QDir locationDir(location);
|
||||
if(!locationDir.exists())
|
||||
if (!locationDir.exists())
|
||||
locationDir.mkpath(locationDir.absolutePath());
|
||||
return location;
|
||||
}
|
||||
@@ -612,61 +612,61 @@ QString misc::cacheLocation() {
|
||||
// see http://en.wikipedia.org/wiki/Kilobyte
|
||||
// value must be given in bytes
|
||||
QString misc::friendlyUnit(qreal val) {
|
||||
if(val < 0)
|
||||
if (val < 0)
|
||||
return tr("Unknown", "Unknown (size)");
|
||||
int i = 0;
|
||||
while(val >= 1024. && i++<6)
|
||||
val /= 1024.;
|
||||
if(i == 0)
|
||||
if (i == 0)
|
||||
return QString::number((long)val) + " " + tr(units[0].source, units[0].comment);
|
||||
return QString::number(val, 'f', 1) + " " + tr(units[i].source, units[i].comment);
|
||||
}
|
||||
|
||||
bool misc::isPreviewable(QString extension){
|
||||
if(extension.isEmpty()) return false;
|
||||
if (extension.isEmpty()) return false;
|
||||
extension = extension.toUpper();
|
||||
if(extension == "AVI") return true;
|
||||
if(extension == "MP3") return true;
|
||||
if(extension == "OGG") return true;
|
||||
if(extension == "OGV") return true;
|
||||
if(extension == "OGM") return true;
|
||||
if(extension == "WMV") return true;
|
||||
if(extension == "WMA") return true;
|
||||
if(extension == "MPEG") return true;
|
||||
if(extension == "MPG") return true;
|
||||
if(extension == "ASF") return true;
|
||||
if(extension == "QT") return true;
|
||||
if(extension == "RM") return true;
|
||||
if(extension == "RMVB") return true;
|
||||
if(extension == "RMV") return true;
|
||||
if(extension == "SWF") return true;
|
||||
if(extension == "FLV") return true;
|
||||
if(extension == "WAV") return true;
|
||||
if(extension == "MOV") return true;
|
||||
if(extension == "VOB") return true;
|
||||
if(extension == "MID") return true;
|
||||
if(extension == "AC3") return true;
|
||||
if(extension == "MP4") return true;
|
||||
if(extension == "MP2") return true;
|
||||
if(extension == "AVI") return true;
|
||||
if(extension == "FLAC") return true;
|
||||
if(extension == "AU") return true;
|
||||
if(extension == "MPE") return true;
|
||||
if(extension == "MOV") return true;
|
||||
if(extension == "MKV") return true;
|
||||
if(extension == "AIF") return true;
|
||||
if(extension == "AIFF") return true;
|
||||
if(extension == "AIFC") return true;
|
||||
if(extension == "RA") return true;
|
||||
if(extension == "RAM") return true;
|
||||
if(extension == "M4P") return true;
|
||||
if(extension == "M4A") return true;
|
||||
if(extension == "3GP") return true;
|
||||
if(extension == "AAC") return true;
|
||||
if(extension == "SWA") return true;
|
||||
if(extension == "MPC") return true;
|
||||
if(extension == "MPP") return true;
|
||||
if(extension == "M3U") return true;
|
||||
if (extension == "AVI") return true;
|
||||
if (extension == "MP3") return true;
|
||||
if (extension == "OGG") return true;
|
||||
if (extension == "OGV") return true;
|
||||
if (extension == "OGM") return true;
|
||||
if (extension == "WMV") return true;
|
||||
if (extension == "WMA") return true;
|
||||
if (extension == "MPEG") return true;
|
||||
if (extension == "MPG") return true;
|
||||
if (extension == "ASF") return true;
|
||||
if (extension == "QT") return true;
|
||||
if (extension == "RM") return true;
|
||||
if (extension == "RMVB") return true;
|
||||
if (extension == "RMV") return true;
|
||||
if (extension == "SWF") return true;
|
||||
if (extension == "FLV") return true;
|
||||
if (extension == "WAV") return true;
|
||||
if (extension == "MOV") return true;
|
||||
if (extension == "VOB") return true;
|
||||
if (extension == "MID") return true;
|
||||
if (extension == "AC3") return true;
|
||||
if (extension == "MP4") return true;
|
||||
if (extension == "MP2") return true;
|
||||
if (extension == "AVI") return true;
|
||||
if (extension == "FLAC") return true;
|
||||
if (extension == "AU") return true;
|
||||
if (extension == "MPE") return true;
|
||||
if (extension == "MOV") return true;
|
||||
if (extension == "MKV") return true;
|
||||
if (extension == "AIF") return true;
|
||||
if (extension == "AIFF") return true;
|
||||
if (extension == "AIFC") return true;
|
||||
if (extension == "RA") return true;
|
||||
if (extension == "RAM") return true;
|
||||
if (extension == "M4P") return true;
|
||||
if (extension == "M4A") return true;
|
||||
if (extension == "3GP") return true;
|
||||
if (extension == "AAC") return true;
|
||||
if (extension == "SWA") return true;
|
||||
if (extension == "MPC") return true;
|
||||
if (extension == "MPP") return true;
|
||||
if (extension == "M3U") return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -676,7 +676,7 @@ QString misc::bcLinkToMagnet(QString bc_link) {
|
||||
raw_bc = QByteArray::fromBase64(raw_bc); // Decode base64
|
||||
// Format is now AA/url_encoded_filename/size_bytes/info_hash/ZZ
|
||||
QStringList parts = QString(raw_bc).split("/");
|
||||
if(parts.size() != 5) return QString::null;
|
||||
if (parts.size() != 5) return QString::null;
|
||||
QString filename = parts.at(1);
|
||||
QString hash = parts.at(3);
|
||||
QString magnet = "magnet:?xt=urn:btih:" + hash;
|
||||
@@ -688,7 +688,7 @@ QString misc::magnetUriToName(QString magnet_uri) {
|
||||
QString name = "";
|
||||
QRegExp regHex("dn=([^&]+)");
|
||||
const int pos = regHex.indexIn(magnet_uri);
|
||||
if(pos > -1) {
|
||||
if (pos > -1) {
|
||||
const QString found = regHex.cap(1);
|
||||
// URL decode
|
||||
name = QUrl::fromPercentEncoding(found.toLocal8Bit()).replace("+", " ");
|
||||
@@ -701,10 +701,10 @@ QString misc::magnetUriToHash(QString magnet_uri) {
|
||||
QRegExp regHex("urn:btih:([0-9A-Za-z]+)");
|
||||
// Hex
|
||||
int pos = regHex.indexIn(magnet_uri);
|
||||
if(pos > -1) {
|
||||
if (pos > -1) {
|
||||
const QString found = regHex.cap(1);
|
||||
qDebug() << Q_FUNC_INFO << "regex found: " << found;
|
||||
if(found.length() == 40) {
|
||||
if (found.length() == 40) {
|
||||
const sha1_hash sha1(QByteArray::fromHex(found.toAscii()).constData());
|
||||
qDebug("magnetUriToHash (Hex): hash: %s", qPrintable(misc::toQString(sha1)));
|
||||
return misc::toQString(sha1);
|
||||
@@ -713,9 +713,9 @@ QString misc::magnetUriToHash(QString magnet_uri) {
|
||||
// Base 32
|
||||
QRegExp regBase32("urn:btih:([A-Za-z2-7=]+)");
|
||||
pos = regBase32.indexIn(magnet_uri);
|
||||
if(pos > -1) {
|
||||
if (pos > -1) {
|
||||
const QString found = regBase32.cap(1);
|
||||
if(found.length() > 20 && (found.length()*5)%40 == 0) {
|
||||
if (found.length() > 20 && (found.length()*5)%40 == 0) {
|
||||
const sha1_hash sha1(base32decode(regBase32.cap(1).toStdString()));
|
||||
hash = misc::toQString(sha1);
|
||||
}
|
||||
@@ -727,14 +727,14 @@ QString misc::magnetUriToHash(QString magnet_uri) {
|
||||
// Replace ~ in path
|
||||
QString misc::expandPath(QString path) {
|
||||
path = path.trimmed();
|
||||
if(path.isEmpty()) return path;
|
||||
if(path.length() == 1) {
|
||||
if(path[0] == '~' ) return QDir::homePath();
|
||||
if (path.isEmpty()) return path;
|
||||
if (path.length() == 1) {
|
||||
if (path[0] == '~' ) return QDir::homePath();
|
||||
}
|
||||
if(path[0] == '~' && path[1] == QDir::separator()) {
|
||||
if (path[0] == '~' && path[1] == QDir::separator()) {
|
||||
path.replace(0, 1, QDir::homePath());
|
||||
} else {
|
||||
if(QDir::isAbsolutePath(path)) {
|
||||
if (QDir::isAbsolutePath(path)) {
|
||||
path = QDir(path).absolutePath();
|
||||
}
|
||||
}
|
||||
@@ -744,27 +744,27 @@ QString misc::expandPath(QString path) {
|
||||
// Take a number of seconds and return an user-friendly
|
||||
// time duration like "1d 2h 10m".
|
||||
QString misc::userFriendlyDuration(qlonglong seconds) {
|
||||
if(seconds < 0 || seconds >= MAX_ETA) {
|
||||
if (seconds < 0 || seconds >= MAX_ETA) {
|
||||
return QString::fromUtf8("∞");
|
||||
}
|
||||
if(seconds == 0) {
|
||||
if (seconds == 0) {
|
||||
return "0";
|
||||
}
|
||||
if(seconds < 60) {
|
||||
if (seconds < 60) {
|
||||
return tr("< 1m", "< 1 minute");
|
||||
}
|
||||
int minutes = seconds / 60;
|
||||
if(minutes < 60) {
|
||||
if (minutes < 60) {
|
||||
return tr("%1m","e.g: 10minutes").arg(QString::number(minutes));
|
||||
}
|
||||
int hours = minutes / 60;
|
||||
minutes = minutes - hours*60;
|
||||
if(hours < 24) {
|
||||
if (hours < 24) {
|
||||
return tr("%1h %2m", "e.g: 3hours 5minutes").arg(QString::number(hours)).arg(QString::number(minutes));
|
||||
}
|
||||
int days = hours / 24;
|
||||
hours = hours - days * 24;
|
||||
if(days < 100) {
|
||||
if (days < 100) {
|
||||
return tr("%1d %2h", "e.g: 2days 10hours").arg(QString::number(days)).arg(QString::number(hours));
|
||||
}
|
||||
return QString::fromUtf8("∞");
|
||||
@@ -785,7 +785,7 @@ QString misc::getUserIDString() {
|
||||
|
||||
QStringList misc::toStringList(const QList<bool> &l) {
|
||||
QStringList ret;
|
||||
foreach(const bool &b, l) {
|
||||
foreach (const bool &b, l) {
|
||||
ret << (b ? "1" : "0");
|
||||
}
|
||||
return ret;
|
||||
@@ -793,7 +793,7 @@ QStringList misc::toStringList(const QList<bool> &l) {
|
||||
|
||||
QList<int> misc::intListfromStringList(const QStringList &l) {
|
||||
QList<int> ret;
|
||||
foreach(const QString &s, l) {
|
||||
foreach (const QString &s, l) {
|
||||
ret << s.toInt();
|
||||
}
|
||||
return ret;
|
||||
@@ -801,7 +801,7 @@ QList<int> misc::intListfromStringList(const QStringList &l) {
|
||||
|
||||
QList<bool> misc::boolListfromStringList(const QStringList &l) {
|
||||
QList<bool> ret;
|
||||
foreach(const QString &s, l) {
|
||||
foreach (const QString &s, l) {
|
||||
ret << (s=="1");
|
||||
}
|
||||
return ret;
|
||||
@@ -811,13 +811,13 @@ quint64 misc::computePathSize(QString path)
|
||||
{
|
||||
// Check if it is a file
|
||||
QFileInfo fi(path);
|
||||
if(!fi.exists()) return 0;
|
||||
if(fi.isFile()) return fi.size();
|
||||
if (!fi.exists()) return 0;
|
||||
if (fi.isFile()) return fi.size();
|
||||
// Compute folder size
|
||||
quint64 size = 0;
|
||||
foreach(const QFileInfo &subfi, QDir(path).entryInfoList(QDir::Dirs|QDir::Files)) {
|
||||
if(subfi.fileName().startsWith(".")) continue;
|
||||
if(subfi.isDir())
|
||||
foreach (const QFileInfo &subfi, QDir(path).entryInfoList(QDir::Dirs|QDir::Files)) {
|
||||
if (subfi.fileName().startsWith(".")) continue;
|
||||
if (subfi.isDir())
|
||||
size += misc::computePathSize(subfi.absoluteFilePath());
|
||||
else
|
||||
size += subfi.size();
|
||||
@@ -828,7 +828,7 @@ quint64 misc::computePathSize(QString path)
|
||||
bool misc::isValidTorrentFile(const QString &torrent_path) {
|
||||
try {
|
||||
boost::intrusive_ptr<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();
|
||||
} catch(std::exception&) {
|
||||
return false;
|
||||
@@ -842,13 +842,13 @@ bool misc::isValidTorrentFile(const QString &torrent_path) {
|
||||
*/
|
||||
QString misc::branchPath(QString file_path, bool uses_slashes)
|
||||
{
|
||||
if(!uses_slashes)
|
||||
if (!uses_slashes)
|
||||
file_path.replace("\\", "/");
|
||||
Q_ASSERT(!file_path.contains("\\"));
|
||||
if(file_path.endsWith("/"))
|
||||
if (file_path.endsWith("/"))
|
||||
file_path.chop(1); // Remove trailing slash
|
||||
qDebug() << Q_FUNC_INFO << "before:" << file_path;
|
||||
if(file_path.contains("/"))
|
||||
if (file_path.contains("/"))
|
||||
return file_path.left(file_path.lastIndexOf('/'));
|
||||
return "";
|
||||
}
|
||||
@@ -864,7 +864,7 @@ QString misc::fileName(QString file_path)
|
||||
{
|
||||
file_path.replace("\\", "/");
|
||||
const int slash_index = file_path.lastIndexOf('/');
|
||||
if(slash_index == -1)
|
||||
if (slash_index == -1)
|
||||
return file_path;
|
||||
return file_path.mid(slash_index+1);
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ public:
|
||||
static inline QString file_extension(const QString &filename) {
|
||||
QString extension;
|
||||
int point_index = filename.lastIndexOf(".");
|
||||
if(point_index >= 0) {
|
||||
if (point_index >= 0) {
|
||||
extension = filename.mid(point_index+1);
|
||||
}
|
||||
return extension;
|
||||
|
||||
@@ -56,13 +56,13 @@ PowerManagement::~PowerManagement()
|
||||
|
||||
void PowerManagement::setActivityState(bool busy)
|
||||
{
|
||||
if(busy) setBusy();
|
||||
if (busy) setBusy();
|
||||
else setIdle();
|
||||
}
|
||||
|
||||
void PowerManagement::setBusy()
|
||||
{
|
||||
if(m_busy) return;
|
||||
if (m_busy) return;
|
||||
m_busy = true;
|
||||
|
||||
#ifdef Q_WS_WIN
|
||||
@@ -71,13 +71,13 @@ void PowerManagement::setBusy()
|
||||
m_inhibitor->RequestBusy();
|
||||
#elif defined(Q_WS_MAC)
|
||||
IOReturn success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &m_assertionID);
|
||||
if(success != kIOReturnSuccess) m_busy = false;
|
||||
if (success != kIOReturnSuccess) m_busy = false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void PowerManagement::setIdle()
|
||||
{
|
||||
if(!m_busy) return;
|
||||
if (!m_busy) return;
|
||||
m_busy = false;
|
||||
|
||||
#ifdef Q_WS_WIN
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
|
||||
PowerManagementInhibitor::PowerManagementInhibitor(QObject *parent) : QObject(parent)
|
||||
{
|
||||
if(!QDBusConnection::sessionBus().isConnected())
|
||||
if (!QDBusConnection::sessionBus().isConnected())
|
||||
{
|
||||
qDebug("D-Bus: Could not connect to session bus");
|
||||
m_state = error;
|
||||
@@ -134,7 +134,7 @@ void PowerManagementInhibitor::OnAsyncReply(QDBusPendingCallWatcher *call)
|
||||
{
|
||||
QDBusPendingReply<> reply = *call;
|
||||
|
||||
if(reply.isError())
|
||||
if (reply.isError())
|
||||
{
|
||||
qDebug("D-Bus: Reply: Error: %s", qPrintable(reply.error().message()));
|
||||
m_state = error;
|
||||
@@ -150,7 +150,7 @@ void PowerManagementInhibitor::OnAsyncReply(QDBusPendingCallWatcher *call)
|
||||
{
|
||||
QDBusPendingReply<uint> reply = *call;
|
||||
|
||||
if(reply.isError())
|
||||
if (reply.isError())
|
||||
{
|
||||
qDebug("D-Bus: Reply: Error: %s", qPrintable(reply.error().message()));
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ public slots:
|
||||
// Super seeding
|
||||
pref.enableSuperSeeding(cb_super_seeding.isChecked());
|
||||
// Network interface
|
||||
if(combo_iface.currentIndex() == 0) {
|
||||
if (combo_iface.currentIndex() == 0) {
|
||||
// All interfaces (default)
|
||||
pref.setNetworkInterface(QString::null);
|
||||
} else {
|
||||
@@ -92,7 +92,7 @@ public slots:
|
||||
}
|
||||
// Network address
|
||||
QHostAddress addr(txt_network_address.text().trimmed());
|
||||
if(addr.isNull())
|
||||
if (addr.isNull())
|
||||
pref.setNetworkAddress("");
|
||||
else
|
||||
pref.setNetworkAddress(addr.toString());
|
||||
@@ -199,10 +199,10 @@ private slots:
|
||||
combo_iface.addItem(tr("Any interface", "i.e. Any network interface"));
|
||||
const QString current_iface = pref.getNetworkInterface();
|
||||
int i = 1;
|
||||
foreach(const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) {
|
||||
if(iface.flags() & QNetworkInterface::IsLoopBack) continue;
|
||||
foreach (const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) {
|
||||
if (iface.flags() & QNetworkInterface::IsLoopBack) continue;
|
||||
combo_iface.addItem(iface.name());
|
||||
if(!current_iface.isEmpty() && iface.name() == current_iface)
|
||||
if (!current_iface.isEmpty() && iface.name() == current_iface)
|
||||
combo_iface.setCurrentIndex(i);
|
||||
++i;
|
||||
}
|
||||
|
||||
@@ -81,8 +81,8 @@ options_imp::options_imp(QWidget *parent):
|
||||
hsplitter->setCollapsible(1, false);
|
||||
// Get apply button in button box
|
||||
QList<QAbstractButton *> buttons = buttonBox->buttons();
|
||||
foreach(QAbstractButton *button, buttons){
|
||||
if(buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole){
|
||||
foreach (QAbstractButton *button, buttons){
|
||||
if (buttonBox->buttonRole(button) == QDialogButtonBox::ApplyRole){
|
||||
applyButton = button;
|
||||
break;
|
||||
}
|
||||
@@ -98,7 +98,7 @@ options_imp::options_imp(QWidget *parent):
|
||||
initializeLanguageCombo();
|
||||
|
||||
// Load week days (scheduler)
|
||||
for(uint i=1; i<=7; ++i) {
|
||||
for (uint i=1; i<=7; ++i) {
|
||||
#if QT_VERSION >= 0x040500
|
||||
schedule_days->addItem(QDate::longDayName(i, QDate::StandaloneFormat));
|
||||
#else
|
||||
@@ -109,7 +109,7 @@ options_imp::options_imp(QWidget *parent):
|
||||
// Load options
|
||||
loadOptions();
|
||||
// Disable systray integration if it is not supported by the system
|
||||
if(!QSystemTrayIcon::isSystemTrayAvailable()){
|
||||
if (!QSystemTrayIcon::isSystemTrayAvailable()){
|
||||
checkShowSystray->setChecked(false);
|
||||
checkShowSystray->setEnabled(false);
|
||||
}
|
||||
@@ -267,7 +267,7 @@ void options_imp::initializeLanguageCombo()
|
||||
// List language files
|
||||
const QDir lang_dir(":/lang");
|
||||
const QStringList lang_files = lang_dir.entryList(QStringList() << "qbittorrent_*.qm", QDir::Files);
|
||||
foreach(QString lang_file, lang_files) {
|
||||
foreach (QString lang_file, lang_files) {
|
||||
QString localeStr = lang_file.mid(12); // remove "qbittorrent_"
|
||||
localeStr.chop(3); // Remove ".qm"
|
||||
QLocale locale(localeStr);
|
||||
@@ -297,13 +297,13 @@ void options_imp::loadWindowState() {
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
|
||||
resize(settings.value(QString::fromUtf8("Preferences/State/size"), sizeFittingScreen()).toSize());
|
||||
QPoint p = settings.value(QString::fromUtf8("Preferences/State/pos"), QPoint()).toPoint();
|
||||
if(!p.isNull())
|
||||
if (!p.isNull())
|
||||
move(p);
|
||||
// Load slider size
|
||||
const QStringList sizes_str = settings.value("Preferences/State/hSplitterSizes", QStringList()).toStringList();
|
||||
// Splitter size
|
||||
QList<int> sizes;
|
||||
if(sizes_str.size() == 2) {
|
||||
if (sizes_str.size() == 2) {
|
||||
sizes << sizes_str.first().toInt();
|
||||
sizes << sizes_str.last().toInt();
|
||||
} else {
|
||||
@@ -328,16 +328,16 @@ QSize options_imp::sizeFittingScreen() const {
|
||||
int scrn = 0;
|
||||
QWidget *w = this->topLevelWidget();
|
||||
|
||||
if(w)
|
||||
if (w)
|
||||
scrn = QApplication::desktop()->screenNumber(w);
|
||||
else if(QApplication::desktop()->isVirtualDesktop())
|
||||
else if (QApplication::desktop()->isVirtualDesktop())
|
||||
scrn = QApplication::desktop()->screenNumber(QCursor::pos());
|
||||
else
|
||||
scrn = QApplication::desktop()->screenNumber(this);
|
||||
|
||||
QRect desk(QApplication::desktop()->availableGeometry(scrn));
|
||||
if(width() > desk.width() || height() > desk.height()) {
|
||||
if(desk.width() > 0 && desk.height() > 0)
|
||||
if (width() > desk.width() || height() > desk.height()) {
|
||||
if (desk.width() > 0 && desk.height() > 0)
|
||||
return QSize(desk.width(), desk.height());
|
||||
}
|
||||
return size();
|
||||
@@ -348,9 +348,9 @@ void options_imp::saveOptions(){
|
||||
Preferences pref;
|
||||
// Load the translation
|
||||
QString locale = getLocale();
|
||||
if(pref.getLocale() != locale) {
|
||||
if (pref.getLocale() != locale) {
|
||||
QTranslator *translator = new QTranslator;
|
||||
if(translator->load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){
|
||||
if (translator->load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){
|
||||
qDebug("%s locale recognized, using translation.", qPrintable(locale));
|
||||
}else{
|
||||
qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale));
|
||||
@@ -454,7 +454,7 @@ void options_imp::saveOptions(){
|
||||
// Misc preferences
|
||||
// * IPFilter
|
||||
pref.setFilteringEnabled(isFilteringEnabled());
|
||||
if(isFilteringEnabled()){
|
||||
if (isFilteringEnabled()){
|
||||
QString filter_path = textFilterPath->text();
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
filter_path.replace("\\", "/");
|
||||
@@ -471,12 +471,12 @@ void options_imp::saveOptions(){
|
||||
// End Queueing system preferences
|
||||
// Web UI
|
||||
pref.setWebUiEnabled(isWebUiEnabled());
|
||||
if(isWebUiEnabled())
|
||||
if (isWebUiEnabled())
|
||||
{
|
||||
pref.setWebUiPort(webUiPort());
|
||||
pref.setUPnPForWebUIPort(checkWebUIUPnP->isChecked());
|
||||
pref.setWebUiHttpsEnabled(checkWebUiHttps->isChecked());
|
||||
if(checkWebUiHttps->isChecked())
|
||||
if (checkWebUiHttps->isChecked())
|
||||
{
|
||||
pref.setWebUiHttpsCertificate(m_sslCert);
|
||||
pref.setWebUiHttpsKey(m_sslKey);
|
||||
@@ -508,12 +508,12 @@ int options_imp::getProxyType() const{
|
||||
return Proxy::SOCKS4;
|
||||
break;
|
||||
case 2:
|
||||
if(isProxyAuthEnabled()){
|
||||
if (isProxyAuthEnabled()){
|
||||
return Proxy::SOCKS5_PW;
|
||||
}
|
||||
return Proxy::SOCKS5;
|
||||
case 3:
|
||||
if(isProxyAuthEnabled()){
|
||||
if (isProxyAuthEnabled()){
|
||||
return Proxy::HTTP_PW;
|
||||
}
|
||||
return Proxy::HTTP;
|
||||
@@ -532,7 +532,7 @@ void options_imp::loadOptions(){
|
||||
checkAltRowColors->setChecked(pref.useAlternatingRowColors());
|
||||
checkShowSystray->setChecked(pref.systrayIntegration());
|
||||
checkShowSplash->setChecked(!pref.isSlashScreenDisabled());
|
||||
if(checkShowSystray->isChecked()) {
|
||||
if (checkShowSystray->isChecked()) {
|
||||
checkCloseToSystray->setChecked(pref.closeToTray());
|
||||
checkMinimizeToSysTray->setChecked(pref.minimizeToTray());
|
||||
checkStartMinimized->setChecked(pref.startMinimized());
|
||||
@@ -552,7 +552,7 @@ void options_imp::loadOptions(){
|
||||
save_path.replace("/", "\\");
|
||||
#endif
|
||||
textSavePath->setText(save_path);
|
||||
if(pref.isTempPathEnabled()) {
|
||||
if (pref.isTempPathEnabled()) {
|
||||
// enable
|
||||
checkTempFolder->setChecked(true);
|
||||
} else {
|
||||
@@ -570,7 +570,7 @@ void options_imp::loadOptions(){
|
||||
checkStartPaused->setChecked(pref.addTorrentsInPause());
|
||||
|
||||
strValue = pref.getExportDir();
|
||||
if(strValue.isEmpty()) {
|
||||
if (strValue.isEmpty()) {
|
||||
// Disable
|
||||
checkExportDir->setChecked(false);
|
||||
} else {
|
||||
@@ -591,11 +591,11 @@ void options_imp::loadOptions(){
|
||||
autoRunBox->setChecked(pref.isAutoRunEnabled());
|
||||
autoRun_txt->setText(pref.getAutoRunProgram());
|
||||
intValue = pref.getActionOnDblClOnTorrentDl();
|
||||
if(intValue >= actionTorrentDlOnDblClBox->count())
|
||||
if (intValue >= actionTorrentDlOnDblClBox->count())
|
||||
intValue = 0;
|
||||
actionTorrentDlOnDblClBox->setCurrentIndex(intValue);
|
||||
intValue = pref.getActionOnDblClOnTorrentFn();
|
||||
if(intValue >= actionTorrentFnOnDblClBox->count())
|
||||
if (intValue >= actionTorrentFnOnDblClBox->count())
|
||||
intValue = 1;
|
||||
actionTorrentFnOnDblClBox->setCurrentIndex(intValue);
|
||||
// End Downloads preferences
|
||||
@@ -603,7 +603,7 @@ void options_imp::loadOptions(){
|
||||
spinPort->setValue(pref.getSessionPort());
|
||||
checkUPnP->setChecked(pref.isUPnPEnabled());
|
||||
intValue = pref.getGlobalDownloadLimit();
|
||||
if(intValue > 0) {
|
||||
if (intValue > 0) {
|
||||
// Enabled
|
||||
checkDownloadLimit->setChecked(true);
|
||||
spinDownloadLimit->setEnabled(true);
|
||||
@@ -614,7 +614,7 @@ void options_imp::loadOptions(){
|
||||
spinDownloadLimit->setEnabled(false);
|
||||
}
|
||||
intValue = pref.getGlobalUploadLimit();
|
||||
if(intValue != -1) {
|
||||
if (intValue != -1) {
|
||||
// Enabled
|
||||
checkUploadLimit->setChecked(true);
|
||||
spinUploadLimit->setEnabled(true);
|
||||
@@ -653,7 +653,7 @@ void options_imp::loadOptions(){
|
||||
comboProxyType->setCurrentIndex(0);
|
||||
}
|
||||
enableProxy(comboProxyType->currentIndex());
|
||||
//if(isProxyEnabled()) {
|
||||
//if (isProxyEnabled()) {
|
||||
// Proxy is enabled, save settings
|
||||
textProxyIP->setText(pref.getProxyIp());
|
||||
spinProxyPort->setValue(pref.getProxyPort());
|
||||
@@ -665,7 +665,7 @@ void options_imp::loadOptions(){
|
||||
// End Connection preferences
|
||||
// Bittorrent preferences
|
||||
intValue = pref.getMaxConnecs();
|
||||
if(intValue > 0) {
|
||||
if (intValue > 0) {
|
||||
// enable
|
||||
checkMaxConnecs->setChecked(true);
|
||||
spinMaxConnec->setEnabled(true);
|
||||
@@ -676,7 +676,7 @@ void options_imp::loadOptions(){
|
||||
spinMaxConnec->setEnabled(false);
|
||||
}
|
||||
intValue = pref.getMaxConnecsPerTorrent();
|
||||
if(intValue > 0) {
|
||||
if (intValue > 0) {
|
||||
// enable
|
||||
checkMaxConnecsPerTorrent->setChecked(true);
|
||||
spinMaxConnecPerTorrent->setEnabled(true);
|
||||
@@ -687,7 +687,7 @@ void options_imp::loadOptions(){
|
||||
spinMaxConnecPerTorrent->setEnabled(false);
|
||||
}
|
||||
intValue = pref.getMaxUploadsPerTorrent();
|
||||
if(intValue > 0) {
|
||||
if (intValue > 0) {
|
||||
// enable
|
||||
checkMaxUploadsPerTorrent->setChecked(true);
|
||||
spinMaxUploadsPerTorrent->setEnabled(true);
|
||||
@@ -708,7 +708,7 @@ void options_imp::loadOptions(){
|
||||
#endif
|
||||
// Ratio limit
|
||||
floatValue = pref.getGlobalMaxRatio();
|
||||
if(floatValue >= 0.) {
|
||||
if (floatValue >= 0.) {
|
||||
// Enable
|
||||
checkMaxRatio->setChecked(true);
|
||||
spinMaxRatio->setEnabled(true);
|
||||
@@ -783,12 +783,12 @@ int options_imp::getMaxActiveTorrents() const {
|
||||
}
|
||||
|
||||
bool options_imp::minimizeToTray() const{
|
||||
if(!checkShowSystray->isChecked()) return false;
|
||||
if (!checkShowSystray->isChecked()) return false;
|
||||
return checkMinimizeToSysTray->isChecked();
|
||||
}
|
||||
|
||||
bool options_imp::closeToTray() const{
|
||||
if(!checkShowSystray->isChecked()) return false;
|
||||
if (!checkShowSystray->isChecked()) return false;
|
||||
return checkCloseToSystray->isChecked();
|
||||
}
|
||||
|
||||
@@ -812,17 +812,17 @@ bool options_imp::isUPnPEnabled() const{
|
||||
// [download,upload]
|
||||
QPair<int,int> options_imp::getGlobalBandwidthLimits() const{
|
||||
int DL = -1, UP = -1;
|
||||
if(checkDownloadLimit->isChecked()){
|
||||
if (checkDownloadLimit->isChecked()){
|
||||
DL = spinDownloadLimit->value();
|
||||
}
|
||||
if(checkUploadLimit->isChecked()){
|
||||
if (checkUploadLimit->isChecked()){
|
||||
UP = spinUploadLimit->value();
|
||||
}
|
||||
return qMakePair(DL, UP);
|
||||
}
|
||||
|
||||
bool options_imp::startMinimized() const {
|
||||
if(checkStartMinimized->isChecked()) return true;
|
||||
if (checkStartMinimized->isChecked()) return true;
|
||||
return checkStartMinimized->isChecked();
|
||||
}
|
||||
|
||||
@@ -837,7 +837,7 @@ int options_imp::getDHTPort() const {
|
||||
|
||||
// Return Share ratio
|
||||
qreal options_imp::getMaxRatio() const{
|
||||
if(checkMaxRatio->isChecked()){
|
||||
if (checkMaxRatio->isChecked()){
|
||||
return spinMaxRatio->value();
|
||||
}
|
||||
return -1;
|
||||
@@ -845,7 +845,7 @@ qreal options_imp::getMaxRatio() const{
|
||||
|
||||
// Return Save Path
|
||||
QString options_imp::getSavePath() const{
|
||||
if(textSavePath->text().trimmed().isEmpty()){
|
||||
if (textSavePath->text().trimmed().isEmpty()){
|
||||
QString save_path = Preferences().getSavePath();
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
save_path.replace("/", "\\");
|
||||
@@ -865,7 +865,7 @@ bool options_imp::isTempPathEnabled() const {
|
||||
|
||||
// Return max connections number
|
||||
int options_imp::getMaxConnecs() const{
|
||||
if(!checkMaxConnecs->isChecked()){
|
||||
if (!checkMaxConnecs->isChecked()){
|
||||
return -1;
|
||||
}else{
|
||||
return spinMaxConnec->value();
|
||||
@@ -873,7 +873,7 @@ int options_imp::getMaxConnecs() const{
|
||||
}
|
||||
|
||||
int options_imp::getMaxConnecsPerTorrent() const{
|
||||
if(!checkMaxConnecsPerTorrent->isChecked()){
|
||||
if (!checkMaxConnecsPerTorrent->isChecked()){
|
||||
return -1;
|
||||
}else{
|
||||
return spinMaxConnecPerTorrent->value();
|
||||
@@ -881,7 +881,7 @@ int options_imp::getMaxConnecsPerTorrent() const{
|
||||
}
|
||||
|
||||
int options_imp::getMaxUploadsPerTorrent() const{
|
||||
if(!checkMaxUploadsPerTorrent->isChecked()){
|
||||
if (!checkMaxUploadsPerTorrent->isChecked()){
|
||||
return -1;
|
||||
}else{
|
||||
return spinMaxUploadsPerTorrent->value();
|
||||
@@ -889,7 +889,7 @@ int options_imp::getMaxUploadsPerTorrent() const{
|
||||
}
|
||||
|
||||
void options_imp::on_buttonBox_accepted(){
|
||||
if(applyButton->isEnabled()){
|
||||
if (applyButton->isEnabled()){
|
||||
saveOptions();
|
||||
applyButton->setEnabled(false);
|
||||
this->hide();
|
||||
@@ -900,7 +900,7 @@ void options_imp::on_buttonBox_accepted(){
|
||||
}
|
||||
|
||||
void options_imp::applySettings(QAbstractButton* button) {
|
||||
if(button == applyButton){
|
||||
if (button == applyButton){
|
||||
saveOptions();
|
||||
emit status_changed();
|
||||
}
|
||||
@@ -925,14 +925,14 @@ void options_imp::enableApplyButton(){
|
||||
}
|
||||
|
||||
void options_imp::enableProxy(int index){
|
||||
if(index){
|
||||
if (index){
|
||||
//enable
|
||||
lblProxyIP->setEnabled(true);
|
||||
textProxyIP->setEnabled(true);
|
||||
lblProxyPort->setEnabled(true);
|
||||
spinProxyPort->setEnabled(true);
|
||||
checkProxyPeerConnecs->setEnabled(true);
|
||||
if(index > 1) {
|
||||
if (index > 1) {
|
||||
checkProxyAuth->setEnabled(true);
|
||||
} else {
|
||||
checkProxyAuth->setEnabled(false);
|
||||
@@ -1008,7 +1008,7 @@ void options_imp::setLocale(const QString &localeStr) {
|
||||
QLocale locale(localeStr);
|
||||
// Attempt to find exact match
|
||||
int index = comboI18n->findData(locale.name(), Qt::UserRole);
|
||||
if(index < 0) {
|
||||
if (index < 0) {
|
||||
// Unreconized, use US English
|
||||
index = comboI18n->findData(QLocale("en").name(), Qt::UserRole);
|
||||
Q_ASSERT(index >= 0);
|
||||
@@ -1017,21 +1017,21 @@ void options_imp::setLocale(const QString &localeStr) {
|
||||
}
|
||||
|
||||
QString options_imp::getExportDir() const {
|
||||
if(checkExportDir->isChecked())
|
||||
if (checkExportDir->isChecked())
|
||||
return misc::expandPath(textExportDir->text());
|
||||
return QString();
|
||||
}
|
||||
|
||||
// Return action on double-click on a downloading torrent set in options
|
||||
int options_imp::getActionOnDblClOnTorrentDl() const {
|
||||
if(actionTorrentDlOnDblClBox->currentIndex() < 1)
|
||||
if (actionTorrentDlOnDblClBox->currentIndex() < 1)
|
||||
return 0;
|
||||
return actionTorrentDlOnDblClBox->currentIndex();
|
||||
}
|
||||
|
||||
// Return action on double-click on a finished torrent set in options
|
||||
int options_imp::getActionOnDblClOnTorrentFn() const {
|
||||
if(actionTorrentFnOnDblClBox->currentIndex() < 1)
|
||||
if (actionTorrentFnOnDblClBox->currentIndex() < 1)
|
||||
return 0;
|
||||
return actionTorrentFnOnDblClBox->currentIndex();
|
||||
}
|
||||
@@ -1079,12 +1079,12 @@ void options_imp::on_browseExportDirButton_clicked() {
|
||||
const QString export_path = misc::expandPath(textExportDir->text());
|
||||
QDir exportDir(export_path);
|
||||
QString dir;
|
||||
if(!export_path.isEmpty() && exportDir.exists()) {
|
||||
if (!export_path.isEmpty() && exportDir.exists()) {
|
||||
dir = QFileDialog::getExistingDirectory(this, tr("Choose export directory"), exportDir.absolutePath());
|
||||
} else {
|
||||
dir = QFileDialog::getExistingDirectory(this, tr("Choose export directory"), QDir::homePath());
|
||||
}
|
||||
if(!dir.isNull()){
|
||||
if (!dir.isNull()){
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
dir.replace("/", "\\");
|
||||
#endif
|
||||
@@ -1096,12 +1096,12 @@ void options_imp::on_browseFilterButton_clicked() {
|
||||
const QString filter_path = misc::expandPath(textFilterPath->text());
|
||||
QDir filterDir(filter_path);
|
||||
QString ipfilter;
|
||||
if(!filter_path.isEmpty() && filterDir.exists()) {
|
||||
if (!filter_path.isEmpty() && filterDir.exists()) {
|
||||
ipfilter = QFileDialog::getOpenFileName(this, tr("Choose an ip filter file"), filterDir.absolutePath(), tr("Filters")+QString(" (*.dat *.p2p *.p2b)"));
|
||||
} else {
|
||||
ipfilter = QFileDialog::getOpenFileName(this, tr("Choose an ip filter file"), QDir::homePath(), tr("Filters")+QString(" (*.dat *.p2p *.p2b)"));
|
||||
}
|
||||
if(!ipfilter.isNull()){
|
||||
if (!ipfilter.isNull()){
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
ipfilter.replace("/", "\\");
|
||||
#endif
|
||||
@@ -1114,12 +1114,12 @@ void options_imp::on_browseSaveDirButton_clicked(){
|
||||
const QString save_path = misc::expandPath(textSavePath->text());
|
||||
QDir saveDir(save_path);
|
||||
QString dir;
|
||||
if(!save_path.isEmpty() && saveDir.exists()) {
|
||||
if (!save_path.isEmpty() && saveDir.exists()) {
|
||||
dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), saveDir.absolutePath());
|
||||
} else {
|
||||
dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), QDir::homePath());
|
||||
}
|
||||
if(!dir.isNull()){
|
||||
if (!dir.isNull()){
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
dir.replace("/", "\\");
|
||||
#endif
|
||||
@@ -1131,12 +1131,12 @@ void options_imp::on_browseTempDirButton_clicked(){
|
||||
const QString temp_path = misc::expandPath(textTempPath->text());
|
||||
QDir tempDir(temp_path);
|
||||
QString dir;
|
||||
if(!temp_path.isEmpty() && tempDir.exists()) {
|
||||
if (!temp_path.isEmpty() && tempDir.exists()) {
|
||||
dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), tempDir.absolutePath());
|
||||
} else {
|
||||
dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), QDir::homePath());
|
||||
}
|
||||
if(!dir.isNull()){
|
||||
if (!dir.isNull()){
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
dir.replace("/", "\\");
|
||||
#endif
|
||||
@@ -1178,7 +1178,7 @@ void options_imp::showConnectionTab()
|
||||
|
||||
void options_imp::on_btnWebUiCrt_clicked() {
|
||||
QString filename = QFileDialog::getOpenFileName(this, QString(), QString(), tr("SSL Certificate (*.crt *.pem)"));
|
||||
if(filename.isNull())
|
||||
if (filename.isNull())
|
||||
return;
|
||||
QFile file(filename);
|
||||
if (file.open(QIODevice::ReadOnly)) {
|
||||
@@ -1189,7 +1189,7 @@ void options_imp::on_btnWebUiCrt_clicked() {
|
||||
|
||||
void options_imp::on_btnWebUiKey_clicked() {
|
||||
QString filename = QFileDialog::getOpenFileName(this, QString(), QString(), tr("SSL Key (*.key *.pem)"));
|
||||
if(filename.isNull())
|
||||
if (filename.isNull())
|
||||
return;
|
||||
QFile file(filename);
|
||||
if (file.open(QIODevice::ReadOnly)) {
|
||||
@@ -1203,7 +1203,7 @@ void options_imp::on_registerDNSBtn_clicked() {
|
||||
}
|
||||
|
||||
void options_imp::on_IpFilterRefreshBtn_clicked() {
|
||||
if(m_refreshingIpFilter) return;
|
||||
if (m_refreshingIpFilter) return;
|
||||
m_refreshingIpFilter = true;
|
||||
// Updating program preferences
|
||||
Preferences pref;
|
||||
@@ -1218,7 +1218,7 @@ void options_imp::on_IpFilterRefreshBtn_clicked() {
|
||||
void options_imp::handleIPFilterParsed(bool error, int ruleCount)
|
||||
{
|
||||
setCursor(QCursor(Qt::ArrowCursor));
|
||||
if(error) {
|
||||
if (error) {
|
||||
QMessageBox::warning(this, tr("Parsing error"), tr("Failed to parse the provided IP filter"));
|
||||
} else {
|
||||
QMessageBox::information(this, tr("Successfully refreshed"), tr("Successfuly parsed the provided IP filter: %1 rules were applied.", "%1 is a number").arg(ruleCount));
|
||||
@@ -1240,7 +1240,7 @@ QString options_imp::languageToLocalizedString(QLocale::Language language, const
|
||||
case QLocale::Catalan: return QString::fromUtf8("Català");
|
||||
case QLocale::Galician: return QString::fromUtf8("Galego");
|
||||
case QLocale::Portuguese: {
|
||||
if(country == "br")
|
||||
if (country == "br")
|
||||
return QString::fromUtf8("Português brasileiro");
|
||||
return QString::fromUtf8("Português");
|
||||
}
|
||||
@@ -1266,7 +1266,7 @@ QString options_imp::languageToLocalizedString(QLocale::Language language, const
|
||||
case QLocale::Georgian: return QString::fromUtf8("ქართული");
|
||||
case QLocale::Byelorussian: return QString::fromUtf8("Беларуская");
|
||||
case QLocale::Chinese: {
|
||||
if(country == "cn")
|
||||
if (country == "cn")
|
||||
return QString::fromUtf8("中文 (简体)");
|
||||
return QString::fromUtf8("中文 (繁體)");
|
||||
}
|
||||
|
||||
@@ -280,7 +280,7 @@ public:
|
||||
|
||||
void setExportDir(QString path) {
|
||||
path = path.trimmed();
|
||||
if(path.isEmpty())
|
||||
if (path.isEmpty())
|
||||
path = QString();
|
||||
setValue(QString::fromUtf8("Preferences/Downloads/TorrentExport"), path);
|
||||
}
|
||||
@@ -379,7 +379,7 @@ public:
|
||||
}
|
||||
|
||||
void setGlobalDownloadLimit(int limit) {
|
||||
if(limit <= 0) limit = -1;
|
||||
if (limit <= 0) limit = -1;
|
||||
setValue("Preferences/Connection/GlobalDLLimit", limit);
|
||||
}
|
||||
|
||||
@@ -388,31 +388,31 @@ public:
|
||||
}
|
||||
|
||||
void setGlobalUploadLimit(int limit) {
|
||||
if(limit <= 0) limit = -1;
|
||||
if (limit <= 0) limit = -1;
|
||||
setValue("Preferences/Connection/GlobalUPLimit", limit);
|
||||
}
|
||||
|
||||
int getAltGlobalDownloadLimit() const {
|
||||
int ret = value(QString::fromUtf8("Preferences/Connection/GlobalDLLimitAlt"), 10).toInt();
|
||||
if(ret <= 0)
|
||||
if (ret <= 0)
|
||||
ret = 10;
|
||||
return ret;
|
||||
}
|
||||
|
||||
void setAltGlobalDownloadLimit(int limit) {
|
||||
if(limit <= 0) limit = -1;
|
||||
if (limit <= 0) limit = -1;
|
||||
setValue("Preferences/Connection/GlobalDLLimitAlt", limit);
|
||||
}
|
||||
|
||||
int getAltGlobalUploadLimit() const {
|
||||
int ret = value(QString::fromUtf8("Preferences/Connection/GlobalUPLimitAlt"), 10).toInt();
|
||||
if(ret <= 0)
|
||||
if (ret <= 0)
|
||||
ret = 10;
|
||||
return ret;
|
||||
}
|
||||
|
||||
void setAltGlobalUploadLimit(int limit) {
|
||||
if(limit <= 0) limit = -1;
|
||||
if (limit <= 0) limit = -1;
|
||||
setValue("Preferences/Connection/GlobalUPLimitAlt", limit);
|
||||
}
|
||||
|
||||
@@ -523,7 +523,7 @@ public:
|
||||
}
|
||||
|
||||
void setMaxConnecs(int val) {
|
||||
if(val <= 0) val = -1;
|
||||
if (val <= 0) val = -1;
|
||||
setValue(QString::fromUtf8("Preferences/Bittorrent/MaxConnecs"), val);
|
||||
}
|
||||
|
||||
@@ -532,7 +532,7 @@ public:
|
||||
}
|
||||
|
||||
void setMaxConnecsPerTorrent(int val) {
|
||||
if(val <= 0) val = -1;
|
||||
if (val <= 0) val = -1;
|
||||
setValue(QString::fromUtf8("Preferences/Bittorrent/MaxConnecsPerTorrent"), val);
|
||||
}
|
||||
|
||||
@@ -541,7 +541,7 @@ public:
|
||||
}
|
||||
|
||||
void setMaxUploadsPerTorrent(int val) {
|
||||
if(val <= 0) val = -1;
|
||||
if (val <= 0) val = -1;
|
||||
setValue(QString::fromUtf8("Preferences/Bittorrent/MaxUploadsPerTorrent"), val);
|
||||
}
|
||||
|
||||
@@ -644,7 +644,7 @@ public:
|
||||
|
||||
void banIP(const QString &ip) {
|
||||
QStringList banned_ips = value(QString::fromUtf8("Preferences/IPFilter/BannedIPs"), QStringList()).toStringList();
|
||||
if(!banned_ips.contains(ip)) {
|
||||
if (!banned_ips.contains(ip)) {
|
||||
banned_ips << ip;
|
||||
setValue("Preferences/IPFilter/BannedIPs", banned_ips);
|
||||
}
|
||||
@@ -687,7 +687,7 @@ public:
|
||||
}
|
||||
|
||||
void setMaxActiveDownloads(int val) {
|
||||
if(val < 0) val = -1;
|
||||
if (val < 0) val = -1;
|
||||
setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveDownloads"), val);
|
||||
}
|
||||
|
||||
@@ -696,7 +696,7 @@ public:
|
||||
}
|
||||
|
||||
void setMaxActiveUploads(int val) {
|
||||
if(val < 0) val = -1;
|
||||
if (val < 0) val = -1;
|
||||
setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveUploads"), val);
|
||||
}
|
||||
|
||||
@@ -705,7 +705,7 @@ public:
|
||||
}
|
||||
|
||||
void setMaxActiveTorrents(int val) {
|
||||
if(val < 0) val = -1;
|
||||
if (val < 0) val = -1;
|
||||
setValue(QString::fromUtf8("Preferences/Queueing/MaxActiveTorrents"), val);
|
||||
}
|
||||
|
||||
@@ -761,7 +761,7 @@ public:
|
||||
// Get current password md5
|
||||
QString current_pass_md5 = getWebUiPassword();
|
||||
// Check if password did not change
|
||||
if(current_pass_md5 == new_password) return;
|
||||
if (current_pass_md5 == new_password) return;
|
||||
// Encode to md5 and save
|
||||
QCryptographicHash md5(QCryptographicHash::Md5);
|
||||
md5.addData(getWebUiUsername().toLocal8Bit()+":"+QBT_REALM+":");
|
||||
@@ -772,7 +772,7 @@ public:
|
||||
|
||||
QString getWebUiPassword() const {
|
||||
QString pass_ha1 = value("Preferences/WebUI/Password_ha1", "").toString();
|
||||
if(pass_ha1.isEmpty()) {
|
||||
if (pass_ha1.isEmpty()) {
|
||||
QCryptographicHash md5(QCryptographicHash::Md5);
|
||||
md5.addData(getWebUiUsername().toLocal8Bit()+":"+QBT_REALM+":");
|
||||
md5.addData("adminadmin");
|
||||
@@ -988,12 +988,12 @@ public:
|
||||
|
||||
int getMaxHalfOpenConnections() const {
|
||||
const int val = value(QString::fromUtf8("Preferences/Connection/MaxHalfOpenConnec"), 50).toInt();
|
||||
if(val <= 0) return -1;
|
||||
if (val <= 0) return -1;
|
||||
return val;
|
||||
}
|
||||
|
||||
void setMaxHalfOpenConnections(int value) {
|
||||
if(value <= 0) value = -1;
|
||||
if (value <= 0) value = -1;
|
||||
setValue(QString::fromUtf8("Preferences/Connection/MaxHalfOpenConnec"), value);
|
||||
}
|
||||
|
||||
@@ -1055,14 +1055,14 @@ public:
|
||||
|
||||
void addTorrentLabel(const QString& label) {
|
||||
QStringList labels = value("TransferListFilters/customLabels").toStringList();
|
||||
if(!labels.contains(label))
|
||||
if (!labels.contains(label))
|
||||
labels << label;
|
||||
setValue("TransferListFilters/customLabels", labels);
|
||||
}
|
||||
|
||||
void removeTorrentLabel(const QString& label) {
|
||||
QStringList labels = value("TransferListFilters/customLabels").toStringList();
|
||||
if(labels.contains(label))
|
||||
if (labels.contains(label))
|
||||
labels.removeOne(label);
|
||||
setValue("TransferListFilters/customLabels", labels);
|
||||
}
|
||||
@@ -1086,7 +1086,7 @@ public:
|
||||
const QString version = versions.takeLast();
|
||||
qDebug("Detected possible Python v%s location", qPrintable(version));
|
||||
QString path = reg_python.value(version+"/InstallPath/Default", "").toString().replace("/", "\\");
|
||||
if(!path.isEmpty() && QDir(path).exists("python.exe")) {
|
||||
if (!path.isEmpty() && QDir(path).exists("python.exe")) {
|
||||
qDebug("Found python.exe at %s", qPrintable(path));
|
||||
return path;
|
||||
}
|
||||
@@ -1094,8 +1094,8 @@ public:
|
||||
// Fallback: Detect python from default locations
|
||||
QStringList supported_versions;
|
||||
supported_versions << "32" << "31" << "30" << "27" << "26" << "25";
|
||||
foreach(const QString &v, supported_versions) {
|
||||
if(QFile::exists("C:/Python"+v+"/python.exe")) {
|
||||
foreach (const QString &v, supported_versions) {
|
||||
if (QFile::exists("C:/Python"+v+"/python.exe")) {
|
||||
reg_python.setValue(v[0]+"."+v[1]+"/InstallPath/Default", QString("C:\\Python"+v));
|
||||
return "C:\\Python"+v;
|
||||
}
|
||||
@@ -1113,7 +1113,7 @@ public:
|
||||
|
||||
static bool isTorrentFileAssocSet() {
|
||||
QSettings settings("HKEY_CLASSES_ROOT", QIniSettings::NativeFormat);
|
||||
if(settings.value(".torrent/Default").toString() != "qBittorrent") {
|
||||
if (settings.value(".torrent/Default").toString() != "qBittorrent") {
|
||||
qDebug(".torrent != qBittorrent");
|
||||
return false;
|
||||
}
|
||||
@@ -1121,15 +1121,15 @@ public:
|
||||
QString shell_command = settings.value("qBittorrent/shell/open/command/Default", "").toString();
|
||||
qDebug("Shell command is: %s", qPrintable(shell_command));
|
||||
QRegExp exe_reg("\"([^\"]+)\".*");
|
||||
if(exe_reg.indexIn(shell_command) < 0)
|
||||
if (exe_reg.indexIn(shell_command) < 0)
|
||||
return false;
|
||||
QString assoc_exe = exe_reg.cap(1);
|
||||
qDebug("exe: %s", qPrintable(assoc_exe));
|
||||
if(assoc_exe.compare(qApp->applicationFilePath().replace("/", "\\"), Qt::CaseInsensitive) != 0)
|
||||
if (assoc_exe.compare(qApp->applicationFilePath().replace("/", "\\"), Qt::CaseInsensitive) != 0)
|
||||
return false;
|
||||
// Icon
|
||||
const QString icon_str = "\""+qApp->applicationFilePath().replace("/", "\\")+"\",1";
|
||||
if(settings.value("qBittorrent/DefaultIcon/Default", icon_str).toString().compare(icon_str, Qt::CaseInsensitive) != 0)
|
||||
if (settings.value("qBittorrent/DefaultIcon/Default", icon_str).toString().compare(icon_str, Qt::CaseInsensitive) != 0)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
@@ -1141,11 +1141,11 @@ public:
|
||||
// Check magnet link assoc
|
||||
QRegExp exe_reg("\"([^\"]+)\".*");
|
||||
QString shell_command = settings.value("Magnet/shell/open/command/Default", "").toString();
|
||||
if(exe_reg.indexIn(shell_command) < 0)
|
||||
if (exe_reg.indexIn(shell_command) < 0)
|
||||
return false;
|
||||
QString assoc_exe = exe_reg.cap(1);
|
||||
qDebug("exe: %s", qPrintable(assoc_exe));
|
||||
if(assoc_exe.compare(qApp->applicationFilePath().replace("/", "\\"), Qt::CaseInsensitive) != 0)
|
||||
if (assoc_exe.compare(qApp->applicationFilePath().replace("/", "\\"), Qt::CaseInsensitive) != 0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -56,10 +56,10 @@ PreviewSelect::PreviewSelect(QWidget* parent, QTorrentHandle h): QDialog(parent)
|
||||
std::vector<libtorrent::size_type> fp;
|
||||
h.file_progress(fp);
|
||||
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 extension = fileName.split(QString::fromUtf8(".")).last().toUpper();
|
||||
if(misc::isPreviewable(extension)) {
|
||||
if (misc::isPreviewable(extension)) {
|
||||
int row = previewListModel->rowCount();
|
||||
previewListModel->insertRow(row);
|
||||
previewListModel->setData(previewListModel->index(row, NAME), QVariant(fileName));
|
||||
@@ -71,12 +71,12 @@ PreviewSelect::PreviewSelect(QWidget* parent, QTorrentHandle h): QDialog(parent)
|
||||
previewList->selectionModel()->select(previewListModel->index(0, NAME), QItemSelectionModel::Select);
|
||||
previewList->selectionModel()->select(previewListModel->index(0, SIZE), QItemSelectionModel::Select);
|
||||
previewList->selectionModel()->select(previewListModel->index(0, PROGRESS), QItemSelectionModel::Select);
|
||||
if(!previewListModel->rowCount()){
|
||||
if (!previewListModel->rowCount()){
|
||||
QMessageBox::critical(0, tr("Preview impossible"), tr("Sorry, we can't preview this file"));
|
||||
close();
|
||||
}
|
||||
connect(this, SIGNAL(readyToPreviewFile(QString)), parent, SLOT(previewFile(QString)));
|
||||
if(previewListModel->rowCount() == 1){
|
||||
if (previewListModel->rowCount() == 1){
|
||||
qDebug("Torrent file only contains one file, no need to display selection dialog before preview");
|
||||
// Only one file : no choice
|
||||
on_previewButton_clicked();
|
||||
@@ -95,15 +95,15 @@ PreviewSelect::~PreviewSelect(){
|
||||
void PreviewSelect::on_previewButton_clicked(){
|
||||
QModelIndex index;
|
||||
QModelIndexList selectedIndexes = previewList->selectionModel()->selectedRows(NAME);
|
||||
if(selectedIndexes.size() == 0) return;
|
||||
if (selectedIndexes.size() == 0) return;
|
||||
// Flush data
|
||||
h.flush_cache();
|
||||
|
||||
QString path;
|
||||
foreach(index, selectedIndexes){
|
||||
foreach (index, selectedIndexes){
|
||||
path = h.absolute_files_path().at(indexes.at(index.row()));
|
||||
// File
|
||||
if(QFile::exists(path)){
|
||||
if (QFile::exists(path)){
|
||||
emit readyToPreviewFile(path);
|
||||
} else {
|
||||
QMessageBox::critical(0, tr("Preview impossible"), tr("Sorry, we can't preview this file"));
|
||||
|
||||
@@ -55,7 +55,7 @@ ProgramUpdater::ProgramUpdater(QObject *parent) :
|
||||
mp_manager = new QNetworkAccessManager(this);
|
||||
Preferences pref;
|
||||
// Proxy support
|
||||
if(pref.isProxyEnabled()) {
|
||||
if (pref.isProxyEnabled()) {
|
||||
QNetworkProxy proxy;
|
||||
switch(pref.getProxyType()) {
|
||||
case Proxy::SOCKS4:
|
||||
@@ -69,7 +69,7 @@ ProgramUpdater::ProgramUpdater(QObject *parent) :
|
||||
proxy.setHostName(pref.getProxyIp());
|
||||
proxy.setPort(pref.getProxyPort());
|
||||
// Proxy authentication
|
||||
if(pref.isProxyAuthEnabled()) {
|
||||
if (pref.isProxyAuthEnabled()) {
|
||||
proxy.setUser(pref.getProxyUsername());
|
||||
proxy.setPassword(pref.getProxyPassword());
|
||||
}
|
||||
@@ -101,7 +101,7 @@ void ProgramUpdater::rssDownloadFinished(QNetworkReply *reply)
|
||||
disconnect(mp_manager, 0, this, 0);
|
||||
qDebug("Finished downloading the new qBittorrent updates RSS");
|
||||
QString new_version;
|
||||
if(!reply->error()) {
|
||||
if (!reply->error()) {
|
||||
qDebug("No download error, good.");
|
||||
QXmlStreamReader xml(reply);
|
||||
QString item_title;
|
||||
@@ -117,16 +117,16 @@ void ProgramUpdater::rssDownloadFinished(QNetworkReply *reply)
|
||||
in_item = true;
|
||||
}
|
||||
} else if (xml.isEndElement()) {
|
||||
if(in_item && xml.name() == "title") {
|
||||
if (in_item && xml.name() == "title") {
|
||||
in_title = false;
|
||||
const QString ext = misc::file_extension(item_title).toUpper();
|
||||
qDebug("Found an update with file extension: %s", qPrintable(ext));
|
||||
if(ext == FILE_EXT) {
|
||||
if (ext == FILE_EXT) {
|
||||
qDebug("The last update available is %s", qPrintable(item_title));
|
||||
new_version = extractVersionNumber(item_title);
|
||||
if(!new_version.isEmpty()) {
|
||||
if (!new_version.isEmpty()) {
|
||||
qDebug("Detected version is %s", qPrintable(new_version));
|
||||
if(isVersionMoreRecent(new_version))
|
||||
if (isVersionMoreRecent(new_version))
|
||||
setUpdateUrl(item_title);
|
||||
}
|
||||
break;
|
||||
@@ -135,7 +135,7 @@ void ProgramUpdater::rssDownloadFinished(QNetworkReply *reply)
|
||||
in_item = false;
|
||||
}
|
||||
} else if (xml.isCharacters() && !xml.isWhitespace()) {
|
||||
if(in_item && in_title)
|
||||
if (in_item && in_title)
|
||||
item_title += xml.text().toString();
|
||||
}
|
||||
}
|
||||
@@ -161,14 +161,14 @@ void ProgramUpdater::updateProgram()
|
||||
// Disconnect SIGNAL/SLOT
|
||||
disconnect(mp_manager, 0, this, 0);
|
||||
// Process the download
|
||||
if(!reply->error()) {
|
||||
if (!reply->error()) {
|
||||
// Save the file
|
||||
const QString installer_path = QDir::temp().absoluteFilePath("qbittorrent_update."+FILE_EXT.toLower());
|
||||
QFile update_installer(installer_path);
|
||||
if(update_installer.exists()) {
|
||||
if (update_installer.exists()) {
|
||||
update_installer.remove();
|
||||
}
|
||||
if(update_installer.open(QIODevice::WriteOnly)) {
|
||||
if (update_installer.open(QIODevice::WriteOnly)) {
|
||||
update_installer.write(reply->readAll());
|
||||
reply->close();
|
||||
update_installer.close();
|
||||
|
||||
@@ -59,7 +59,7 @@ public:
|
||||
|
||||
QString getIP() const {
|
||||
QHostAddress ip(lineIP->text());
|
||||
if(!ip.isNull()) {
|
||||
if (!ip.isNull()) {
|
||||
// QHostAddress::toString() cleans up the IP for libtorrent
|
||||
return ip.toString();
|
||||
}
|
||||
@@ -73,11 +73,11 @@ public:
|
||||
static libtorrent::asio::ip::tcp::endpoint askForPeerEndpoint() {
|
||||
libtorrent::asio::ip::tcp::endpoint ep;
|
||||
PeerAdditionDlg dlg;
|
||||
if(dlg.exec() == QDialog::Accepted) {
|
||||
if (dlg.exec() == QDialog::Accepted) {
|
||||
QString ip = dlg.getIP();
|
||||
boost::system::error_code ec;
|
||||
libtorrent::address addr = libtorrent::address::from_string(qPrintable(ip), ec);
|
||||
if(ec) {
|
||||
if (ec) {
|
||||
qDebug("Unable to parse the provided IP: %s", qPrintable(ip));
|
||||
return ep;
|
||||
}
|
||||
@@ -90,7 +90,7 @@ public:
|
||||
|
||||
protected slots:
|
||||
void validateInput() {
|
||||
if(getIP().isEmpty()) {
|
||||
if (getIP().isEmpty()) {
|
||||
QMessageBox::warning(this, tr("Invalid IP"),
|
||||
tr("The IP you provided is invalid."),
|
||||
QMessageBox::Ok);
|
||||
|
||||
@@ -92,30 +92,30 @@ PeerListWidget::~PeerListWidget() {
|
||||
delete proxyModel;
|
||||
delete listModel;
|
||||
delete listDelegate;
|
||||
if(resolver)
|
||||
if (resolver)
|
||||
delete resolver;
|
||||
}
|
||||
|
||||
void PeerListWidget::updatePeerHostNameResolutionState() {
|
||||
if(Preferences().resolvePeerHostNames()) {
|
||||
if(!resolver) {
|
||||
if (Preferences().resolvePeerHostNames()) {
|
||||
if (!resolver) {
|
||||
resolver = new ReverseResolution(this);
|
||||
connect(resolver, SIGNAL(ip_resolved(QString,QString)), this, SLOT(handleResolved(QString,QString)));
|
||||
loadPeers(properties->getCurrentTorrent(), true);
|
||||
}
|
||||
} else {
|
||||
if(resolver) {
|
||||
if (resolver) {
|
||||
delete resolver;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void PeerListWidget::updatePeerCountryResolutionState() {
|
||||
if(Preferences().resolvePeerCountries() != display_flags) {
|
||||
if (Preferences().resolvePeerCountries() != display_flags) {
|
||||
display_flags = !display_flags;
|
||||
if(display_flags) {
|
||||
if (display_flags) {
|
||||
const QTorrentHandle h = properties->getCurrentTorrent();
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
loadPeers(h);
|
||||
}
|
||||
}
|
||||
@@ -125,17 +125,17 @@ void PeerListWidget::showPeerListMenu(QPoint) {
|
||||
QMenu menu;
|
||||
bool empty_menu = true;
|
||||
QTorrentHandle h = properties->getCurrentTorrent();
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
QModelIndexList selectedIndexes = selectionModel()->selectedRows();
|
||||
QStringList selectedPeerIPs;
|
||||
foreach(const QModelIndex &index, selectedIndexes) {
|
||||
foreach (const QModelIndex &index, selectedIndexes) {
|
||||
int row = proxyModel->mapToSource(index).row();
|
||||
QString myip = listModel->data(listModel->index(row, PeerListDelegate::IP_HIDDEN)).toString();
|
||||
selectedPeerIPs << myip;
|
||||
}
|
||||
// Add Peer Action
|
||||
QAction *addPeerAct = 0;
|
||||
if(!h.is_queued() && !h.is_checking()) {
|
||||
if (!h.is_queued() && !h.is_checking()) {
|
||||
addPeerAct = menu.addAction(IconProvider::instance()->getIcon("user-group-new"), tr("Add a new peer..."));
|
||||
empty_menu = false;
|
||||
}
|
||||
@@ -144,7 +144,7 @@ void PeerListWidget::showPeerListMenu(QPoint) {
|
||||
QAction *dlLimitAct = 0;
|
||||
QAction *banAct = 0;
|
||||
QAction *copyIPAct = 0;
|
||||
if(!selectedPeerIPs.isEmpty()) {
|
||||
if (!selectedPeerIPs.isEmpty()) {
|
||||
copyIPAct = menu.addAction(IconProvider::instance()->getIcon("edit-copy"), tr("Copy IP"));
|
||||
menu.addSeparator();
|
||||
dlLimitAct = menu.addAction(QIcon(":/Icons/skin/download.png"), tr("Limit download rate..."));
|
||||
@@ -153,12 +153,12 @@ void PeerListWidget::showPeerListMenu(QPoint) {
|
||||
banAct = menu.addAction(IconProvider::instance()->getIcon("user-group-delete"), tr("Ban peer permanently"));
|
||||
empty_menu = false;
|
||||
}
|
||||
if(empty_menu) return;
|
||||
if (empty_menu) return;
|
||||
QAction *act = menu.exec(QCursor::pos());
|
||||
if(act == 0) return;
|
||||
if(act == addPeerAct) {
|
||||
if (act == 0) return;
|
||||
if (act == addPeerAct) {
|
||||
libtorrent::asio::ip::tcp::endpoint ep = PeerAdditionDlg::askForPeerEndpoint();
|
||||
if(ep != libtorrent::asio::ip::tcp::endpoint()) {
|
||||
if (ep != libtorrent::asio::ip::tcp::endpoint()) {
|
||||
try {
|
||||
h.connect_peer(ep);
|
||||
QMessageBox::information(0, tr("Peer addition"), tr("The peer was added to this torrent."));
|
||||
@@ -170,19 +170,19 @@ void PeerListWidget::showPeerListMenu(QPoint) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(act == upLimitAct) {
|
||||
if (act == upLimitAct) {
|
||||
limitUpRateSelectedPeers(selectedPeerIPs);
|
||||
return;
|
||||
}
|
||||
if(act == dlLimitAct) {
|
||||
if (act == dlLimitAct) {
|
||||
limitDlRateSelectedPeers(selectedPeerIPs);
|
||||
return;
|
||||
}
|
||||
if(act == banAct) {
|
||||
if (act == banAct) {
|
||||
banSelectedPeers(selectedPeerIPs);
|
||||
return;
|
||||
}
|
||||
if(act == copyIPAct) {
|
||||
if (act == copyIPAct) {
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
QApplication::clipboard()->setText(selectedPeerIPs.join("\r\n"));
|
||||
#else
|
||||
@@ -196,8 +196,8 @@ void PeerListWidget::banSelectedPeers(QStringList peer_ips) {
|
||||
int ret = QMessageBox::question(this, tr("Are you sure? -- qBittorrent"), tr("Are you sure you want to ban permanently the selected peers?"),
|
||||
tr("&Yes"), tr("&No"),
|
||||
QString(), 0, 1);
|
||||
if(ret) return;
|
||||
foreach(const QString &ip, peer_ips) {
|
||||
if (ret) return;
|
||||
foreach (const QString &ip, peer_ips) {
|
||||
qDebug("Banning peer %s...", ip.toLocal8Bit().data());
|
||||
QBtSession::instance()->addConsoleMessage(tr("Manually banning peer %1...").arg(ip));
|
||||
QBtSession::instance()->banIP(ip);
|
||||
@@ -207,22 +207,22 @@ void PeerListWidget::banSelectedPeers(QStringList peer_ips) {
|
||||
}
|
||||
|
||||
void PeerListWidget::limitUpRateSelectedPeers(QStringList peer_ips) {
|
||||
if(peer_ips.empty()) return;
|
||||
if (peer_ips.empty()) return;
|
||||
QTorrentHandle h = properties->getCurrentTorrent();
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
bool ok=false;
|
||||
int cur_limit = -1;
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
libtorrent::asio::ip::tcp::endpoint first_ep = peerEndpoints.value(peer_ips.first(),
|
||||
libtorrent::asio::ip::tcp::endpoint());
|
||||
if(first_ep != libtorrent::asio::ip::tcp::endpoint())
|
||||
if (first_ep != libtorrent::asio::ip::tcp::endpoint())
|
||||
cur_limit = h.get_peer_upload_limit(first_ep);
|
||||
#endif
|
||||
long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Upload rate limiting"), cur_limit, Preferences().getGlobalUploadLimit()*1024.);
|
||||
if(!ok) return;
|
||||
foreach(const QString &ip, peer_ips) {
|
||||
if (!ok) return;
|
||||
foreach (const QString &ip, peer_ips) {
|
||||
libtorrent::asio::ip::tcp::endpoint ep = peerEndpoints.value(ip, libtorrent::asio::ip::tcp::endpoint());
|
||||
if(ep != libtorrent::asio::ip::tcp::endpoint()) {
|
||||
if (ep != libtorrent::asio::ip::tcp::endpoint()) {
|
||||
qDebug("Settings Upload limit of %.1f Kb/s to peer %s", limit/1024., ip.toLocal8Bit().data());
|
||||
try {
|
||||
h.set_peer_upload_limit(ep, limit);
|
||||
@@ -237,20 +237,20 @@ void PeerListWidget::limitUpRateSelectedPeers(QStringList peer_ips) {
|
||||
|
||||
void PeerListWidget::limitDlRateSelectedPeers(QStringList peer_ips) {
|
||||
QTorrentHandle h = properties->getCurrentTorrent();
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
bool ok=false;
|
||||
int cur_limit = -1;
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
libtorrent::asio::ip::tcp::endpoint first_ep = peerEndpoints.value(peer_ips.first(),
|
||||
libtorrent::asio::ip::tcp::endpoint());
|
||||
if(first_ep != libtorrent::asio::ip::tcp::endpoint())
|
||||
if (first_ep != libtorrent::asio::ip::tcp::endpoint())
|
||||
cur_limit = h.get_peer_download_limit(first_ep);
|
||||
#endif
|
||||
long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Download rate limiting"), cur_limit, Preferences().getGlobalDownloadLimit()*1024.);
|
||||
if(!ok) return;
|
||||
foreach(const QString &ip, peer_ips) {
|
||||
if (!ok) return;
|
||||
foreach (const QString &ip, peer_ips) {
|
||||
libtorrent::asio::ip::tcp::endpoint ep = peerEndpoints.value(ip, libtorrent::asio::ip::tcp::endpoint());
|
||||
if(ep != libtorrent::asio::ip::tcp::endpoint()) {
|
||||
if (ep != libtorrent::asio::ip::tcp::endpoint()) {
|
||||
qDebug("Settings Download limit of %.1f Kb/s to peer %s", limit/1024., ip.toLocal8Bit().data());
|
||||
try {
|
||||
h.set_peer_download_limit(ep, limit);
|
||||
@@ -270,7 +270,7 @@ void PeerListWidget::clear() {
|
||||
peerEndpoints.clear();
|
||||
missingFlags.clear();
|
||||
int nbrows = listModel->rowCount();
|
||||
if(nbrows > 0) {
|
||||
if (nbrows > 0) {
|
||||
qDebug("Cleared %d peers", nbrows);
|
||||
listModel->removeRows(0, nbrows);
|
||||
}
|
||||
@@ -287,24 +287,24 @@ void PeerListWidget::saveSettings() const {
|
||||
}
|
||||
|
||||
void PeerListWidget::loadPeers(const QTorrentHandle &h, bool force_hostname_resolution) {
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
boost::system::error_code ec;
|
||||
std::vector<peer_info> peers;
|
||||
h.get_peer_info(peers);
|
||||
std::vector<peer_info>::iterator itr;
|
||||
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;
|
||||
QString peer_ip = misc::toQString(peer.ip.address().to_string(ec));
|
||||
if(ec) continue;
|
||||
if(peerItems.contains(peer_ip)) {
|
||||
if (ec) continue;
|
||||
if (peerItems.contains(peer_ip)) {
|
||||
// Update existing peer
|
||||
updatePeer(peer_ip, peer);
|
||||
old_peers_set.remove(peer_ip);
|
||||
if(force_hostname_resolution) {
|
||||
if(resolver) {
|
||||
if (force_hostname_resolution) {
|
||||
if (resolver) {
|
||||
const QString host = resolver->getHostFromCache(peer.ip);
|
||||
if(host.isNull()) {
|
||||
if (host.isNull()) {
|
||||
resolver->resolve(peer.ip);
|
||||
} else {
|
||||
qDebug("Got peer IP from cache");
|
||||
@@ -334,20 +334,20 @@ QStandardItem* PeerListWidget::addPeer(QString ip, peer_info peer) {
|
||||
// Adding Peer to peer list
|
||||
listModel->insertRow(row);
|
||||
QString host;
|
||||
if(resolver) {
|
||||
if (resolver) {
|
||||
host = resolver->getHostFromCache(peer.ip);
|
||||
}
|
||||
if(host.isNull())
|
||||
if (host.isNull())
|
||||
listModel->setData(listModel->index(row, PeerListDelegate::IP), ip);
|
||||
else
|
||||
listModel->setData(listModel->index(row, PeerListDelegate::IP), host);
|
||||
listModel->setData(listModel->index(row, PeerListDelegate::IP_HIDDEN), ip);
|
||||
// Resolve peer host name is asked
|
||||
if(resolver && host.isNull())
|
||||
if (resolver && host.isNull())
|
||||
resolver->resolve(peer.ip);
|
||||
if(display_flags) {
|
||||
if (display_flags) {
|
||||
const QIcon ico = GeoIPManager::CountryISOCodeToIcon(peer.country);
|
||||
if(!ico.isNull()) {
|
||||
if (!ico.isNull()) {
|
||||
listModel->setData(listModel->index(row, PeerListDelegate::IP), ico, Qt::DecorationRole);
|
||||
const QString country_name = GeoIPManager::CountryISOCodeToName(peer.country);
|
||||
listModel->setData(listModel->index(row, PeerListDelegate::IP), country_name, Qt::ToolTipRole);
|
||||
@@ -368,9 +368,9 @@ QStandardItem* PeerListWidget::addPeer(QString ip, peer_info peer) {
|
||||
void PeerListWidget::updatePeer(QString ip, peer_info peer) {
|
||||
QStandardItem *item = peerItems.value(ip);
|
||||
int row = item->row();
|
||||
if(display_flags) {
|
||||
if (display_flags) {
|
||||
const QIcon ico = GeoIPManager::CountryISOCodeToIcon(peer.country);
|
||||
if(!ico.isNull()) {
|
||||
if (!ico.isNull()) {
|
||||
listModel->setData(listModel->index(row, PeerListDelegate::IP), ico, Qt::DecorationRole);
|
||||
const QString country_name = GeoIPManager::CountryISOCodeToName(peer.country);
|
||||
listModel->setData(listModel->index(row, PeerListDelegate::IP), country_name, Qt::ToolTipRole);
|
||||
@@ -388,7 +388,7 @@ void PeerListWidget::updatePeer(QString ip, peer_info peer) {
|
||||
|
||||
void PeerListWidget::handleResolved(const QString &ip, const QString &hostname) {
|
||||
QStandardItem *item = peerItems.value(ip, 0);
|
||||
if(item) {
|
||||
if (item) {
|
||||
qDebug("Resolved %s -> %s", qPrintable(ip), qPrintable(hostname));
|
||||
item->setData(hostname, Qt::DisplayRole);
|
||||
//listModel->setData(listModel->index(item->row(), IP), hostname, Qt::DisplayRole);
|
||||
@@ -397,7 +397,7 @@ void PeerListWidget::handleResolved(const QString &ip, const QString &hostname)
|
||||
|
||||
void PeerListWidget::handleSortColumnChanged(int col)
|
||||
{
|
||||
if(col == 0) {
|
||||
if (col == 0) {
|
||||
qDebug("Sorting by decoration");
|
||||
proxyModel->setSortRole(Qt::ToolTipRole);
|
||||
} else {
|
||||
|
||||
@@ -140,7 +140,7 @@ void PropertiesWidget::showPiecesAvailability(bool show) {
|
||||
avail_pieces_lbl->setVisible(show);
|
||||
pieces_availability->setVisible(show);
|
||||
avail_average_lbl->setVisible(show);
|
||||
if(show || (!show && !downloaded_pieces->isVisible()))
|
||||
if (show || (!show && !downloaded_pieces->isVisible()))
|
||||
line_2->setVisible(show);
|
||||
}
|
||||
|
||||
@@ -148,12 +148,12 @@ void PropertiesWidget::showPiecesDownloaded(bool show) {
|
||||
downloaded_pieces_lbl->setVisible(show);
|
||||
downloaded_pieces->setVisible(show);
|
||||
progress_lbl->setVisible(show);
|
||||
if(show || (!show && !pieces_availability->isVisible()))
|
||||
if (show || (!show && !pieces_availability->isVisible()))
|
||||
line_2->setVisible(show);
|
||||
}
|
||||
|
||||
void PropertiesWidget::setVisibility(bool visible) {
|
||||
if(!visible && state == VISIBLE) {
|
||||
if (!visible && state == VISIBLE) {
|
||||
QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
|
||||
stackedProperties->setVisible(false);
|
||||
slideSizes = hSplitter->sizes();
|
||||
@@ -165,7 +165,7 @@ void PropertiesWidget::setVisibility(bool visible) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(visible && state == REDUCED) {
|
||||
if (visible && state == REDUCED) {
|
||||
stackedProperties->setVisible(true);
|
||||
QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
|
||||
hSplitter->handle(1)->setDisabled(false);
|
||||
@@ -212,13 +212,13 @@ QTorrentHandle PropertiesWidget::getCurrentTorrent() const {
|
||||
}
|
||||
|
||||
void PropertiesWidget::updateSavePath(const QTorrentHandle& _h) {
|
||||
if(h.is_valid() && h == _h) {
|
||||
if (h.is_valid() && h == _h) {
|
||||
QString p;
|
||||
if(h.has_metadata() && h.num_files() == 1) {
|
||||
if (h.has_metadata() && h.num_files() == 1) {
|
||||
p = h.firstFileSavePath();
|
||||
} else {
|
||||
p = TorrentPersistentData::getSavePath(h.hash());
|
||||
if(p.isEmpty())
|
||||
if (p.isEmpty())
|
||||
p = h.save_path();
|
||||
}
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
@@ -229,7 +229,7 @@ void PropertiesWidget::updateSavePath(const QTorrentHandle& _h) {
|
||||
}
|
||||
|
||||
void PropertiesWidget::updateTorrentInfos(const QTorrentHandle& _h) {
|
||||
if(h.is_valid() && h == _h) {
|
||||
if (h.is_valid() && h == _h) {
|
||||
loadTorrentInfos(h);
|
||||
}
|
||||
}
|
||||
@@ -237,7 +237,7 @@ void PropertiesWidget::updateTorrentInfos(const QTorrentHandle& _h) {
|
||||
void PropertiesWidget::loadTorrentInfos(const QTorrentHandle &_h) {
|
||||
clear();
|
||||
h = _h;
|
||||
if(!h.is_valid()) {
|
||||
if (!h.is_valid()) {
|
||||
clear();
|
||||
return;
|
||||
}
|
||||
@@ -250,7 +250,7 @@ void PropertiesWidget::loadTorrentInfos(const QTorrentHandle &_h) {
|
||||
// Hash
|
||||
hash_lbl->setText(h.hash());
|
||||
PropListModel->model()->clear();
|
||||
if(h.has_metadata()) {
|
||||
if (h.has_metadata()) {
|
||||
// Creation date
|
||||
lbl_creationDate->setText(h.creation_date());
|
||||
// Pieces size
|
||||
@@ -273,7 +273,7 @@ void PropertiesWidget::readSettings() {
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
|
||||
// Restore splitter sizes
|
||||
QStringList sizes_str = settings.value(QString::fromUtf8("TorrentProperties/SplitterSizes"), QString()).toString().split(",");
|
||||
if(sizes_str.size() == 2) {
|
||||
if (sizes_str.size() == 2) {
|
||||
slideSizes << sizes_str.first().toInt();
|
||||
slideSizes << sizes_str.last().toInt();
|
||||
QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
|
||||
@@ -284,7 +284,7 @@ void PropertiesWidget::readSettings() {
|
||||
}
|
||||
const int current_tab = settings.value("TorrentProperties/CurrentTab", -1).toInt();
|
||||
m_tabBar->setCurrentIndex(current_tab);
|
||||
if(!settings.value("TorrentProperties/Visible", false).toBool()) {
|
||||
if (!settings.value("TorrentProperties/Visible", false).toBool()) {
|
||||
setVisibility(false);
|
||||
}
|
||||
}
|
||||
@@ -295,12 +295,12 @@ void PropertiesWidget::saveSettings() {
|
||||
// Splitter sizes
|
||||
QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
|
||||
QList<int> sizes;
|
||||
if(state == VISIBLE)
|
||||
if (state == VISIBLE)
|
||||
sizes = hSplitter->sizes();
|
||||
else
|
||||
sizes = slideSizes;
|
||||
qDebug("Sizes: %d", sizes.size());
|
||||
if(sizes.size() == 2) {
|
||||
if (sizes.size() == 2) {
|
||||
settings.setValue(QString::fromUtf8("TorrentProperties/SplitterSizes"), QVariant(QString::number(sizes.first())+','+QString::number(sizes.last())));
|
||||
}
|
||||
settings.setValue("TorrentProperties/FilesListState", filesList->header()->saveState());
|
||||
@@ -316,27 +316,27 @@ void PropertiesWidget::reloadPreferences() {
|
||||
|
||||
void PropertiesWidget::loadDynamicData() {
|
||||
// Refresh only if the torrent handle is valid and if visible
|
||||
if(!h.is_valid() || main_window->getCurrentTabWidget() != transferList || state != VISIBLE) return;
|
||||
if (!h.is_valid() || main_window->getCurrentTabWidget() != transferList || state != VISIBLE) return;
|
||||
try {
|
||||
// Transfer infos
|
||||
if(stackedProperties->currentIndex() == PropTabBar::MAIN_TAB) {
|
||||
if (stackedProperties->currentIndex() == PropTabBar::MAIN_TAB) {
|
||||
wasted->setText(misc::friendlyUnit(h.total_failed_bytes()+h.total_redundant_bytes()));
|
||||
upTotal->setText(misc::friendlyUnit(h.all_time_upload()) + " ("+misc::friendlyUnit(h.total_payload_upload())+" "+tr("this session")+")");
|
||||
dlTotal->setText(misc::friendlyUnit(h.all_time_download()) + " ("+misc::friendlyUnit(h.total_payload_download())+" "+tr("this session")+")");
|
||||
if(h.upload_limit() <= 0)
|
||||
if (h.upload_limit() <= 0)
|
||||
lbl_uplimit->setText(QString::fromUtf8("∞"));
|
||||
else
|
||||
lbl_uplimit->setText(misc::friendlyUnit(h.upload_limit())+tr("/s", "/second (i.e. per second)"));
|
||||
if(h.download_limit() <= 0)
|
||||
if (h.download_limit() <= 0)
|
||||
lbl_dllimit->setText(QString::fromUtf8("∞"));
|
||||
else
|
||||
lbl_dllimit->setText(misc::friendlyUnit(h.download_limit())+tr("/s", "/second (i.e. per second)"));
|
||||
QString elapsed_txt = misc::userFriendlyDuration(h.active_time());
|
||||
if(h.is_seed()) {
|
||||
if (h.is_seed()) {
|
||||
elapsed_txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(misc::userFriendlyDuration(h.seeding_time()))+")";
|
||||
}
|
||||
lbl_elapsed->setText(elapsed_txt);
|
||||
if(h.connections_limit() > 0)
|
||||
if (h.connections_limit() > 0)
|
||||
lbl_connections->setText(QString::number(h.num_connections())+" ("+tr("%1 max", "e.g. 10 max").arg(QString::number(h.connections_limit()))+")");
|
||||
else
|
||||
lbl_connections->setText(QString::number(h.num_connections()));
|
||||
@@ -344,18 +344,18 @@ void PropertiesWidget::loadDynamicData() {
|
||||
reannounce_lbl->setText(h.next_announce());
|
||||
// Update ratio info
|
||||
const qreal ratio = QBtSession::instance()->getRealRatio(h.hash());
|
||||
if(ratio > QBtSession::MAX_RATIO)
|
||||
if (ratio > QBtSession::MAX_RATIO)
|
||||
shareRatio->setText(QString::fromUtf8("∞"));
|
||||
else
|
||||
shareRatio->setText(QString(QByteArray::number(ratio, 'f', 2)));
|
||||
if(!h.is_seed()) {
|
||||
if (!h.is_seed()) {
|
||||
showPiecesDownloaded(true);
|
||||
// Downloaded pieces
|
||||
bitfield bf(h.get_torrent_info().num_pieces(), 0);
|
||||
h.downloading_pieces(bf);
|
||||
downloaded_pieces->setProgress(h.pieces(), bf);
|
||||
// Pieces availability
|
||||
if(h.has_metadata() && !h.is_paused() && !h.is_queued() && !h.is_checking()) {
|
||||
if (h.has_metadata() && !h.is_paused() && !h.is_queued() && !h.is_checking()) {
|
||||
showPiecesAvailability(true);
|
||||
std::vector<int> avail;
|
||||
h.piece_availability(avail);
|
||||
@@ -366,7 +366,7 @@ void PropertiesWidget::loadDynamicData() {
|
||||
}
|
||||
// Progress
|
||||
qreal progress = h.progress()*100.;
|
||||
if(progress > 99.94 && progress < 100.)
|
||||
if (progress > 99.94 && progress < 100.)
|
||||
progress = 99.9;
|
||||
progress_lbl->setText(QString::number(progress, 'f', 1)+"%");
|
||||
} else {
|
||||
@@ -375,19 +375,19 @@ void PropertiesWidget::loadDynamicData() {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(stackedProperties->currentIndex() == PropTabBar::TRACKERS_TAB) {
|
||||
if (stackedProperties->currentIndex() == PropTabBar::TRACKERS_TAB) {
|
||||
// Trackers
|
||||
trackerList->loadTrackers();
|
||||
return;
|
||||
}
|
||||
if(stackedProperties->currentIndex() == PropTabBar::PEERS_TAB) {
|
||||
if (stackedProperties->currentIndex() == PropTabBar::PEERS_TAB) {
|
||||
// Load peers
|
||||
peersList->loadPeers(h);
|
||||
return;
|
||||
}
|
||||
if(stackedProperties->currentIndex() == PropTabBar::FILES_TAB) {
|
||||
if (stackedProperties->currentIndex() == PropTabBar::FILES_TAB) {
|
||||
// Files progress
|
||||
if(h.is_valid() && h.has_metadata()) {
|
||||
if (h.is_valid() && h.has_metadata()) {
|
||||
qDebug("Updating priorities in files tab");
|
||||
filesList->setUpdatesEnabled(false);
|
||||
std::vector<size_type> fp;
|
||||
@@ -405,16 +405,16 @@ void PropertiesWidget::loadUrlSeeds(){
|
||||
qDebug("Loading URL seeds");
|
||||
const QStringList hc_seeds = h.url_seeds();
|
||||
// Add url seeds
|
||||
foreach(const QString &hc_seed, hc_seeds){
|
||||
foreach (const QString &hc_seed, hc_seeds){
|
||||
qDebug("Loading URL seed: %s", qPrintable(hc_seed));
|
||||
new QListWidgetItem(hc_seed, listWebSeeds);
|
||||
}
|
||||
}
|
||||
|
||||
void PropertiesWidget::openDoubleClickedFile(QModelIndex index) {
|
||||
if(!index.isValid()) return;
|
||||
if(!h.is_valid() || !h.has_metadata()) return;
|
||||
if(PropListModel->getType(index) == TorrentFileItem::TFILE) {
|
||||
if (!index.isValid()) return;
|
||||
if (!h.is_valid() || !h.has_metadata()) return;
|
||||
if (PropListModel->getType(index) == TorrentFileItem::TFILE) {
|
||||
int i = PropListModel->getFileIndex(index);
|
||||
const QDir saveDir(h.save_path());
|
||||
const QString filename = h.filepath_at(i);
|
||||
@@ -422,7 +422,7 @@ void PropertiesWidget::openDoubleClickedFile(QModelIndex index) {
|
||||
qDebug("Trying to open file at %s", qPrintable(file_path));
|
||||
// Flush data
|
||||
h.flush_cache();
|
||||
if(QFile::exists(file_path)) {
|
||||
if (QFile::exists(file_path)) {
|
||||
QDesktopServices::openUrl(QUrl::fromLocalFile(file_path));
|
||||
} else {
|
||||
QMessageBox::warning(this, tr("I/O Error"), tr("This file does not exist yet."));
|
||||
@@ -442,7 +442,7 @@ void PropertiesWidget::openDoubleClickedFile(QModelIndex index) {
|
||||
qDebug("Trying to open folder at %s", qPrintable(file_path));
|
||||
// Flush data
|
||||
h.flush_cache();
|
||||
if(QFile::exists(file_path)) {
|
||||
if (QFile::exists(file_path)) {
|
||||
QDesktopServices::openUrl(QUrl::fromLocalFile(file_path));
|
||||
} else {
|
||||
QMessageBox::warning(this, tr("I/O Error"), tr("This folder does not exist yet."));
|
||||
@@ -454,15 +454,15 @@ void PropertiesWidget::displayFilesListMenu(const QPoint&){
|
||||
QMenu myFilesLlistMenu;
|
||||
QModelIndexList selectedRows = filesList->selectionModel()->selectedRows(0);
|
||||
QAction *actRename = 0;
|
||||
if(selectedRows.size() == 1) {
|
||||
if (selectedRows.size() == 1) {
|
||||
actRename = myFilesLlistMenu.addAction(IconProvider::instance()->getIcon("edit-rename"), tr("Rename..."));
|
||||
myFilesLlistMenu.addSeparator();
|
||||
}
|
||||
QMenu subMenu;
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
if(!h.status(0x0).is_seeding) {
|
||||
if (!h.status(0x0).is_seeding) {
|
||||
#else
|
||||
if(!static_cast<torrent_handle>(h).is_seed()) {
|
||||
if (!static_cast<torrent_handle>(h).is_seed()) {
|
||||
#endif
|
||||
subMenu.setTitle(tr("Priority"));
|
||||
subMenu.addAction(actionNot_downloaded);
|
||||
@@ -473,24 +473,24 @@ void PropertiesWidget::displayFilesListMenu(const QPoint&){
|
||||
}
|
||||
// Call menu
|
||||
const QAction *act = myFilesLlistMenu.exec(QCursor::pos());
|
||||
if(act) {
|
||||
if(act == actRename) {
|
||||
if (act) {
|
||||
if (act == actRename) {
|
||||
renameSelectedFile();
|
||||
} else {
|
||||
int prio = 1;
|
||||
if(act == actionHigh) {
|
||||
if (act == actionHigh) {
|
||||
prio = prio::HIGH;
|
||||
} else {
|
||||
if(act == actionMaximum) {
|
||||
if (act == actionMaximum) {
|
||||
prio = prio::MAXIMUM;
|
||||
} else {
|
||||
if(act == actionNot_downloaded) {
|
||||
if (act == actionNot_downloaded) {
|
||||
prio = prio::IGNORED;
|
||||
}
|
||||
}
|
||||
}
|
||||
qDebug("Setting files priority");
|
||||
foreach(QModelIndex index, selectedRows) {
|
||||
foreach (QModelIndex index, selectedRows) {
|
||||
qDebug("Setting priority(%d) for file at row %d", prio, index.row());
|
||||
PropListModel->setData(PropListModel->index(index.row(), PRIORITY, index.parent()), prio);
|
||||
}
|
||||
@@ -510,36 +510,36 @@ void PropertiesWidget::renameSelectedFile() {
|
||||
tr("New name:"), QLineEdit::Normal,
|
||||
index.data().toString(), &ok);
|
||||
if (ok && !new_name_last.isEmpty()) {
|
||||
if(!misc::isValidFileSystemName(new_name_last)) {
|
||||
if (!misc::isValidFileSystemName(new_name_last)) {
|
||||
QMessageBox::warning(this, tr("The file could not be renamed"),
|
||||
tr("This file name contains forbidden characters, please choose a different one."),
|
||||
QMessageBox::Ok);
|
||||
return;
|
||||
}
|
||||
if(PropListModel->getType(index) == TorrentFileItem::TFILE) {
|
||||
if (PropListModel->getType(index) == TorrentFileItem::TFILE) {
|
||||
// File renaming
|
||||
const int file_index = PropListModel->getFileIndex(index);
|
||||
if(!h.is_valid() || !h.has_metadata()) return;
|
||||
if (!h.is_valid() || !h.has_metadata()) return;
|
||||
QString old_name = h.filepath_at(file_index).replace("\\", "/");
|
||||
if(old_name.endsWith(".!qB") && !new_name_last.endsWith(".!qB")) {
|
||||
if (old_name.endsWith(".!qB") && !new_name_last.endsWith(".!qB")) {
|
||||
new_name_last += ".!qB";
|
||||
}
|
||||
QStringList path_items = old_name.split("/");
|
||||
path_items.removeLast();
|
||||
path_items << new_name_last;
|
||||
QString new_name = path_items.join("/");
|
||||
if(old_name == new_name) {
|
||||
if (old_name == new_name) {
|
||||
qDebug("Name did not change");
|
||||
return;
|
||||
}
|
||||
new_name = QDir::cleanPath(new_name);
|
||||
// Check if that name is already used
|
||||
for(int i=0; i<h.num_files(); ++i) {
|
||||
if(i == file_index) continue;
|
||||
for (int i=0; i<h.num_files(); ++i) {
|
||||
if (i == file_index) continue;
|
||||
#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
|
||||
if(h.filepath_at(i).compare(new_name, Qt::CaseInsensitive) == 0) {
|
||||
if (h.filepath_at(i).compare(new_name, Qt::CaseInsensitive) == 0) {
|
||||
#endif
|
||||
// Display error message
|
||||
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));
|
||||
h.rename_file(file_index, new_name);
|
||||
// Force recheck
|
||||
if(force_recheck) h.force_recheck();
|
||||
if (force_recheck) h.force_recheck();
|
||||
// Rename if torrent files model too
|
||||
if(new_name_last.endsWith(".!qB"))
|
||||
if (new_name_last.endsWith(".!qB"))
|
||||
new_name_last.chop(4);
|
||||
PropListModel->setData(index, new_name_last);
|
||||
} else {
|
||||
@@ -570,15 +570,15 @@ void PropertiesWidget::renameSelectedFile() {
|
||||
path_items.removeLast();
|
||||
path_items << new_name_last;
|
||||
QString new_path = path_items.join("/");
|
||||
if(!new_path.endsWith("/")) new_path += "/";
|
||||
if (!new_path.endsWith("/")) new_path += "/";
|
||||
// Check for overwriting
|
||||
const int num_files = h.num_files();
|
||||
for(int i=0; i<num_files; ++i) {
|
||||
for (int i=0; i<num_files; ++i) {
|
||||
const QString current_name = h.filepath_at(i);
|
||||
#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
|
||||
if(current_name.startsWith(new_path, Qt::CaseInsensitive)) {
|
||||
if (current_name.startsWith(new_path, Qt::CaseInsensitive)) {
|
||||
#endif
|
||||
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."),
|
||||
@@ -588,12 +588,12 @@ void PropertiesWidget::renameSelectedFile() {
|
||||
}
|
||||
bool force_recheck = false;
|
||||
// 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);
|
||||
if(current_name.startsWith(old_path)) {
|
||||
if (current_name.startsWith(old_path)) {
|
||||
QString new_name = current_name;
|
||||
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;
|
||||
new_name = QDir::cleanPath(new_name);
|
||||
qDebug("Rename %s to %s", qPrintable(current_name), qPrintable(new_name));
|
||||
@@ -601,7 +601,7 @@ void PropertiesWidget::renameSelectedFile() {
|
||||
}
|
||||
}
|
||||
// Force recheck
|
||||
if(force_recheck) h.force_recheck();
|
||||
if (force_recheck) h.force_recheck();
|
||||
// Rename folder in torrent files model too
|
||||
PropListModel->setData(index, new_name_last);
|
||||
// Remove old folder
|
||||
@@ -622,9 +622,9 @@ void PropertiesWidget::askWebSeed(){
|
||||
const QString url_seed = QInputDialog::getText(this, tr("New url seed", "New HTTP source"),
|
||||
tr("New url seed:"), QLineEdit::Normal,
|
||||
QString::fromUtf8("http://www."), &ok);
|
||||
if(!ok) return;
|
||||
if (!ok) return;
|
||||
qDebug("Adding %s web seed", qPrintable(url_seed));
|
||||
if(!listWebSeeds->findItems(url_seed, Qt::MatchFixedString).empty()) {
|
||||
if (!listWebSeeds->findItems(url_seed, Qt::MatchFixedString).empty()) {
|
||||
QMessageBox::warning(this, tr("qBittorrent"),
|
||||
tr("This url seed is already in the list."),
|
||||
QMessageBox::Ok);
|
||||
@@ -638,12 +638,12 @@ void PropertiesWidget::askWebSeed(){
|
||||
void PropertiesWidget::deleteSelectedUrlSeeds(){
|
||||
const QList<QListWidgetItem *> selectedItems = listWebSeeds->selectedItems();
|
||||
bool change = false;
|
||||
foreach(const QListWidgetItem *item, selectedItems){
|
||||
foreach (const QListWidgetItem *item, selectedItems){
|
||||
QString url_seed = item->text();
|
||||
h.remove_url_seed(url_seed);
|
||||
change = true;
|
||||
}
|
||||
if(change){
|
||||
if (change){
|
||||
// Refresh list
|
||||
loadUrlSeeds();
|
||||
}
|
||||
@@ -658,45 +658,45 @@ bool PropertiesWidget::applyPriorities() {
|
||||
qDebug("prioritize files: %d", priorities[0]);
|
||||
h.prioritize_files(priorities);
|
||||
// Restore first/last piece first option if necessary
|
||||
if(first_last_piece_first)
|
||||
if (first_last_piece_first)
|
||||
h.prioritize_first_last_piece(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
void PropertiesWidget::on_changeSavePathButton_clicked() {
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
QString new_path;
|
||||
if(h.has_metadata() && h.num_files() == 1) {
|
||||
if (h.has_metadata() && h.num_files() == 1) {
|
||||
new_path = QFileDialog::getSaveFileName(this, tr("Choose save path"), h.firstFileSavePath());
|
||||
} else {
|
||||
const QDir saveDir(TorrentPersistentData::getSavePath(h.hash()));
|
||||
new_path = QFileDialog::getExistingDirectory(this, tr("Choose save path"), saveDir.absolutePath(),
|
||||
QFileDialog::DontConfirmOverwrite|QFileDialog::ShowDirsOnly|QFileDialog::HideNameFilterDetails);
|
||||
}
|
||||
if(!new_path.isEmpty()){
|
||||
if (!new_path.isEmpty()){
|
||||
// Check if savePath exists
|
||||
QString save_path_dir = new_path.replace("\\", "/");
|
||||
QString new_file_name;
|
||||
if(h.has_metadata() && h.num_files() == 1) {
|
||||
if (h.has_metadata() && h.num_files() == 1) {
|
||||
new_file_name = misc::fileName(save_path_dir); // New file name
|
||||
save_path_dir = misc::branchPath(save_path_dir, true); // Skip file name
|
||||
}
|
||||
QDir savePath(misc::expandPath(save_path_dir));
|
||||
// Actually move storage
|
||||
if(!QBtSession::instance()->useTemporaryFolder() || h.is_seed()) {
|
||||
if(!savePath.exists()) savePath.mkpath(savePath.absolutePath());
|
||||
if (!QBtSession::instance()->useTemporaryFolder() || h.is_seed()) {
|
||||
if (!savePath.exists()) savePath.mkpath(savePath.absolutePath());
|
||||
h.move_storage(savePath.absolutePath());
|
||||
}
|
||||
// Update save_path in dialog
|
||||
QString display_path;
|
||||
if(h.has_metadata() && h.num_files() == 1) {
|
||||
if (h.has_metadata() && h.num_files() == 1) {
|
||||
// Rename the file
|
||||
Q_ASSERT(!new_file_name.isEmpty());
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
if(h.filename_at(0).compare(new_file_name, Qt::CaseInsensitive) != 0) {
|
||||
if (h.filename_at(0).compare(new_file_name, Qt::CaseInsensitive) != 0) {
|
||||
#else
|
||||
if(h.filename_at(0).compare(new_file_name, Qt::CaseSensitive) != 0) {
|
||||
if (h.filename_at(0).compare(new_file_name, Qt::CaseSensitive) != 0) {
|
||||
#endif
|
||||
qDebug("Renaming single file to %s", qPrintable(new_file_name));
|
||||
h.rename_file(0, new_file_name);
|
||||
@@ -715,7 +715,7 @@ void PropertiesWidget::on_changeSavePathButton_clicked() {
|
||||
}
|
||||
|
||||
void PropertiesWidget::filteredFilesChanged() {
|
||||
if(h.is_valid()) {
|
||||
if (h.is_valid()) {
|
||||
applyPriorities();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ public:
|
||||
newopt.rect = opt.rect;
|
||||
// We don't want to display 100% unless
|
||||
// the torrent is really complete
|
||||
if(progress > 99.94 && progress < 100.)
|
||||
if (progress > 99.94 && progress < 100.)
|
||||
progress = 99.9;
|
||||
newopt.text = QString(QByteArray::number(progress, 'f', 1))+QString::fromUtf8("%");
|
||||
newopt.progress = (int)progress;
|
||||
@@ -158,16 +158,16 @@ public:
|
||||
}
|
||||
|
||||
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, const QModelIndex &index) const {
|
||||
if(index.column() != PRIORITY) return 0;
|
||||
if(properties) {
|
||||
if (index.column() != PRIORITY) return 0;
|
||||
if (properties) {
|
||||
QTorrentHandle h = properties->getCurrentTorrent();
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
if(!h.is_valid() || !h.has_metadata() || h.status(0x0).is_seeding) return 0;
|
||||
if (!h.is_valid() || !h.has_metadata() || h.status(0x0).is_seeding) return 0;
|
||||
#else
|
||||
if(!h.is_valid() || !h.has_metadata() || static_cast<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
|
||||
}
|
||||
if(index.data().toInt() <= 0) {
|
||||
if (index.data().toInt() <= 0) {
|
||||
// IGNORED or MIXED
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ PropTabBar::PropTabBar(QWidget *parent) :
|
||||
// SIGNAL/SLOT
|
||||
connect(m_btnGroup, SIGNAL(buttonClicked(int)), SLOT(setCurrentIndex(int)));
|
||||
// Disable buttons focus
|
||||
foreach(QAbstractButton *btn, m_btnGroup->buttons()) {
|
||||
foreach (QAbstractButton *btn, m_btnGroup->buttons()) {
|
||||
btn->setFocusPolicy(Qt::NoFocus);
|
||||
}
|
||||
}
|
||||
@@ -103,11 +103,11 @@ int PropTabBar::currentIndex() const
|
||||
|
||||
void PropTabBar::setCurrentIndex(int index)
|
||||
{
|
||||
if(index >= m_btnGroup->buttons().size())
|
||||
if (index >= m_btnGroup->buttons().size())
|
||||
index = 0;
|
||||
// If asked to hide or if the currently selected tab is clicked
|
||||
if(index < 0 || m_currentIndex == index) {
|
||||
if(m_currentIndex >= 0) {
|
||||
if (index < 0 || m_currentIndex == index) {
|
||||
if (m_currentIndex >= 0) {
|
||||
m_btnGroup->button(m_currentIndex)->setStyleSheet(DEFAULT_BUTTON_CSS);
|
||||
m_currentIndex = -1;
|
||||
emit visibilityToggled(false);
|
||||
@@ -115,7 +115,7 @@ void PropTabBar::setCurrentIndex(int index)
|
||||
return;
|
||||
}
|
||||
// Unselect previous tab
|
||||
if(m_currentIndex >= 0) {
|
||||
if (m_currentIndex >= 0) {
|
||||
m_btnGroup->button(m_currentIndex)->setStyleSheet(DEFAULT_BUTTON_CSS);
|
||||
} else {
|
||||
// Nothing was selected, show!
|
||||
|
||||
@@ -83,8 +83,8 @@ TrackerList::~TrackerList() {
|
||||
QList<QTreeWidgetItem*> TrackerList::getSelectedTrackerItems() const {
|
||||
QList<QTreeWidgetItem*> selected_items = selectedItems();
|
||||
QList<QTreeWidgetItem*> selected_trackers;
|
||||
foreach(QTreeWidgetItem *item, selectedItems()) {
|
||||
if(indexOfTopLevelItem(item) >= NB_STICKY_ITEM) { // Ignore STICKY ITEMS
|
||||
foreach (QTreeWidgetItem *item, selectedItems()) {
|
||||
if (indexOfTopLevelItem(item) >= NB_STICKY_ITEM) { // Ignore STICKY ITEMS
|
||||
selected_trackers << item;
|
||||
}
|
||||
}
|
||||
@@ -94,37 +94,37 @@ QList<QTreeWidgetItem*> TrackerList::getSelectedTrackerItems() const {
|
||||
void TrackerList::setRowColor(int row, QColor color) {
|
||||
unsigned int nbColumns = columnCount();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
void TrackerList::moveSelectionUp() {
|
||||
QTorrentHandle h = properties->getCurrentTorrent();
|
||||
if(!h.is_valid()) {
|
||||
if (!h.is_valid()) {
|
||||
clear();
|
||||
return;
|
||||
}
|
||||
QList<QTreeWidgetItem *> selected_items = getSelectedTrackerItems();
|
||||
if(selected_items.isEmpty()) return;
|
||||
if (selected_items.isEmpty()) return;
|
||||
bool change = false;
|
||||
foreach(QTreeWidgetItem *item, selected_items){
|
||||
foreach (QTreeWidgetItem *item, selected_items){
|
||||
int index = indexOfTopLevelItem(item);
|
||||
if(index > NB_STICKY_ITEM) {
|
||||
if (index > NB_STICKY_ITEM) {
|
||||
insertTopLevelItem(index-1, takeTopLevelItem(index));
|
||||
change = true;
|
||||
}
|
||||
}
|
||||
if(!change) return;
|
||||
if (!change) return;
|
||||
// Restore selection
|
||||
QItemSelectionModel *selection = selectionModel();
|
||||
foreach(QTreeWidgetItem *item, selected_items) {
|
||||
foreach (QTreeWidgetItem *item, selected_items) {
|
||||
selection->select(indexFromItem(item), QItemSelectionModel::Rows|QItemSelectionModel::Select);
|
||||
}
|
||||
setSelectionModel(selection);
|
||||
// Update torrent trackers
|
||||
std::vector<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();
|
||||
announce_entry e(tracker_url.toStdString());
|
||||
e.tier = i-NB_STICKY_ITEM;
|
||||
@@ -137,30 +137,30 @@ void TrackerList::moveSelectionUp() {
|
||||
|
||||
void TrackerList::moveSelectionDown() {
|
||||
QTorrentHandle h = properties->getCurrentTorrent();
|
||||
if(!h.is_valid()) {
|
||||
if (!h.is_valid()) {
|
||||
clear();
|
||||
return;
|
||||
}
|
||||
QList<QTreeWidgetItem *> selected_items = getSelectedTrackerItems();
|
||||
if(selected_items.isEmpty()) return;
|
||||
if (selected_items.isEmpty()) return;
|
||||
bool change = false;
|
||||
for(int i=selectedItems().size()-1; i>= 0; --i) {
|
||||
for (int i=selectedItems().size()-1; i>= 0; --i) {
|
||||
int index = indexOfTopLevelItem(selected_items.at(i));
|
||||
if(index < topLevelItemCount()-1) {
|
||||
if (index < topLevelItemCount()-1) {
|
||||
insertTopLevelItem(index+1, takeTopLevelItem(index));
|
||||
change = true;
|
||||
}
|
||||
}
|
||||
if(!change) return;
|
||||
if (!change) return;
|
||||
// Restore selection
|
||||
QItemSelectionModel *selection = selectionModel();
|
||||
foreach(QTreeWidgetItem *item, selected_items) {
|
||||
foreach (QTreeWidgetItem *item, selected_items) {
|
||||
selection->select(indexFromItem(item), QItemSelectionModel::Rows|QItemSelectionModel::Select);
|
||||
}
|
||||
setSelectionModel(selection);
|
||||
// Update torrent trackers
|
||||
std::vector<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();
|
||||
announce_entry e(tracker_url.toStdString());
|
||||
e.tier = i-NB_STICKY_ITEM;
|
||||
@@ -192,32 +192,32 @@ void TrackerList::loadStickyItems(const QTorrentHandle &h) {
|
||||
std::vector<peer_info> peers;
|
||||
h.get_peer_info(peers);
|
||||
std::vector<peer_info>::iterator it;
|
||||
for(it=peers.begin(); it!=peers.end(); it++) {
|
||||
if(it->source & peer_info::dht)
|
||||
for (it=peers.begin(); it!=peers.end(); it++) {
|
||||
if (it->source & peer_info::dht)
|
||||
++nb_dht;
|
||||
if(it->source & peer_info::lsd)
|
||||
if (it->source & peer_info::lsd)
|
||||
++nb_lsd;
|
||||
if(it->source & peer_info::pex)
|
||||
if (it->source & peer_info::pex)
|
||||
++nb_pex;
|
||||
}
|
||||
// load DHT information
|
||||
if(QBtSession::instance()->isDHTEnabled() && h.has_metadata() && !h.priv()) {
|
||||
if (QBtSession::instance()->isDHTEnabled() && h.has_metadata() && !h.priv()) {
|
||||
dht_item->setText(COL_STATUS, tr("Working"));
|
||||
} else {
|
||||
dht_item->setText(COL_STATUS, tr("Disabled"));
|
||||
}
|
||||
dht_item->setText(COL_PEERS, QString::number(nb_dht));
|
||||
if(h.has_metadata() && h.priv()) {
|
||||
if (h.has_metadata() && h.priv()) {
|
||||
dht_item->setText(COL_MSG, tr("This torrent is private"));
|
||||
}
|
||||
// Load PeX Information
|
||||
if(QBtSession::instance()->isPexEnabled())
|
||||
if (QBtSession::instance()->isPexEnabled())
|
||||
pex_item->setText(COL_STATUS, tr("Working"));
|
||||
else
|
||||
pex_item->setText(COL_STATUS, tr("Disabled"));
|
||||
pex_item->setText(COL_PEERS, QString::number(nb_pex));
|
||||
// Load LSD Information
|
||||
if(QBtSession::instance()->isLSDEnabled())
|
||||
if (QBtSession::instance()->isLSDEnabled())
|
||||
lsd_item->setText(COL_STATUS, tr("Working"));
|
||||
else
|
||||
lsd_item->setText(COL_STATUS, tr("Disabled"));
|
||||
@@ -227,16 +227,16 @@ void TrackerList::loadStickyItems(const QTorrentHandle &h) {
|
||||
void TrackerList::loadTrackers() {
|
||||
// Load trackers from torrent handle
|
||||
QTorrentHandle h = properties->getCurrentTorrent();
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
loadStickyItems(h);
|
||||
// Load actual trackers information
|
||||
QHash<QString, TrackerInfos> trackers_data = QBtSession::instance()->getTrackersInfo(h.hash());
|
||||
QStringList old_trackers_urls = tracker_items.keys();
|
||||
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);
|
||||
QTreeWidgetItem *item = tracker_items.value(tracker_url, 0);
|
||||
if(!item) {
|
||||
if (!item) {
|
||||
item = new QTreeWidgetItem();
|
||||
item->setText(COL_TIER, QString::number(it->tier));
|
||||
item->setText(COL_URL, tracker_url);
|
||||
@@ -247,15 +247,15 @@ void TrackerList::loadTrackers() {
|
||||
}
|
||||
TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url));
|
||||
QString error_message = data.last_message.trimmed();
|
||||
if(it->verified) {
|
||||
if (it->verified) {
|
||||
item->setText(COL_STATUS, tr("Working"));
|
||||
item->setText(COL_MSG, "");
|
||||
} else {
|
||||
if(it->updating && it->fails == 0) {
|
||||
if (it->updating && it->fails == 0) {
|
||||
item->setText(COL_STATUS, tr("Updating..."));
|
||||
item->setText(COL_MSG, "");
|
||||
} else {
|
||||
if(it->fails > 0) {
|
||||
if (it->fails > 0) {
|
||||
item->setText(COL_STATUS, tr("Not working"));
|
||||
item->setText(COL_MSG, error_message);
|
||||
} else {
|
||||
@@ -267,7 +267,7 @@ void TrackerList::loadTrackers() {
|
||||
item->setText(COL_PEERS, QString::number(trackers_data.value(tracker_url, TrackerInfos(tracker_url)).num_peers));
|
||||
}
|
||||
// Remove old trackers
|
||||
foreach(const QString &tracker, old_trackers_urls) {
|
||||
foreach (const QString &tracker, old_trackers_urls) {
|
||||
delete tracker_items.take(tracker);
|
||||
}
|
||||
}
|
||||
@@ -275,11 +275,11 @@ void TrackerList::loadTrackers() {
|
||||
// Ask the user for new trackers and add them to the torrent
|
||||
void TrackerList::askForTrackers(){
|
||||
QTorrentHandle h = properties->getCurrentTorrent();
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
QStringList trackers = TrackersAdditionDlg::askForTrackers(h);
|
||||
if(!trackers.empty()) {
|
||||
foreach(const QString& tracker, trackers) {
|
||||
if(tracker.trimmed().isEmpty()) continue;
|
||||
if (!trackers.empty()) {
|
||||
foreach (const QString& tracker, trackers) {
|
||||
if (tracker.trimmed().isEmpty()) continue;
|
||||
announce_entry url(tracker.toStdString());
|
||||
url.tier = 0;
|
||||
h.add_tracker(url);
|
||||
@@ -293,14 +293,14 @@ void TrackerList::askForTrackers(){
|
||||
|
||||
void TrackerList::deleteSelectedTrackers(){
|
||||
QTorrentHandle h = properties->getCurrentTorrent();
|
||||
if(!h.is_valid()) {
|
||||
if (!h.is_valid()) {
|
||||
clear();
|
||||
return;
|
||||
}
|
||||
QList<QTreeWidgetItem *> selected_items = getSelectedTrackerItems();
|
||||
if(selected_items.isEmpty()) return;
|
||||
if (selected_items.isEmpty()) return;
|
||||
QStringList urls_to_remove;
|
||||
foreach(QTreeWidgetItem *item, selected_items){
|
||||
foreach (QTreeWidgetItem *item, selected_items){
|
||||
QString tracker_url = item->data(COL_URL, Qt::DisplayRole).toString();
|
||||
urls_to_remove << tracker_url;
|
||||
tracker_items.remove(tracker_url);
|
||||
@@ -310,8 +310,8 @@ void TrackerList::deleteSelectedTrackers(){
|
||||
std::vector<announce_entry> remaining_trackers;
|
||||
std::vector<announce_entry> trackers = h.trackers();
|
||||
std::vector<announce_entry>::iterator it;
|
||||
for(it = trackers.begin(); it != trackers.end(); it++) {
|
||||
if(!urls_to_remove.contains(misc::toQString((*it).url))) {
|
||||
for (it = trackers.begin(); it != trackers.end(); it++) {
|
||||
if (!urls_to_remove.contains(misc::toQString((*it).url))) {
|
||||
remaining_trackers.push_back(*it);
|
||||
}
|
||||
}
|
||||
@@ -323,28 +323,28 @@ void TrackerList::deleteSelectedTrackers(){
|
||||
|
||||
void TrackerList::showTrackerListMenu(QPoint) {
|
||||
QTorrentHandle h = properties->getCurrentTorrent();
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
//QList<QTreeWidgetItem*> selected_items = getSelectedTrackerItems();
|
||||
QMenu menu;
|
||||
// Add actions
|
||||
QAction *addAct = menu.addAction(IconProvider::instance()->getIcon("list-add"), tr("Add a new tracker..."));
|
||||
QAction *delAct = 0;
|
||||
if(!getSelectedTrackerItems().isEmpty()) {
|
||||
if (!getSelectedTrackerItems().isEmpty()) {
|
||||
delAct = menu.addAction(IconProvider::instance()->getIcon("list-remove"), tr("Remove tracker"));
|
||||
}
|
||||
menu.addSeparator();
|
||||
QAction *reannounceAct = menu.addAction(IconProvider::instance()->getIcon("view-refresh"), tr("Force reannounce"));
|
||||
QAction *act = menu.exec(QCursor::pos());
|
||||
if(act == 0) return;
|
||||
if(act == addAct) {
|
||||
if (act == 0) return;
|
||||
if (act == addAct) {
|
||||
askForTrackers();
|
||||
return;
|
||||
}
|
||||
if(act == delAct) {
|
||||
if (act == delAct) {
|
||||
deleteSelectedTrackers();
|
||||
return;
|
||||
}
|
||||
if(act == reannounceAct) {
|
||||
if (act == reannounceAct) {
|
||||
properties->getCurrentTorrent().force_reannounce();
|
||||
return;
|
||||
}
|
||||
@@ -352,7 +352,7 @@ void TrackerList::showTrackerListMenu(QPoint) {
|
||||
|
||||
void TrackerList::loadSettings() {
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
|
||||
if(!header()->restoreState(settings.value("TorrentProperties/Trackers/TrackerListState").toByteArray())) {
|
||||
if (!header()->restoreState(settings.value("TorrentProperties/Trackers/TrackerListState").toByteArray())) {
|
||||
setColumnWidth(0, 30);
|
||||
setColumnWidth(1, 300);
|
||||
}
|
||||
|
||||
@@ -94,18 +94,18 @@ public slots:
|
||||
}
|
||||
// Load from current user list
|
||||
QStringList tmp = trackers_list->toPlainText().split("\n");
|
||||
foreach(const QString &user_url_str, tmp) {
|
||||
foreach (const QString &user_url_str, tmp) {
|
||||
QUrl user_url(user_url_str);
|
||||
if(!existingTrackers.contains(user_url))
|
||||
if (!existingTrackers.contains(user_url))
|
||||
existingTrackers << user_url;
|
||||
}
|
||||
// Add new trackers to the list
|
||||
if(!trackers_list->toPlainText().isEmpty() && !trackers_list->toPlainText().endsWith("\n"))
|
||||
if (!trackers_list->toPlainText().isEmpty() && !trackers_list->toPlainText().endsWith("\n"))
|
||||
trackers_list->insertPlainText("\n");
|
||||
int nb = 0;
|
||||
while (!list_file.atEnd()) {
|
||||
const QByteArray line = list_file.readLine().trimmed();
|
||||
if(line.isEmpty()) continue;
|
||||
if (line.isEmpty()) continue;
|
||||
QUrl url(line);
|
||||
if (!existingTrackers.contains(url)) {
|
||||
trackers_list->insertPlainText(line + "\n");
|
||||
@@ -119,7 +119,7 @@ public slots:
|
||||
setCursor(Qt::ArrowCursor);
|
||||
uTorrentListButton->setEnabled(true);
|
||||
// Display information message if necessary
|
||||
if(nb == 0) {
|
||||
if (nb == 0) {
|
||||
QMessageBox::information(this, tr("No change"), tr("No additional trackers were found."), QMessageBox::Ok);
|
||||
}
|
||||
sender()->deleteLater();
|
||||
@@ -138,7 +138,7 @@ public:
|
||||
static QStringList askForTrackers(QTorrentHandle h) {
|
||||
QStringList trackers;
|
||||
TrackersAdditionDlg dlg(h);
|
||||
if(dlg.exec() == QDialog::Accepted) {
|
||||
if (dlg.exec() == QDialog::Accepted) {
|
||||
return dlg.newTrackers();
|
||||
}
|
||||
return trackers;
|
||||
|
||||
@@ -56,14 +56,14 @@ public:
|
||||
QVariant value(const QString & key, const QVariant &defaultValue = QVariant()) const {
|
||||
QString key_tmp(key);
|
||||
QVariant ret = QSettings::value(key_tmp);
|
||||
if(ret.isNull())
|
||||
if (ret.isNull())
|
||||
return defaultValue;
|
||||
return ret;
|
||||
}
|
||||
|
||||
void setValue(const QString &key, const QVariant &val) {
|
||||
QString key_tmp(key);
|
||||
if(format() == QSettings::NativeFormat)
|
||||
if (format() == QSettings::NativeFormat)
|
||||
key_tmp.replace("\\", "/");
|
||||
QSettings::setValue(key_tmp, val);
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ bool QMacApplication::event(QEvent * ev) {
|
||||
case QEvent::FileOpen:
|
||||
{
|
||||
QString path = static_cast<QFileOpenEvent *>(ev)->file();
|
||||
if(path.isEmpty()) {
|
||||
if (path.isEmpty()) {
|
||||
// Get the url instead
|
||||
path = static_cast<QFileOpenEvent *>(ev)->url().toString();
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ public slots:
|
||||
|
||||
QTime startAltSpeeds = pref.getSchedulerStartTime();
|
||||
QTime endAltSpeeds = pref.getSchedulerEndTime();
|
||||
if(startAltSpeeds == endAltSpeeds) {
|
||||
if (startAltSpeeds == endAltSpeeds) {
|
||||
std::cerr << "Error: bandwidth scheduler have the same start time and end time." << std::endl;
|
||||
std::cerr << "The bandwidth scheduler will be disabled" << std::endl;
|
||||
stop();
|
||||
@@ -41,7 +41,7 @@ public slots:
|
||||
QTime now = QTime::currentTime();
|
||||
uint time_to_start = secsTo(now, startAltSpeeds);
|
||||
uint time_to_end = secsTo(now, endAltSpeeds);
|
||||
if(time_to_end < time_to_start) {
|
||||
if (time_to_end < time_to_start) {
|
||||
// We should be in alternative mode
|
||||
in_alternative_mode = true;
|
||||
// Start counting
|
||||
@@ -61,9 +61,9 @@ public slots:
|
||||
// Get the day this mode was started (either today or yesterday)
|
||||
QDate current_date = QDateTime::currentDateTime().toLocalTime().date();
|
||||
int day = current_date.dayOfWeek();
|
||||
if(in_alternative_mode) {
|
||||
if (in_alternative_mode) {
|
||||
// It is possible that starttime was yesterday
|
||||
if(QTime::currentTime().secsTo(pref.getSchedulerStartTime()) > 0) {
|
||||
if (QTime::currentTime().secsTo(pref.getSchedulerStartTime()) > 0) {
|
||||
current_date.addDays(-1); // Go to yesterday
|
||||
day = current_date.day();
|
||||
}
|
||||
@@ -75,17 +75,17 @@ public slots:
|
||||
emit switchToAlternativeMode(!in_alternative_mode);
|
||||
break;
|
||||
case WEEK_ENDS:
|
||||
if(day == Qt::Saturday || day == Qt::Sunday)
|
||||
if (day == Qt::Saturday || day == Qt::Sunday)
|
||||
emit switchToAlternativeMode(!in_alternative_mode);
|
||||
break;
|
||||
case WEEK_DAYS:
|
||||
if(day != Qt::Saturday && day != Qt::Sunday)
|
||||
if (day != Qt::Saturday && day != Qt::Sunday)
|
||||
emit switchToAlternativeMode(!in_alternative_mode);
|
||||
break;
|
||||
default:
|
||||
// Convert our enum index to Qt enum index
|
||||
int scheduler_day = ((int)pref.getSchedulerDays()) - 2;
|
||||
if(day == scheduler_day)
|
||||
if (day == scheduler_day)
|
||||
emit switchToAlternativeMode(!in_alternative_mode);
|
||||
break;
|
||||
}
|
||||
@@ -101,7 +101,7 @@ private:
|
||||
// don't want that
|
||||
uint secsTo(QTime now, QTime t) {
|
||||
int diff = now.secsTo(t);
|
||||
if(diff < 0) {
|
||||
if (diff < 0) {
|
||||
// 86400 seconds in a day
|
||||
diff += 86400;
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ public:
|
||||
int ruleCount = 0;
|
||||
QFile file(filePath);
|
||||
if (file.exists()){
|
||||
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
|
||||
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
|
||||
std::cerr << "I/O Error: Could not open ip filer file in read mode." << std::endl;
|
||||
return ruleCount;
|
||||
}
|
||||
@@ -79,9 +79,9 @@ public:
|
||||
QByteArray line = file.readLine();
|
||||
// Ignoring empty lines
|
||||
line = line.trimmed();
|
||||
if(line.isEmpty()) continue;
|
||||
if (line.isEmpty()) continue;
|
||||
// Ignoring commented lines
|
||||
if(line.startsWith('#') || line.startsWith("//")) continue;
|
||||
if (line.startsWith('#') || line.startsWith("//")) continue;
|
||||
|
||||
// Line should be splitted by commas
|
||||
QList<QByteArray> partsList = line.split(',');
|
||||
@@ -89,7 +89,7 @@ public:
|
||||
|
||||
// IP Range should be splitted by a dash
|
||||
QList<QByteArray> IPs = partsList.first().split('-');
|
||||
if(IPs.size() != 2) {
|
||||
if (IPs.size() != 2) {
|
||||
qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
|
||||
qDebug("Line was %s", line.constData());
|
||||
continue;
|
||||
@@ -97,30 +97,30 @@ public:
|
||||
|
||||
boost::system::error_code ec;
|
||||
const QString strStartIP = cleanupIPAddress(IPs.at(0));
|
||||
if(strStartIP.isEmpty()) {
|
||||
if (strStartIP.isEmpty()) {
|
||||
qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
|
||||
qDebug("Start IP of the range is malformated: %s", qPrintable(strStartIP));
|
||||
continue;
|
||||
}
|
||||
libtorrent::address startAddr = libtorrent::address::from_string(qPrintable(strStartIP), ec);
|
||||
if(ec) {
|
||||
if (ec) {
|
||||
qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
|
||||
qDebug("Start IP of the range is malformated: %s", qPrintable(strStartIP));
|
||||
continue;
|
||||
}
|
||||
const QString strEndIP = cleanupIPAddress(IPs.at(1));
|
||||
if(strEndIP.isEmpty()) {
|
||||
if (strEndIP.isEmpty()) {
|
||||
qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
|
||||
qDebug("End IP of the range is malformated: %s", qPrintable(strEndIP));
|
||||
continue;
|
||||
}
|
||||
libtorrent::address endAddr = libtorrent::address::from_string(qPrintable(strEndIP), ec);
|
||||
if(ec) {
|
||||
if (ec) {
|
||||
qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
|
||||
qDebug("End IP of the range is malformated: %s", qPrintable(strEndIP));
|
||||
continue;
|
||||
}
|
||||
if(startAddr.is_v4() != endAddr.is_v4()) {
|
||||
if (startAddr.is_v4() != endAddr.is_v4()) {
|
||||
qDebug("Ipfilter.dat: line %d is malformed.", nbLine);
|
||||
qDebug("One IP is IPv4 and the other is IPv6!");
|
||||
continue;
|
||||
@@ -128,12 +128,12 @@ public:
|
||||
|
||||
// Check if there is an access value (apparently not mandatory)
|
||||
int nbAccess = 0;
|
||||
if(nbElem > 1) {
|
||||
if (nbElem > 1) {
|
||||
// There is possibly one
|
||||
nbAccess = partsList.at(1).trimmed().toInt();
|
||||
}
|
||||
|
||||
if(nbAccess > 127) {
|
||||
if (nbAccess > 127) {
|
||||
// Ignoring this rule because access value is too high
|
||||
continue;
|
||||
}
|
||||
@@ -155,7 +155,7 @@ public:
|
||||
int ruleCount = 0;
|
||||
QFile file(filePath);
|
||||
if (file.exists()){
|
||||
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
|
||||
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
|
||||
std::cerr << "I/O Error: Could not open ip filer file in read mode." << std::endl;
|
||||
return ruleCount;
|
||||
}
|
||||
@@ -163,48 +163,48 @@ public:
|
||||
while (!file.atEnd() && !abort) {
|
||||
++nbLine;
|
||||
QByteArray line = file.readLine().trimmed();
|
||||
if(line.isEmpty()) continue;
|
||||
if (line.isEmpty()) continue;
|
||||
// Ignoring commented lines
|
||||
if(line.startsWith('#') || line.startsWith("//")) continue;
|
||||
if (line.startsWith('#') || line.startsWith("//")) continue;
|
||||
// Line is splitted by :
|
||||
QList<QByteArray> partsList = line.split(':');
|
||||
if(partsList.size() < 2){
|
||||
if (partsList.size() < 2){
|
||||
qDebug("p2p file: line %d is malformed.", nbLine);
|
||||
continue;
|
||||
}
|
||||
// Get IP range
|
||||
QList<QByteArray> IPs = partsList.last().split('-');
|
||||
if(IPs.size() != 2) {
|
||||
if (IPs.size() != 2) {
|
||||
qDebug("p2p file: line %d is malformed.", nbLine);
|
||||
qDebug("line was: %s", line.constData());
|
||||
continue;
|
||||
}
|
||||
boost::system::error_code ec;
|
||||
QString strStartIP = cleanupIPAddress(IPs.at(0));
|
||||
if(strStartIP.isEmpty()) {
|
||||
if (strStartIP.isEmpty()) {
|
||||
qDebug("p2p file: line %d is malformed.", nbLine);
|
||||
qDebug("Start IP is invalid: %s", qPrintable(strStartIP));
|
||||
continue;
|
||||
}
|
||||
libtorrent::address startAddr = libtorrent::address::from_string(qPrintable(strStartIP), ec);
|
||||
if(ec) {
|
||||
if (ec) {
|
||||
qDebug("p2p file: line %d is malformed.", nbLine);
|
||||
qDebug("Start IP is invalid: %s", qPrintable(strStartIP));
|
||||
continue;
|
||||
}
|
||||
QString strEndIP = cleanupIPAddress(IPs.at(1));
|
||||
if(strEndIP.isEmpty()) {
|
||||
if (strEndIP.isEmpty()) {
|
||||
qDebug("p2p file: line %d is malformed.", nbLine);
|
||||
qDebug("End IP is invalid: %s", qPrintable(strStartIP));
|
||||
continue;
|
||||
}
|
||||
libtorrent::address endAddr = libtorrent::address::from_string(qPrintable(strEndIP), ec);
|
||||
if(ec) {
|
||||
if (ec) {
|
||||
qDebug("p2p file: line %d is malformed.", nbLine);
|
||||
qDebug("End IP is invalid: %s", qPrintable(strStartIP));
|
||||
continue;
|
||||
}
|
||||
if(startAddr.is_v4() != endAddr.is_v4()) {
|
||||
if (startAddr.is_v4() != endAddr.is_v4()) {
|
||||
qDebug("p2p file: line %d is malformed.", nbLine);
|
||||
qDebug("Line was: %s", line.constData());
|
||||
continue;
|
||||
@@ -230,8 +230,8 @@ public:
|
||||
do {
|
||||
read = stream.readRawData(&c, 1);
|
||||
total_read += read;
|
||||
if(read > 0) {
|
||||
if(c != delim) {
|
||||
if (read > 0) {
|
||||
if (c != delim) {
|
||||
name += c;
|
||||
} else {
|
||||
// Delim found
|
||||
@@ -247,7 +247,7 @@ public:
|
||||
int ruleCount = 0;
|
||||
QFile file(filePath);
|
||||
if (file.exists()){
|
||||
if(!file.open(QIODevice::ReadOnly)){
|
||||
if (!file.open(QIODevice::ReadOnly)){
|
||||
std::cerr << "I/O Error: Could not open ip filer file in read mode." << std::endl;
|
||||
return ruleCount;
|
||||
}
|
||||
@@ -255,7 +255,7 @@ public:
|
||||
// Read header
|
||||
char buf[7];
|
||||
unsigned char version;
|
||||
if(
|
||||
if (
|
||||
!stream.readRawData(buf, sizeof(buf)) ||
|
||||
memcmp(buf, "\xFF\xFF\xFF\xFFP2B", 7) ||
|
||||
!stream.readRawData((char*)&version, sizeof(version))
|
||||
@@ -264,13 +264,13 @@ public:
|
||||
return ruleCount;
|
||||
}
|
||||
|
||||
if(version==1 || version==2) {
|
||||
if (version==1 || version==2) {
|
||||
qDebug ("p2b version 1 or 2");
|
||||
unsigned int start, end;
|
||||
|
||||
string name;
|
||||
while(getlineInStream(stream, name, '\0') && !abort) {
|
||||
if(
|
||||
if (
|
||||
!stream.readRawData((char*)&start, sizeof(start)) ||
|
||||
!stream.readRawData((char*)&end, sizeof(end))
|
||||
) {
|
||||
@@ -289,26 +289,26 @@ public:
|
||||
} catch(std::exception&) {}
|
||||
}
|
||||
}
|
||||
else if(version==3) {
|
||||
else if (version==3) {
|
||||
qDebug ("p2b version 3");
|
||||
unsigned int namecount;
|
||||
if(!stream.readRawData((char*)&namecount, sizeof(namecount))) {
|
||||
if (!stream.readRawData((char*)&namecount, sizeof(namecount))) {
|
||||
std::cerr << "Parsing Error: The filter file is not a valid PeerGuardian P2B file." << std::endl;
|
||||
return ruleCount;
|
||||
}
|
||||
namecount=ntohl(namecount);
|
||||
// Reading names although, we don't really care about them
|
||||
for(unsigned int i=0; i<namecount; i++) {
|
||||
for (unsigned int i=0; i<namecount; i++) {
|
||||
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;
|
||||
return ruleCount;
|
||||
}
|
||||
if(abort) return ruleCount;
|
||||
if (abort) return ruleCount;
|
||||
}
|
||||
// Reading the ranges
|
||||
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;
|
||||
return ruleCount;
|
||||
}
|
||||
@@ -316,8 +316,8 @@ public:
|
||||
|
||||
unsigned int name, start, end;
|
||||
|
||||
for(unsigned int i=0; i<rangecount; i++) {
|
||||
if(
|
||||
for (unsigned int i=0; i<rangecount; i++) {
|
||||
if (
|
||||
!stream.readRawData((char*)&name, sizeof(name)) ||
|
||||
!stream.readRawData((char*)&start, sizeof(start)) ||
|
||||
!stream.readRawData((char*)&end, sizeof(end))
|
||||
@@ -335,7 +335,7 @@ public:
|
||||
filter.add_rule(first, last, libtorrent::ip_filter::blocked);
|
||||
++ruleCount;
|
||||
} catch(std::exception&) {}
|
||||
if(abort) return ruleCount;
|
||||
if (abort) return ruleCount;
|
||||
}
|
||||
} else {
|
||||
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){
|
||||
// First, import current filter
|
||||
filter = s->get_ip_filter();
|
||||
if(isRunning()) {
|
||||
if (isRunning()) {
|
||||
// Already parsing a filter, abort first
|
||||
abort = true;
|
||||
wait();
|
||||
@@ -368,12 +368,12 @@ public:
|
||||
static void processFilterList(libtorrent::session *s, const QStringList& IPs) {
|
||||
// First, import current filter
|
||||
libtorrent::ip_filter filter = s->get_ip_filter();
|
||||
foreach(const QString &ip, IPs) {
|
||||
foreach (const QString &ip, IPs) {
|
||||
qDebug("Manual ban of peer %s", ip.toLocal8Bit().constData());
|
||||
boost::system::error_code ec;
|
||||
libtorrent::address addr = libtorrent::address::from_string(ip.toLocal8Bit().constData(), ec);
|
||||
Q_ASSERT(!ec);
|
||||
if(!ec)
|
||||
if (!ec)
|
||||
filter.add_rule(addr, addr, libtorrent::ip_filter::blocked);
|
||||
}
|
||||
s->set_ip_filter(filter);
|
||||
@@ -386,7 +386,7 @@ signals:
|
||||
protected:
|
||||
QString cleanupIPAddress(QString _ip) {
|
||||
QHostAddress ip(_ip.trimmed());
|
||||
if(ip.isNull()) {
|
||||
if (ip.isNull()) {
|
||||
return QString();
|
||||
}
|
||||
return ip.toString();
|
||||
@@ -395,11 +395,11 @@ protected:
|
||||
void run(){
|
||||
qDebug("Processing filter file");
|
||||
int ruleCount = 0;
|
||||
if(filePath.endsWith(".p2p", Qt::CaseInsensitive)) {
|
||||
if (filePath.endsWith(".p2p", Qt::CaseInsensitive)) {
|
||||
// PeerGuardian p2p file
|
||||
ruleCount = parseP2PFilterFile(filePath);
|
||||
} else {
|
||||
if(filePath.endsWith(".p2b", Qt::CaseInsensitive)) {
|
||||
if (filePath.endsWith(".p2b", Qt::CaseInsensitive)) {
|
||||
// PeerGuardian p2b file
|
||||
ruleCount = parseP2BFilterFile(filePath);
|
||||
} else {
|
||||
@@ -407,7 +407,7 @@ protected:
|
||||
ruleCount = parseDATFilterFile(filePath);
|
||||
}
|
||||
}
|
||||
if(abort)
|
||||
if (abort)
|
||||
return;
|
||||
try {
|
||||
s->set_ip_filter(filter);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -56,7 +56,7 @@ using namespace std;
|
||||
|
||||
#if LIBTORRENT_VERSION_MINOR < 16
|
||||
static QString boostTimeToQString(const boost::posix_time::ptime &boostDate) {
|
||||
if(boostDate.is_not_a_date_time()) return "";
|
||||
if (boostDate.is_not_a_date_time()) return "";
|
||||
struct std::tm tm;
|
||||
try {
|
||||
tm = boost::posix_time::to_tm(boostDate);
|
||||
@@ -81,7 +81,7 @@ QString QTorrentHandle::hash() const {
|
||||
|
||||
QString QTorrentHandle::name() const {
|
||||
QString name = TorrentPersistentData::getName(hash());
|
||||
if(name.isEmpty()) {
|
||||
if (name.isEmpty()) {
|
||||
name = misc::toQStringU(torrent_handle::name());
|
||||
}
|
||||
return name;
|
||||
@@ -124,7 +124,7 @@ qreal QTorrentHandle::progress() const {
|
||||
#else
|
||||
torrent_status st = torrent_handle::status();
|
||||
#endif
|
||||
if(!st.total_wanted)
|
||||
if (!st.total_wanted)
|
||||
return 0.;
|
||||
if (st.total_wanted_done == st.total_wanted)
|
||||
return 1.;
|
||||
@@ -182,19 +182,19 @@ int QTorrentHandle::num_pieces() const {
|
||||
bool QTorrentHandle::first_last_piece_first() const {
|
||||
// Detect first media file
|
||||
int index = 0;
|
||||
for(index = 0; index < num_files(); ++index) {
|
||||
for (index = 0; index < num_files(); ++index) {
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
QString path = misc::toQStringU(get_torrent_info().file_at(index).path);
|
||||
#else
|
||||
QString path = misc::toQStringU(get_torrent_info().file_at(index).path.string());
|
||||
#endif
|
||||
const QString ext = misc::file_extension(path);
|
||||
if(misc::isPreviewable(ext) && torrent_handle::file_priority(index) > 0) {
|
||||
if (misc::isPreviewable(ext) && torrent_handle::file_priority(index) > 0) {
|
||||
break;
|
||||
}
|
||||
++index;
|
||||
}
|
||||
if(index >= torrent_handle::get_torrent_info().num_files()) return false;
|
||||
if (index >= torrent_handle::get_torrent_info().num_files()) return false;
|
||||
file_entry media_file = torrent_handle::get_torrent_info().file_at(index);
|
||||
int piece_size = torrent_handle::get_torrent_info().piece_length();
|
||||
Q_ASSERT(piece_size>0);
|
||||
@@ -285,7 +285,7 @@ QStringList QTorrentHandle::url_seeds() const {
|
||||
try {
|
||||
const std::set<std::string> existing_seeds = torrent_handle::url_seeds();
|
||||
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());
|
||||
res << misc::toQString(*it);
|
||||
}
|
||||
@@ -306,8 +306,8 @@ size_type QTorrentHandle::actual_size() const {
|
||||
|
||||
bool QTorrentHandle::has_filtered_pieces() const {
|
||||
std::vector<int> piece_priorities = torrent_handle::piece_priorities();
|
||||
for(unsigned int i = 0; i<piece_priorities.size(); ++i) {
|
||||
if(!piece_priorities[i]) return true;
|
||||
for (unsigned int i = 0; i<piece_priorities.size(); ++i) {
|
||||
if (!piece_priorities[i]) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -432,7 +432,7 @@ size_type QTorrentHandle::total_payload_upload() const {
|
||||
QStringList QTorrentHandle::absolute_files_path() const {
|
||||
QDir saveDir(save_path());
|
||||
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)));
|
||||
}
|
||||
return res;
|
||||
@@ -442,10 +442,10 @@ QStringList QTorrentHandle::absolute_files_path_uneeded() const {
|
||||
QDir saveDir(save_path());
|
||||
QStringList res;
|
||||
std::vector<int> fp = torrent_handle::file_priorities();
|
||||
for(uint i = 0; i < fp.size(); ++i) {
|
||||
if(fp[i] == 0) {
|
||||
for (uint i = 0; i < fp.size(); ++i) {
|
||||
if (fp[i] == 0) {
|
||||
const QString file_path = QDir::cleanPath(saveDir.absoluteFilePath(filepath_at(i)));
|
||||
if(file_path.contains(".unwanted"))
|
||||
if (file_path.contains(".unwanted"))
|
||||
res << file_path;
|
||||
}
|
||||
}
|
||||
@@ -454,14 +454,14 @@ QStringList QTorrentHandle::absolute_files_path_uneeded() const {
|
||||
|
||||
bool QTorrentHandle::has_missing_files() const {
|
||||
const QStringList paths = absolute_files_path();
|
||||
foreach(const QString &path, paths) {
|
||||
if(!QFile::exists(path)) return true;
|
||||
foreach (const QString &path, paths) {
|
||||
if (!QFile::exists(path)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int QTorrentHandle::queue_position() const {
|
||||
if(torrent_handle::queue_position() < 0)
|
||||
if (torrent_handle::queue_position() < 0)
|
||||
return -1;
|
||||
return torrent_handle::queue_position()+1;
|
||||
}
|
||||
@@ -540,14 +540,14 @@ bool QTorrentHandle::priv() const {
|
||||
QString QTorrentHandle::firstFileSavePath() const {
|
||||
Q_ASSERT(has_metadata());
|
||||
QString fsave_path = TorrentPersistentData::getSavePath(hash());
|
||||
if(fsave_path.isEmpty())
|
||||
if (fsave_path.isEmpty())
|
||||
fsave_path = save_path();
|
||||
fsave_path.replace("\\", "/");
|
||||
if(!fsave_path.endsWith("/"))
|
||||
if (!fsave_path.endsWith("/"))
|
||||
fsave_path += "/";
|
||||
fsave_path += filepath_at(0);
|
||||
// Remove .!qB extension
|
||||
if(fsave_path.endsWith(".!qB", Qt::CaseInsensitive))
|
||||
if (fsave_path.endsWith(".!qB", Qt::CaseInsensitive))
|
||||
fsave_path.chop(4);
|
||||
return fsave_path;
|
||||
}
|
||||
@@ -572,7 +572,7 @@ QString QTorrentHandle::error() const {
|
||||
void QTorrentHandle::downloading_pieces(bitfield &bf) const {
|
||||
std::vector<partial_piece_info> 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);
|
||||
}
|
||||
return;
|
||||
@@ -609,22 +609,22 @@ void QTorrentHandle::pause() const {
|
||||
}
|
||||
|
||||
void QTorrentHandle::resume() const {
|
||||
if(has_error()) torrent_handle::clear_error();
|
||||
if (has_error()) torrent_handle::clear_error();
|
||||
const QString torrent_hash = hash();
|
||||
bool has_persistant_error = TorrentPersistentData::hasError(torrent_hash);
|
||||
TorrentPersistentData::setErrorState(torrent_hash, false);
|
||||
bool temp_path_enabled = Preferences().isTempPathEnabled();
|
||||
if(has_persistant_error && temp_path_enabled) {
|
||||
if (has_persistant_error && temp_path_enabled) {
|
||||
// Torrent was supposed to be seeding, checking again in final destination
|
||||
qDebug("Resuming a torrent with error...");
|
||||
const QString final_save_path = TorrentPersistentData::getSavePath(torrent_hash);
|
||||
qDebug("Torrent final path is: %s", qPrintable(final_save_path));
|
||||
if(!final_save_path.isEmpty())
|
||||
if (!final_save_path.isEmpty())
|
||||
move_storage(final_save_path);
|
||||
}
|
||||
torrent_handle::auto_managed(true);
|
||||
torrent_handle::resume();
|
||||
if(has_persistant_error && temp_path_enabled) {
|
||||
if (has_persistant_error && temp_path_enabled) {
|
||||
// Force recheck
|
||||
torrent_handle::force_recheck();
|
||||
}
|
||||
@@ -645,7 +645,7 @@ void QTorrentHandle::set_tracker_login(QString username, QString password) const
|
||||
}
|
||||
|
||||
void QTorrentHandle::move_storage(QString new_path) const {
|
||||
if(QDir(save_path()) == QDir(new_path)) return;
|
||||
if (QDir(save_path()) == QDir(new_path)) return;
|
||||
TorrentPersistentData::setPreviousSavePath(hash(), save_path());
|
||||
// Create destination directory if necessary
|
||||
// or move_storage() will fail...
|
||||
@@ -655,12 +655,12 @@ void QTorrentHandle::move_storage(QString new_path) const {
|
||||
}
|
||||
|
||||
bool QTorrentHandle::save_torrent_file(QString path) const {
|
||||
if(!has_metadata()) return false;
|
||||
if (!has_metadata()) return false;
|
||||
|
||||
entry meta = bdecode(torrent_handle::get_torrent_info().metadata().get(), torrent_handle::get_torrent_info().metadata().get()+torrent_handle::get_torrent_info().metadata_size());
|
||||
entry torrent_entry(entry::dictionary_t);
|
||||
torrent_entry["info"] = meta;
|
||||
if(!torrent_handle::trackers().empty())
|
||||
if (!torrent_handle::trackers().empty())
|
||||
torrent_entry["announce"] = torrent_handle::trackers().front().url;
|
||||
|
||||
vector<char> out;
|
||||
@@ -677,14 +677,14 @@ bool QTorrentHandle::save_torrent_file(QString path) const {
|
||||
|
||||
void QTorrentHandle::file_priority(int index, int priority) const {
|
||||
vector<int> priorities = torrent_handle::file_priorities();
|
||||
if(priorities[index] != priority) {
|
||||
if (priorities[index] != priority) {
|
||||
priorities[index] = priority;
|
||||
prioritize_files(priorities);
|
||||
}
|
||||
}
|
||||
|
||||
void QTorrentHandle::prioritize_files(const vector<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;
|
||||
bool was_seed = is_seed();
|
||||
vector<size_type> progress;
|
||||
@@ -692,25 +692,25 @@ void QTorrentHandle::prioritize_files(const vector<int> &files) const {
|
||||
qDebug() << Q_FUNC_INFO << "Changing files priorities...";
|
||||
torrent_handle::prioritize_files(files);
|
||||
qDebug() << Q_FUNC_INFO << "Moving unwanted files to .unwanted folder...";
|
||||
for(uint i=0; i<files.size(); ++i) {
|
||||
for (uint i=0; i<files.size(); ++i) {
|
||||
// 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);
|
||||
// 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() << "We do not move it to .unwanted folder";
|
||||
continue;
|
||||
}
|
||||
QString old_name = filename_at(i);
|
||||
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");
|
||||
qDebug() << "Unwanted path is" << unwanted_abspath;
|
||||
bool created = QDir().mkpath(unwanted_abspath);
|
||||
#ifdef Q_WS_WIN
|
||||
qDebug() << "unwanted folder was created:" << created;
|
||||
if(created) {
|
||||
if (created) {
|
||||
// Hide the folder on Windows
|
||||
qDebug() << "Hiding folder (Windows)";
|
||||
wstring win_path = unwanted_abspath.replace("/","\\").toStdWString();
|
||||
@@ -721,16 +721,16 @@ void QTorrentHandle::prioritize_files(const vector<int> &files) const {
|
||||
#else
|
||||
Q_UNUSED(created);
|
||||
#endif
|
||||
if(!parent_path.isEmpty() && !parent_path.endsWith("/"))
|
||||
if (!parent_path.isEmpty() && !parent_path.endsWith("/"))
|
||||
parent_path += "/";
|
||||
rename_file(i, parent_path+".unwanted/"+old_name);
|
||||
}
|
||||
}
|
||||
// Move wanted files back to their original folder
|
||||
qDebug() << Q_FUNC_INFO << "Moving wanted files back from .unwanted folder";
|
||||
if(files[i] > 0) {
|
||||
if (files[i] > 0) {
|
||||
QString parent_relpath = misc::branchPath(filepath_at(i));
|
||||
if(QDir(parent_relpath).dirName() == ".unwanted") {
|
||||
if (QDir(parent_relpath).dirName() == ".unwanted") {
|
||||
QString old_name = filename_at(i);
|
||||
QString new_relpath = misc::branchPath(parent_relpath);
|
||||
if (new_relpath.isEmpty())
|
||||
@@ -744,16 +744,16 @@ void QTorrentHandle::prioritize_files(const vector<int> &files) const {
|
||||
}
|
||||
}
|
||||
|
||||
if(was_seed && !is_seed()) {
|
||||
if (was_seed && !is_seed()) {
|
||||
qDebug() << "Torrent is no longer SEEDING";
|
||||
// Save seed status
|
||||
TorrentPersistentData::saveSeedStatus(*this);
|
||||
// Move to temp folder if necessary
|
||||
const Preferences pref;
|
||||
if(pref.isTempPathEnabled()) {
|
||||
if (pref.isTempPathEnabled()) {
|
||||
QString tmp_path = pref.getTempPath();
|
||||
QString root_folder = TorrentPersistentData::getRootFolder(hash());
|
||||
if(!root_folder.isEmpty())
|
||||
if (!root_folder.isEmpty())
|
||||
tmp_path = QDir(tmp_path).absoluteFilePath(root_folder);
|
||||
qDebug() << "tmp folder is enabled, move torrent to " << tmp_path << " from " << save_path();
|
||||
move_storage(tmp_path);
|
||||
@@ -768,7 +768,7 @@ void QTorrentHandle::add_tracker(const announce_entry& url) const {
|
||||
void QTorrentHandle::prioritize_first_last_piece(int file_index, bool b) const {
|
||||
// Determine the priority to set
|
||||
int prio = 7; // MAX
|
||||
if(!b) prio = torrent_handle::file_priority(file_index);
|
||||
if (!b) prio = torrent_handle::file_priority(file_index);
|
||||
file_entry file = get_torrent_info().file_at(file_index);
|
||||
// Determine the first and last piece of the file
|
||||
int piece_size = torrent_handle::get_torrent_info().piece_length();
|
||||
@@ -785,13 +785,13 @@ void QTorrentHandle::prioritize_first_last_piece(int file_index, bool b) const {
|
||||
}
|
||||
|
||||
void QTorrentHandle::prioritize_first_last_piece(bool b) const {
|
||||
if(!has_metadata()) return;
|
||||
if (!has_metadata()) return;
|
||||
// Download first and last pieces first for all media files in the torrent
|
||||
int index = 0;
|
||||
for(index = 0; index < num_files(); ++index) {
|
||||
for (index = 0; index < num_files(); ++index) {
|
||||
const QString path = filepath_at(index);
|
||||
const QString ext = misc::file_extension(path);
|
||||
if(misc::isPreviewable(ext) && torrent_handle::file_priority(index) > 0) {
|
||||
if (misc::isPreviewable(ext) && torrent_handle::file_priority(index) > 0) {
|
||||
qDebug() << "File" << path << "is previewable, toggle downloading of first/last pieces first";
|
||||
prioritize_first_last_piece(index, b);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ TorrentModelItem::TorrentModelItem(const QTorrentHandle &h)
|
||||
m_torrent = h;
|
||||
m_hash = h.hash();
|
||||
m_name = TorrentPersistentData::getName(h.hash());
|
||||
if(m_name.isEmpty()) m_name = h.name();
|
||||
if (m_name.isEmpty()) m_name = h.name();
|
||||
m_addedTime = TorrentPersistentData::getAddedDate(h.hash());
|
||||
m_seedTime = TorrentPersistentData::getSeedDate(h.hash());
|
||||
m_label = TorrentPersistentData::getLabel(h.hash());
|
||||
@@ -51,13 +51,13 @@ TorrentModelItem::State TorrentModelItem::state() const
|
||||
{
|
||||
try {
|
||||
// Pause or Queued
|
||||
if(m_torrent.is_paused()) {
|
||||
if (m_torrent.is_paused()) {
|
||||
m_icon = QIcon(":/Icons/skin/paused.png");
|
||||
m_fgColor = QColor("red");
|
||||
return m_torrent.is_seed() ? STATE_PAUSED_UP : STATE_PAUSED_DL;
|
||||
}
|
||||
if(m_torrent.is_queued()) {
|
||||
if(m_torrent.state() != torrent_status::queued_for_checking
|
||||
if (m_torrent.is_queued()) {
|
||||
if (m_torrent.state() != torrent_status::queued_for_checking
|
||||
&& m_torrent.state() != torrent_status::checking_resume_data
|
||||
&& m_torrent.state() != torrent_status::checking_files) {
|
||||
m_icon = QIcon(":/Icons/skin/queued.png");
|
||||
@@ -70,7 +70,7 @@ TorrentModelItem::State TorrentModelItem::state() const
|
||||
case torrent_status::allocating:
|
||||
case torrent_status::downloading_metadata:
|
||||
case torrent_status::downloading: {
|
||||
if(m_torrent.download_payload_rate() > 0) {
|
||||
if (m_torrent.download_payload_rate() > 0) {
|
||||
m_icon = QIcon(":/Icons/skin/downloading.png");
|
||||
m_fgColor = QColor("green");
|
||||
return STATE_DOWNLOADING;
|
||||
@@ -82,7 +82,7 @@ TorrentModelItem::State TorrentModelItem::state() const
|
||||
}
|
||||
case torrent_status::finished:
|
||||
case torrent_status::seeding:
|
||||
if(m_torrent.upload_payload_rate() > 0) {
|
||||
if (m_torrent.upload_payload_rate() > 0) {
|
||||
m_icon = QIcon(":/Icons/skin/uploading.png");
|
||||
m_fgColor = QColor("orange");
|
||||
return STATE_SEEDING;
|
||||
@@ -112,7 +112,7 @@ TorrentModelItem::State TorrentModelItem::state() const
|
||||
bool TorrentModelItem::setData(int column, const QVariant &value, int role)
|
||||
{
|
||||
qDebug() << Q_FUNC_INFO << column << value;
|
||||
if(role != Qt::DisplayRole) return false;
|
||||
if (role != Qt::DisplayRole) return false;
|
||||
// Label and Name columns can be edited
|
||||
switch(column) {
|
||||
case TR_NAME:
|
||||
@@ -121,7 +121,7 @@ bool TorrentModelItem::setData(int column, const QVariant &value, int role)
|
||||
return true;
|
||||
case TR_LABEL: {
|
||||
QString new_label = value.toString();
|
||||
if(m_label != new_label) {
|
||||
if (m_label != new_label) {
|
||||
QString old_label = m_label;
|
||||
m_label = new_label;
|
||||
TorrentPersistentData::saveLabel(m_torrent.hash(), new_label);
|
||||
@@ -137,13 +137,13 @@ bool TorrentModelItem::setData(int column, const QVariant &value, int role)
|
||||
|
||||
QVariant TorrentModelItem::data(int column, int role) const
|
||||
{
|
||||
if(role == Qt::DecorationRole && column == TR_NAME) {
|
||||
if (role == Qt::DecorationRole && column == TR_NAME) {
|
||||
return m_icon;
|
||||
}
|
||||
if(role == Qt::ForegroundRole) {
|
||||
if (role == Qt::ForegroundRole) {
|
||||
return m_fgColor;
|
||||
}
|
||||
if(role != Qt::DisplayRole && role != Qt::UserRole) return QVariant();
|
||||
if (role != Qt::DisplayRole && role != Qt::UserRole) return QVariant();
|
||||
switch(column) {
|
||||
case TR_NAME:
|
||||
return m_name.isEmpty()? m_torrent.name() : m_name;
|
||||
@@ -167,7 +167,7 @@ QVariant TorrentModelItem::data(int column, int role) const
|
||||
return m_torrent.upload_payload_rate();
|
||||
case TR_ETA: {
|
||||
// XXX: Is this correct?
|
||||
if(m_torrent.is_seed() || m_torrent.is_paused() || m_torrent.is_queued()) return MAX_ETA;
|
||||
if (m_torrent.is_seed() || m_torrent.is_paused() || m_torrent.is_queued()) return MAX_ETA;
|
||||
return QBtSession::instance()->getETA(m_torrent.hash());
|
||||
}
|
||||
case TR_RATIO:
|
||||
@@ -206,7 +206,7 @@ void TorrentModel::populate() {
|
||||
// Load the torrents
|
||||
std::vector<torrent_handle> torrents = QBtSession::instance()->getSession()->get_torrents();
|
||||
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));
|
||||
}
|
||||
// Refresh timer
|
||||
@@ -234,7 +234,7 @@ QVariant TorrentModel::headerData(int section, Qt::Orientation orientation,
|
||||
int role) const
|
||||
{
|
||||
if (orientation == Qt::Horizontal) {
|
||||
if(role == Qt::DisplayRole) {
|
||||
if (role == Qt::DisplayRole) {
|
||||
switch(section) {
|
||||
case TorrentModelItem::TR_NAME: return tr("Name", "i.e: torrent name");
|
||||
case TorrentModelItem::TR_PRIORITY: return "#";
|
||||
@@ -260,7 +260,7 @@ QVariant TorrentModel::headerData(int section, Qt::Orientation orientation,
|
||||
return QVariant();
|
||||
}
|
||||
}
|
||||
if(role == Qt::TextAlignmentRole) {
|
||||
if (role == Qt::TextAlignmentRole) {
|
||||
switch(section) {
|
||||
case TorrentModelItem::TR_PRIORITY:
|
||||
case TorrentModelItem::TR_SIZE:
|
||||
@@ -287,9 +287,9 @@ QVariant TorrentModel::headerData(int section, Qt::Orientation orientation,
|
||||
|
||||
QVariant TorrentModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if(!index.isValid()) return QVariant();
|
||||
if (!index.isValid()) return QVariant();
|
||||
try {
|
||||
if(index.row() >= 0 && index.row() < rowCount() && index.column() >= 0 && index.column() < columnCount())
|
||||
if (index.row() >= 0 && index.row() < rowCount() && index.column() >= 0 && index.column() < columnCount())
|
||||
return m_torrents[index.row()]->data(index.column(), role);
|
||||
} catch(invalid_handle&) {}
|
||||
return QVariant();
|
||||
@@ -298,12 +298,12 @@ QVariant TorrentModel::data(const QModelIndex &index, int role) const
|
||||
bool TorrentModel::setData(const QModelIndex &index, const QVariant &value, int role)
|
||||
{
|
||||
qDebug() << Q_FUNC_INFO << value;
|
||||
if(!index.isValid() || role != Qt::DisplayRole) return false;
|
||||
if (!index.isValid() || role != Qt::DisplayRole) return false;
|
||||
qDebug("Index is valid and role is DisplayRole");
|
||||
try {
|
||||
if(index.row() >= 0 && index.row() < rowCount() && index.column() >= 0 && index.column() < columnCount()) {
|
||||
if (index.row() >= 0 && index.row() < rowCount() && index.column() >= 0 && index.column() < columnCount()) {
|
||||
bool change = m_torrents[index.row()]->setData(index.column(), value, role);
|
||||
if(change)
|
||||
if (change)
|
||||
notifyTorrentChanged(index.row());
|
||||
return change;
|
||||
}
|
||||
@@ -315,8 +315,8 @@ int TorrentModel::torrentRow(const QString &hash) const
|
||||
{
|
||||
QList<TorrentModelItem*>::const_iterator it;
|
||||
int row = 0;
|
||||
for(it = m_torrents.constBegin(); it != m_torrents.constEnd(); it++) {
|
||||
if((*it)->hash() == hash) return row;
|
||||
for (it = m_torrents.constBegin(); it != m_torrents.constEnd(); it++) {
|
||||
if ((*it)->hash() == hash) return row;
|
||||
++row;
|
||||
}
|
||||
return -1;
|
||||
@@ -324,7 +324,7 @@ int TorrentModel::torrentRow(const QString &hash) const
|
||||
|
||||
void TorrentModel::addTorrent(const QTorrentHandle &h)
|
||||
{
|
||||
if(torrentRow(h.hash()) < 0) {
|
||||
if (torrentRow(h.hash()) < 0) {
|
||||
beginInsertTorrent(m_torrents.size());
|
||||
TorrentModelItem *item = new TorrentModelItem(h);
|
||||
connect(item, SIGNAL(labelChanged(QString,QString)), SLOT(handleTorrentLabelChange(QString,QString)));
|
||||
@@ -338,7 +338,7 @@ void TorrentModel::removeTorrent(const QString &hash)
|
||||
{
|
||||
const int row = torrentRow(hash);
|
||||
qDebug() << Q_FUNC_INFO << hash << row;
|
||||
if(row >= 0) {
|
||||
if (row >= 0) {
|
||||
beginRemoveTorrent(row);
|
||||
m_torrents.removeAt(row);
|
||||
endRemoveTorrent();
|
||||
@@ -368,7 +368,7 @@ void TorrentModel::endRemoveTorrent()
|
||||
void TorrentModel::handleTorrentUpdate(const QTorrentHandle &h)
|
||||
{
|
||||
const int row = torrentRow(h.hash());
|
||||
if(row >= 0) {
|
||||
if (row >= 0) {
|
||||
notifyTorrentChanged(row);
|
||||
}
|
||||
}
|
||||
@@ -380,7 +380,7 @@ void TorrentModel::notifyTorrentChanged(int row)
|
||||
|
||||
void TorrentModel::setRefreshInterval(int refreshInterval)
|
||||
{
|
||||
if(m_refreshInterval != refreshInterval) {
|
||||
if (m_refreshInterval != refreshInterval) {
|
||||
m_refreshInterval = refreshInterval;
|
||||
m_refreshTimer.stop();
|
||||
m_refreshTimer.start(m_refreshInterval);
|
||||
@@ -396,7 +396,7 @@ TorrentStatusReport TorrentModel::getTorrentStatusReport() const
|
||||
{
|
||||
TorrentStatusReport report;
|
||||
QList<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()) {
|
||||
case TorrentModelItem::STATE_DOWNLOADING:
|
||||
++report.nb_active;
|
||||
@@ -446,7 +446,7 @@ void TorrentModel::handleTorrentLabelChange(QString previous, QString current)
|
||||
|
||||
QString TorrentModel::torrentHash(int row) const
|
||||
{
|
||||
if(row >= 0 && row < rowCount())
|
||||
if (row >= 0 && row < rowCount())
|
||||
return m_torrents.at(row)->hash();
|
||||
return QString();
|
||||
}
|
||||
@@ -454,7 +454,7 @@ QString TorrentModel::torrentHash(int row) const
|
||||
void TorrentModel::handleTorrentAboutToBeRemoved(const QTorrentHandle &h)
|
||||
{
|
||||
const int row = torrentRow(h.hash());
|
||||
if(row >= 0) {
|
||||
if (row >= 0) {
|
||||
emit torrentAboutToBeRemoved(m_torrents.at(row));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,13 +79,13 @@ void TorrentSpeedMonitor::run()
|
||||
void SpeedSample::addSample(int s)
|
||||
{
|
||||
m_speedSamples << s;
|
||||
if(m_speedSamples.size() > max_samples)
|
||||
if (m_speedSamples.size() > max_samples)
|
||||
m_speedSamples.removeFirst();
|
||||
}
|
||||
|
||||
qreal SpeedSample::average() const
|
||||
{
|
||||
if(m_speedSamples.empty()) return 0;
|
||||
if (m_speedSamples.empty()) return 0;
|
||||
qlonglong sum = 0;
|
||||
foreach (int s, m_speedSamples) {
|
||||
sum += s;
|
||||
@@ -113,9 +113,9 @@ qlonglong TorrentSpeedMonitor::getETA(const QString &hash) const
|
||||
{
|
||||
QMutexLocker locker(&m_mutex);
|
||||
QTorrentHandle h = m_session->getTorrentHandle(hash);
|
||||
if(h.is_paused() || !m_samples.contains(hash)) return -1;
|
||||
if (h.is_paused() || !m_samples.contains(hash)) return -1;
|
||||
const qreal speed_average = m_samples.value(hash).average();
|
||||
if(speed_average == 0) return -1;
|
||||
if (speed_average == 0) return -1;
|
||||
return (h.total_wanted() - h.total_done()) / speed_average;
|
||||
}
|
||||
|
||||
@@ -123,14 +123,14 @@ void TorrentSpeedMonitor::getSamples()
|
||||
{
|
||||
const std::vector<torrent_handle> torrents = m_session->getSession()->get_torrents();
|
||||
std::vector<torrent_handle>::const_iterator it;
|
||||
for(it = torrents.begin(); it != torrents.end(); it++) {
|
||||
for (it = torrents.begin(); it != torrents.end(); it++) {
|
||||
try {
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
torrent_status st = it->status(0x0);
|
||||
if(!st.paused)
|
||||
if (!st.paused)
|
||||
m_samples[misc::toQString(it->info_hash())].addSample(st.download_payload_rate);
|
||||
#else
|
||||
if(!it->is_paused())
|
||||
if (!it->is_paused())
|
||||
m_samples[misc::toQString(it->info_hash())].addSample(it->status().download_payload_rate);
|
||||
#endif
|
||||
} catch(invalid_handle&){}
|
||||
|
||||
@@ -148,7 +148,7 @@ bool QtLocalPeer::sendMessage(const QString &message, int timeout)
|
||||
|
||||
QLocalSocket socket;
|
||||
bool connOk = false;
|
||||
for(int i = 0; i < 2; i++) {
|
||||
for (int i = 0; i < 2; i++) {
|
||||
// Try twice, in case the other instance is just starting up
|
||||
socket.connectToServer(socketName);
|
||||
connOk = socket.waitForConnected(timeout/2);
|
||||
|
||||
@@ -64,7 +64,7 @@ public:
|
||||
const QString ip_str = misc::toQString(ip.address().to_string(ec));
|
||||
if (ec) return QString();
|
||||
QString ret;
|
||||
if(m_cache.contains(ip_str)) {
|
||||
if (m_cache.contains(ip_str)) {
|
||||
qDebug("Got host name from cache");
|
||||
ret = *m_cache.object(ip_str);
|
||||
} else {
|
||||
@@ -77,7 +77,7 @@ public:
|
||||
boost::system::error_code ec;
|
||||
const QString ip_str = misc::toQString(ip.address().to_string(ec));
|
||||
if (ec) return;
|
||||
if(m_cache.contains(ip_str)) {
|
||||
if (m_cache.contains(ip_str)) {
|
||||
qDebug("Resolved host name using cache");
|
||||
emit ip_resolved(ip_str, *m_cache.object(ip_str));
|
||||
return;
|
||||
@@ -93,9 +93,9 @@ private slots:
|
||||
void hostResolved(const QHostInfo& host) {
|
||||
if (host.error() == QHostInfo::NoError) {
|
||||
const QString hostname = host.hostName();
|
||||
if(host.addresses().isEmpty() || hostname.isEmpty()) return;
|
||||
if (host.addresses().isEmpty() || hostname.isEmpty()) return;
|
||||
const QString ip = host.addresses().first().toString();
|
||||
if(hostname != ip) {
|
||||
if (hostname != ip) {
|
||||
//qDebug() << Q_FUNC_INFO << ip << QString("->") << hostname;
|
||||
m_cache.insert(ip, new QString(hostname));
|
||||
emit ip_resolved(ip, hostname);
|
||||
|
||||
@@ -122,19 +122,19 @@ void AutomatedRssDownloader::saveSettings()
|
||||
void AutomatedRssDownloader::loadRulesList()
|
||||
{
|
||||
// Make sure we save the current item before clearing
|
||||
if(m_editedRule) {
|
||||
if (m_editedRule) {
|
||||
saveEditedRule();
|
||||
}
|
||||
ui->listRules->clear();
|
||||
foreach (const QString &rule_name, m_ruleList->ruleNames()) {
|
||||
QListWidgetItem *item = new QListWidgetItem(rule_name, ui->listRules);
|
||||
item->setFlags(item->flags()|Qt::ItemIsUserCheckable);
|
||||
if(m_ruleList->getRule(rule_name)->isEnabled())
|
||||
if (m_ruleList->getRule(rule_name)->isEnabled())
|
||||
item->setCheckState(Qt::Checked);
|
||||
else
|
||||
item->setCheckState(Qt::Unchecked);
|
||||
}
|
||||
if(ui->listRules->count() > 0 && !ui->listRules->currentItem())
|
||||
if (ui->listRules->count() > 0 && !ui->listRules->currentItem())
|
||||
ui->listRules->setCurrentRow(0);
|
||||
}
|
||||
|
||||
@@ -144,11 +144,11 @@ void AutomatedRssDownloader::loadFeedList()
|
||||
const QStringList feed_aliases = settings.getRssFeedsAliases();
|
||||
const QStringList feed_urls = settings.getRssFeedsUrls();
|
||||
QStringList existing_urls;
|
||||
for(int i=0; i<feed_aliases.size(); ++i) {
|
||||
for (int i=0; i<feed_aliases.size(); ++i) {
|
||||
QString feed_url = feed_urls.at(i);
|
||||
feed_url = feed_url.split("\\").last();
|
||||
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);
|
||||
item->setData(Qt::UserRole, feed_url);
|
||||
item->setFlags(item->flags()|Qt::ItemIsUserCheckable);
|
||||
@@ -159,18 +159,18 @@ void AutomatedRssDownloader::loadFeedList()
|
||||
void AutomatedRssDownloader::updateFeedList()
|
||||
{
|
||||
disconnect(ui->listFeeds, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(handleFeedCheckStateChange(QListWidgetItem*)));
|
||||
for(int i=0; i<ui->listFeeds->count(); ++i) {
|
||||
for (int i=0; i<ui->listFeeds->count(); ++i) {
|
||||
QListWidgetItem *item = ui->listFeeds->item(i);
|
||||
const QString feed_url = item->data(Qt::UserRole).toString();
|
||||
bool all_enabled = false;
|
||||
foreach(const QListWidgetItem *ruleItem, ui->listRules->selectedItems()) {
|
||||
foreach (const QListWidgetItem *ruleItem, ui->listRules->selectedItems()) {
|
||||
RssDownloadRulePtr rule = m_ruleList->getRule(ruleItem->text());
|
||||
if(!rule) continue;
|
||||
if (!rule) continue;
|
||||
qDebug() << "Rule" << rule->name() << "affects" << rule->rssFeeds().size() << "feeds.";
|
||||
foreach(QString test, rule->rssFeeds()) {
|
||||
foreach (QString test, rule->rssFeeds()) {
|
||||
qDebug() << "Feed is " << test;
|
||||
}
|
||||
if(rule->rssFeeds().contains(feed_url)) {
|
||||
if (rule->rssFeeds().contains(feed_url)) {
|
||||
qDebug() << "Rule " << rule->name() << " affects feed " << feed_url;
|
||||
all_enabled = true;
|
||||
} else {
|
||||
@@ -179,7 +179,7 @@ void AutomatedRssDownloader::updateFeedList()
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(all_enabled)
|
||||
if (all_enabled)
|
||||
item->setCheckState(Qt::Checked);
|
||||
else
|
||||
item->setCheckState(Qt::Unchecked);
|
||||
@@ -201,7 +201,7 @@ void AutomatedRssDownloader::updateRuleDefinitionBox()
|
||||
saveEditedRule();
|
||||
// Update rule definition box
|
||||
const QList<QListWidgetItem*> selection = ui->listRules->selectedItems();
|
||||
if(selection.count() == 1) {
|
||||
if (selection.count() == 1) {
|
||||
m_editedRule = selection.first();
|
||||
RssDownloadRulePtr rule = getCurrentRule();
|
||||
if (rule) {
|
||||
@@ -250,7 +250,7 @@ void AutomatedRssDownloader::clearRuleDefinitionBox()
|
||||
RssDownloadRulePtr AutomatedRssDownloader::getCurrentRule() const
|
||||
{
|
||||
QListWidgetItem * current_item = ui->listRules->currentItem();
|
||||
if(current_item)
|
||||
if (current_item)
|
||||
return m_ruleList->getRule(current_item->text());
|
||||
return RssDownloadRulePtr();
|
||||
}
|
||||
@@ -259,16 +259,16 @@ void AutomatedRssDownloader::initLabelCombobox()
|
||||
{
|
||||
// Load custom labels
|
||||
const QStringList customLabels = Preferences().getTorrentLabels();
|
||||
foreach(const QString& label, customLabels) {
|
||||
foreach (const QString& label, customLabels) {
|
||||
ui->comboLabel->addItem(label);
|
||||
}
|
||||
}
|
||||
|
||||
void AutomatedRssDownloader::saveEditedRule()
|
||||
{
|
||||
if(!m_editedRule) return;
|
||||
if (!m_editedRule) return;
|
||||
qDebug() << Q_FUNC_INFO << m_editedRule;
|
||||
if(ui->listRules->findItems(m_editedRule->text(), Qt::MatchExactly).isEmpty()) {
|
||||
if (ui->listRules->findItems(m_editedRule->text(), Qt::MatchExactly).isEmpty()) {
|
||||
qDebug() << "Could not find rule" << m_editedRule->text() << "in the UI list";
|
||||
qDebug() << "Probably removed the item, no need to save it";
|
||||
return;
|
||||
@@ -284,13 +284,13 @@ void AutomatedRssDownloader::saveEditedRule()
|
||||
rule->setUseRegex(ui->checkRegex->isChecked());
|
||||
rule->setMustContain(ui->lineContains->text());
|
||||
rule->setMustNotContain(ui->lineNotContains->text());
|
||||
if(ui->saveDiffDir_check->isChecked())
|
||||
if (ui->saveDiffDir_check->isChecked())
|
||||
rule->setSavePath(ui->lineSavePath->text());
|
||||
else
|
||||
rule->setSavePath("");
|
||||
rule->setLabel(ui->comboLabel->currentText());
|
||||
// Save new label
|
||||
if(!rule->label().isEmpty())
|
||||
if (!rule->label().isEmpty())
|
||||
Preferences().addTorrentLabel(rule->label());
|
||||
//rule->setRssFeeds(getSelectedFeeds());
|
||||
// Save it
|
||||
@@ -302,9 +302,9 @@ void AutomatedRssDownloader::on_addRuleBtn_clicked()
|
||||
{
|
||||
// Ask for a rule name
|
||||
const QString rule_name = QInputDialog::getText(this, tr("New rule name"), tr("Please type the name of the new download rule->"));
|
||||
if(rule_name.isEmpty()) return;
|
||||
if (rule_name.isEmpty()) return;
|
||||
// Check if this rule name already exists
|
||||
if(m_ruleList->getRule(rule_name)) {
|
||||
if (m_ruleList->getRule(rule_name)) {
|
||||
QMessageBox::warning(this, tr("Rule name conflict"), tr("A rule with this name already exists, please choose another name."));
|
||||
return;
|
||||
}
|
||||
@@ -319,16 +319,16 @@ void AutomatedRssDownloader::on_addRuleBtn_clicked()
|
||||
void AutomatedRssDownloader::on_removeRuleBtn_clicked()
|
||||
{
|
||||
const QList<QListWidgetItem*> selection = ui->listRules->selectedItems();
|
||||
if(selection.isEmpty()) return;
|
||||
if (selection.isEmpty()) return;
|
||||
// Ask for confirmation
|
||||
QString confirm_text;
|
||||
if(selection.count() == 1)
|
||||
if (selection.count() == 1)
|
||||
confirm_text = tr("Are you sure you want to remove the download rule named %1?").arg(selection.first()->text());
|
||||
else
|
||||
confirm_text = tr("Are you sure you want to remove the selected download rules?");
|
||||
if(QMessageBox::question(this, tr("Rule deletion confirmation"), confirm_text, QMessageBox::Yes, QMessageBox::No) != QMessageBox::Yes)
|
||||
if (QMessageBox::question(this, tr("Rule deletion confirmation"), confirm_text, QMessageBox::Yes, QMessageBox::No) != QMessageBox::Yes)
|
||||
return;
|
||||
foreach(QListWidgetItem *item, selection) {
|
||||
foreach (QListWidgetItem *item, selection) {
|
||||
// Actually remove the item
|
||||
ui->listRules->removeItemWidget(item);
|
||||
const QString rule_name = item->text();
|
||||
@@ -343,22 +343,22 @@ void AutomatedRssDownloader::on_removeRuleBtn_clicked()
|
||||
void AutomatedRssDownloader::on_browseSP_clicked()
|
||||
{
|
||||
QString save_path = QFileDialog::getExistingDirectory(this, tr("Destination directory"), QDir::homePath());
|
||||
if(!save_path.isEmpty())
|
||||
if (!save_path.isEmpty())
|
||||
ui->lineSavePath->setText(save_path);
|
||||
}
|
||||
|
||||
void AutomatedRssDownloader::on_exportBtn_clicked()
|
||||
{
|
||||
if(m_ruleList->isEmpty()) {
|
||||
if (m_ruleList->isEmpty()) {
|
||||
QMessageBox::warning(this, tr("Invalid action"), tr("The list is empty, there is nothing to export."));
|
||||
return;
|
||||
}
|
||||
// Ask for a save path
|
||||
QString save_path = QFileDialog::getSaveFileName(this, tr("Where would you like to save the list?"), QDir::homePath(), tr("Rules list (*.rssrules)"));
|
||||
if(save_path.isEmpty()) return;
|
||||
if(!save_path.endsWith(".rssrules", Qt::CaseInsensitive))
|
||||
if (save_path.isEmpty()) return;
|
||||
if (!save_path.endsWith(".rssrules", Qt::CaseInsensitive))
|
||||
save_path += ".rssrules";
|
||||
if(!m_ruleList->serialize(save_path)) {
|
||||
if (!m_ruleList->serialize(save_path)) {
|
||||
QMessageBox::warning(this, tr("I/O Error"), tr("Failed to create the destination file"));
|
||||
return;
|
||||
}
|
||||
@@ -368,9 +368,9 @@ void AutomatedRssDownloader::on_importBtn_clicked()
|
||||
{
|
||||
// Ask for filter path
|
||||
QString load_path = QFileDialog::getOpenFileName(this, tr("Please point to the RSS download rules file"), QDir::homePath(), tr("Rules list (*.rssrules *.filters)"));
|
||||
if(load_path.isEmpty() || !QFile::exists(load_path)) return;
|
||||
if (load_path.isEmpty() || !QFile::exists(load_path)) return;
|
||||
// Load it
|
||||
if(!m_ruleList->unserialize(load_path)) {
|
||||
if (!m_ruleList->unserialize(load_path)) {
|
||||
QMessageBox::warning(this, tr("Import Error"), tr("Failed to import the selected rules file"));
|
||||
return;
|
||||
}
|
||||
@@ -386,8 +386,8 @@ void AutomatedRssDownloader::displayRulesListMenu(const QPoint &pos)
|
||||
QAction *delAct = 0;
|
||||
QAction *renameAct = 0;
|
||||
const QList<QListWidgetItem*> selection = ui->listRules->selectedItems();
|
||||
if(!selection.isEmpty()) {
|
||||
if(selection.count() == 1) {
|
||||
if (!selection.isEmpty()) {
|
||||
if (selection.count() == 1) {
|
||||
delAct = menu.addAction(IconProvider::instance()->getIcon("list-remove"), tr("Delete rule"));
|
||||
menu.addSeparator();
|
||||
renameAct = menu.addAction(IconProvider::instance()->getIcon("edit-rename"), tr("Rename rule->.."));
|
||||
@@ -396,16 +396,16 @@ void AutomatedRssDownloader::displayRulesListMenu(const QPoint &pos)
|
||||
}
|
||||
}
|
||||
QAction *act = menu.exec(QCursor::pos());
|
||||
if(!act) return;
|
||||
if(act == addAct) {
|
||||
if (!act) return;
|
||||
if (act == addAct) {
|
||||
on_addRuleBtn_clicked();
|
||||
return;
|
||||
}
|
||||
if(act == delAct) {
|
||||
if (act == delAct) {
|
||||
on_removeRuleBtn_clicked();
|
||||
return;
|
||||
}
|
||||
if(act == renameAct) {
|
||||
if (act == renameAct) {
|
||||
renameSelectedRule();
|
||||
return;
|
||||
}
|
||||
@@ -414,12 +414,12 @@ void AutomatedRssDownloader::displayRulesListMenu(const QPoint &pos)
|
||||
void AutomatedRssDownloader::renameSelectedRule()
|
||||
{
|
||||
QListWidgetItem *item = ui->listRules->currentItem();
|
||||
if(!item) return;
|
||||
if (!item) return;
|
||||
forever {
|
||||
QString new_name = QInputDialog::getText(this, tr("Rule renaming"), tr("Please type the new rule name"), QLineEdit::Normal, item->text());
|
||||
new_name = new_name.trimmed();
|
||||
if(new_name.isEmpty()) return;
|
||||
if(m_ruleList->ruleNames().contains(new_name, Qt::CaseInsensitive)) {
|
||||
if (new_name.isEmpty()) return;
|
||||
if (m_ruleList->ruleNames().contains(new_name, Qt::CaseInsensitive)) {
|
||||
QMessageBox::warning(this, tr("Rule name conflict"), tr("A rule with this name already exists, please choose another name."));
|
||||
} else {
|
||||
// Rename the rule
|
||||
@@ -432,7 +432,7 @@ void AutomatedRssDownloader::renameSelectedRule()
|
||||
|
||||
void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feed_item)
|
||||
{
|
||||
if(ui->ruleDefBox->isEnabled()) {
|
||||
if (ui->ruleDefBox->isEnabled()) {
|
||||
// Make sure the current rule is saved
|
||||
saveEditedRule();
|
||||
}
|
||||
@@ -441,15 +441,15 @@ void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feed_it
|
||||
RssDownloadRulePtr rule = m_ruleList->getRule(rule_item->text());
|
||||
Q_ASSERT(rule);
|
||||
QStringList affected_feeds = rule->rssFeeds();
|
||||
if(feed_item->checkState() == Qt::Checked) {
|
||||
if(!affected_feeds.contains(feed_url))
|
||||
if (feed_item->checkState() == Qt::Checked) {
|
||||
if (!affected_feeds.contains(feed_url))
|
||||
affected_feeds << feed_url;
|
||||
} else {
|
||||
if(affected_feeds.contains(feed_url))
|
||||
if (affected_feeds.contains(feed_url))
|
||||
affected_feeds.removeOne(feed_url);
|
||||
}
|
||||
// Save the updated rule
|
||||
if(affected_feeds.size() != rule->rssFeeds().size()) {
|
||||
if (affected_feeds.size() != rule->rssFeeds().size()) {
|
||||
rule->setRssFeeds(affected_feeds);
|
||||
m_ruleList->saveRule(rule);
|
||||
}
|
||||
@@ -461,7 +461,7 @@ void AutomatedRssDownloader::handleFeedCheckStateChange(QListWidgetItem *feed_it
|
||||
void AutomatedRssDownloader::updateMatchingArticles()
|
||||
{
|
||||
ui->treeMatchingArticles->clear();
|
||||
if(ui->ruleDefBox->isEnabled()) {
|
||||
if (ui->ruleDefBox->isEnabled()) {
|
||||
saveEditedRule();
|
||||
}
|
||||
RssManagerPtr manager = m_manager.toStrongRef();
|
||||
@@ -469,17 +469,17 @@ void AutomatedRssDownloader::updateMatchingArticles()
|
||||
return;
|
||||
const QHash<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());
|
||||
if(!rule) continue;
|
||||
foreach(const QString &feed_url, rule->rssFeeds()) {
|
||||
if (!rule) continue;
|
||||
foreach (const QString &feed_url, rule->rssFeeds()) {
|
||||
qDebug() << Q_FUNC_INFO << feed_url;
|
||||
if(!all_feeds.contains(feed_url)) continue; // Feed was removed
|
||||
if (!all_feeds.contains(feed_url)) continue; // Feed was removed
|
||||
RssFeedPtr feed = all_feeds.value(feed_url);
|
||||
Q_ASSERT(feed);
|
||||
if(!feed) continue;
|
||||
if (!feed) continue;
|
||||
const QStringList matching_articles = rule->findMatchingArticles(feed);
|
||||
if(!matching_articles.isEmpty())
|
||||
if (!matching_articles.isEmpty())
|
||||
addFeedArticlesToTree(feed, matching_articles);
|
||||
}
|
||||
}
|
||||
@@ -489,15 +489,15 @@ void AutomatedRssDownloader::addFeedArticlesToTree(const RssFeedPtr& feed, const
|
||||
{
|
||||
// Check if this feed is already in the tree
|
||||
QTreeWidgetItem *treeFeedItem = 0;
|
||||
for(int i=0; i<ui->treeMatchingArticles->topLevelItemCount(); ++i) {
|
||||
for (int i=0; i<ui->treeMatchingArticles->topLevelItemCount(); ++i) {
|
||||
QTreeWidgetItem *item = ui->treeMatchingArticles->topLevelItem(i);
|
||||
if(item->data(0, Qt::UserRole).toString() == feed->url()) {
|
||||
if (item->data(0, Qt::UserRole).toString() == feed->url()) {
|
||||
treeFeedItem = item;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// If there is none, create it
|
||||
if(!treeFeedItem) {
|
||||
if (!treeFeedItem) {
|
||||
treeFeedItem = new QTreeWidgetItem(QStringList() << feed->displayName());
|
||||
treeFeedItem->setToolTip(0, feed->displayName());
|
||||
QFont f = treeFeedItem->font(0);
|
||||
@@ -508,7 +508,7 @@ void AutomatedRssDownloader::addFeedArticlesToTree(const RssFeedPtr& feed, const
|
||||
ui->treeMatchingArticles->addTopLevelItem(treeFeedItem);
|
||||
}
|
||||
// Insert the articles
|
||||
foreach(const QString &art, articles) {
|
||||
foreach (const QString &art, articles) {
|
||||
QTreeWidgetItem *item = new QTreeWidgetItem(QStringList() << art);
|
||||
item->setToolTip(0, art);
|
||||
treeFeedItem->addChild(item);
|
||||
@@ -519,7 +519,7 @@ void AutomatedRssDownloader::addFeedArticlesToTree(const RssFeedPtr& feed, const
|
||||
void AutomatedRssDownloader::updateFieldsToolTips(bool regex)
|
||||
{
|
||||
QString tip;
|
||||
if(regex) {
|
||||
if (regex) {
|
||||
tip = tr("Regex mode: use Perl-like regular expressions");
|
||||
ui->lineContains->setToolTip(tip);
|
||||
ui->lineNotContains->setToolTip(tip);
|
||||
@@ -536,18 +536,18 @@ void AutomatedRssDownloader::updateMustLineValidity()
|
||||
const QString text = ui->lineContains->text();
|
||||
bool valid = true;
|
||||
QStringList tokens;
|
||||
if(ui->checkRegex->isChecked())
|
||||
if (ui->checkRegex->isChecked())
|
||||
tokens << text;
|
||||
else
|
||||
tokens << text.split(" ");
|
||||
foreach(const QString &token, tokens) {
|
||||
foreach (const QString &token, tokens) {
|
||||
QRegExp reg(token, Qt::CaseInsensitive, ui->checkRegex->isChecked() ? QRegExp::RegExp : QRegExp::Wildcard);
|
||||
if(!reg.isValid()) {
|
||||
if (!reg.isValid()) {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(valid) {
|
||||
if (valid) {
|
||||
ui->lineContains->setStyleSheet("");
|
||||
ui->lbl_must_stat->setPixmap(QPixmap());
|
||||
} else {
|
||||
@@ -561,18 +561,18 @@ void AutomatedRssDownloader::updateMustNotLineValidity()
|
||||
const QString text = ui->lineNotContains->text();
|
||||
bool valid = true;
|
||||
QStringList tokens;
|
||||
if(ui->checkRegex->isChecked())
|
||||
if (ui->checkRegex->isChecked())
|
||||
tokens << text;
|
||||
else
|
||||
tokens << text.split(QRegExp("[\\s|]"));
|
||||
foreach(const QString &token, tokens) {
|
||||
foreach (const QString &token, tokens) {
|
||||
QRegExp reg(token, Qt::CaseInsensitive, ui->checkRegex->isChecked() ? QRegExp::RegExp : QRegExp::Wildcard);
|
||||
if(!reg.isValid()) {
|
||||
if (!reg.isValid()) {
|
||||
valid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(valid) {
|
||||
if (valid) {
|
||||
ui->lineNotContains->setStyleSheet("");
|
||||
ui->lbl_mustnot_stat->setPixmap(QPixmap());
|
||||
} else {
|
||||
|
||||
@@ -46,9 +46,9 @@ CookiesDlg::CookiesDlg(QWidget *parent, const QList<QByteArray> &raw_cookies) :
|
||||
ui->del_btn->setIcon(IconProvider::instance()->getIcon("list-remove"));
|
||||
|
||||
ui->infos_lbl->setText(tr("Common keys for cookies are : '%1', '%2'.\nYou should get this information from your Web browser preferences.").arg("uid").arg("pass"));
|
||||
foreach(const QByteArray &raw_cookie, raw_cookies) {
|
||||
foreach (const QByteArray &raw_cookie, raw_cookies) {
|
||||
QList<QByteArray> cookie_parts = raw_cookie.split('=');
|
||||
if(cookie_parts.size() != 2) continue;
|
||||
if (cookie_parts.size() != 2) continue;
|
||||
const int i = ui->cookiesTable->rowCount();
|
||||
ui->cookiesTable->setRowCount(i+1);
|
||||
ui->cookiesTable->setItem(i, COOKIE_KEY, new QTableWidgetItem(cookie_parts.first().data()));
|
||||
@@ -70,21 +70,21 @@ void CookiesDlg::on_add_btn_clicked() {
|
||||
void CookiesDlg::on_del_btn_clicked() {
|
||||
// Get selected cookie
|
||||
QList<QTableWidgetItem*> selection = ui->cookiesTable->selectedItems();
|
||||
if(!selection.isEmpty()) {
|
||||
if (!selection.isEmpty()) {
|
||||
ui->cookiesTable->removeRow(selection.first()->row());
|
||||
}
|
||||
}
|
||||
|
||||
QList<QByteArray> CookiesDlg::getCookies() const {
|
||||
QList<QByteArray> ret;
|
||||
for(int i=0; i<ui->cookiesTable->rowCount(); ++i) {
|
||||
for (int i=0; i<ui->cookiesTable->rowCount(); ++i) {
|
||||
QString key;
|
||||
if(ui->cookiesTable->item(i, COOKIE_KEY))
|
||||
if (ui->cookiesTable->item(i, COOKIE_KEY))
|
||||
key = ui->cookiesTable->item(i, COOKIE_KEY)->text().trimmed();
|
||||
QString value;
|
||||
if(ui->cookiesTable->item(i, COOKIE_VALUE))
|
||||
if (ui->cookiesTable->item(i, COOKIE_VALUE))
|
||||
value = ui->cookiesTable->item(i, COOKIE_VALUE)->text().trimmed();
|
||||
if(!key.isEmpty() && !value.isEmpty()) {
|
||||
if (!key.isEmpty() && !value.isEmpty()) {
|
||||
const QString raw_cookie = key+"="+value;
|
||||
qDebug("Cookie: %s", qPrintable(raw_cookie));
|
||||
ret << raw_cookie.toLocal8Bit();
|
||||
@@ -95,7 +95,7 @@ QList<QByteArray> CookiesDlg::getCookies() const {
|
||||
|
||||
QList<QByteArray> CookiesDlg::askForCookies(QWidget *parent, const QList<QByteArray> &raw_cookies, bool *ok) {
|
||||
CookiesDlg dlg(parent, raw_cookies);
|
||||
if(dlg.exec()) {
|
||||
if (dlg.exec()) {
|
||||
*ok = true;
|
||||
return dlg.getCookies();
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ void FeedListWidget::itemAboutToBeRemoved(QTreeWidgetItem *item) {
|
||||
m_feedsItems.remove(feed->id());
|
||||
} if (RssFolderPtr folder = qSharedPointerDynamicCast<RssFolder>(file)) {
|
||||
RssFeedList feeds = folder->getAllFeeds();
|
||||
foreach(const RssFeedPtr& feed, feeds) {
|
||||
foreach (const RssFeedPtr& feed, feeds) {
|
||||
m_feedsItems.remove(feed->id());
|
||||
}
|
||||
}
|
||||
@@ -84,8 +84,8 @@ QTreeWidgetItem* FeedListWidget::stickyUnreadItem() const {
|
||||
|
||||
QStringList FeedListWidget::getItemPath(QTreeWidgetItem* item) const {
|
||||
QStringList path;
|
||||
if(item) {
|
||||
if(item->parent())
|
||||
if (item) {
|
||||
if (item->parent())
|
||||
path << getItemPath(item->parent());
|
||||
path.append(getRSSItem(item)->id());
|
||||
}
|
||||
@@ -95,19 +95,19 @@ QStringList FeedListWidget::getItemPath(QTreeWidgetItem* item) const {
|
||||
QList<QTreeWidgetItem*> FeedListWidget::getAllOpenFolders(QTreeWidgetItem *parent) const {
|
||||
QList<QTreeWidgetItem*> open_folders;
|
||||
int nbChildren;
|
||||
if(parent)
|
||||
if (parent)
|
||||
nbChildren = parent->childCount();
|
||||
else
|
||||
nbChildren = topLevelItemCount();
|
||||
for(int i=0; i<nbChildren; ++i) {
|
||||
for (int i=0; i<nbChildren; ++i) {
|
||||
QTreeWidgetItem *item;
|
||||
if(parent)
|
||||
if (parent)
|
||||
item = parent->child(i);
|
||||
else
|
||||
item = topLevelItem(i);
|
||||
if(isFolder(item) && item->isExpanded()) {
|
||||
if (isFolder(item) && item->isExpanded()) {
|
||||
QList<QTreeWidgetItem*> open_subfolders = getAllOpenFolders(item);
|
||||
if(!open_subfolders.empty()) {
|
||||
if (!open_subfolders.empty()) {
|
||||
open_folders << open_subfolders;
|
||||
} else {
|
||||
open_folders << item;
|
||||
@@ -120,9 +120,9 @@ QList<QTreeWidgetItem*> FeedListWidget::getAllOpenFolders(QTreeWidgetItem *paren
|
||||
QList<QTreeWidgetItem*> FeedListWidget::getAllFeedItems(QTreeWidgetItem* folder) {
|
||||
QList<QTreeWidgetItem*> feeds;
|
||||
const int nbChildren = folder->childCount();
|
||||
for(int i=0; i<nbChildren; ++i) {
|
||||
for (int i=0; i<nbChildren; ++i) {
|
||||
QTreeWidgetItem *item = folder->child(i);
|
||||
if(isFeed(item)) {
|
||||
if (isFeed(item)) {
|
||||
feeds << item;
|
||||
} else {
|
||||
feeds << getAllFeedItems(item);
|
||||
@@ -166,21 +166,21 @@ QTreeWidgetItem* FeedListWidget::currentFeed() const {
|
||||
}
|
||||
|
||||
void FeedListWidget::updateCurrentFeed(QTreeWidgetItem* new_item) {
|
||||
if(!new_item) return;
|
||||
if(!m_rssMapping.contains(new_item)) return;
|
||||
if(isFeed(new_item) || new_item == m_unreadStickyItem)
|
||||
if (!new_item) return;
|
||||
if (!m_rssMapping.contains(new_item)) return;
|
||||
if (isFeed(new_item) || new_item == m_unreadStickyItem)
|
||||
m_currentFeed = new_item;
|
||||
}
|
||||
|
||||
void FeedListWidget::dragMoveEvent(QDragMoveEvent * event) {
|
||||
QTreeWidgetItem *item = itemAt(event->pos());
|
||||
if(item == m_unreadStickyItem) {
|
||||
if (item == m_unreadStickyItem) {
|
||||
event->ignore();
|
||||
} else {
|
||||
if(item && isFolder(item))
|
||||
if (item && isFolder(item))
|
||||
event->ignore();
|
||||
else {
|
||||
if(selectedItems().contains(m_unreadStickyItem)) {
|
||||
if (selectedItems().contains(m_unreadStickyItem)) {
|
||||
event->ignore();
|
||||
} else {
|
||||
QTreeWidget::dragMoveEvent(event);
|
||||
@@ -194,7 +194,7 @@ void FeedListWidget::dropEvent(QDropEvent *event) {
|
||||
QList<QTreeWidgetItem*> folders_altered;
|
||||
QTreeWidgetItem *dest_folder_item = itemAt(event->pos());
|
||||
RssFolderPtr dest_folder;
|
||||
if(dest_folder_item) {
|
||||
if (dest_folder_item) {
|
||||
dest_folder = qSharedPointerCast<RssFolder>(getRSSItem(dest_folder_item));
|
||||
folders_altered << dest_folder_item;
|
||||
} else {
|
||||
@@ -202,26 +202,26 @@ void FeedListWidget::dropEvent(QDropEvent *event) {
|
||||
}
|
||||
QList<QTreeWidgetItem *> src_items = selectedItems();
|
||||
// Check if there is not going to overwrite another file
|
||||
foreach(QTreeWidgetItem *src_item, src_items) {
|
||||
foreach (QTreeWidgetItem *src_item, src_items) {
|
||||
RssFilePtr file = getRSSItem(src_item);
|
||||
if(dest_folder->hasChild(file->id())) {
|
||||
if (dest_folder->hasChild(file->id())) {
|
||||
emit overwriteAttempt(file->id());
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Proceed with the move
|
||||
foreach(QTreeWidgetItem *src_item, src_items) {
|
||||
foreach (QTreeWidgetItem *src_item, src_items) {
|
||||
QTreeWidgetItem *parent_folder = src_item->parent();
|
||||
if(parent_folder && !folders_altered.contains(parent_folder))
|
||||
if (parent_folder && !folders_altered.contains(parent_folder))
|
||||
folders_altered << parent_folder;
|
||||
// Actually move the file
|
||||
RssFilePtr file = getRSSItem(src_item);
|
||||
m_rssManager->moveFile(file, dest_folder);
|
||||
}
|
||||
QTreeWidget::dropEvent(event);
|
||||
if(dest_folder_item)
|
||||
if (dest_folder_item)
|
||||
dest_folder_item->setExpanded(true);
|
||||
// Emit signal for update
|
||||
if(!folders_altered.empty())
|
||||
if (!folders_altered.empty())
|
||||
emit foldersAltered(folders_altered);
|
||||
}
|
||||
|
||||
@@ -63,22 +63,22 @@ enum ArticleRoles {
|
||||
|
||||
// display a right-click menu
|
||||
void RSSImp::displayRSSListMenu(const QPoint& pos){
|
||||
if(!m_feedList->indexAt(pos).isValid()) {
|
||||
if (!m_feedList->indexAt(pos).isValid()) {
|
||||
// No item under the mouse, clear selection
|
||||
m_feedList->clearSelection();
|
||||
}
|
||||
QMenu myRSSListMenu(this);
|
||||
QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems();
|
||||
if(selectedItems.size() > 0) {
|
||||
if (selectedItems.size() > 0) {
|
||||
myRSSListMenu.addAction(actionUpdate);
|
||||
myRSSListMenu.addAction(actionMark_items_read);
|
||||
myRSSListMenu.addSeparator();
|
||||
if(selectedItems.size() == 1) {
|
||||
if(m_feedList->getRSSItem(selectedItems.first()) != m_rssManager) {
|
||||
if (selectedItems.size() == 1) {
|
||||
if (m_feedList->getRSSItem(selectedItems.first()) != m_rssManager) {
|
||||
myRSSListMenu.addAction(actionRename);
|
||||
myRSSListMenu.addAction(actionDelete);
|
||||
myRSSListMenu.addSeparator();
|
||||
if(m_feedList->isFolder(selectedItems.first())) {
|
||||
if (m_feedList->isFolder(selectedItems.first())) {
|
||||
myRSSListMenu.addAction(actionNew_folder);
|
||||
} else {
|
||||
myRSSListMenu.addAction(actionManage_cookies);
|
||||
@@ -86,7 +86,7 @@ void RSSImp::displayRSSListMenu(const QPoint& pos){
|
||||
}
|
||||
}
|
||||
myRSSListMenu.addAction(actionNew_subscription);
|
||||
if(m_feedList->isFeed(selectedItems.first())) {
|
||||
if (m_feedList->isFeed(selectedItems.first())) {
|
||||
myRSSListMenu.addSeparator();
|
||||
myRSSListMenu.addAction(actionCopy_feed_URL);
|
||||
}
|
||||
@@ -102,18 +102,18 @@ void RSSImp::displayRSSListMenu(const QPoint& pos){
|
||||
void RSSImp::displayItemsListMenu(const QPoint&){
|
||||
QMenu myItemListMenu(this);
|
||||
QList<QListWidgetItem*> selectedItems = listArticles->selectedItems();
|
||||
if(selectedItems.size() > 0) {
|
||||
if (selectedItems.size() > 0) {
|
||||
bool has_attachment = false;
|
||||
foreach(const QListWidgetItem *item, selectedItems) {
|
||||
foreach (const QListWidgetItem *item, selectedItems) {
|
||||
qDebug("text(3) URL: %s", qPrintable(item->data(Article::FeedUrlRole).toString()));
|
||||
qDebug("text(2) TITLE: %s", qPrintable(item->data(Article::TitleRole).toString()));
|
||||
if(m_feedList->getRSSItemFromUrl(item->data(Article::FeedUrlRole).toString())
|
||||
if (m_feedList->getRSSItemFromUrl(item->data(Article::FeedUrlRole).toString())
|
||||
->getItem(item->data(Article::IdRole).toString())->hasAttachment()) {
|
||||
has_attachment = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(has_attachment)
|
||||
if (has_attachment)
|
||||
myItemListMenu.addAction(actionDownload_torrent);
|
||||
myItemListMenu.addAction(actionOpen_news_URL);
|
||||
}
|
||||
@@ -130,7 +130,7 @@ void RSSImp::on_actionManage_cookies_triggered() {
|
||||
bool ok = false;
|
||||
RssSettings settings;
|
||||
QList<QByteArray> raw_cookies = CookiesDlg::askForCookies(this, settings.getHostNameCookies(feed_hostname), &ok);
|
||||
if(ok) {
|
||||
if (ok) {
|
||||
settings.setHostNameCookies(feed_hostname, raw_cookies);
|
||||
}
|
||||
}
|
||||
@@ -138,7 +138,7 @@ void RSSImp::on_actionManage_cookies_triggered() {
|
||||
void RSSImp::askNewFolder() {
|
||||
QTreeWidgetItem *parent_item = 0;
|
||||
RssFolderPtr rss_parent;
|
||||
if(m_feedList->selectedItems().size() > 0) {
|
||||
if (m_feedList->selectedItems().size() > 0) {
|
||||
parent_item = m_feedList->selectedItems().at(0);
|
||||
rss_parent = qSharedPointerDynamicCast<RssFolder>(m_feedList->getRSSItem(parent_item));
|
||||
Q_ASSERT(rss_parent);
|
||||
@@ -147,10 +147,10 @@ void RSSImp::askNewFolder() {
|
||||
}
|
||||
bool ok;
|
||||
QString new_name = QInputDialog::getText(this, tr("Please choose a folder name"), tr("Folder name:"), QLineEdit::Normal, tr("New folder"), &ok);
|
||||
if(ok) {
|
||||
if (ok) {
|
||||
RssFolderPtr new_folder = rss_parent->addFolder(new_name);
|
||||
QTreeWidgetItem* folder_item;
|
||||
if(parent_item)
|
||||
if (parent_item)
|
||||
folder_item = new QTreeWidgetItem(parent_item);
|
||||
else
|
||||
folder_item = new QTreeWidgetItem(m_feedList);
|
||||
@@ -160,7 +160,7 @@ void RSSImp::askNewFolder() {
|
||||
folder_item->setText(0, new_folder->displayName() + QString::fromUtf8(" (0)"));
|
||||
folder_item->setData(0,Qt::DecorationRole, QVariant(IconProvider::instance()->getIcon("inode-directory")));
|
||||
// Expand parent folder to display new folder
|
||||
if(parent_item)
|
||||
if (parent_item)
|
||||
parent_item->setExpanded(true);
|
||||
m_rssManager->saveStreamList();
|
||||
}
|
||||
@@ -177,18 +177,18 @@ void RSSImp::on_newFeedButton_clicked() {
|
||||
// Determine parent folder for new feed
|
||||
QTreeWidgetItem *parent_item = 0;
|
||||
QList<QTreeWidgetItem *> selected_items = m_feedList->selectedItems();
|
||||
if(!selected_items.empty()) {
|
||||
if (!selected_items.empty()) {
|
||||
parent_item = selected_items.first();
|
||||
// Consider the case where the user clicked on Unread item
|
||||
if(parent_item == m_feedList->stickyUnreadItem()) {
|
||||
if (parent_item == m_feedList->stickyUnreadItem()) {
|
||||
parent_item = 0;
|
||||
} else {
|
||||
if(m_feedList->isFolder(parent_item))
|
||||
if (m_feedList->isFolder(parent_item))
|
||||
parent_item = parent_item->parent();
|
||||
}
|
||||
}
|
||||
RssFolderPtr rss_parent;
|
||||
if(parent_item) {
|
||||
if (parent_item) {
|
||||
rss_parent = qSharedPointerCast<RssFolder>(m_feedList->getRSSItem(parent_item));
|
||||
} else {
|
||||
rss_parent = m_rssManager;
|
||||
@@ -197,14 +197,14 @@ void RSSImp::on_newFeedButton_clicked() {
|
||||
bool ok;
|
||||
QString clip_txt = qApp->clipboard()->text();
|
||||
QString default_url = "http://";
|
||||
if(clip_txt.startsWith("http://", Qt::CaseInsensitive) || clip_txt.startsWith("https://", Qt::CaseInsensitive) || clip_txt.startsWith("ftp://", Qt::CaseInsensitive)) {
|
||||
if (clip_txt.startsWith("http://", Qt::CaseInsensitive) || clip_txt.startsWith("https://", Qt::CaseInsensitive) || clip_txt.startsWith("ftp://", Qt::CaseInsensitive)) {
|
||||
default_url = clip_txt;
|
||||
}
|
||||
QString newUrl = QInputDialog::getText(this, tr("Please type a rss stream url"), tr("Stream URL:"), QLineEdit::Normal, default_url, &ok);
|
||||
if(ok) {
|
||||
if (ok) {
|
||||
newUrl = newUrl.trimmed();
|
||||
if(!newUrl.isEmpty()){
|
||||
if(m_feedList->hasFeed(newUrl)) {
|
||||
if (!newUrl.isEmpty()){
|
||||
if (m_feedList->hasFeed(newUrl)) {
|
||||
QMessageBox::warning(this, tr("qBittorrent"),
|
||||
tr("This rss feed is already in the list."),
|
||||
QMessageBox::Ok);
|
||||
@@ -213,7 +213,7 @@ void RSSImp::on_newFeedButton_clicked() {
|
||||
RssFeedPtr stream = rss_parent->addStream(m_rssManager.data(), newUrl);
|
||||
// Create TreeWidget item
|
||||
QTreeWidgetItem* item;
|
||||
if(parent_item)
|
||||
if (parent_item)
|
||||
item = new QTreeWidgetItem(parent_item);
|
||||
else
|
||||
item = new QTreeWidgetItem(m_feedList);
|
||||
@@ -231,9 +231,9 @@ void RSSImp::on_newFeedButton_clicked() {
|
||||
// delete a stream by a button
|
||||
void RSSImp::deleteSelectedItems() {
|
||||
QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems();
|
||||
if(selectedItems.size() == 0) return;
|
||||
if (selectedItems.size() == 0) return;
|
||||
int ret;
|
||||
if(selectedItems.size() > 1)
|
||||
if (selectedItems.size() > 1)
|
||||
ret = QMessageBox::question(this, tr("Are you sure? -- qBittorrent"), tr("Are you sure you want to delete these elements from the list?"),
|
||||
tr("&Yes"), tr("&No"),
|
||||
QString(), 0, 1);
|
||||
@@ -241,9 +241,9 @@ void RSSImp::deleteSelectedItems() {
|
||||
ret = QMessageBox::question(this, tr("Are you sure? -- qBittorrent"), tr("Are you sure you want to delete this element from the list?"),
|
||||
tr("&Yes"), tr("&No"),
|
||||
QString(), 0, 1);
|
||||
if(!ret) {
|
||||
foreach(QTreeWidgetItem *item, selectedItems){
|
||||
if(m_feedList->currentFeed() == item){
|
||||
if (!ret) {
|
||||
foreach (QTreeWidgetItem *item, selectedItems){
|
||||
if (m_feedList->currentFeed() == item){
|
||||
textBrowser->clear();
|
||||
m_currentArticle = 0;
|
||||
listArticles->clear();
|
||||
@@ -272,22 +272,22 @@ void RSSImp::loadFoldersOpenState() {
|
||||
settings.beginGroup("Rss");
|
||||
QStringList open_folders = settings.value("open_folders", QStringList()).toStringList();
|
||||
settings.endGroup();
|
||||
foreach(QString var_path, open_folders) {
|
||||
foreach (QString var_path, open_folders) {
|
||||
QStringList path = var_path.split("\\");
|
||||
QTreeWidgetItem *parent = 0;
|
||||
foreach(QString name, path) {
|
||||
foreach (QString name, path) {
|
||||
int nbChildren = 0;
|
||||
if(parent)
|
||||
if (parent)
|
||||
nbChildren = parent->childCount();
|
||||
else
|
||||
nbChildren = m_feedList->topLevelItemCount();
|
||||
for(int i=0; i<nbChildren; ++i) {
|
||||
for (int i=0; i<nbChildren; ++i) {
|
||||
QTreeWidgetItem* child;
|
||||
if(parent)
|
||||
if (parent)
|
||||
child = parent->child(i);
|
||||
else
|
||||
child = m_feedList->topLevelItem(i);
|
||||
if(m_feedList->getRSSItem(child)->id() == name) {
|
||||
if (m_feedList->getRSSItem(child)->id() == name) {
|
||||
parent = child;
|
||||
parent->setExpanded(true);
|
||||
qDebug("expanding folder %s", qPrintable(name));
|
||||
@@ -301,7 +301,7 @@ void RSSImp::loadFoldersOpenState() {
|
||||
void RSSImp::saveFoldersOpenState() {
|
||||
QStringList open_folders;
|
||||
QList<QTreeWidgetItem*> items = m_feedList->getAllOpenFolders();
|
||||
foreach(QTreeWidgetItem* item, items) {
|
||||
foreach (QTreeWidgetItem* item, items) {
|
||||
QString path = m_feedList->getItemPath(item).join("\\");
|
||||
qDebug("saving open folder: %s", qPrintable(path));
|
||||
open_folders << path;
|
||||
@@ -314,7 +314,7 @@ void RSSImp::saveFoldersOpenState() {
|
||||
|
||||
// refresh all streams by a button
|
||||
void RSSImp::on_updateAllButton_clicked() {
|
||||
foreach(QTreeWidgetItem *item, m_feedList->getAllFeedItems()) {
|
||||
foreach (QTreeWidgetItem *item, m_feedList->getAllFeedItems()) {
|
||||
item->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png")));
|
||||
}
|
||||
m_rssManager->refresh();
|
||||
@@ -322,10 +322,10 @@ void RSSImp::on_updateAllButton_clicked() {
|
||||
|
||||
void RSSImp::downloadTorrent() {
|
||||
QList<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())
|
||||
->getItem(item->data(Article::IdRole).toString());
|
||||
if(article->hasAttachment()) {
|
||||
if (article->hasAttachment()) {
|
||||
QBtSession::instance()->downloadFromUrl(article->torrentUrl());
|
||||
} else {
|
||||
QBtSession::instance()->downloadFromUrl(article->link());
|
||||
@@ -336,11 +336,11 @@ void RSSImp::downloadTorrent() {
|
||||
// open the url of the news in a browser
|
||||
void RSSImp::openNewsUrl() {
|
||||
QList<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())
|
||||
->getItem(item->data(Article::IdRole).toString());
|
||||
const QString link = news->link();
|
||||
if(!link.isEmpty())
|
||||
if (!link.isEmpty())
|
||||
QDesktopServices::openUrl(QUrl(link));
|
||||
}
|
||||
}
|
||||
@@ -356,8 +356,8 @@ void RSSImp::renameFiles() {
|
||||
do {
|
||||
newName = QInputDialog::getText(this, tr("Please choose a new name for this RSS feed"), tr("New feed name:"), QLineEdit::Normal, m_feedList->getRSSItem(item)->displayName(), &ok);
|
||||
// Check if name is already taken
|
||||
if(ok) {
|
||||
if(rss_item->parent()->hasChild(newName)) {
|
||||
if (ok) {
|
||||
if (rss_item->parent()->hasChild(newName)) {
|
||||
QMessageBox::warning(0, tr("Name already in use"), tr("This name is already used by another item, please choose another one."));
|
||||
ok = false;
|
||||
}
|
||||
@@ -374,11 +374,11 @@ void RSSImp::renameFiles() {
|
||||
//right-click on stream : refresh it
|
||||
void RSSImp::refreshSelectedItems() {
|
||||
QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems();
|
||||
foreach(QTreeWidgetItem* item, selectedItems){
|
||||
foreach (QTreeWidgetItem* item, selectedItems){
|
||||
RssFilePtr file = m_feedList->getRSSItem(item);
|
||||
// Update icons
|
||||
if(item == m_feedList->stickyUnreadItem()) {
|
||||
foreach(QTreeWidgetItem *feed, m_feedList->getAllFeedItems()) {
|
||||
if (item == m_feedList->stickyUnreadItem()) {
|
||||
foreach (QTreeWidgetItem *feed, m_feedList->getAllFeedItems()) {
|
||||
feed->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png")));
|
||||
}
|
||||
file->refresh();
|
||||
@@ -388,7 +388,7 @@ void RSSImp::refreshSelectedItems() {
|
||||
item->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png")));
|
||||
} else if (qSharedPointerDynamicCast<RssFolder>(file)) {
|
||||
// Update feeds in the folder
|
||||
foreach(QTreeWidgetItem *feed, m_feedList->getAllFeedItems(item)) {
|
||||
foreach (QTreeWidgetItem *feed, m_feedList->getAllFeedItems(item)) {
|
||||
feed->setData(0,Qt::DecorationRole, QVariant(QIcon(":/Icons/loading.png")));
|
||||
}
|
||||
}
|
||||
@@ -402,8 +402,8 @@ void RSSImp::copySelectedFeedsURL() {
|
||||
QStringList URLs;
|
||||
QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems();
|
||||
QTreeWidgetItem* item;
|
||||
foreach(item, selectedItems){
|
||||
if(m_feedList->isFeed(item))
|
||||
foreach (item, selectedItems){
|
||||
if (m_feedList->isFeed(item))
|
||||
URLs << m_feedList->getItemID(item);
|
||||
}
|
||||
qApp->clipboard()->setText(URLs.join("\n"));
|
||||
@@ -412,25 +412,25 @@ void RSSImp::copySelectedFeedsURL() {
|
||||
void RSSImp::on_markReadButton_clicked() {
|
||||
QList<QTreeWidgetItem*> selectedItems = m_feedList->selectedItems();
|
||||
QTreeWidgetItem* item;
|
||||
foreach(item, selectedItems){
|
||||
foreach (item, selectedItems){
|
||||
RssFilePtr rss_item = m_feedList->getRSSItem(item);
|
||||
rss_item->markAsRead();
|
||||
updateItemInfos(item);
|
||||
}
|
||||
if(selectedItems.size())
|
||||
if (selectedItems.size())
|
||||
refreshArticleList(m_feedList->currentItem());
|
||||
}
|
||||
|
||||
void RSSImp::fillFeedsList(QTreeWidgetItem *parent, const RssFolderPtr& rss_parent) {
|
||||
QList<RssFilePtr> children;
|
||||
if(parent) {
|
||||
if (parent) {
|
||||
children = rss_parent->getContent();
|
||||
} else {
|
||||
children = m_rssManager->getContent();
|
||||
}
|
||||
foreach (const RssFilePtr& rss_child, children){
|
||||
QTreeWidgetItem* item;
|
||||
if(!parent)
|
||||
if (!parent)
|
||||
item = new QTreeWidgetItem(m_feedList);
|
||||
else
|
||||
item = new QTreeWidgetItem(parent);
|
||||
@@ -438,7 +438,7 @@ void RSSImp::fillFeedsList(QTreeWidgetItem *parent, const RssFolderPtr& rss_pare
|
||||
// Notify TreeWidget of item addition
|
||||
m_feedList->itemAdded(item, rss_child);
|
||||
// Set Icon
|
||||
if(qSharedPointerDynamicCast<RssFeed>(rss_child)) {
|
||||
if (qSharedPointerDynamicCast<RssFeed>(rss_child)) {
|
||||
item->setData(0,Qt::DecorationRole, QVariant(QIcon(QString::fromUtf8(":/Icons/loading.png"))));
|
||||
} else if (RssFolderPtr folder = qSharedPointerDynamicCast<RssFolder>(rss_child)) {
|
||||
item->setData(0,Qt::DecorationRole, QVariant(IconProvider::instance()->getIcon("inode-directory")));
|
||||
@@ -450,19 +450,19 @@ void RSSImp::fillFeedsList(QTreeWidgetItem *parent, const RssFolderPtr& rss_pare
|
||||
|
||||
// fills the newsList
|
||||
void RSSImp::refreshArticleList(QTreeWidgetItem* item) {
|
||||
if(!item) {
|
||||
if (!item) {
|
||||
listArticles->clear();
|
||||
return;
|
||||
}
|
||||
|
||||
RssFilePtr rss_item = m_feedList->getRSSItem(item);
|
||||
if(!rss_item) return;
|
||||
if (!rss_item) return;
|
||||
|
||||
qDebug("Getting the list of news");
|
||||
RssArticleList news;
|
||||
if(rss_item == m_rssManager)
|
||||
if (rss_item == m_rssManager)
|
||||
news = rss_item->unreadArticleList();
|
||||
else if(rss_item)
|
||||
else if (rss_item)
|
||||
news = rss_item->articleList();
|
||||
// Sort
|
||||
RssManager::sortNewsList(news);
|
||||
@@ -471,12 +471,12 @@ void RSSImp::refreshArticleList(QTreeWidgetItem* item) {
|
||||
m_currentArticle = 0;
|
||||
listArticles->clear();
|
||||
qDebug("Got the list of news");
|
||||
foreach(const RssArticlePtr &article, news){
|
||||
foreach (const RssArticlePtr &article, news){
|
||||
QListWidgetItem* it = new QListWidgetItem(listArticles);
|
||||
it->setData(Article::TitleRole, article->title());
|
||||
it->setData(Article::FeedUrlRole, article->parent()->url());
|
||||
it->setData(Article::IdRole, article->guid());
|
||||
if(article->isRead()){
|
||||
if (article->isRead()){
|
||||
it->setData(Article::ColorRole, QVariant(QColor("grey")));
|
||||
it->setData(Article::IconRole, QVariant(QIcon(":/Icons/sphere.png")));
|
||||
}else{
|
||||
@@ -491,14 +491,14 @@ void RSSImp::refreshArticleList(QTreeWidgetItem* item) {
|
||||
// display a news
|
||||
void RSSImp::refreshTextBrowser() {
|
||||
QList<QListWidgetItem*> selection = listArticles->selectedItems();
|
||||
if(selection.empty()) return;
|
||||
if (selection.empty()) return;
|
||||
Q_ASSERT(selection.size() == 1);
|
||||
QListWidgetItem *item = selection.first();
|
||||
Q_ASSERT(item);
|
||||
if(item == m_currentArticle) return;
|
||||
if (item == m_currentArticle) return;
|
||||
// Stop displaying previous news if necessary
|
||||
if(m_feedList->currentFeed() == m_feedList->stickyUnreadItem()) {
|
||||
if(m_currentArticle) {
|
||||
if (m_feedList->currentFeed() == m_feedList->stickyUnreadItem()) {
|
||||
if (m_currentArticle) {
|
||||
disconnect(listArticles, SIGNAL(itemSelectionChanged()), this, SLOT(refreshTextBrowser()));
|
||||
listArticles->removeItemWidget(m_currentArticle);
|
||||
Q_ASSERT(m_currentArticle);
|
||||
@@ -512,10 +512,10 @@ void RSSImp::refreshTextBrowser() {
|
||||
QString html;
|
||||
html += "<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>";
|
||||
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>";
|
||||
}
|
||||
if(!article->author().isEmpty()) {
|
||||
if (!article->author().isEmpty()) {
|
||||
html += "<div style='background-color: #efefef;'><b>"+tr("Author: ")+"</b>"+article->author()+"</div>";
|
||||
}
|
||||
html += "</div>";
|
||||
@@ -540,17 +540,17 @@ void RSSImp::saveSlidersPosition() {
|
||||
void RSSImp::restoreSlidersPosition() {
|
||||
QIniSettings settings("qBittorrent", "qBittorrent");
|
||||
QByteArray pos_h = settings.value("rss/splitter_h", QByteArray()).toByteArray();
|
||||
if(!pos_h.isNull()) {
|
||||
if (!pos_h.isNull()) {
|
||||
splitter_h->restoreState(pos_h);
|
||||
}
|
||||
QByteArray pos_v = settings.value("rss/splitter_v", QByteArray()).toByteArray();
|
||||
if(!pos_v.isNull()) {
|
||||
if (!pos_v.isNull()) {
|
||||
splitter_v->restoreState(pos_v);
|
||||
}
|
||||
}
|
||||
|
||||
void RSSImp::updateItemsInfos(const QList<QTreeWidgetItem *> &items) {
|
||||
foreach(QTreeWidgetItem* item, items) {
|
||||
foreach (QTreeWidgetItem* item, items) {
|
||||
updateItemInfos(item);
|
||||
}
|
||||
}
|
||||
@@ -561,13 +561,13 @@ void RSSImp::updateItemInfos(QTreeWidgetItem *item) {
|
||||
return;
|
||||
|
||||
QString name;
|
||||
if(rss_item == m_rssManager)
|
||||
if (rss_item == m_rssManager)
|
||||
name = tr("Unread");
|
||||
else
|
||||
name = rss_item->displayName();
|
||||
item->setText(0, name + QString::fromUtf8(" (") + QString::number(rss_item->unreadCount(), 10)+ QString(")"));
|
||||
// If item has a parent, update it too
|
||||
if(item->parent())
|
||||
if (item->parent())
|
||||
updateItemInfos(item->parent());
|
||||
}
|
||||
|
||||
@@ -581,19 +581,19 @@ void RSSImp::updateFeedInfos(const QString &url, const QString &display_name, ui
|
||||
QTreeWidgetItem *item = m_feedList->getTreeItemFromUrl(url);
|
||||
RssFeedPtr stream = qSharedPointerCast<RssFeed>(m_feedList->getRSSItem(item));
|
||||
item->setText(0, display_name + QString::fromUtf8(" (") + QString::number(nbUnread, 10)+ QString(")"));
|
||||
if(!stream->isLoading())
|
||||
if (!stream->isLoading())
|
||||
item->setData(0,Qt::DecorationRole, QVariant(QIcon(stream->icon())));
|
||||
// Update parent
|
||||
if(item->parent())
|
||||
if (item->parent())
|
||||
updateItemInfos(item->parent());
|
||||
// Update Unread item
|
||||
updateItemInfos(m_feedList->stickyUnreadItem());
|
||||
// If the feed is selected, update the displayed news
|
||||
if(m_feedList->currentItem() == item ){
|
||||
if (m_feedList->currentItem() == item ){
|
||||
refreshArticleList(item);
|
||||
} else {
|
||||
// Update unread items
|
||||
if(m_feedList->currentItem() == m_feedList->stickyUnreadItem()) {
|
||||
if (m_feedList->currentItem() == m_feedList->stickyUnreadItem()) {
|
||||
refreshArticleList(m_feedList->stickyUnreadItem());
|
||||
}
|
||||
}
|
||||
@@ -680,7 +680,7 @@ RSSImp::~RSSImp(){
|
||||
|
||||
void RSSImp::on_settingsButton_clicked() {
|
||||
RssSettingsDlg dlg(this);
|
||||
if(dlg.exec())
|
||||
if (dlg.exec())
|
||||
updateRefreshInterval(RssSettings().getRSSRefreshInterval());
|
||||
}
|
||||
|
||||
@@ -688,6 +688,6 @@ void RSSImp::on_rssDownloaderBtn_clicked()
|
||||
{
|
||||
AutomatedRssDownloader dlg(m_rssManager, this);
|
||||
dlg.exec();
|
||||
if(dlg.isRssDownloaderEnabled())
|
||||
if (dlg.isRssDownloaderEnabled())
|
||||
on_updateAllButton_clicked();
|
||||
}
|
||||
|
||||
@@ -223,33 +223,33 @@ RssArticlePtr xmlToRssArticle(RssFeed* parent, QXmlStreamReader& xml)
|
||||
while(!xml.atEnd()) {
|
||||
xml.readNext();
|
||||
|
||||
if(xml.isEndElement() && xml.name() == "item")
|
||||
if (xml.isEndElement() && xml.name() == "item")
|
||||
break;
|
||||
|
||||
if(xml.isStartElement()) {
|
||||
if(xml.name() == "title") {
|
||||
if (xml.isStartElement()) {
|
||||
if (xml.name() == "title") {
|
||||
title = xml.readElementText();
|
||||
}
|
||||
else if(xml.name() == "enclosure") {
|
||||
if(xml.attributes().value("type") == "application/x-bittorrent") {
|
||||
else if (xml.name() == "enclosure") {
|
||||
if (xml.attributes().value("type") == "application/x-bittorrent") {
|
||||
torrentUrl = xml.attributes().value("url").toString();
|
||||
}
|
||||
}
|
||||
else if(xml.name() == "link") {
|
||||
else if (xml.name() == "link") {
|
||||
link = xml.readElementText();
|
||||
if(guid.isEmpty())
|
||||
if (guid.isEmpty())
|
||||
guid = link;
|
||||
}
|
||||
else if(xml.name() == "description") {
|
||||
else if (xml.name() == "description") {
|
||||
description = xml.readElementText();
|
||||
}
|
||||
else if(xml.name() == "pubDate") {
|
||||
else if (xml.name() == "pubDate") {
|
||||
date = RssArticle::parseDate(xml.readElementText());
|
||||
}
|
||||
else if(xml.name() == "author") {
|
||||
else if (xml.name() == "author") {
|
||||
author = xml.readElementText();
|
||||
}
|
||||
else if(xml.name() == "guid") {
|
||||
else if (xml.name() == "guid") {
|
||||
guid = xml.readElementText();
|
||||
}
|
||||
}
|
||||
@@ -271,7 +271,7 @@ RssArticlePtr xmlToRssArticle(RssFeed* parent, QXmlStreamReader& xml)
|
||||
|
||||
RssArticlePtr hashToRssArticle(RssFeed* parent, const QVariantHash &h) {
|
||||
const QString guid = h.value("id").toString();
|
||||
if(guid.isEmpty()) return RssArticlePtr();
|
||||
if (guid.isEmpty()) return RssArticlePtr();
|
||||
|
||||
RssArticlePtr art(new RssArticle(parent, guid));
|
||||
art->m_title = h.value("title", "").toString();
|
||||
@@ -302,7 +302,7 @@ QString RssArticle::link() const {
|
||||
}
|
||||
|
||||
QString RssArticle::description() const{
|
||||
if(m_description.isNull())
|
||||
if (m_description.isNull())
|
||||
return "";
|
||||
return m_description;
|
||||
}
|
||||
|
||||
@@ -43,26 +43,26 @@ RssDownloadRule::RssDownloadRule(): m_enabled(false), m_useRegex(false)
|
||||
|
||||
bool RssDownloadRule::matches(const QString &article_title) const
|
||||
{
|
||||
foreach(const QString& token, m_mustContain) {
|
||||
if(token.isEmpty() || token == "")
|
||||
foreach (const QString& token, m_mustContain) {
|
||||
if (token.isEmpty() || token == "")
|
||||
continue;
|
||||
QRegExp reg(token, Qt::CaseInsensitive, m_useRegex ? QRegExp::RegExp : QRegExp::Wildcard);
|
||||
//reg.setMinimal(false);
|
||||
if(reg.indexIn(article_title) < 0) return false;
|
||||
if (reg.indexIn(article_title) < 0) return false;
|
||||
}
|
||||
qDebug("Checking not matching tokens");
|
||||
// Checking not matching
|
||||
foreach(const QString& token, m_mustNotContain) {
|
||||
if(token.isEmpty()) continue;
|
||||
foreach (const QString& token, m_mustNotContain) {
|
||||
if (token.isEmpty()) continue;
|
||||
QRegExp reg(token, Qt::CaseInsensitive, m_useRegex ? QRegExp::RegExp : QRegExp::Wildcard);
|
||||
if(reg.indexIn(article_title) > -1) return false;
|
||||
if (reg.indexIn(article_title) > -1) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void RssDownloadRule::setMustContain(const QString &tokens)
|
||||
{
|
||||
if(m_useRegex)
|
||||
if (m_useRegex)
|
||||
m_mustContain = QStringList() << tokens;
|
||||
else
|
||||
m_mustContain = tokens.split(" ");
|
||||
@@ -70,7 +70,7 @@ void RssDownloadRule::setMustContain(const QString &tokens)
|
||||
|
||||
void RssDownloadRule::setMustNotContain(const QString &tokens)
|
||||
{
|
||||
if(m_useRegex)
|
||||
if (m_useRegex)
|
||||
m_mustNotContain = QStringList() << tokens;
|
||||
else
|
||||
m_mustNotContain = tokens.split(QRegExp("[\\s|]"));
|
||||
@@ -83,7 +83,7 @@ RssDownloadRulePtr RssDownloadRule::fromOldFormat(const QVariantHash &rule_hash,
|
||||
rule->setName(rule_name);
|
||||
rule->setMustContain(rule_hash.value("matches", "").toString());
|
||||
rule->setMustNotContain(rule_hash.value("not", "").toString());
|
||||
if(!feed_url.isEmpty())
|
||||
if (!feed_url.isEmpty())
|
||||
rule->setRssFeeds(QStringList() << feed_url);
|
||||
rule->setSavePath(rule_hash.value("save_path", "").toString());
|
||||
// Is enabled?
|
||||
@@ -128,7 +128,7 @@ bool RssDownloadRule::operator==(const RssDownloadRule &other) {
|
||||
|
||||
void RssDownloadRule::setSavePath(const QString &save_path)
|
||||
{
|
||||
if(!save_path.isEmpty() && QDir(save_path) != QDir(Preferences().getSavePath()))
|
||||
if (!save_path.isEmpty() && QDir(save_path) != QDir(Preferences().getSavePath()))
|
||||
m_savePath = save_path;
|
||||
else
|
||||
m_savePath = QString();
|
||||
@@ -138,7 +138,7 @@ QStringList RssDownloadRule::findMatchingArticles(const RssFeedPtr& feed) const
|
||||
{
|
||||
QStringList ret;
|
||||
const RssArticleHash& feed_articles = feed->articleHash();
|
||||
for(RssArticleHash::ConstIterator artIt = feed_articles.begin(); artIt != feed_articles.end(); artIt++) {
|
||||
for (RssArticleHash::ConstIterator artIt = feed_articles.begin(); artIt != feed_articles.end(); artIt++) {
|
||||
const QString title = artIt.value()->title();
|
||||
if (matches(title))
|
||||
ret << title;
|
||||
|
||||
@@ -44,7 +44,7 @@ RssDownloadRuleList::RssDownloadRuleList(){
|
||||
|
||||
RssDownloadRuleList* RssDownloadRuleList::instance()
|
||||
{
|
||||
if(!m_instance)
|
||||
if (!m_instance)
|
||||
m_instance = new RssDownloadRuleList;
|
||||
return m_instance;
|
||||
}
|
||||
@@ -61,9 +61,9 @@ RssDownloadRulePtr RssDownloadRuleList::findMatchingRule(const QString &feed_url
|
||||
{
|
||||
Q_ASSERT(RssSettings().isRssDownloadingEnabled());
|
||||
QStringList rule_names = m_feedRules.value(feed_url);
|
||||
foreach(const QString &rule_name, rule_names) {
|
||||
foreach (const QString &rule_name, rule_names) {
|
||||
RssDownloadRulePtr rule = m_rules[rule_name];
|
||||
if(rule->isEnabled() && rule->matches(article_title)) return rule;
|
||||
if (rule->isEnabled() && rule->matches(article_title)) return rule;
|
||||
}
|
||||
return RssDownloadRulePtr();
|
||||
}
|
||||
@@ -77,7 +77,7 @@ void RssDownloadRuleList::saveRulesToStorage()
|
||||
void RssDownloadRuleList::loadRulesFromStorage()
|
||||
{
|
||||
QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss");
|
||||
if(qBTRSS.contains("feed_filters")) {
|
||||
if (qBTRSS.contains("feed_filters")) {
|
||||
importFeedsInOldFormat(qBTRSS.value("feed_filters").toHash());
|
||||
// Remove outdated rules
|
||||
qBTRSS.remove("feed_filters");
|
||||
@@ -91,16 +91,16 @@ void RssDownloadRuleList::loadRulesFromStorage()
|
||||
|
||||
void RssDownloadRuleList::importFeedsInOldFormat(const QHash<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());
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
if(!rule) continue;
|
||||
if (!rule) continue;
|
||||
// Check for rule name clash
|
||||
while(m_rules.contains(rule->name())) {
|
||||
rule->setName(rule->name()+"_");
|
||||
@@ -113,7 +113,7 @@ void RssDownloadRuleList::importFeedRulesInOldFormat(const QString &feed_url, co
|
||||
QVariantHash RssDownloadRuleList::toVariantHash() const
|
||||
{
|
||||
QVariantHash ret;
|
||||
foreach(const RssDownloadRulePtr &rule, m_rules.values()) {
|
||||
foreach (const RssDownloadRulePtr &rule, m_rules.values()) {
|
||||
ret.insert(rule->name(), rule->toVariantHash());
|
||||
}
|
||||
return ret;
|
||||
@@ -121,9 +121,9 @@ QVariantHash RssDownloadRuleList::toVariantHash() const
|
||||
|
||||
void RssDownloadRuleList::loadRulesFromVariantHash(const QVariantHash &h)
|
||||
{
|
||||
foreach(const QVariant& v, h.values()) {
|
||||
foreach (const QVariant& v, h.values()) {
|
||||
RssDownloadRulePtr rule = RssDownloadRule::fromNewFormat(v.toHash());
|
||||
if(rule && !rule->name().isEmpty()) {
|
||||
if (rule && !rule->name().isEmpty()) {
|
||||
saveRule(rule);
|
||||
}
|
||||
}
|
||||
@@ -133,13 +133,13 @@ void RssDownloadRuleList::saveRule(const RssDownloadRulePtr &rule)
|
||||
{
|
||||
qDebug() << Q_FUNC_INFO << rule->name();
|
||||
Q_ASSERT(rule);
|
||||
if(m_rules.contains(rule->name())) {
|
||||
if (m_rules.contains(rule->name())) {
|
||||
qDebug("This is an update, removing old rule first");
|
||||
removeRule(rule->name());
|
||||
}
|
||||
m_rules.insert(rule->name(), rule);
|
||||
// Update feedRules hashtable
|
||||
foreach(const QString &feed_url, rule->rssFeeds()) {
|
||||
foreach (const QString &feed_url, rule->rssFeeds()) {
|
||||
m_feedRules[feed_url].append(rule->name());
|
||||
}
|
||||
// Save rules
|
||||
@@ -150,10 +150,10 @@ void RssDownloadRuleList::saveRule(const RssDownloadRulePtr &rule)
|
||||
void RssDownloadRuleList::removeRule(const QString &name)
|
||||
{
|
||||
qDebug() << Q_FUNC_INFO << name;
|
||||
if(!m_rules.contains(name)) return;
|
||||
if (!m_rules.contains(name)) return;
|
||||
RssDownloadRulePtr rule = m_rules.take(name);
|
||||
// Update feedRules hashtable
|
||||
foreach(const QString &feed_url, rule->rssFeeds()) {
|
||||
foreach (const QString &feed_url, rule->rssFeeds()) {
|
||||
m_feedRules[feed_url].removeOne(rule->name());
|
||||
}
|
||||
// Save rules
|
||||
@@ -162,12 +162,12 @@ void RssDownloadRuleList::removeRule(const QString &name)
|
||||
|
||||
void RssDownloadRuleList::renameRule(const QString &old_name, const QString &new_name)
|
||||
{
|
||||
if(!m_rules.contains(old_name)) return;
|
||||
if (!m_rules.contains(old_name)) return;
|
||||
RssDownloadRulePtr rule = m_rules.take(old_name);
|
||||
rule->setName(new_name);
|
||||
m_rules.insert(new_name, rule);
|
||||
// Update feedRules hashtable
|
||||
foreach(const QString &feed_url, rule->rssFeeds()) {
|
||||
foreach (const QString &feed_url, rule->rssFeeds()) {
|
||||
m_feedRules[feed_url].replace(m_feedRules[feed_url].indexOf(old_name), new_name);
|
||||
}
|
||||
// Save rules
|
||||
@@ -182,7 +182,7 @@ RssDownloadRulePtr RssDownloadRuleList::getRule(const QString &name) const
|
||||
bool RssDownloadRuleList::serialize(const QString& path)
|
||||
{
|
||||
QFile f(path);
|
||||
if(f.open(QIODevice::WriteOnly)) {
|
||||
if (f.open(QIODevice::WriteOnly)) {
|
||||
QDataStream out(&f);
|
||||
out.setVersion(QDataStream::Qt_4_5);
|
||||
out << toVariantHash();
|
||||
@@ -196,16 +196,16 @@ bool RssDownloadRuleList::serialize(const QString& path)
|
||||
bool RssDownloadRuleList::unserialize(const QString &path)
|
||||
{
|
||||
QFile f(path);
|
||||
if(f.open(QIODevice::ReadOnly)) {
|
||||
if (f.open(QIODevice::ReadOnly)) {
|
||||
QDataStream in(&f);
|
||||
if(path.endsWith(".filters", Qt::CaseInsensitive)) {
|
||||
if (path.endsWith(".filters", Qt::CaseInsensitive)) {
|
||||
// Old format (< 2.5.0)
|
||||
qDebug("Old serialization format detected, processing...");
|
||||
in.setVersion(QDataStream::Qt_4_3);
|
||||
QVariantHash tmp;
|
||||
in >> tmp;
|
||||
f.close();
|
||||
if(tmp.isEmpty()) return false;
|
||||
if (tmp.isEmpty()) return false;
|
||||
qDebug("Processing was successful!");
|
||||
// Unfortunately the feed_url is lost
|
||||
importFeedRulesInOldFormat("", tmp);
|
||||
@@ -215,7 +215,7 @@ bool RssDownloadRuleList::unserialize(const QString &path)
|
||||
QVariantHash tmp;
|
||||
in >> tmp;
|
||||
f.close();
|
||||
if(tmp.isEmpty()) return false;
|
||||
if (tmp.isEmpty()) return false;
|
||||
qDebug("Processing was successful!");
|
||||
loadRulesFromVariantHash(tmp);
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ RssFeed::RssFeed(RssManager* manager, RssFolder* parent, const QString &url):
|
||||
}
|
||||
|
||||
RssFeed::~RssFeed(){
|
||||
if(!m_icon.startsWith(":/") && QFile::exists(m_icon))
|
||||
if (!m_icon.startsWith(":/") && QFile::exists(m_icon))
|
||||
QFile::remove(m_icon);
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ void RssFeed::loadItemsFromDisk() {
|
||||
}
|
||||
|
||||
void RssFeed::refresh() {
|
||||
if(m_loading) {
|
||||
if (m_loading) {
|
||||
qWarning() << Q_FUNC_INFO << "Feed" << this->displayName() << "is already being refreshed, ignoring request";
|
||||
return;
|
||||
}
|
||||
@@ -143,11 +143,11 @@ void RssFeed::rename(const QString &new_name){
|
||||
|
||||
// Return the alias if the stream has one, the url if it has no alias
|
||||
QString RssFeed::displayName() const {
|
||||
if(!m_alias.isEmpty()) {
|
||||
if (!m_alias.isEmpty()) {
|
||||
//qDebug("getName() returned alias: %s", (const char*)alias.toLocal8Bit());
|
||||
return m_alias;
|
||||
}
|
||||
if(!m_title.isEmpty()) {
|
||||
if (!m_title.isEmpty()) {
|
||||
//qDebug("getName() returned title: %s", (const char*)title.toLocal8Bit());
|
||||
return m_title;
|
||||
}
|
||||
@@ -160,7 +160,7 @@ QString RssFeed::url() const{
|
||||
}
|
||||
|
||||
QString RssFeed::icon() const{
|
||||
if(m_downloadFailure)
|
||||
if (m_downloadFailure)
|
||||
return ":/Icons/oxygen/unavailable.png";
|
||||
return m_icon;
|
||||
}
|
||||
@@ -170,7 +170,7 @@ bool RssFeed::hasCustomIcon() const{
|
||||
}
|
||||
|
||||
void RssFeed::setIconPath(const QString &path) {
|
||||
if(path.isEmpty() || !QFile::exists(path)) return;
|
||||
if (path.isEmpty() || !QFile::exists(path)) return;
|
||||
m_icon = path;
|
||||
}
|
||||
|
||||
@@ -192,7 +192,7 @@ void RssFeed::markAsRead() {
|
||||
uint RssFeed::unreadCount() const{
|
||||
uint nbUnread = 0;
|
||||
for (RssArticleHash::ConstIterator it=m_articles.begin(); it != m_articles.end(); it++) {
|
||||
if(!it.value()->isRead())
|
||||
if (!it.value()->isRead())
|
||||
++nbUnread;
|
||||
}
|
||||
return nbUnread;
|
||||
@@ -205,7 +205,7 @@ RssArticleList RssFeed::articleList() const{
|
||||
RssArticleList RssFeed::unreadArticleList() const {
|
||||
RssArticleList unread_news;
|
||||
for (RssArticleHash::ConstIterator it = m_articles.begin(); it != m_articles.end(); it++) {
|
||||
if(!it.value()->isRead())
|
||||
if (!it.value()->isRead())
|
||||
unread_news << it.value();
|
||||
}
|
||||
return unread_news;
|
||||
@@ -229,8 +229,8 @@ bool RssFeed::parseRSS(QIODevice* device) {
|
||||
}
|
||||
while (!xml.atEnd()) {
|
||||
xml.readNext();
|
||||
if(xml.isStartElement()) {
|
||||
if(xml.name() != "rss") {
|
||||
if (xml.isStartElement()) {
|
||||
if (xml.name() != "rss") {
|
||||
qDebug("ERROR: this is not a rss file, root tag is <%s>", qPrintable(xml.name().toString()));
|
||||
return false;
|
||||
} else {
|
||||
@@ -242,37 +242,37 @@ bool RssFeed::parseRSS(QIODevice* device) {
|
||||
while(!xml.atEnd()) {
|
||||
xml.readNext();
|
||||
|
||||
if(!xml.isStartElement())
|
||||
if (!xml.isStartElement())
|
||||
continue;
|
||||
|
||||
if(xml.name() != "channel")
|
||||
if (xml.name() != "channel")
|
||||
continue;
|
||||
|
||||
// Parse channel content
|
||||
while(!xml.atEnd()) {
|
||||
xml.readNext();
|
||||
|
||||
if(xml.isEndElement() && xml.name() == "channel")
|
||||
if (xml.isEndElement() && xml.name() == "channel")
|
||||
break; // End of this channel, parse the next one
|
||||
|
||||
if(!xml.isStartElement())
|
||||
if (!xml.isStartElement())
|
||||
continue;
|
||||
|
||||
if(xml.name() == "title") {
|
||||
if (xml.name() == "title") {
|
||||
m_title = xml.readElementText();
|
||||
if(m_alias == url())
|
||||
if (m_alias == url())
|
||||
rename(m_title);
|
||||
}
|
||||
else if(xml.name() == "image") {
|
||||
else if (xml.name() == "image") {
|
||||
QString icon_path = xml.attributes().value("url").toString();
|
||||
if(!icon_path.isEmpty()) {
|
||||
if (!icon_path.isEmpty()) {
|
||||
m_iconUrl = icon_path;
|
||||
m_manager->rssDownloader()->downloadUrl(m_iconUrl);
|
||||
}
|
||||
}
|
||||
else if(xml.name() == "item") {
|
||||
else if (xml.name() == "item") {
|
||||
RssArticlePtr art = xmlToRssArticle(this, xml);
|
||||
if(art && !itemAlreadyExists(art->guid()))
|
||||
if (art && !itemAlreadyExists(art->guid()))
|
||||
m_articles.insert(art->guid(), art);
|
||||
}
|
||||
}
|
||||
@@ -282,7 +282,7 @@ bool RssFeed::parseRSS(QIODevice* device) {
|
||||
resizeList();
|
||||
|
||||
// RSS Feed Downloader
|
||||
if(RssSettings().isRssDownloadingEnabled())
|
||||
if (RssSettings().isRssDownloadingEnabled())
|
||||
downloadMatchingArticleTorrents();
|
||||
|
||||
// Save items to disk (for safety)
|
||||
@@ -295,15 +295,15 @@ void RssFeed::downloadMatchingArticleTorrents() {
|
||||
Q_ASSERT(RssSettings().isRssDownloadingEnabled());
|
||||
for (RssArticleHash::ConstIterator it = m_articles.begin(); it != m_articles.end(); it++) {
|
||||
RssArticlePtr item = it.value();
|
||||
if(item->isRead()) continue;
|
||||
if (item->isRead()) continue;
|
||||
QString torrent_url;
|
||||
if(item->hasAttachment())
|
||||
if (item->hasAttachment())
|
||||
torrent_url = item->torrentUrl();
|
||||
else
|
||||
torrent_url = item->link();
|
||||
// Check if the item should be automatically downloaded
|
||||
RssDownloadRulePtr matching_rule = RssDownloadRuleList::instance()->findMatchingRule(m_url, item->title());
|
||||
if(matching_rule) {
|
||||
if (matching_rule) {
|
||||
// Item was downloaded, consider it as Read
|
||||
item->markAsRead();
|
||||
// Download the torrent
|
||||
@@ -316,11 +316,11 @@ void RssFeed::downloadMatchingArticleTorrents() {
|
||||
void RssFeed::resizeList() {
|
||||
const uint max_articles = RssSettings().getRSSMaxArticlesPerFeed();
|
||||
const uint nb_articles = m_articles.size();
|
||||
if(nb_articles > max_articles) {
|
||||
if (nb_articles > max_articles) {
|
||||
RssArticleList listItems = m_articles.values();
|
||||
RssManager::sortNewsList(listItems);
|
||||
const int excess = nb_articles - max_articles;
|
||||
for(uint i=nb_articles-excess; i<nb_articles; ++i){
|
||||
for (uint i=nb_articles-excess; i<nb_articles; ++i){
|
||||
m_articles.remove(listItems.at(i)->guid());
|
||||
}
|
||||
}
|
||||
@@ -330,9 +330,9 @@ void RssFeed::resizeList() {
|
||||
bool RssFeed::parseXmlFile(const QString &file_path){
|
||||
qDebug("openRss() called");
|
||||
QFile fileRss(file_path);
|
||||
if(!fileRss.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
||||
if (!fileRss.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
||||
qDebug("openRss error: open failed, no file or locked, %s", qPrintable(file_path));
|
||||
if(QFile::exists(file_path)) {
|
||||
if (QFile::exists(file_path)) {
|
||||
fileRss.remove();
|
||||
}
|
||||
return false;
|
||||
@@ -341,25 +341,25 @@ bool RssFeed::parseXmlFile(const QString &file_path){
|
||||
// start reading the xml
|
||||
bool ret = parseRSS(&fileRss);
|
||||
fileRss.close();
|
||||
if(QFile::exists(file_path))
|
||||
if (QFile::exists(file_path))
|
||||
fileRss.remove();
|
||||
return ret;
|
||||
}
|
||||
|
||||
// read and store the downloaded rss' informations
|
||||
void RssFeed::handleFinishedDownload(const QString& url, const QString &file_path) {
|
||||
if(url == m_url) {
|
||||
if (url == m_url) {
|
||||
qDebug() << Q_FUNC_INFO << "Successfuly downloaded RSS feed at" << url;
|
||||
m_downloadFailure = false;
|
||||
m_loading = false;
|
||||
// Parse the download RSS
|
||||
if(parseXmlFile(file_path)) {
|
||||
if (parseXmlFile(file_path)) {
|
||||
m_refreshed = true;
|
||||
m_manager->forwardFeedInfosChanged(m_url, displayName(), unreadCount()); // XXX: Ugly
|
||||
qDebug() << Q_FUNC_INFO << "Feed parsed successfuly";
|
||||
}
|
||||
}
|
||||
else if(url == m_iconUrl) {
|
||||
else if (url == m_iconUrl) {
|
||||
m_icon = file_path;
|
||||
qDebug() << Q_FUNC_INFO << "icon path:" << m_icon;
|
||||
m_manager->forwardFeedIconChanged(m_url, m_icon); // XXX: Ugly
|
||||
@@ -367,7 +367,7 @@ void RssFeed::handleFinishedDownload(const QString& url, const QString &file_pat
|
||||
}
|
||||
|
||||
void RssFeed::handleDownloadFailure(const QString &url, const QString& error) {
|
||||
if(url != m_url) return;
|
||||
if (url != m_url) return;
|
||||
m_downloadFailure = true;
|
||||
m_loading = false;
|
||||
m_manager->forwardFeedInfosChanged(m_url, displayName(), unreadCount()); // XXX: Ugly
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
|
||||
QStringList RssFile::pathHierarchy() const {
|
||||
QStringList path;
|
||||
if(parent())
|
||||
if (parent())
|
||||
path << parent()->pathHierarchy();
|
||||
path << id();
|
||||
return path;
|
||||
|
||||
@@ -186,7 +186,7 @@ void RssFolder::removeAllSettings() {
|
||||
|
||||
void RssFolder::saveItemsToDisk()
|
||||
{
|
||||
foreach(const RssFilePtr& child, m_children.values()) {
|
||||
foreach (const RssFilePtr& child, m_children.values()) {
|
||||
child->saveItemsToDisk();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ RssManager::~RssManager(){
|
||||
}
|
||||
|
||||
void RssManager::updateRefreshInterval(uint val){
|
||||
if(m_refreshInterval != val) {
|
||||
if (m_refreshInterval != val) {
|
||||
m_refreshInterval = val;
|
||||
m_refreshTimer.start(m_refreshInterval*60000);
|
||||
qDebug("New RSS refresh interval is now every %dmin", m_refreshInterval);
|
||||
@@ -65,20 +65,20 @@ void RssManager::loadStreamList() {
|
||||
RssSettings settings;
|
||||
const QStringList streamsUrl = settings.getRssFeedsUrls();
|
||||
const QStringList aliases = settings.getRssFeedsAliases();
|
||||
if(streamsUrl.size() != aliases.size()){
|
||||
if (streamsUrl.size() != aliases.size()){
|
||||
std::cerr << "Corrupted Rss list, not loading it\n";
|
||||
return;
|
||||
}
|
||||
uint i = 0;
|
||||
qDebug() << Q_FUNC_INFO << streamsUrl;
|
||||
foreach(QString s, streamsUrl){
|
||||
foreach (QString s, streamsUrl){
|
||||
QStringList path = s.split("\\", QString::SkipEmptyParts);
|
||||
if(path.empty()) continue;
|
||||
if (path.empty()) continue;
|
||||
const QString feed_url = path.takeLast();
|
||||
qDebug() << "Feed URL:" << feed_url;
|
||||
// Create feed path (if it does not exists)
|
||||
RssFolder* feed_parent = this;
|
||||
foreach(const QString &folder_name, path) {
|
||||
foreach (const QString &folder_name, path) {
|
||||
qDebug() << "Adding parent folder:" << folder_name;
|
||||
feed_parent = feed_parent->addFolder(folder_name).data();
|
||||
}
|
||||
@@ -86,7 +86,7 @@ void RssManager::loadStreamList() {
|
||||
qDebug() << "Adding feed to parent folder";
|
||||
RssFeedPtr stream = feed_parent->addStream(this, feed_url);
|
||||
const QString alias = aliases.at(i);
|
||||
if(!alias.isEmpty()) {
|
||||
if (!alias.isEmpty()) {
|
||||
stream->rename(alias);
|
||||
}
|
||||
++i;
|
||||
@@ -104,7 +104,7 @@ void RssManager::forwardFeedIconChanged(const QString &url, const QString &icon_
|
||||
|
||||
void RssManager::moveFile(const RssFilePtr& file, const RssFolderPtr& dest_folder) {
|
||||
RssFolder* src_folder = file->parent();
|
||||
if(dest_folder != src_folder) {
|
||||
if (dest_folder != src_folder) {
|
||||
// Remove reference in old folder
|
||||
src_folder->takeChild(file->id());
|
||||
// add to new Folder
|
||||
@@ -118,9 +118,9 @@ void RssManager::saveStreamList() const {
|
||||
QStringList streamsUrl;
|
||||
QStringList aliases;
|
||||
QList<RssFeedPtr> streams = getAllFeeds();
|
||||
foreach(const RssFeedPtr& stream, streams) {
|
||||
foreach (const RssFeedPtr& stream, streams) {
|
||||
QString stream_path = stream->pathHierarchy().join("\\");
|
||||
if(stream_path.isNull()) {
|
||||
if (stream_path.isNull()) {
|
||||
stream_path = "";
|
||||
}
|
||||
qDebug("Saving stream path: %s", qPrintable(stream_path));
|
||||
|
||||
@@ -89,7 +89,7 @@ public:
|
||||
|
||||
QList<QByteArray> getHostNameCookies(const QString &host_name) const {
|
||||
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();
|
||||
return raw_cookies.split(':');
|
||||
}
|
||||
@@ -97,10 +97,10 @@ public:
|
||||
void setHostNameCookies(const QString &host_name, const QList<QByteArray> &cookies) {
|
||||
QMap<QString, QVariant> hosts_table = value("Rss/hosts_cookies").toMap();
|
||||
QByteArray raw_cookies = "";
|
||||
foreach(const QByteArray& cookie, cookies) {
|
||||
foreach (const QByteArray& cookie, cookies) {
|
||||
raw_cookies += cookie + ":";
|
||||
}
|
||||
if(raw_cookies.endsWith(":"))
|
||||
if (raw_cookies.endsWith(":"))
|
||||
raw_cookies.chop(1);
|
||||
hosts_table.insert(host_name, raw_cookies);
|
||||
setValue("Rss/hosts_cookies", hosts_table);
|
||||
|
||||
@@ -76,15 +76,15 @@ engineSelectDlg::~engineSelectDlg() {
|
||||
void engineSelectDlg::dropEvent(QDropEvent *event) {
|
||||
event->acceptProposedAction();
|
||||
QStringList files=event->mimeData()->text().split(QString::fromUtf8("\n"));
|
||||
foreach(QString file, files) {
|
||||
foreach (QString file, files) {
|
||||
qDebug("dropped %s", qPrintable(file));
|
||||
if(misc::isUrl(file)) {
|
||||
if (misc::isUrl(file)) {
|
||||
setCursor(QCursor(Qt::WaitCursor));
|
||||
downloader->downloadUrl(file);
|
||||
continue;
|
||||
}
|
||||
if(file.endsWith(".py", Qt::CaseInsensitive)) {
|
||||
if(file.startsWith("file:", Qt::CaseInsensitive))
|
||||
if (file.endsWith(".py", Qt::CaseInsensitive)) {
|
||||
if (file.startsWith("file:", Qt::CaseInsensitive))
|
||||
file = QUrl(file).toLocalFile();
|
||||
QString plugin_name = misc::fileName(file);
|
||||
plugin_name.chop(3); // Remove extension
|
||||
@@ -96,7 +96,7 @@ void engineSelectDlg::dropEvent(QDropEvent *event) {
|
||||
// Decode if we accept drag 'n drop or not
|
||||
void engineSelectDlg::dragEnterEvent(QDragEnterEvent *event) {
|
||||
QString mime;
|
||||
foreach(mime, event->mimeData()->formats()){
|
||||
foreach (mime, event->mimeData()->formats()){
|
||||
qDebug("mimeData: %s", qPrintable(mime));
|
||||
}
|
||||
if (event->mimeData()->hasFormat(QString::fromUtf8("text/plain")) || event->mimeData()->hasFormat(QString::fromUtf8("text/uri-list"))) {
|
||||
@@ -113,7 +113,7 @@ void engineSelectDlg::on_updateButton_clicked() {
|
||||
void engineSelectDlg::toggleEngineState(QTreeWidgetItem *item, int) {
|
||||
SupportedEngine *engine = supported_engines->value(item->text(ENGINE_ID));
|
||||
engine->setEnabled(!engine->isEnabled());
|
||||
if(engine->isEnabled()) {
|
||||
if (engine->isEnabled()) {
|
||||
item->setText(ENGINE_STATE, tr("Yes"));
|
||||
setRowColor(pluginsTree->indexOfTopLevelItem(item), "green");
|
||||
} else {
|
||||
@@ -126,7 +126,7 @@ void engineSelectDlg::displayContextMenu(const QPoint&) {
|
||||
QMenu myContextMenu(this);
|
||||
// Enable/disable pause/start action given the DL state
|
||||
QList<QTreeWidgetItem *> items = pluginsTree->selectedItems();
|
||||
if(items.isEmpty()) return;
|
||||
if (items.isEmpty()) return;
|
||||
QString first_id = items.first()->text(ENGINE_ID);
|
||||
actionEnable->setChecked(supported_engines->value(first_id)->isEnabled());
|
||||
myContextMenu.addAction(actionEnable);
|
||||
@@ -143,11 +143,11 @@ void engineSelectDlg::on_actionUninstall_triggered() {
|
||||
QList<QTreeWidgetItem *> items = pluginsTree->selectedItems();
|
||||
QTreeWidgetItem *item;
|
||||
bool error = false;
|
||||
foreach(item, items) {
|
||||
foreach (item, items) {
|
||||
int index = pluginsTree->indexOfTopLevelItem(item);
|
||||
Q_ASSERT(index != -1);
|
||||
QString id = item->text(ENGINE_ID);
|
||||
if(QFile::exists(":/nova/engines/"+id+".py")) {
|
||||
if (QFile::exists(":/nova/engines/"+id+".py")) {
|
||||
error = true;
|
||||
// Disable it instead
|
||||
supported_engines->value(id)->setEnabled(false);
|
||||
@@ -162,7 +162,7 @@ void engineSelectDlg::on_actionUninstall_triggered() {
|
||||
filters << id+".*";
|
||||
QStringList files = enginesFolder.entryList(filters, QDir::Files, QDir::Unsorted);
|
||||
QString file;
|
||||
foreach(file, files) {
|
||||
foreach (file, files) {
|
||||
enginesFolder.remove(file);
|
||||
}
|
||||
// Remove it from supported engines
|
||||
@@ -170,7 +170,7 @@ void engineSelectDlg::on_actionUninstall_triggered() {
|
||||
delete item;
|
||||
}
|
||||
}
|
||||
if(error)
|
||||
if (error)
|
||||
QMessageBox::warning(0, tr("Uninstall warning"), tr("Some plugins could not be uninstalled because they are included in qBittorrent.\n Only the ones you added yourself can be uninstalled.\nHowever, those plugins were disabled."));
|
||||
else
|
||||
QMessageBox::information(0, tr("Uninstall success"), tr("All selected plugins were uninstalled successfully"));
|
||||
@@ -179,12 +179,12 @@ void engineSelectDlg::on_actionUninstall_triggered() {
|
||||
void engineSelectDlg::enableSelection(bool enable) {
|
||||
QList<QTreeWidgetItem *> items = pluginsTree->selectedItems();
|
||||
QTreeWidgetItem *item;
|
||||
foreach(item, items) {
|
||||
foreach (item, items) {
|
||||
int index = pluginsTree->indexOfTopLevelItem(item);
|
||||
Q_ASSERT(index != -1);
|
||||
QString id = item->text(ENGINE_ID);
|
||||
supported_engines->value(id)->setEnabled(enable);
|
||||
if(enable) {
|
||||
if (enable) {
|
||||
item->setText(ENGINE_STATE, tr("Yes"));
|
||||
setRowColor(index, "green");
|
||||
} else {
|
||||
@@ -197,16 +197,16 @@ void engineSelectDlg::enableSelection(bool enable) {
|
||||
// Set the color of a row in data model
|
||||
void engineSelectDlg::setRowColor(int row, QString color){
|
||||
QTreeWidgetItem *item = pluginsTree->topLevelItem(row);
|
||||
for(int i=0; i<pluginsTree->columnCount(); ++i){
|
||||
for (int i=0; i<pluginsTree->columnCount(); ++i){
|
||||
item->setData(i, Qt::ForegroundRole, QVariant(QColor(color)));
|
||||
}
|
||||
}
|
||||
|
||||
QList<QTreeWidgetItem*> engineSelectDlg::findItemsWithUrl(QString url){
|
||||
QList<QTreeWidgetItem*> res;
|
||||
for(int i=0; i<pluginsTree->topLevelItemCount(); ++i) {
|
||||
for (int i=0; i<pluginsTree->topLevelItemCount(); ++i) {
|
||||
QTreeWidgetItem *item = pluginsTree->topLevelItem(i);
|
||||
if(url.startsWith(item->text(ENGINE_URL), Qt::CaseInsensitive))
|
||||
if (url.startsWith(item->text(ENGINE_URL), Qt::CaseInsensitive))
|
||||
res << item;
|
||||
}
|
||||
return res;
|
||||
@@ -214,9 +214,9 @@ QList<QTreeWidgetItem*> engineSelectDlg::findItemsWithUrl(QString url){
|
||||
|
||||
QTreeWidgetItem* engineSelectDlg::findItemWithID(QString id){
|
||||
QList<QTreeWidgetItem*> res;
|
||||
for(int i=0; i<pluginsTree->topLevelItemCount(); ++i) {
|
||||
for (int i=0; i<pluginsTree->topLevelItemCount(); ++i) {
|
||||
QTreeWidgetItem *item = pluginsTree->topLevelItem(i);
|
||||
if(id == item->text(ENGINE_ID))
|
||||
if (id == item->text(ENGINE_ID))
|
||||
return item;
|
||||
}
|
||||
return 0;
|
||||
@@ -232,7 +232,7 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
|
||||
qDebug("Asked to install plugin at %s", qPrintable(path));
|
||||
qreal new_version = SearchEngine::getPluginVersion(path);
|
||||
qDebug("Version to be installed: %.2f", new_version);
|
||||
if(!isUpdateNeeded(plugin_name, new_version)) {
|
||||
if (!isUpdateNeeded(plugin_name, new_version)) {
|
||||
qDebug("Apparently update is not needed, we have a more recent version");
|
||||
QMessageBox::information(this, tr("Search plugin install")+" -- "+tr("qBittorrent"), tr("A more recent version of %1 search engine plugin is already installed.", "%1 is the name of the search engine").arg(plugin_name));
|
||||
return;
|
||||
@@ -240,7 +240,7 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
|
||||
// Process with install
|
||||
QString dest_path = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+plugin_name+".py";
|
||||
bool update = false;
|
||||
if(QFile::exists(dest_path)) {
|
||||
if (QFile::exists(dest_path)) {
|
||||
// Backup in case install fails
|
||||
QFile::copy(dest_path, dest_path+".bak");
|
||||
QFile::remove(dest_path);
|
||||
@@ -252,8 +252,8 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
|
||||
// Update supported plugins
|
||||
supported_engines->update();
|
||||
// Check if this was correctly installed
|
||||
if(!supported_engines->contains(plugin_name)) {
|
||||
if(update) {
|
||||
if (!supported_engines->contains(plugin_name)) {
|
||||
if (update) {
|
||||
// Remove broken file
|
||||
QFile::remove(dest_path);
|
||||
// restore backup
|
||||
@@ -269,10 +269,10 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
|
||||
}
|
||||
}
|
||||
// Install was successful, remove backup
|
||||
if(update) {
|
||||
if (update) {
|
||||
QFile::remove(dest_path+".bak");
|
||||
}
|
||||
if(update) {
|
||||
if (update) {
|
||||
QMessageBox::information(this, tr("Search plugin install")+" -- "+tr("qBittorrent"), tr("%1 search engine plugin was successfully updated.", "%1 is the name of the search engine").arg(plugin_name));
|
||||
return;
|
||||
} else {
|
||||
@@ -284,7 +284,7 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
|
||||
void engineSelectDlg::loadSupportedSearchEngines() {
|
||||
// Some clean up first
|
||||
pluginsTree->clear();
|
||||
foreach(QString name, supported_engines->keys()) {
|
||||
foreach (QString name, supported_engines->keys()) {
|
||||
addNewEngine(name);
|
||||
}
|
||||
}
|
||||
@@ -295,7 +295,7 @@ void engineSelectDlg::addNewEngine(QString engine_name) {
|
||||
item->setText(ENGINE_NAME, engine->getFullName());
|
||||
item->setText(ENGINE_URL, engine->getUrl());
|
||||
item->setText(ENGINE_ID, engine->getName());
|
||||
if(engine->isEnabled()) {
|
||||
if (engine->isEnabled()) {
|
||||
item->setText(ENGINE_STATE, tr("Yes"));
|
||||
setRowColor(pluginsTree->indexOfTopLevelItem(item), "green");
|
||||
} else {
|
||||
@@ -304,12 +304,12 @@ void engineSelectDlg::addNewEngine(QString engine_name) {
|
||||
}
|
||||
// Handle icon
|
||||
QString iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+engine->getName()+".png";
|
||||
if(QFile::exists(iconPath)) {
|
||||
if (QFile::exists(iconPath)) {
|
||||
// Good, we already have the icon
|
||||
item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath)));
|
||||
} else {
|
||||
iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+engine->getName()+".ico";
|
||||
if(QFile::exists(iconPath)) { // ICO support
|
||||
if (QFile::exists(iconPath)) { // ICO support
|
||||
item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath)));
|
||||
} else {
|
||||
// Icon is missing, we must download it
|
||||
@@ -340,8 +340,8 @@ void engineSelectDlg::askForLocalPlugin() {
|
||||
tr("Select search plugins"), QDir::homePath(),
|
||||
tr("qBittorrent search plugins")+QString::fromUtf8(" (*.py)"));
|
||||
QString path;
|
||||
foreach(path, pathsList) {
|
||||
if(path.endsWith(".py", Qt::CaseInsensitive)) {
|
||||
foreach (path, pathsList) {
|
||||
if (path.endsWith(".py", Qt::CaseInsensitive)) {
|
||||
QString plugin_name = path.split(QDir::separator()).last();
|
||||
plugin_name.replace(".py", "", Qt::CaseInsensitive);
|
||||
installPlugin(path, plugin_name);
|
||||
@@ -353,7 +353,7 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) {
|
||||
qDebug("Checking if update is needed");
|
||||
bool file_correct = false;
|
||||
QFile versions(versions_file);
|
||||
if(!versions.open(QIODevice::ReadOnly | QIODevice::Text)){
|
||||
if (!versions.open(QIODevice::ReadOnly | QIODevice::Text)){
|
||||
qDebug("* Error: Could not read versions.txt file");
|
||||
return false;
|
||||
}
|
||||
@@ -362,19 +362,19 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) {
|
||||
QByteArray line = versions.readLine();
|
||||
line.replace("\n", "");
|
||||
line = line.trimmed();
|
||||
if(line.isEmpty()) continue;
|
||||
if(line.startsWith("#")) continue;
|
||||
if (line.isEmpty()) continue;
|
||||
if (line.startsWith("#")) continue;
|
||||
QList<QByteArray> list = line.split(' ');
|
||||
if(list.size() != 2) continue;
|
||||
if (list.size() != 2) continue;
|
||||
QString plugin_name = QString(list.first());
|
||||
if(!plugin_name.endsWith(":")) continue;
|
||||
if (!plugin_name.endsWith(":")) continue;
|
||||
plugin_name.chop(1); // remove trailing ':'
|
||||
bool ok;
|
||||
qreal version = list.last().toFloat(&ok);
|
||||
qDebug("read line %s: %.2f", qPrintable(plugin_name), version);
|
||||
if(!ok) continue;
|
||||
if (!ok) continue;
|
||||
file_correct = true;
|
||||
if(isUpdateNeeded(plugin_name, version)) {
|
||||
if (isUpdateNeeded(plugin_name, version)) {
|
||||
qDebug("Plugin: %s is outdated", qPrintable(plugin_name));
|
||||
// Downloading update
|
||||
setCursor(QCursor(Qt::WaitCursor));
|
||||
@@ -389,7 +389,7 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) {
|
||||
versions.close();
|
||||
// Clean up tmp file
|
||||
QFile::remove(versions_file);
|
||||
if(file_correct && !updated) {
|
||||
if (file_correct && !updated) {
|
||||
QMessageBox::information(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("All your plugins are already up to date."));
|
||||
}
|
||||
return file_correct;
|
||||
@@ -398,18 +398,18 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) {
|
||||
void engineSelectDlg::processDownloadedFile(QString url, QString filePath) {
|
||||
setCursor(QCursor(Qt::ArrowCursor));
|
||||
qDebug("engineSelectDlg received %s", qPrintable(url));
|
||||
if(url.endsWith("favicon.ico", Qt::CaseInsensitive)){
|
||||
if (url.endsWith("favicon.ico", Qt::CaseInsensitive)){
|
||||
// Icon downloaded
|
||||
QImage fileIcon;
|
||||
if(fileIcon.load(filePath)) {
|
||||
if (fileIcon.load(filePath)) {
|
||||
QList<QTreeWidgetItem*> items = findItemsWithUrl(url);
|
||||
QTreeWidgetItem *item;
|
||||
foreach(item, items){
|
||||
foreach (item, items){
|
||||
QString id = item->text(ENGINE_ID);
|
||||
QString iconPath;
|
||||
QFile icon(filePath);
|
||||
icon.open(QIODevice::ReadOnly);
|
||||
if(ICOHandler::canRead(&icon))
|
||||
if (ICOHandler::canRead(&icon))
|
||||
iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".ico";
|
||||
else
|
||||
iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".png";
|
||||
@@ -421,14 +421,14 @@ void engineSelectDlg::processDownloadedFile(QString url, QString filePath) {
|
||||
QFile::remove(filePath);
|
||||
return;
|
||||
}
|
||||
if(url.endsWith("versions.txt")) {
|
||||
if(!parseVersionsFile(filePath)) {
|
||||
if (url.endsWith("versions.txt")) {
|
||||
if (!parseVersionsFile(filePath)) {
|
||||
QMessageBox::warning(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("Sorry, update server is temporarily unavailable."));
|
||||
}
|
||||
QFile::remove(filePath);
|
||||
return;
|
||||
}
|
||||
if(url.endsWith(".py", Qt::CaseInsensitive)) {
|
||||
if (url.endsWith(".py", Qt::CaseInsensitive)) {
|
||||
QString plugin_name = misc::fileName(url);
|
||||
plugin_name.chop(3); // Remove extension
|
||||
installPlugin(filePath, plugin_name);
|
||||
@@ -439,15 +439,15 @@ void engineSelectDlg::processDownloadedFile(QString url, QString filePath) {
|
||||
|
||||
void engineSelectDlg::handleDownloadFailure(QString url, QString reason) {
|
||||
setCursor(QCursor(Qt::ArrowCursor));
|
||||
if(url.endsWith("favicon.ico", Qt::CaseInsensitive)){
|
||||
if (url.endsWith("favicon.ico", Qt::CaseInsensitive)){
|
||||
qDebug("Could not download favicon: %s, reason: %s", qPrintable(url), qPrintable(reason));
|
||||
return;
|
||||
}
|
||||
if(url.endsWith("versions.txt")) {
|
||||
if (url.endsWith("versions.txt")) {
|
||||
QMessageBox::warning(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("Sorry, update server is temporarily unavailable."));
|
||||
return;
|
||||
}
|
||||
if(url.endsWith(".py", Qt::CaseInsensitive)) {
|
||||
if (url.endsWith(".py", Qt::CaseInsensitive)) {
|
||||
// a plugin update download has been failed
|
||||
QString plugin_name = url.split('/').last();
|
||||
plugin_name.replace(".py", "", Qt::CaseInsensitive);
|
||||
|
||||
@@ -114,7 +114,7 @@ void SearchEngine::fillCatCombobox() {
|
||||
comboCategory->clear();
|
||||
comboCategory->addItem(full_cat_names["all"], QVariant("all"));
|
||||
QStringList supported_cat = supported_engines->supportedCategories();
|
||||
foreach(QString cat, supported_cat) {
|
||||
foreach (QString cat, supported_cat) {
|
||||
qDebug("Supported category: %s", qPrintable(cat));
|
||||
comboCategory->addItem(full_cat_names[cat], QVariant(cat));
|
||||
}
|
||||
@@ -123,10 +123,10 @@ void SearchEngine::fillCatCombobox() {
|
||||
#ifdef Q_WS_WIN
|
||||
bool SearchEngine::addPythonPathToEnv() {
|
||||
QString python_path = Preferences::getPythonPath();
|
||||
if(!python_path.isEmpty()) {
|
||||
if (!python_path.isEmpty()) {
|
||||
// Add it to PATH envvar
|
||||
QString path_envar = QString::fromLocal8Bit(qgetenv("PATH").constData());
|
||||
if(path_envar.isNull()) {
|
||||
if (path_envar.isNull()) {
|
||||
path_envar = "";
|
||||
}
|
||||
path_envar = python_path+";"+path_envar;
|
||||
@@ -162,7 +162,7 @@ void SearchEngine::pythonDownloadSuccess(QString url, QString file_path) {
|
||||
qDebug("Setup should be complete!");
|
||||
// Reload search engine
|
||||
has_python = addPythonPathToEnv();
|
||||
if(has_python) {
|
||||
if (has_python) {
|
||||
supported_engines->update();
|
||||
// Launch the search again
|
||||
on_search_button_clicked();
|
||||
@@ -189,7 +189,7 @@ SearchEngine::~SearchEngine(){
|
||||
saveSearchHistory();
|
||||
searchProcess->kill();
|
||||
searchProcess->waitForFinished();
|
||||
foreach(QProcess *downloader, downloaders) {
|
||||
foreach (QProcess *downloader, downloaders) {
|
||||
// Make sure we disconnect the SIGNAL/SLOT first
|
||||
// To avoid qreal free
|
||||
downloader->disconnect();
|
||||
@@ -203,7 +203,7 @@ SearchEngine::~SearchEngine(){
|
||||
delete searchTimeout;
|
||||
delete searchProcess;
|
||||
delete supported_engines;
|
||||
if(searchCompleter)
|
||||
if (searchCompleter)
|
||||
delete searchCompleter;
|
||||
}
|
||||
|
||||
@@ -215,24 +215,24 @@ void SearchEngine::displayPatternContextMenu(QPoint) {
|
||||
QAction clearAct(IconProvider::instance()->getIcon("edit-clear"), tr("Clear field"), &myMenu);
|
||||
QAction clearHistoryAct(IconProvider::instance()->getIcon("edit-clear-history"), tr("Clear completion history"), &myMenu);
|
||||
bool hasCopyAct = false;
|
||||
if(search_pattern->hasSelectedText()) {
|
||||
if (search_pattern->hasSelectedText()) {
|
||||
myMenu.addAction(&cutAct);
|
||||
myMenu.addAction(©Act);
|
||||
hasCopyAct = true;
|
||||
}
|
||||
if(qApp->clipboard()->mimeData()->hasText()) {
|
||||
if (qApp->clipboard()->mimeData()->hasText()) {
|
||||
myMenu.addAction(&pasteAct);
|
||||
hasCopyAct = true;
|
||||
}
|
||||
if(hasCopyAct)
|
||||
if (hasCopyAct)
|
||||
myMenu.addSeparator();
|
||||
myMenu.addAction(&clearHistoryAct);
|
||||
myMenu.addAction(&clearAct);
|
||||
QAction *act = myMenu.exec(QCursor::pos());
|
||||
if(act != 0) {
|
||||
if(act == &clearHistoryAct) {
|
||||
if (act != 0) {
|
||||
if (act == &clearHistoryAct) {
|
||||
// Ask for confirmation
|
||||
if(QMessageBox::question(this, tr("Confirmation"), tr("Are you sure you want to clear the history?"), QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
|
||||
if (QMessageBox::question(this, tr("Confirmation"), tr("Are you sure you want to clear the history?"), QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
|
||||
// Clear history
|
||||
searchHistory.setStringList(QStringList());
|
||||
}
|
||||
@@ -255,9 +255,9 @@ void SearchEngine::displayPatternContextMenu(QPoint) {
|
||||
void SearchEngine::tab_changed(int t)
|
||||
{//when we switch from a tab that is not empty to another that is empty the download button
|
||||
//doesn't have to be available
|
||||
if(t>-1)
|
||||
if (t>-1)
|
||||
{//-1 = no more tab
|
||||
if(all_tab.at(tabWidget->currentIndex())->getCurrentSearchListModel()->rowCount()) {
|
||||
if (all_tab.at(tabWidget->currentIndex())->getCurrentSearchListModel()->rowCount()) {
|
||||
download_button->setEnabled(true);
|
||||
goToDescBtn->setEnabled(true);
|
||||
} else {
|
||||
@@ -296,8 +296,8 @@ void SearchEngine::giveFocusToSearchInput() {
|
||||
// Function called when we click on search button
|
||||
void SearchEngine::on_search_button_clicked(){
|
||||
#ifdef Q_WS_WIN
|
||||
if(!has_python) {
|
||||
if(QMessageBox::question(this, tr("Missing Python Interpreter"),
|
||||
if (!has_python) {
|
||||
if (QMessageBox::question(this, tr("Missing Python Interpreter"),
|
||||
tr("Python 2.x is required to use the search engine but it does not seem to be installed.\nDo you want to install it now?"),
|
||||
QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
|
||||
// Download and Install Python
|
||||
@@ -306,17 +306,17 @@ void SearchEngine::on_search_button_clicked(){
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if(searchProcess->state() != QProcess::NotRunning){
|
||||
if (searchProcess->state() != QProcess::NotRunning){
|
||||
#ifdef Q_WS_WIN
|
||||
searchProcess->kill();
|
||||
#else
|
||||
searchProcess->terminate();
|
||||
#endif
|
||||
search_stopped = true;
|
||||
if(searchTimeout->isActive()) {
|
||||
if (searchTimeout->isActive()) {
|
||||
searchTimeout->stop();
|
||||
}
|
||||
if(search_button->text() != tr("Search")) {
|
||||
if (search_button->text() != tr("Search")) {
|
||||
search_button->setText(tr("Search"));
|
||||
return;
|
||||
}
|
||||
@@ -327,7 +327,7 @@ void SearchEngine::on_search_button_clicked(){
|
||||
|
||||
const QString pattern = search_pattern->text().trimmed();
|
||||
// No search pattern entered
|
||||
if(pattern.isEmpty()){
|
||||
if (pattern.isEmpty()){
|
||||
QMessageBox::critical(0, tr("Empty search pattern"), tr("Please type a search pattern first"));
|
||||
return;
|
||||
}
|
||||
@@ -344,11 +344,11 @@ void SearchEngine::on_search_button_clicked(){
|
||||
#endif
|
||||
// if the pattern is not in the pattern
|
||||
QStringList wordList = searchHistory.stringList();
|
||||
if(wordList.indexOf(pattern) == -1){
|
||||
if (wordList.indexOf(pattern) == -1){
|
||||
//update the searchHistory list
|
||||
wordList.append(pattern);
|
||||
// verify the max size of the history
|
||||
if(wordList.size() > SEARCHHISTORY_MAXSIZE)
|
||||
if (wordList.size() > SEARCHHISTORY_MAXSIZE)
|
||||
wordList = wordList.mid(wordList.size()/2);
|
||||
searchHistory.setStringList(wordList);
|
||||
}
|
||||
@@ -373,7 +373,7 @@ void SearchEngine::on_search_button_clicked(){
|
||||
}
|
||||
|
||||
void SearchEngine::createCompleter() {
|
||||
if(searchCompleter)
|
||||
if (searchCompleter)
|
||||
delete searchCompleter;
|
||||
searchCompleter = new QCompleter(&searchHistory);
|
||||
searchCompleter->setCaseSensitivity(Qt::CaseInsensitive);
|
||||
@@ -381,14 +381,14 @@ void SearchEngine::createCompleter() {
|
||||
}
|
||||
|
||||
void SearchEngine::propagateSectionResized(int index, int , int newsize) {
|
||||
foreach(SearchTab * tab, all_tab) {
|
||||
foreach (SearchTab * tab, all_tab) {
|
||||
tab->getCurrentTreeView()->setColumnWidth(index, newsize);
|
||||
}
|
||||
saveResultsColumnsWidth();
|
||||
}
|
||||
|
||||
void SearchEngine::saveResultsColumnsWidth() {
|
||||
if(all_tab.size() > 0) {
|
||||
if (all_tab.size() > 0) {
|
||||
QTreeView* treeview = all_tab.first()->getCurrentTreeView();
|
||||
QIniSettings settings("qBittorrent", "qBittorrent");
|
||||
QStringList width_list;
|
||||
@@ -396,14 +396,14 @@ void SearchEngine::saveResultsColumnsWidth() {
|
||||
short nbColumns = all_tab.first()->getCurrentSearchListModel()->columnCount();
|
||||
|
||||
QString line = settings.value("SearchResultsColsWidth", QString()).toString();
|
||||
if(!line.isEmpty()) {
|
||||
if (!line.isEmpty()) {
|
||||
width_list = line.split(' ');
|
||||
}
|
||||
for(short i=0; i<nbColumns; ++i){
|
||||
if(treeview->columnWidth(i)<1 && width_list.size() == nbColumns && width_list.at(i).toInt()>=1) {
|
||||
for (short i=0; i<nbColumns; ++i){
|
||||
if (treeview->columnWidth(i)<1 && width_list.size() == nbColumns && width_list.at(i).toInt()>=1) {
|
||||
// load the former width
|
||||
new_width_list << width_list.at(i);
|
||||
} else if(treeview->columnWidth(i)>=1) {
|
||||
} else if (treeview->columnWidth(i)>=1) {
|
||||
// usual case, save the current width
|
||||
new_width_list << QString::number(treeview->columnWidth(i));
|
||||
} else {
|
||||
@@ -417,11 +417,11 @@ void SearchEngine::saveResultsColumnsWidth() {
|
||||
}
|
||||
|
||||
void SearchEngine::downloadTorrent(QString engine_url, QString torrent_url) {
|
||||
if(torrent_url.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
if (torrent_url.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
qDebug("Converting bc link to magnet link");
|
||||
torrent_url = misc::bcLinkToMagnet(torrent_url);
|
||||
}
|
||||
if(torrent_url.startsWith("magnet:")) {
|
||||
if (torrent_url.startsWith("magnet:")) {
|
||||
QStringList urls;
|
||||
urls << torrent_url;
|
||||
mp_mainWindow->downloadFromURLList(urls);
|
||||
@@ -453,24 +453,24 @@ void SearchEngine::readSearchOutput(){
|
||||
QByteArray output = searchProcess->readAllStandardOutput();
|
||||
output.replace("\r", "");
|
||||
QList<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();
|
||||
lines_list.prepend(search_result_line_truncated+end_of_line);
|
||||
}
|
||||
search_result_line_truncated = lines_list.takeLast().trimmed();
|
||||
foreach(const QByteArray &line, lines_list){
|
||||
foreach (const QByteArray &line, lines_list){
|
||||
appendSearchResult(QString::fromUtf8(line));
|
||||
}
|
||||
if(currentSearchTab)
|
||||
if (currentSearchTab)
|
||||
currentSearchTab->getCurrentLabel()->setText(tr("Results")+QString::fromUtf8(" <i>(")+QString::number(nb_search_results)+QString::fromUtf8(")</i>:"));
|
||||
}
|
||||
|
||||
void SearchEngine::downloadFinished(int exitcode, QProcess::ExitStatus) {
|
||||
QProcess *downloadProcess = (QProcess*)sender();
|
||||
if(exitcode == 0) {
|
||||
if (exitcode == 0) {
|
||||
QString line = QString::fromUtf8(downloadProcess->readAllStandardOutput()).trimmed();
|
||||
QStringList parts = line.split(' ');
|
||||
if(parts.size() == 2) {
|
||||
if (parts.size() == 2) {
|
||||
QString path = parts[0];
|
||||
QString url = parts[1];
|
||||
QBtSession::instance()->processDownloadedFile(url, path);
|
||||
@@ -490,7 +490,7 @@ void SearchEngine::updateNova() {
|
||||
QFile package_file(search_dir.absoluteFilePath("__init__.py"));
|
||||
package_file.open(QIODevice::WriteOnly | QIODevice::Text);
|
||||
package_file.close();
|
||||
if(!search_dir.exists("engines")){
|
||||
if (!search_dir.exists("engines")){
|
||||
search_dir.mkdir("engines");
|
||||
}
|
||||
QFile package_file2(search_dir.absolutePath().replace("\\", "/")+"/engines/__init__.py");
|
||||
@@ -498,8 +498,8 @@ void SearchEngine::updateNova() {
|
||||
package_file2.close();
|
||||
// Copy search plugin files (if necessary)
|
||||
QString filePath = search_dir.absoluteFilePath("nova2.py");
|
||||
if(getPluginVersion(":/"+nova_folder+"/nova2.py") > getPluginVersion(filePath)) {
|
||||
if(QFile::exists(filePath)) {
|
||||
if (getPluginVersion(":/"+nova_folder+"/nova2.py") > getPluginVersion(filePath)) {
|
||||
if (QFile::exists(filePath)) {
|
||||
QFile::remove(filePath);
|
||||
QFile::remove(filePath+"c");
|
||||
}
|
||||
@@ -507,8 +507,8 @@ void SearchEngine::updateNova() {
|
||||
}
|
||||
|
||||
filePath = search_dir.absoluteFilePath("nova2dl.py");
|
||||
if(getPluginVersion(":/"+nova_folder+"/nova2dl.py") > getPluginVersion(filePath)) {
|
||||
if(QFile::exists(filePath)){
|
||||
if (getPluginVersion(":/"+nova_folder+"/nova2dl.py") > getPluginVersion(filePath)) {
|
||||
if (QFile::exists(filePath)){
|
||||
QFile::remove(filePath);
|
||||
QFile::remove(filePath+"c");
|
||||
}
|
||||
@@ -516,8 +516,8 @@ void SearchEngine::updateNova() {
|
||||
}
|
||||
|
||||
filePath = search_dir.absoluteFilePath("novaprinter.py");
|
||||
if(getPluginVersion(":/"+nova_folder+"/novaprinter.py") > getPluginVersion(filePath)) {
|
||||
if(QFile::exists(filePath)){
|
||||
if (getPluginVersion(":/"+nova_folder+"/novaprinter.py") > getPluginVersion(filePath)) {
|
||||
if (QFile::exists(filePath)){
|
||||
QFile::remove(filePath);
|
||||
QFile::remove(filePath+"c");
|
||||
}
|
||||
@@ -525,8 +525,8 @@ void SearchEngine::updateNova() {
|
||||
}
|
||||
|
||||
filePath = search_dir.absoluteFilePath("helpers.py");
|
||||
if(getPluginVersion(":/"+nova_folder+"/helpers.py") > getPluginVersion(filePath)) {
|
||||
if(QFile::exists(filePath)){
|
||||
if (getPluginVersion(":/"+nova_folder+"/helpers.py") > getPluginVersion(filePath)) {
|
||||
if (QFile::exists(filePath)){
|
||||
QFile::remove(filePath);
|
||||
QFile::remove(filePath+"c");
|
||||
}
|
||||
@@ -534,7 +534,7 @@ void SearchEngine::updateNova() {
|
||||
}
|
||||
|
||||
filePath = search_dir.absoluteFilePath("socks.py");
|
||||
if(QFile::exists(filePath)){
|
||||
if (QFile::exists(filePath)){
|
||||
QFile::remove(filePath);
|
||||
QFile::remove(filePath+"c");
|
||||
}
|
||||
@@ -542,7 +542,7 @@ void SearchEngine::updateNova() {
|
||||
|
||||
if (nova_folder == "nova3") {
|
||||
filePath = search_dir.absoluteFilePath("sgmllib3.py");
|
||||
if(QFile::exists(filePath)){
|
||||
if (QFile::exists(filePath)){
|
||||
QFile::remove(filePath);
|
||||
QFile::remove(filePath+"c");
|
||||
}
|
||||
@@ -551,14 +551,14 @@ void SearchEngine::updateNova() {
|
||||
QDir destDir(QDir(misc::searchEngineLocation()).absoluteFilePath("engines"));
|
||||
QDir shipped_subDir(":/"+nova_folder+"/engines/");
|
||||
QStringList files = shipped_subDir.entryList();
|
||||
foreach(const QString &file, files){
|
||||
foreach (const QString &file, files){
|
||||
QString shipped_file = shipped_subDir.absoluteFilePath(file);
|
||||
// Copy python classes
|
||||
if(file.endsWith(".py")) {
|
||||
if (file.endsWith(".py")) {
|
||||
const QString dest_file = destDir.absoluteFilePath(file);
|
||||
if(getPluginVersion(shipped_file) > getPluginVersion(dest_file) ) {
|
||||
if (getPluginVersion(shipped_file) > getPluginVersion(dest_file) ) {
|
||||
qDebug("shipped %s is more recent then local plugin, updating...", qPrintable(file));
|
||||
if(QFile::exists(dest_file)) {
|
||||
if (QFile::exists(dest_file)) {
|
||||
qDebug("Removing old %s", qPrintable(dest_file));
|
||||
QFile::remove(dest_file);
|
||||
QFile::remove(dest_file+"c");
|
||||
@@ -568,8 +568,8 @@ void SearchEngine::updateNova() {
|
||||
}
|
||||
} else {
|
||||
// Copy icons
|
||||
if(file.endsWith(".png")) {
|
||||
if(!QFile::exists(destDir.absoluteFilePath(file))) {
|
||||
if (file.endsWith(".png")) {
|
||||
if (!QFile::exists(destDir.absoluteFilePath(file))) {
|
||||
QFile::copy(shipped_file, destDir.absoluteFilePath(file));
|
||||
}
|
||||
}
|
||||
@@ -581,32 +581,32 @@ void SearchEngine::updateNova() {
|
||||
// Search can be finished for 3 reasons :
|
||||
// Error | Stopped by user | Finished normally
|
||||
void SearchEngine::searchFinished(int exitcode,QProcess::ExitStatus){
|
||||
if(searchTimeout->isActive()) {
|
||||
if (searchTimeout->isActive()) {
|
||||
searchTimeout->stop();
|
||||
}
|
||||
QIniSettings settings("qBittorrent", "qBittorrent");
|
||||
bool useNotificationBalloons = settings.value("Preferences/General/NotificationBaloons", true).toBool();
|
||||
if(useNotificationBalloons && mp_mainWindow->getCurrentTabWidget() != this) {
|
||||
if (useNotificationBalloons && mp_mainWindow->getCurrentTabWidget() != this) {
|
||||
mp_mainWindow->showNotificationBaloon(tr("Search Engine"), tr("Search has finished"));
|
||||
}
|
||||
if(exitcode){
|
||||
if (exitcode){
|
||||
#ifdef Q_WS_WIN
|
||||
search_status->setText(tr("Search aborted"));
|
||||
#else
|
||||
search_status->setText(tr("An error occured during search..."));
|
||||
#endif
|
||||
}else{
|
||||
if(search_stopped){
|
||||
if (search_stopped){
|
||||
search_status->setText(tr("Search aborted"));
|
||||
}else{
|
||||
if(no_search_results){
|
||||
if (no_search_results){
|
||||
search_status->setText(tr("Search returned no results"));
|
||||
}else{
|
||||
search_status->setText(tr("Search has finished"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if(currentSearchTab)
|
||||
if (currentSearchTab)
|
||||
currentSearchTab->getCurrentLabel()->setText(tr("Results", "i.e: Search results")+QString::fromUtf8(" <i>(")+QString::number(nb_search_results)+QString::fromUtf8(")</i>:"));
|
||||
search_button->setText("Search");
|
||||
}
|
||||
@@ -615,11 +615,11 @@ void SearchEngine::searchFinished(int exitcode,QProcess::ExitStatus){
|
||||
// Line is in the following form :
|
||||
// file url | file name | file size | nb seeds | nb leechers | Search engine url
|
||||
void SearchEngine::appendSearchResult(const QString &line){
|
||||
if(!currentSearchTab) {
|
||||
if(searchProcess->state() != QProcess::NotRunning){
|
||||
if (!currentSearchTab) {
|
||||
if (searchProcess->state() != QProcess::NotRunning){
|
||||
searchProcess->terminate();
|
||||
}
|
||||
if(searchTimeout->isActive()) {
|
||||
if (searchTimeout->isActive()) {
|
||||
searchTimeout->stop();
|
||||
}
|
||||
search_stopped = true;
|
||||
@@ -627,7 +627,7 @@ void SearchEngine::appendSearchResult(const QString &line){
|
||||
}
|
||||
const QStringList parts = line.split("|");
|
||||
const int nb_fields = parts.size();
|
||||
if(nb_fields < NB_PLUGIN_COLUMNS-1){ //-1 because desc_link is optional
|
||||
if (nb_fields < NB_PLUGIN_COLUMNS-1){ //-1 because desc_link is optional
|
||||
return;
|
||||
}
|
||||
Q_ASSERT(currentSearchTab);
|
||||
@@ -642,20 +642,20 @@ void SearchEngine::appendSearchResult(const QString &line){
|
||||
cur_model->setData(cur_model->index(row, SIZE), parts.at(PL_SIZE).trimmed().toLongLong()); // Size
|
||||
bool ok = false;
|
||||
qlonglong nb_seeders = parts.at(PL_SEEDS).trimmed().toLongLong(&ok);
|
||||
if(!ok || nb_seeders < 0) {
|
||||
if (!ok || nb_seeders < 0) {
|
||||
cur_model->setData(cur_model->index(row, SEEDS), tr("Unknown")); // Seeders
|
||||
} else {
|
||||
cur_model->setData(cur_model->index(row, SEEDS), nb_seeders); // Seeders
|
||||
}
|
||||
qlonglong nb_leechers = parts.at(PL_LEECHS).trimmed().toLongLong(&ok);
|
||||
if(!ok || nb_leechers < 0) {
|
||||
if (!ok || nb_leechers < 0) {
|
||||
cur_model->setData(cur_model->index(row, LEECHS), tr("Unknown")); // Leechers
|
||||
} else {
|
||||
cur_model->setData(cur_model->index(row, LEECHS), nb_leechers); // Leechers
|
||||
}
|
||||
cur_model->setData(cur_model->index(row, ENGINE_URL), parts.at(PL_ENGINE_URL).trimmed()); // Engine URL
|
||||
// Description Link
|
||||
if(nb_fields == NB_PLUGIN_COLUMNS)
|
||||
if (nb_fields == NB_PLUGIN_COLUMNS)
|
||||
cur_model->setData(cur_model->index(row, DESC_LINK), parts.at(PL_DESC_LINK).trimmed());
|
||||
|
||||
no_search_results = false;
|
||||
@@ -667,19 +667,19 @@ void SearchEngine::appendSearchResult(const QString &line){
|
||||
|
||||
#if QT_VERSION >= 0x040500
|
||||
void SearchEngine::closeTab(int index) {
|
||||
if(index == tabWidget->indexOf(currentSearchTab)) {
|
||||
if (index == tabWidget->indexOf(currentSearchTab)) {
|
||||
qDebug("Deleted current search Tab");
|
||||
if(searchProcess->state() != QProcess::NotRunning){
|
||||
if (searchProcess->state() != QProcess::NotRunning){
|
||||
searchProcess->terminate();
|
||||
}
|
||||
if(searchTimeout->isActive()) {
|
||||
if (searchTimeout->isActive()) {
|
||||
searchTimeout->stop();
|
||||
}
|
||||
search_stopped = true;
|
||||
currentSearchTab = 0;
|
||||
}
|
||||
delete all_tab.takeAt(index);
|
||||
if(!all_tab.size()) {
|
||||
if (!all_tab.size()) {
|
||||
download_button->setEnabled(false);
|
||||
goToDescBtn->setEnabled(false);
|
||||
}
|
||||
@@ -687,22 +687,22 @@ void SearchEngine::closeTab(int index) {
|
||||
#else
|
||||
// Clear search results list
|
||||
void SearchEngine::closeTab_button_clicked(){
|
||||
if(all_tab.size()) {
|
||||
if (all_tab.size()) {
|
||||
qDebug("currentTab rank: %d", tabWidget->currentIndex());
|
||||
qDebug("currentSearchTab rank: %d", tabWidget->indexOf(currentSearchTab));
|
||||
if(tabWidget->currentIndex() == tabWidget->indexOf(currentSearchTab)) {
|
||||
if (tabWidget->currentIndex() == tabWidget->indexOf(currentSearchTab)) {
|
||||
qDebug("Deleted current search Tab");
|
||||
if(searchProcess->state() != QProcess::NotRunning){
|
||||
if (searchProcess->state() != QProcess::NotRunning){
|
||||
searchProcess->terminate();
|
||||
}
|
||||
if(searchTimeout->isActive()) {
|
||||
if (searchTimeout->isActive()) {
|
||||
searchTimeout->stop();
|
||||
}
|
||||
search_stopped = true;
|
||||
currentSearchTab = 0;
|
||||
}
|
||||
delete all_tab.takeAt(tabWidget->currentIndex());
|
||||
if(!all_tab.size()) {
|
||||
if (!all_tab.size()) {
|
||||
closeTab_button->setEnabled(false);
|
||||
download_button->setEnabled(false);
|
||||
}
|
||||
@@ -714,8 +714,8 @@ void SearchEngine::closeTab_button_clicked(){
|
||||
void SearchEngine::on_download_button_clicked(){
|
||||
//QModelIndexList selectedIndexes = currentSearchTab->getCurrentTreeView()->selectionModel()->selectedIndexes();
|
||||
QModelIndexList selectedIndexes = all_tab.at(tabWidget->currentIndex())->getCurrentTreeView()->selectionModel()->selectedIndexes();
|
||||
foreach(const QModelIndex &index, selectedIndexes){
|
||||
if(index.column() == NAME){
|
||||
foreach (const QModelIndex &index, selectedIndexes){
|
||||
if (index.column() == NAME){
|
||||
// Get Item url
|
||||
QSortFilterProxyModel* model = all_tab.at(tabWidget->currentIndex())->getCurrentSearchListProxy();
|
||||
QString torrent_url = model->data(model->index(index.row(), URL_COLUMN)).toString();
|
||||
@@ -729,11 +729,11 @@ void SearchEngine::on_download_button_clicked(){
|
||||
void SearchEngine::on_goToDescBtn_clicked()
|
||||
{
|
||||
QModelIndexList selectedIndexes = all_tab.at(tabWidget->currentIndex())->getCurrentTreeView()->selectionModel()->selectedIndexes();
|
||||
foreach(const QModelIndex &index, selectedIndexes){
|
||||
if(index.column() == NAME) {
|
||||
foreach (const QModelIndex &index, selectedIndexes){
|
||||
if (index.column() == NAME) {
|
||||
QSortFilterProxyModel* model = all_tab.at(tabWidget->currentIndex())->getCurrentSearchListProxy();
|
||||
const QString desc_url = model->data(model->index(index.row(), DESC_LINK)).toString();
|
||||
if(!desc_url.isEmpty())
|
||||
if (!desc_url.isEmpty())
|
||||
QDesktopServices::openUrl(QUrl::fromEncoded(desc_url.toUtf8()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,17 +65,17 @@ public:
|
||||
|
||||
static qreal getPluginVersion(QString filePath) {
|
||||
QFile plugin(filePath);
|
||||
if(!plugin.exists()){
|
||||
if (!plugin.exists()){
|
||||
qDebug("%s plugin does not exist, returning 0.0", qPrintable(filePath));
|
||||
return 0.0;
|
||||
}
|
||||
if(!plugin.open(QIODevice::ReadOnly | QIODevice::Text)){
|
||||
if (!plugin.open(QIODevice::ReadOnly | QIODevice::Text)){
|
||||
return 0.0;
|
||||
}
|
||||
qreal version = 0.0;
|
||||
while (!plugin.atEnd()){
|
||||
QByteArray line = plugin.readLine();
|
||||
if(line.startsWith("#VERSION: ")){
|
||||
if (line.startsWith("#VERSION: ")){
|
||||
line = line.split(' ').last().trimmed();
|
||||
version = line.toFloat();
|
||||
qDebug("plugin %s version: %.2f", qPrintable(filePath), version);
|
||||
|
||||
@@ -77,7 +77,7 @@ SearchTab::SearchTab(SearchEngine *parent) : QWidget(), parent(parent)
|
||||
connect(resultsBrowser, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(downloadSelectedItem(const QModelIndex&)));
|
||||
|
||||
// Load last columns width for search results list
|
||||
if(!loadColWidthResultsList()){
|
||||
if (!loadColWidthResultsList()){
|
||||
resultsBrowser->header()->resizeSection(0, 275);
|
||||
}
|
||||
|
||||
@@ -108,13 +108,13 @@ QHeaderView* SearchTab::header() const {
|
||||
bool SearchTab::loadColWidthResultsList() {
|
||||
QIniSettings settings("qBittorrent", "qBittorrent");
|
||||
QString line = settings.value("SearchResultsColsWidth", QString()).toString();
|
||||
if(line.isEmpty())
|
||||
if (line.isEmpty())
|
||||
return false;
|
||||
QStringList width_list = line.split(' ');
|
||||
if(width_list.size() < SearchListModel->columnCount())
|
||||
if (width_list.size() < SearchListModel->columnCount())
|
||||
return false;
|
||||
unsigned int listSize = width_list.size();
|
||||
for(unsigned int i=0; i<listSize; ++i){
|
||||
for (unsigned int i=0; i<listSize; ++i){
|
||||
resultsBrowser->header()->resizeSection(i, width_list.at(i).toInt());
|
||||
}
|
||||
return true;
|
||||
@@ -143,7 +143,7 @@ QStandardItemModel* SearchTab::getCurrentSearchListModel() const
|
||||
// Set the color of a row in data model
|
||||
void SearchTab::setRowColor(int row, QString color){
|
||||
proxyModel->setDynamicSortFilter(false);
|
||||
for(int i=0; i<proxyModel->columnCount(); ++i){
|
||||
for (int i=0; i<proxyModel->columnCount(); ++i){
|
||||
proxyModel->setData(proxyModel->index(row, i), QVariant(QColor(color)), Qt::ForegroundRole);
|
||||
}
|
||||
proxyModel->setDynamicSortFilter(true);
|
||||
|
||||
@@ -89,7 +89,7 @@ public:
|
||||
// Save to Hard disk
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
|
||||
QStringList disabled_engines = settings.value(QString::fromUtf8("SearchEngines/disabledEngines"), QStringList()).toStringList();
|
||||
if(enabled) {
|
||||
if (enabled) {
|
||||
disabled_engines.removeAll(name);
|
||||
} else {
|
||||
disabled_engines.append(name);
|
||||
@@ -106,7 +106,7 @@ signals:
|
||||
|
||||
public:
|
||||
SupportedEngines(bool has_python = true) {
|
||||
if(has_python)
|
||||
if (has_python)
|
||||
update();
|
||||
}
|
||||
|
||||
@@ -116,8 +116,8 @@ public:
|
||||
|
||||
QStringList enginesEnabled() const {
|
||||
QStringList engines;
|
||||
foreach(const SupportedEngine *engine, values()) {
|
||||
if(engine->isEnabled())
|
||||
foreach (const SupportedEngine *engine, values()) {
|
||||
if (engine->isEnabled())
|
||||
engines << engine->getName();
|
||||
}
|
||||
return engines;
|
||||
@@ -125,12 +125,12 @@ public:
|
||||
|
||||
QStringList supportedCategories() const {
|
||||
QStringList supported_cat;
|
||||
foreach(const SupportedEngine *engine, values()) {
|
||||
if(engine->isEnabled()) {
|
||||
foreach (const SupportedEngine *engine, values()) {
|
||||
if (engine->isEnabled()) {
|
||||
const QStringList &s = engine->getSupportedCategories();
|
||||
foreach(QString cat, s) {
|
||||
foreach (QString cat, s) {
|
||||
cat = cat.trimmed();
|
||||
if(!cat.isEmpty() && !supported_cat.contains(cat))
|
||||
if (!cat.isEmpty() && !supported_cat.contains(cat))
|
||||
supported_cat << cat;
|
||||
}
|
||||
}
|
||||
@@ -150,21 +150,21 @@ public slots:
|
||||
nova.waitForFinished();
|
||||
QString capabilities = QString(nova.readAll());
|
||||
QDomDocument xml_doc;
|
||||
if(!xml_doc.setContent(capabilities)) {
|
||||
if (!xml_doc.setContent(capabilities)) {
|
||||
std::cerr << "Could not parse Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data() << std::endl;
|
||||
std::cerr << "Error: " << nova.readAllStandardError().constData() << std::endl;
|
||||
return;
|
||||
}
|
||||
QDomElement root = xml_doc.documentElement();
|
||||
if(root.tagName() != "capabilities") {
|
||||
if (root.tagName() != "capabilities") {
|
||||
std::cout << "Invalid XML file for Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data() << std::endl;
|
||||
return;
|
||||
}
|
||||
for(QDomNode engine_node = root.firstChild(); !engine_node.isNull(); engine_node = engine_node.nextSibling()) {
|
||||
for (QDomNode engine_node = root.firstChild(); !engine_node.isNull(); engine_node = engine_node.nextSibling()) {
|
||||
QDomElement engine_elem = engine_node.toElement();
|
||||
if(!engine_elem.isNull()) {
|
||||
if (!engine_elem.isNull()) {
|
||||
SupportedEngine *s = new SupportedEngine(engine_elem);
|
||||
if(this->contains(s->getName())) {
|
||||
if (this->contains(s->getName())) {
|
||||
// Already in the list
|
||||
delete s;
|
||||
} else {
|
||||
|
||||
12
src/smtp.cpp
12
src/smtp.cpp
@@ -122,14 +122,14 @@ void Smtp::sendMail(const QString &from, const QString &to, const QString &subje
|
||||
this->from = from;
|
||||
rcpt = to;
|
||||
// Authentication
|
||||
if(pref.getMailNotificationSMTPAuth()) {
|
||||
if (pref.getMailNotificationSMTPAuth()) {
|
||||
username = pref.getMailNotificationSMTPUsername();
|
||||
password = pref.getMailNotificationSMTPPassword();
|
||||
}
|
||||
|
||||
// Connect to SMTP server
|
||||
#ifndef QT_NO_OPENSSL
|
||||
if(pref.getMailNotificationSMTPSSL()) {
|
||||
if (pref.getMailNotificationSMTPSSL()) {
|
||||
socket->connectToHostEncrypted(pref.getMailNotificationSMTP(), DEFAULT_PORT_SSL);
|
||||
use_ssl = true;
|
||||
} else {
|
||||
@@ -158,7 +158,7 @@ void Smtp::readyRead()
|
||||
|
||||
switch(state) {
|
||||
case Init: {
|
||||
if(code[0] == '2') {
|
||||
if (code[0] == '2') {
|
||||
// Connection was successful
|
||||
ehlo();
|
||||
} else {
|
||||
@@ -257,7 +257,7 @@ QByteArray Smtp::encode_mime_header(const QString& key, const QString& value, QT
|
||||
if (!prefix.isEmpty()) line += prefix;
|
||||
if (!value.contains("=?") && latin1->canEncode(value)) {
|
||||
bool firstWord = true;
|
||||
foreach(const QByteArray& word, value.toAscii().split(' ')) {
|
||||
foreach (const QByteArray& word, value.toAscii().split(' ')) {
|
||||
if (line.size() > 78) {
|
||||
rv = rv + line + "\r\n";
|
||||
line.clear();
|
||||
@@ -292,7 +292,7 @@ QByteArray Smtp::encode_mime_header(const QString& key, const QString& value, QT
|
||||
void Smtp::ehlo()
|
||||
{
|
||||
QByteArray address = "127.0.0.1";
|
||||
foreach(const QHostAddress& addr, QNetworkInterface::allAddresses())
|
||||
foreach (const QHostAddress& addr, QNetworkInterface::allAddresses())
|
||||
{
|
||||
if (addr == QHostAddress::LocalHost || addr == QHostAddress::LocalHostIPv6)
|
||||
continue;
|
||||
@@ -309,7 +309,7 @@ void Smtp::parseEhloResponse(const QByteArray& code, bool continued, const QStri
|
||||
{
|
||||
if (code != "250") {
|
||||
// Error
|
||||
if(state == EhloSent) {
|
||||
if (state == EhloSent) {
|
||||
// try to send HELO instead of EHLO
|
||||
qDebug() << "EHLO failed, trying HELO instead...";
|
||||
socket->write("helo\r\n");
|
||||
|
||||
@@ -60,10 +60,10 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg {
|
||||
dlg.setWindowTitle(title);
|
||||
dlg.setMaxValue(max_value/1024.);
|
||||
dlg.setDefaultValue(default_value/1024.);
|
||||
if(dlg.exec() == QDialog::Accepted) {
|
||||
if (dlg.exec() == QDialog::Accepted) {
|
||||
*ok = true;
|
||||
int val = dlg.getSpeedLimit();
|
||||
if(val <= 0)
|
||||
if (val <= 0)
|
||||
return -1;
|
||||
return val*1024;
|
||||
} else {
|
||||
@@ -75,7 +75,7 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg {
|
||||
protected slots:
|
||||
void updateSpinValue(int val) const {
|
||||
qDebug("Called updateSpinValue with %d", val);
|
||||
if(val <= 0){
|
||||
if (val <= 0){
|
||||
spinBandwidth->setValue(0);
|
||||
spinBandwidth->setSpecialValueText(QString::fromUtf8("∞"));
|
||||
spinBandwidth->setSuffix(QString::fromUtf8(""));
|
||||
@@ -86,7 +86,7 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg {
|
||||
}
|
||||
|
||||
void updateSliderValue(int val) const {
|
||||
if(val <= 0) {
|
||||
if (val <= 0) {
|
||||
spinBandwidth->setValue(0);
|
||||
spinBandwidth->setSpecialValueText(QString::fromUtf8("∞"));
|
||||
spinBandwidth->setSuffix(QString::fromUtf8(""));
|
||||
@@ -96,21 +96,21 @@ class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg {
|
||||
|
||||
long getSpeedLimit() const {
|
||||
long val = bandwidthSlider->value();
|
||||
if(val > 0)
|
||||
if (val > 0)
|
||||
return val;
|
||||
return -1;
|
||||
}
|
||||
|
||||
void setMaxValue(long val) const {
|
||||
if(val > 0) {
|
||||
if (val > 0) {
|
||||
bandwidthSlider->setMaximum(val);
|
||||
spinBandwidth->setMaximum(val);
|
||||
}
|
||||
}
|
||||
|
||||
void setDefaultValue(long val) const {
|
||||
if(val < 0) val = 0;
|
||||
if(val > bandwidthSlider->maximum()) val = bandwidthSlider->maximum();
|
||||
if (val < 0) val = 0;
|
||||
if (val > bandwidthSlider->maximum()) val = bandwidthSlider->maximum();
|
||||
bandwidthSlider->setValue(val);
|
||||
updateSpinValue(val);
|
||||
}
|
||||
|
||||
@@ -167,11 +167,11 @@ public slots:
|
||||
void refreshStatusBar() {
|
||||
// Update connection status
|
||||
const libtorrent::session_status sessionStatus = QBtSession::instance()->getSessionStatus();
|
||||
if(!QBtSession::instance()->getSession()->is_listening()) {
|
||||
if (!QBtSession::instance()->getSession()->is_listening()) {
|
||||
connecStatusLblIcon->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/disconnected.png")));
|
||||
connecStatusLblIcon->setToolTip(QString::fromUtf8("<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 {
|
||||
if(sessionStatus.has_incoming_connections) {
|
||||
if (sessionStatus.has_incoming_connections) {
|
||||
// Connection OK
|
||||
connecStatusLblIcon->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/connected.png")));
|
||||
connecStatusLblIcon->setToolTip(QString::fromUtf8("<b>")+tr("Connection Status:")+QString::fromUtf8("</b><br>")+tr("Online"));
|
||||
@@ -181,7 +181,7 @@ public slots:
|
||||
}
|
||||
}
|
||||
// Update Number of DHT nodes
|
||||
if(QBtSession::instance()->isDHTEnabled()) {
|
||||
if (QBtSession::instance()->isDHTEnabled()) {
|
||||
DHTLbl->setVisible(true);
|
||||
//statusSep1->setVisible(true);
|
||||
DHTLbl->setText(tr("DHT: %1 nodes").arg(QString::number(sessionStatus.dht_nodes)));
|
||||
@@ -195,7 +195,7 @@ public slots:
|
||||
}
|
||||
|
||||
void updateAltSpeedsBtn(bool alternative) {
|
||||
if(alternative) {
|
||||
if (alternative) {
|
||||
altSpeedsBtn->setIcon(QIcon(":/Icons/slow.png"));
|
||||
altSpeedsBtn->setToolTip(tr("Click to switch to regular speed limits"));
|
||||
altSpeedsBtn->setDown(true);
|
||||
@@ -218,18 +218,18 @@ public slots:
|
||||
int cur_limit = QBtSession::instance()->getSession()->download_rate_limit();
|
||||
#endif
|
||||
long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), cur_limit);
|
||||
if(ok) {
|
||||
if (ok) {
|
||||
Preferences pref;
|
||||
bool alt = pref.isAltBandwidthEnabled();
|
||||
if(new_limit <= 0) {
|
||||
if (new_limit <= 0) {
|
||||
qDebug("Setting global download rate limit to Unlimited");
|
||||
QBtSession::instance()->setDownloadRateLimit(-1);
|
||||
if(!alt)
|
||||
if (!alt)
|
||||
pref.setGlobalDownloadLimit(-1);
|
||||
} else {
|
||||
qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.);
|
||||
QBtSession::instance()->setDownloadRateLimit(new_limit);
|
||||
if(!alt)
|
||||
if (!alt)
|
||||
pref.setGlobalDownloadLimit(new_limit/1024.);
|
||||
}
|
||||
}
|
||||
@@ -243,18 +243,18 @@ public slots:
|
||||
int cur_limit = QBtSession::instance()->getSession()->upload_rate_limit();
|
||||
#endif
|
||||
long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), cur_limit);
|
||||
if(ok) {
|
||||
if (ok) {
|
||||
Preferences pref;
|
||||
bool alt = pref.isAltBandwidthEnabled();
|
||||
if(new_limit <= 0) {
|
||||
if (new_limit <= 0) {
|
||||
qDebug("Setting global upload rate limit to Unlimited");
|
||||
QBtSession::instance()->setUploadRateLimit(-1);
|
||||
if(!alt)
|
||||
if (!alt)
|
||||
Preferences().setGlobalUploadLimit(-1);
|
||||
} else {
|
||||
qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.);
|
||||
QBtSession::instance()->setUploadRateLimit(new_limit);
|
||||
if(!alt)
|
||||
if (!alt)
|
||||
Preferences().setGlobalUploadLimit(new_limit/1024.);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) :
|
||||
|
||||
appendLabelToSavePath = pref.appendTorrentLabel();
|
||||
QString display_path = defaultSavePath.replace("\\", "/");
|
||||
if(!display_path.endsWith("/"))
|
||||
if (!display_path.endsWith("/"))
|
||||
display_path += "/";
|
||||
path_history << display_path;
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
@@ -99,7 +99,7 @@ torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) :
|
||||
#endif
|
||||
savePathTxt->addItem(display_path);
|
||||
|
||||
if(pref.addTorrentsInPause()) {
|
||||
if (pref.addTorrentsInPause()) {
|
||||
addInPause->setChecked(true);
|
||||
//addInPause->setEnabled(false);
|
||||
}
|
||||
@@ -108,7 +108,7 @@ torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) :
|
||||
settings.beginGroup(QString::fromUtf8("TransferListFilters"));
|
||||
const QStringList customLabels = settings.value("customLabels", QStringList()).toStringList();
|
||||
comboLabel->addItem("");
|
||||
foreach(const QString& label, customLabels) {
|
||||
foreach (const QString& label, customLabels) {
|
||||
comboLabel->addItem(label);
|
||||
}
|
||||
|
||||
@@ -142,7 +142,7 @@ void torrentAdditionDialog::readSettings() {
|
||||
}
|
||||
}
|
||||
if (m_showContentList) {
|
||||
if(!torrentContentList->header()->restoreState(settings.value("TorrentAdditionDlg/ContentHeaderState").toByteArray())) {
|
||||
if (!torrentContentList->header()->restoreState(settings.value("TorrentAdditionDlg/ContentHeaderState").toByteArray())) {
|
||||
qDebug() << Q_FUNC_INFO << "First executation, resize first section to 400px...";
|
||||
torrentContentList->header()->resizeSection(0, 400); // Default
|
||||
}
|
||||
@@ -162,16 +162,16 @@ void torrentAdditionDialog::limitDialogWidth() {
|
||||
int scrn = 0;
|
||||
const QWidget *w = this->window();
|
||||
|
||||
if(w)
|
||||
if (w)
|
||||
scrn = QApplication::desktop()->screenNumber(w);
|
||||
else if(QApplication::desktop()->isVirtualDesktop())
|
||||
else if (QApplication::desktop()->isVirtualDesktop())
|
||||
scrn = QApplication::desktop()->screenNumber(QCursor::pos());
|
||||
else
|
||||
scrn = QApplication::desktop()->screenNumber(this);
|
||||
|
||||
QRect desk(QApplication::desktop()->availableGeometry(scrn));
|
||||
int max_width = desk.width();
|
||||
if(max_width > 0)
|
||||
if (max_width > 0)
|
||||
setMaximumWidth(max_width);
|
||||
}
|
||||
|
||||
@@ -179,12 +179,12 @@ void torrentAdditionDialog::hideTorrentContent() {
|
||||
// Disable useless widgets
|
||||
torrentContentList->setVisible(false);
|
||||
//torrentContentLbl->setVisible(false);
|
||||
for(int i=0; i<selectionBtnsLayout->count(); ++i) {
|
||||
if(selectionBtnsLayout->itemAt(i)->widget())
|
||||
for (int i=0; i<selectionBtnsLayout->count(); ++i) {
|
||||
if (selectionBtnsLayout->itemAt(i)->widget())
|
||||
selectionBtnsLayout->itemAt(i)->widget()->setVisible(false);
|
||||
}
|
||||
for(int i=0; i<contentFilterLayout->count(); ++i) {
|
||||
if(contentFilterLayout->itemAt(i)->widget())
|
||||
for (int i=0; i<contentFilterLayout->count(); ++i) {
|
||||
if (contentFilterLayout->itemAt(i)->widget())
|
||||
contentFilterLayout->itemAt(i)->widget()->setVisible(false);
|
||||
}
|
||||
contentFilterLayout->update();
|
||||
@@ -204,13 +204,13 @@ void torrentAdditionDialog::showLoadMagnetURI(QString magnet_uri) {
|
||||
|
||||
// Get torrent hash
|
||||
hash = misc::magnetUriToHash(magnet_uri);
|
||||
if(hash.isEmpty()) {
|
||||
if (hash.isEmpty()) {
|
||||
QBtSession::instance()->addConsoleMessage(tr("Unable to decode magnet link:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red"));
|
||||
return;
|
||||
}
|
||||
// Set torrent name
|
||||
fileName = misc::magnetUriToName(magnet_uri);
|
||||
if(fileName.isEmpty()) {
|
||||
if (fileName.isEmpty()) {
|
||||
fileName = tr("Magnet Link");
|
||||
}
|
||||
fileNameLbl->setText(QString::fromUtf8("<center><b>")+fileName+QString::fromUtf8("</b></center>"));
|
||||
@@ -234,10 +234,10 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
|
||||
is_magnet = false;
|
||||
|
||||
// This is an URL to a local file, switch to local path
|
||||
if(filePath.startsWith("file:", Qt::CaseInsensitive))
|
||||
if (filePath.startsWith("file:", Qt::CaseInsensitive))
|
||||
filePath = QUrl::fromEncoded(filePath.toLocal8Bit()).toLocalFile();
|
||||
|
||||
if(!QFile::exists(filePath)) {
|
||||
if (!QFile::exists(filePath)) {
|
||||
close();
|
||||
return;
|
||||
}
|
||||
@@ -249,11 +249,11 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
|
||||
// Getting torrent file informations
|
||||
try {
|
||||
t = new torrent_info(filePath.toUtf8().data());
|
||||
if(!t->is_valid())
|
||||
if (!t->is_valid())
|
||||
throw std::exception();
|
||||
} catch(std::exception&) {
|
||||
qDebug("Caught error loading torrent");
|
||||
if(!from_url.isNull()){
|
||||
if (!from_url.isNull()){
|
||||
QBtSession::instance()->addConsoleMessage(tr("Unable to decode torrent file:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red"));
|
||||
QFile::remove(filePath);
|
||||
}else{
|
||||
@@ -263,7 +263,7 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
|
||||
return;
|
||||
}
|
||||
nbFiles = t->num_files();
|
||||
if(nbFiles == 0) {
|
||||
if (nbFiles == 0) {
|
||||
// Empty torrent file!?
|
||||
close();
|
||||
return;
|
||||
@@ -278,18 +278,18 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
|
||||
hash = misc::toQString(t->info_hash());
|
||||
// Use left() to remove .old extension
|
||||
QString newFileName;
|
||||
if(fileName.endsWith(QString::fromUtf8(".old"))){
|
||||
if (fileName.endsWith(QString::fromUtf8(".old"))){
|
||||
newFileName = fileName.left(fileName.size()-4);
|
||||
}else{
|
||||
newFileName = fileName;
|
||||
}
|
||||
fileNameLbl->setText(QString::fromUtf8("<center><b>")+newFileName+QString::fromUtf8("</b></center>"));
|
||||
if(t->num_files() > 1) {
|
||||
if (t->num_files() > 1) {
|
||||
// List files in torrent
|
||||
PropListModel->model()->setupModelData(*t);
|
||||
connect(PropDelegate, SIGNAL(filteredFilesChanged()), this, SLOT(updateDiskSpaceLabels()));
|
||||
// Loads files path in the torrent
|
||||
for(uint i=0; i<nbFiles; ++i) {
|
||||
for (uint i=0; i<nbFiles; ++i) {
|
||||
#if LIBTORRENT_VERSION_MINOR >= 16
|
||||
files_path << misc::toQStringU(fs.file_path(t->file_at(i)));
|
||||
#else
|
||||
@@ -310,13 +310,13 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
save_path.replace("/", "\\");
|
||||
#endif
|
||||
if(!save_path.endsWith(QDir::separator()))
|
||||
if (!save_path.endsWith(QDir::separator()))
|
||||
save_path += QDir::separator();
|
||||
// If the torrent has a root folder, append it to the save path
|
||||
if(!root_folder.isEmpty()) {
|
||||
if (!root_folder.isEmpty()) {
|
||||
save_path += root_folder;
|
||||
}
|
||||
if(nbFiles == 1) {
|
||||
if (nbFiles == 1) {
|
||||
// single file torrent
|
||||
#if LIBTORRENT_VERSION_MINOR >= 16
|
||||
QString single_file_relpath = misc::toQStringU(fs.file_path(t->file_at(0)));
|
||||
@@ -334,7 +334,7 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
|
||||
updateDiskSpaceLabels();
|
||||
|
||||
// Hide useless widgets
|
||||
if(t->num_files() <= 1)
|
||||
if (t->num_files() <= 1)
|
||||
hideTorrentContent();
|
||||
|
||||
// Remember dialog geometry
|
||||
@@ -352,7 +352,7 @@ void torrentAdditionDialog::displayContentListMenu(const QPoint&) {
|
||||
QMenu myFilesLlistMenu;
|
||||
const QModelIndexList selectedRows = torrentContentList->selectionModel()->selectedRows(0);
|
||||
QAction *actRename = 0;
|
||||
if(selectedRows.size() == 1 && t->num_files() > 1) {
|
||||
if (selectedRows.size() == 1 && t->num_files() > 1) {
|
||||
actRename = myFilesLlistMenu.addAction(IconProvider::instance()->getIcon("edit-rename"), tr("Rename..."));
|
||||
myFilesLlistMenu.addSeparator();
|
||||
}
|
||||
@@ -365,24 +365,24 @@ void torrentAdditionDialog::displayContentListMenu(const QPoint&) {
|
||||
myFilesLlistMenu.addMenu(&subMenu);
|
||||
// Call menu
|
||||
QAction *act = myFilesLlistMenu.exec(QCursor::pos());
|
||||
if(act) {
|
||||
if(act == actRename) {
|
||||
if (act) {
|
||||
if (act == actRename) {
|
||||
renameSelectedFile();
|
||||
} else {
|
||||
int prio = 1;
|
||||
if(act == actionHigh) {
|
||||
if (act == actionHigh) {
|
||||
prio = prio::HIGH;
|
||||
} else {
|
||||
if(act == actionMaximum) {
|
||||
if (act == actionMaximum) {
|
||||
prio = prio::MAXIMUM;
|
||||
} else {
|
||||
if(act == actionNot_downloaded) {
|
||||
if (act == actionNot_downloaded) {
|
||||
prio = prio::IGNORED;
|
||||
}
|
||||
}
|
||||
}
|
||||
qDebug("Setting files priority");
|
||||
foreach(const QModelIndex &index, selectedRows) {
|
||||
foreach (const QModelIndex &index, selectedRows) {
|
||||
qDebug("Setting priority(%d) for file at row %d", prio, index.row());
|
||||
PropListModel->setData(PropListModel->index(index.row(), PRIORITY, index.parent()), prio);
|
||||
}
|
||||
@@ -401,13 +401,13 @@ void torrentAdditionDialog::renameSelectedFile() {
|
||||
tr("New name:"), QLineEdit::Normal,
|
||||
index.data().toString(), &ok);
|
||||
if (ok && !new_name_last.isEmpty()) {
|
||||
if(!misc::isValidFileSystemName(new_name_last)) {
|
||||
if (!misc::isValidFileSystemName(new_name_last)) {
|
||||
QMessageBox::warning(this, tr("The file could not be renamed"),
|
||||
tr("This file name contains forbidden characters, please choose a different one."),
|
||||
QMessageBox::Ok);
|
||||
return;
|
||||
}
|
||||
if(PropListModel->getType(index) == TorrentFileItem::TFILE) {
|
||||
if (PropListModel->getType(index) == TorrentFileItem::TFILE) {
|
||||
// File renaming
|
||||
const uint file_index = PropListModel->getFileIndex(index);
|
||||
QString old_name = files_path.at(file_index);
|
||||
@@ -417,19 +417,19 @@ void torrentAdditionDialog::renameSelectedFile() {
|
||||
path_items.removeLast();
|
||||
path_items << new_name_last;
|
||||
QString new_name = path_items.join("/");
|
||||
if(old_name == new_name) {
|
||||
if (old_name == new_name) {
|
||||
qDebug("Name did not change");
|
||||
return;
|
||||
}
|
||||
new_name = QDir::cleanPath(new_name);
|
||||
qDebug("New name: %s", qPrintable(new_name));
|
||||
// Check if that name is already used
|
||||
for(uint i=0; i<nbFiles; ++i) {
|
||||
if(i == file_index) continue;
|
||||
for (uint i=0; i<nbFiles; ++i) {
|
||||
if (i == file_index) continue;
|
||||
#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
|
||||
if(files_path.at(i).compare(new_name, Qt::CaseInsensitive) == 0) {
|
||||
if (files_path.at(i).compare(new_name, Qt::CaseInsensitive) == 0) {
|
||||
#endif
|
||||
// Display error message
|
||||
QMessageBox::warning(this, tr("The file could not be renamed"),
|
||||
@@ -457,14 +457,14 @@ void torrentAdditionDialog::renameSelectedFile() {
|
||||
path_items.removeLast();
|
||||
path_items << new_name_last;
|
||||
QString new_path = path_items.join("/");
|
||||
if(!new_path.endsWith("/")) new_path += "/";
|
||||
if (!new_path.endsWith("/")) new_path += "/";
|
||||
// Check for overwriting
|
||||
for(uint i=0; i<nbFiles; ++i) {
|
||||
for (uint i=0; i<nbFiles; ++i) {
|
||||
const QString ¤t_name = files_path.at(i);
|
||||
#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
|
||||
if(current_name.startsWith(new_path, Qt::CaseInsensitive)) {
|
||||
if (current_name.startsWith(new_path, Qt::CaseInsensitive)) {
|
||||
#endif
|
||||
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."),
|
||||
@@ -473,9 +473,9 @@ void torrentAdditionDialog::renameSelectedFile() {
|
||||
}
|
||||
}
|
||||
// Replace path in all files
|
||||
for(uint i=0; i<nbFiles; ++i) {
|
||||
for (uint i=0; i<nbFiles; ++i) {
|
||||
const QString ¤t_name = files_path.at(i);
|
||||
if(current_name.startsWith(old_path)) {
|
||||
if (current_name.startsWith(old_path)) {
|
||||
QString new_name = current_name;
|
||||
new_name.replace(0, old_path.length(), new_path);
|
||||
new_name = QDir::cleanPath(new_name);
|
||||
@@ -494,15 +494,15 @@ void torrentAdditionDialog::updateDiskSpaceLabels() {
|
||||
qDebug("Updating disk space label...");
|
||||
const long long available = misc::freeDiskSpaceOnPath(misc::expandPath(savePathTxt->currentText()));
|
||||
lbl_disk_space->setText(misc::friendlyUnit(available));
|
||||
if(!is_magnet) {
|
||||
if (!is_magnet) {
|
||||
// Determine torrent size
|
||||
qulonglong torrent_size = 0;
|
||||
if(t->num_files() > 1) {
|
||||
if (t->num_files() > 1) {
|
||||
const unsigned int nbFiles = t->num_files();
|
||||
const std::vector<int> priorities = PropListModel->model()->getFilesPriorities(nbFiles);
|
||||
|
||||
for(unsigned int i=0; i<nbFiles; ++i) {
|
||||
if(priorities[i] > 0)
|
||||
for (unsigned int i=0; i<nbFiles; ++i) {
|
||||
if (priorities[i] > 0)
|
||||
torrent_size += t->file_at(i).size;
|
||||
}
|
||||
} else {
|
||||
@@ -511,8 +511,8 @@ void torrentAdditionDialog::updateDiskSpaceLabels() {
|
||||
lbl_torrent_size->setText(misc::friendlyUnit(torrent_size));
|
||||
|
||||
// Check if free space is sufficient
|
||||
if(available > 0) {
|
||||
if((unsigned long long)available > torrent_size) {
|
||||
if (available > 0) {
|
||||
if ((unsigned long long)available > torrent_size) {
|
||||
// Space is sufficient
|
||||
label_space_msg->setText(tr("(%1 left after torrent download)", "e.g. (100MiB left after torrent download)").arg(misc::friendlyUnit(available-torrent_size)));
|
||||
} else {
|
||||
@@ -531,13 +531,13 @@ void torrentAdditionDialog::on_browseButton_clicked(){
|
||||
QString new_path;
|
||||
QString root_folder;
|
||||
const QString label_name = comboLabel->currentText();
|
||||
if(t->num_files() == 1) {
|
||||
if (t->num_files() == 1) {
|
||||
new_path = QFileDialog::getSaveFileName(this, tr("Choose save path"), savePathTxt->currentText(), QString(), 0, QFileDialog::DontConfirmOverwrite);
|
||||
if(!new_path.isEmpty()) {
|
||||
if (!new_path.isEmpty()) {
|
||||
QStringList path_parts = new_path.replace("\\", "/").split("/");
|
||||
const QString filename = path_parts.takeLast();
|
||||
// Append label
|
||||
if(QDir(path_parts.join(QDir::separator())) == QDir(defaultSavePath) && !label_name.isEmpty())
|
||||
if (QDir(path_parts.join(QDir::separator())) == QDir(defaultSavePath) && !label_name.isEmpty())
|
||||
path_parts << label_name;
|
||||
// Append file name
|
||||
path_parts << filename;
|
||||
@@ -546,26 +546,26 @@ void torrentAdditionDialog::on_browseButton_clicked(){
|
||||
}
|
||||
} else {
|
||||
QString truncated_path = getCurrentTruncatedSavePath(&root_folder);
|
||||
if(!truncated_path.isEmpty() && QDir(truncated_path).exists()){
|
||||
if (!truncated_path.isEmpty() && QDir(truncated_path).exists()){
|
||||
new_path = QFileDialog::getExistingDirectory(this, tr("Choose save path"), truncated_path);
|
||||
}else{
|
||||
new_path = QFileDialog::getExistingDirectory(this, tr("Choose save path"), QDir::homePath());
|
||||
}
|
||||
if(!new_path.isEmpty()) {
|
||||
if (!new_path.isEmpty()) {
|
||||
QStringList path_parts = new_path.replace("\\", "/").split("/");
|
||||
if(path_parts.last().isEmpty())
|
||||
if (path_parts.last().isEmpty())
|
||||
path_parts.removeLast();
|
||||
// Append label
|
||||
if(QDir(new_path) == QDir(defaultSavePath) && !label_name.isEmpty())
|
||||
if (QDir(new_path) == QDir(defaultSavePath) && !label_name.isEmpty())
|
||||
path_parts << label_name;
|
||||
// Append root folder
|
||||
if(!root_folder.isEmpty())
|
||||
if (!root_folder.isEmpty())
|
||||
path_parts << root_folder;
|
||||
// Construct new_path
|
||||
new_path = path_parts.join(QDir::separator());
|
||||
}
|
||||
}
|
||||
if(!new_path.isEmpty()) {
|
||||
if (!new_path.isEmpty()) {
|
||||
// Check if this new path already exists in the list
|
||||
QString new_truncated_path = getTruncatedSavePath(new_path);
|
||||
#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
|
||||
@@ -573,7 +573,7 @@ void torrentAdditionDialog::on_browseButton_clicked(){
|
||||
#else
|
||||
const int cur_index = path_history.indexOf(QRegExp(new_truncated_path, Qt::CaseSensitive));
|
||||
#endif
|
||||
if(cur_index >= 0) {
|
||||
if (cur_index >= 0) {
|
||||
savePathTxt->setCurrentIndex(cur_index);
|
||||
}
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
@@ -602,7 +602,7 @@ void torrentAdditionDialog::savePiecesPriorities(){
|
||||
void torrentAdditionDialog::on_OkButton_clicked(){
|
||||
Preferences pref;
|
||||
qDebug() << "void torrentAdditionDialog::on_OkButton_clicked() - ENTER";
|
||||
if(savePathTxt->currentText().trimmed().isEmpty()){
|
||||
if (savePathTxt->currentText().trimmed().isEmpty()){
|
||||
QMessageBox::critical(0, tr("Empty save path"), tr("Please enter a save path"));
|
||||
return;
|
||||
}
|
||||
@@ -612,7 +612,7 @@ void torrentAdditionDialog::on_OkButton_clicked(){
|
||||
#endif
|
||||
save_path = misc::expandPath(save_path);
|
||||
qDebug("Save path is %s", qPrintable(save_path));
|
||||
if(!is_magnet && t->num_files() == 1) {
|
||||
if (!is_magnet && t->num_files() == 1) {
|
||||
// Remove file name
|
||||
QStringList parts = save_path.split("/");
|
||||
const QString single_file_name = parts.takeLast();
|
||||
@@ -631,15 +631,15 @@ void torrentAdditionDialog::on_OkButton_clicked(){
|
||||
qDebug("Saving save path to temp data: %s", qPrintable(savePath.absolutePath()));
|
||||
TorrentTempData::setSavePath(hash, savePath.absolutePath());
|
||||
qDebug("Torrent label is: %s", qPrintable(comboLabel->currentText().trimmed()));
|
||||
if(!current_label.isEmpty())
|
||||
if (!current_label.isEmpty())
|
||||
TorrentTempData::setLabel(hash, current_label);
|
||||
// Is download sequential?
|
||||
TorrentTempData::setSequential(hash, checkIncrementalDL->isChecked());
|
||||
// Save files path
|
||||
// Loads files path in the torrent
|
||||
if(!is_magnet) {
|
||||
if (!is_magnet) {
|
||||
bool path_changed = false;
|
||||
for(uint i=0; i<nbFiles; ++i) {
|
||||
for (uint i=0; i<nbFiles; ++i) {
|
||||
#if LIBTORRENT_VERSION_MINOR >= 16
|
||||
file_storage fs = t->files();
|
||||
QString old_path = misc::toQStringU(fs.file_path(t->file_at(i)));
|
||||
@@ -647,23 +647,23 @@ void torrentAdditionDialog::on_OkButton_clicked(){
|
||||
QString old_path = misc::toQStringU(t->file_at(i).path.string());
|
||||
#endif
|
||||
#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
|
||||
if(files_path.at(i).compare(old_path, Qt::CaseSensitive) != 0) {
|
||||
if (files_path.at(i).compare(old_path, Qt::CaseSensitive) != 0) {
|
||||
#else
|
||||
if(files_path.at(i).compare(old_path, Qt::CaseInsensitive) != 0) {
|
||||
if (files_path.at(i).compare(old_path, Qt::CaseInsensitive) != 0) {
|
||||
#endif
|
||||
path_changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(path_changed) {
|
||||
if (path_changed) {
|
||||
qDebug("Changing files paths");
|
||||
TorrentTempData::setFilesPath(hash, files_path);
|
||||
}
|
||||
}
|
||||
// Skip file checking and directly start seeding
|
||||
if(addInSeed->isChecked()) {
|
||||
if (addInSeed->isChecked()) {
|
||||
// Check if local file(s) actually exist
|
||||
if(is_magnet || QFile::exists(savePathTxt->currentText())) {
|
||||
if (is_magnet || QFile::exists(savePathTxt->currentText())) {
|
||||
TorrentTempData::setSeedingMode(hash, true);
|
||||
} else {
|
||||
QMessageBox::warning(0, tr("Seeding mode error"), tr("You chose to skip file checking. However, local files do not seem to exist in the current destionation folder. Please disable this feature or update the save path."));
|
||||
@@ -671,7 +671,7 @@ void torrentAdditionDialog::on_OkButton_clicked(){
|
||||
}
|
||||
}
|
||||
// Check if there is at least one selected file
|
||||
if(!is_magnet && t->num_files() > 1 && allFiltered()){
|
||||
if (!is_magnet && t->num_files() > 1 && allFiltered()){
|
||||
QMessageBox::warning(0, tr("Invalid file selection"), tr("You must select at least one file in the torrent"));
|
||||
return;
|
||||
}
|
||||
@@ -683,23 +683,23 @@ void torrentAdditionDialog::on_OkButton_clicked(){
|
||||
pref.setSavePath(getCurrentTruncatedSavePath());
|
||||
|
||||
// Check if savePath exists
|
||||
if(!savePath.exists()){
|
||||
if(!savePath.mkpath(savePath.path())){
|
||||
if (!savePath.exists()){
|
||||
if (!savePath.mkpath(savePath.path())){
|
||||
QMessageBox::critical(0, tr("Save path creation error"), tr("Could not create the save path"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// save filtered files
|
||||
if(!is_magnet && t->num_files() > 1)
|
||||
if (!is_magnet && t->num_files() > 1)
|
||||
savePiecesPriorities();
|
||||
// Add to download list
|
||||
QTorrentHandle h;
|
||||
if(is_magnet)
|
||||
if (is_magnet)
|
||||
h = QBtSession::instance()->addMagnetUri(from_url, false);
|
||||
else
|
||||
h = QBtSession::instance()->addTorrent(filePath, false, from_url);
|
||||
if(addInPause->isChecked() && h.is_valid()) {
|
||||
if (addInPause->isChecked() && h.is_valid()) {
|
||||
h.pause();
|
||||
}
|
||||
// Close the dialog
|
||||
@@ -710,14 +710,14 @@ void torrentAdditionDialog::on_OkButton_clicked(){
|
||||
|
||||
void torrentAdditionDialog::resetComboLabelIndex(QString text) {
|
||||
// Select first index
|
||||
if(text != comboLabel->itemText(comboLabel->currentIndex())) {
|
||||
if (text != comboLabel->itemText(comboLabel->currentIndex())) {
|
||||
comboLabel->setItemText(0, text);
|
||||
comboLabel->setCurrentIndex(0);
|
||||
}
|
||||
}
|
||||
|
||||
void torrentAdditionDialog::updateLabelInSavePath(QString label) {
|
||||
if(appendLabelToSavePath) {
|
||||
if (appendLabelToSavePath) {
|
||||
// Update Label in combobox
|
||||
savePathTxt->setItemText(0, misc::updateLabelInSavePath(defaultSavePath, savePathTxt->itemText(0), old_label, label));
|
||||
// update edit text
|
||||
@@ -735,15 +735,15 @@ void torrentAdditionDialog::updateSavePathCurrentText() {
|
||||
QString root_folder_or_file_name = "";
|
||||
getCurrentTruncatedSavePath(&root_folder_or_file_name);
|
||||
// Update other combo items
|
||||
for(int i=0; i<savePathTxt->count(); ++i) {
|
||||
if(i == savePathTxt->currentIndex()) continue;
|
||||
for (int i=0; i<savePathTxt->count(); ++i) {
|
||||
if (i == savePathTxt->currentIndex()) continue;
|
||||
QString item_path = path_history.at(i);
|
||||
if(item_path.isEmpty()) continue;
|
||||
if (item_path.isEmpty()) continue;
|
||||
// Append label
|
||||
if(i == 0 && appendLabelToSavePath && QDir(item_path) == QDir(defaultSavePath) && !comboLabel->currentText().isEmpty())
|
||||
if (i == 0 && appendLabelToSavePath && QDir(item_path) == QDir(defaultSavePath) && !comboLabel->currentText().isEmpty())
|
||||
item_path += comboLabel->currentText() + "/";
|
||||
// Append root_folder or filename
|
||||
if(!root_folder_or_file_name.isEmpty())
|
||||
if (!root_folder_or_file_name.isEmpty())
|
||||
item_path += root_folder_or_file_name;
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
item_path.replace("/", "\\");
|
||||
@@ -763,17 +763,17 @@ QString torrentAdditionDialog::getTruncatedSavePath(QString save_path, QString*
|
||||
save_path = misc::expandPath(save_path);
|
||||
QStringList parts = save_path.replace("\\", "/").split("/");
|
||||
// Remove torrent root folder
|
||||
if(!QDir(save_path).exists() || (!is_magnet && t->num_files() == 1)) {
|
||||
if (!QDir(save_path).exists() || (!is_magnet && t->num_files() == 1)) {
|
||||
QString tmp = parts.takeLast();
|
||||
if(root_folder_or_file_name)
|
||||
if (root_folder_or_file_name)
|
||||
*root_folder_or_file_name = tmp;
|
||||
}
|
||||
// Remove label
|
||||
if(appendLabelToSavePath && savePathTxt->currentIndex() == 0 && parts.last() == comboLabel->currentText()) {
|
||||
if (appendLabelToSavePath && savePathTxt->currentIndex() == 0 && parts.last() == comboLabel->currentText()) {
|
||||
parts.removeLast();
|
||||
}
|
||||
QString truncated_path = parts.join("/");
|
||||
if(!truncated_path.endsWith("/"))
|
||||
if (!truncated_path.endsWith("/"))
|
||||
truncated_path += "/";
|
||||
qDebug("Truncated save path: %s", qPrintable(truncated_path));
|
||||
return truncated_path;
|
||||
@@ -785,14 +785,14 @@ void torrentAdditionDialog::saveTruncatedPathHistory() {
|
||||
// Get current history
|
||||
QStringList history = settings.value("TorrentAdditionDlg/save_path_history").toStringList();
|
||||
#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
|
||||
if(!history.contains(current_save_path, Qt::CaseSensitive)) {
|
||||
if (!history.contains(current_save_path, Qt::CaseSensitive)) {
|
||||
#else
|
||||
if(!history.contains(current_save_path, Qt::CaseInsensitive)) {
|
||||
if (!history.contains(current_save_path, Qt::CaseInsensitive)) {
|
||||
#endif
|
||||
// Add save path to history
|
||||
history << current_save_path;
|
||||
// Limit list size
|
||||
if(history.size() > 8)
|
||||
if (history.size() > 8)
|
||||
history.removeFirst();
|
||||
// Save history
|
||||
settings.setValue("TorrentAdditionDlg/save_path_history", history);
|
||||
@@ -803,8 +803,8 @@ void torrentAdditionDialog::loadSavePathHistory() {
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
|
||||
// Load save path history
|
||||
QStringList raw_path_history = settings.value("TorrentAdditionDlg/save_path_history").toStringList();
|
||||
foreach(const QString &sp, raw_path_history) {
|
||||
if(QDir(sp) != QDir(defaultSavePath)) {
|
||||
foreach (const QString &sp, raw_path_history) {
|
||||
if (QDir(sp) != QDir(defaultSavePath)) {
|
||||
QString dsp = sp;
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
dsp.replace("/", "\\");
|
||||
|
||||
@@ -63,7 +63,7 @@ TorrentCreatorDlg::TorrentCreatorDlg(QWidget *parent): QDialog(parent), creatorT
|
||||
}
|
||||
|
||||
TorrentCreatorDlg::~TorrentCreatorDlg() {
|
||||
if(creatorThread)
|
||||
if (creatorThread)
|
||||
delete creatorThread;
|
||||
}
|
||||
|
||||
@@ -71,14 +71,14 @@ void TorrentCreatorDlg::on_addFolder_button_clicked(){
|
||||
QIniSettings settings("qBittorrent", "qBittorrent");
|
||||
QString last_path = settings.value("CreateTorrent/last_add_path", QDir::homePath()).toString();
|
||||
QString dir = QFileDialog::getExistingDirectory(this, tr("Select a folder to add to the torrent"), last_path, QFileDialog::ShowDirsOnly);
|
||||
if(!dir.isEmpty()) {
|
||||
if (!dir.isEmpty()) {
|
||||
settings.setValue("CreateTorrent/last_add_path", dir);
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
dir.replace("/", "\\");
|
||||
#endif
|
||||
textInputPath->setText(dir);
|
||||
// Update piece size
|
||||
if(checkAutoPieceSize->isChecked())
|
||||
if (checkAutoPieceSize->isChecked())
|
||||
updateOptimalPieceSize();
|
||||
}
|
||||
}
|
||||
@@ -87,14 +87,14 @@ void TorrentCreatorDlg::on_addFile_button_clicked(){
|
||||
QIniSettings settings("qBittorrent", "qBittorrent");
|
||||
QString last_path = settings.value("CreateTorrent/last_add_path", QDir::homePath()).toString();
|
||||
QString file = QFileDialog::getOpenFileName(this, tr("Select a file to add to the torrent"), last_path);
|
||||
if(!file.isEmpty()) {
|
||||
if (!file.isEmpty()) {
|
||||
settings.setValue("CreateTorrent/last_add_path", misc::branchPath(file));
|
||||
#if defined(Q_WS_WIN) || defined(Q_OS_OS2)
|
||||
file.replace("/", "\\");
|
||||
#endif
|
||||
textInputPath->setText(file);
|
||||
// Update piece size
|
||||
if(checkAutoPieceSize->isChecked())
|
||||
if (checkAutoPieceSize->isChecked())
|
||||
updateOptimalPieceSize();
|
||||
}
|
||||
}
|
||||
@@ -108,21 +108,21 @@ void TorrentCreatorDlg::on_createButton_clicked(){
|
||||
QString input = textInputPath->text().trimmed();
|
||||
if (input.endsWith(QDir::separator()))
|
||||
input.chop(1);
|
||||
if(input.isEmpty()){
|
||||
if (input.isEmpty()){
|
||||
QMessageBox::critical(0, tr("No input path set"), tr("Please type an input path first"));
|
||||
return;
|
||||
}
|
||||
QStringList trackers = trackers_list->toPlainText().split("\n");
|
||||
if(!trackers_list->toPlainText().trimmed().isEmpty())
|
||||
if (!trackers_list->toPlainText().trimmed().isEmpty())
|
||||
saveTrackerList();
|
||||
|
||||
QIniSettings settings("qBittorrent", "qBittorrent");
|
||||
QString last_path = settings.value("CreateTorrent/last_save_path", QDir::homePath()).toString();
|
||||
|
||||
QString destination = QFileDialog::getSaveFileName(this, tr("Select destination torrent file"), last_path, tr("Torrent Files")+QString::fromUtf8(" (*.torrent)"));
|
||||
if(!destination.isEmpty()) {
|
||||
if (!destination.isEmpty()) {
|
||||
settings.setValue("CreateTorrent/last_save_path", misc::branchPath(destination));
|
||||
if(!destination.toUpper().endsWith(".TORRENT"))
|
||||
if (!destination.toUpper().endsWith(".TORRENT"))
|
||||
destination += QString::fromUtf8(".torrent");
|
||||
} else {
|
||||
return;
|
||||
@@ -154,7 +154,7 @@ void TorrentCreatorDlg::handleCreationFailure(QString msg) {
|
||||
void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path) {
|
||||
// Remove busy cursor
|
||||
setCursor(QCursor(Qt::ArrowCursor));
|
||||
if(checkStartSeeding->isChecked()) {
|
||||
if (checkStartSeeding->isChecked()) {
|
||||
QString root_folder;
|
||||
// Create save path temp data
|
||||
boost::intrusive_ptr<torrent_info> t;
|
||||
@@ -167,7 +167,7 @@ void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path)
|
||||
}
|
||||
QString hash = misc::toQString(t->info_hash());
|
||||
QString save_path = branch_path;
|
||||
if(!root_folder.isEmpty()) {
|
||||
if (!root_folder.isEmpty()) {
|
||||
save_path = QDir(save_path).absoluteFilePath(root_folder);
|
||||
}
|
||||
TorrentTempData::setSavePath(hash, save_path);
|
||||
@@ -181,7 +181,7 @@ void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path)
|
||||
|
||||
void TorrentCreatorDlg::on_cancelButton_clicked() {
|
||||
// End torrent creation thread
|
||||
if(creatorThread && creatorThread->isRunning()) {
|
||||
if (creatorThread && creatorThread->isRunning()) {
|
||||
creatorThread->abortCreation();
|
||||
creatorThread->terminate();
|
||||
// Wait for termination
|
||||
@@ -219,7 +219,7 @@ void TorrentCreatorDlg::showProgressBar(bool show)
|
||||
void TorrentCreatorDlg::on_checkAutoPieceSize_clicked(bool checked)
|
||||
{
|
||||
comboPieceSize->setEnabled(!checked);
|
||||
if(checked) {
|
||||
if (checked) {
|
||||
updateOptimalPieceSize();
|
||||
}
|
||||
}
|
||||
@@ -228,18 +228,18 @@ void TorrentCreatorDlg::updateOptimalPieceSize()
|
||||
{
|
||||
quint64 torrent_size = misc::computePathSize(textInputPath->text());
|
||||
qDebug("Torrent size is %lld", torrent_size);
|
||||
if(torrent_size == 0) return;
|
||||
if (torrent_size == 0) return;
|
||||
int i = 0;
|
||||
qulonglong nb_pieces = 0;
|
||||
do {
|
||||
nb_pieces = (double)torrent_size/(m_piece_sizes.at(i)*1024.);
|
||||
qDebug("nb_pieces=%lld with piece_size=%s", nb_pieces, qPrintable(comboPieceSize->itemText(i)));
|
||||
if(nb_pieces <= NB_PIECES_MIN) {
|
||||
if(i > 1)
|
||||
if (nb_pieces <= NB_PIECES_MIN) {
|
||||
if (i > 1)
|
||||
--i;
|
||||
break;
|
||||
}
|
||||
if(nb_pieces < NB_PIECES_MAX) {
|
||||
if (nb_pieces < NB_PIECES_MAX) {
|
||||
qDebug("Good, nb_pieces=%lld < %d", nb_pieces, NB_PIECES_MAX);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ void TorrentCreatorThread::create(QString _input_path, QString _save_path, QStri
|
||||
{
|
||||
input_path = _input_path;
|
||||
save_path = _save_path;
|
||||
if(QFile(save_path).exists())
|
||||
if (QFile(save_path).exists())
|
||||
QFile::remove(save_path);
|
||||
trackers = _trackers;
|
||||
url_seeds = _url_seeds;
|
||||
@@ -104,17 +104,17 @@ void TorrentCreatorThread::run() {
|
||||
file_storage fs;
|
||||
// Adding files to the torrent
|
||||
libtorrent::add_files(fs, input_path.toUtf8().constData(), file_filter);
|
||||
if(abort) return;
|
||||
if (abort) return;
|
||||
create_torrent t(fs, piece_size);
|
||||
|
||||
// Add url seeds
|
||||
foreach(const QString &seed, url_seeds){
|
||||
foreach (const QString &seed, url_seeds){
|
||||
t.add_url_seed(seed.trimmed().toStdString());
|
||||
}
|
||||
foreach(const QString &tracker, trackers) {
|
||||
foreach (const QString &tracker, trackers) {
|
||||
t.add_tracker(tracker.trimmed().toStdString());
|
||||
}
|
||||
if(abort) return;
|
||||
if (abort) return;
|
||||
// calculate the hash for all pieces
|
||||
const QString parent_path = misc::branchPath(input_path);
|
||||
set_piece_hashes(t, parent_path.toUtf8().constData(), boost::bind<void>(&sendProgressUpdateSignal, _1, t.num_pieces(), this));
|
||||
@@ -124,13 +124,13 @@ void TorrentCreatorThread::run() {
|
||||
t.set_comment(comment.toUtf8().constData());
|
||||
// Is private ?
|
||||
t.set_priv(is_private);
|
||||
if(abort) return;
|
||||
if (abort) return;
|
||||
// create the torrent and print it to out
|
||||
qDebug("Saving to %s", qPrintable(save_path));
|
||||
std::vector<char> torrent;
|
||||
bencode(back_inserter(torrent), t.generate());
|
||||
QFile outfile(save_path);
|
||||
if(!torrent.empty() && outfile.open(QIODevice::WriteOnly)) {
|
||||
if (!torrent.empty() && outfile.open(QIODevice::WriteOnly)) {
|
||||
outfile.write(&torrent[0], torrent.size());
|
||||
outfile.close();
|
||||
emit updateProgress(100);
|
||||
|
||||
@@ -75,7 +75,7 @@ public:
|
||||
QString name = misc::toQStringU(f.path.filename());
|
||||
#endif
|
||||
// Do not display incomplete extensions
|
||||
if(name.endsWith(".!qB"))
|
||||
if (name.endsWith(".!qB"))
|
||||
name.chop(4);
|
||||
itemData << name;
|
||||
//qDebug("Created a TreeItem file with name %s", qPrintable(getName()));
|
||||
@@ -84,7 +84,7 @@ public:
|
||||
total_done = 0;
|
||||
itemData << 0.; // Progress;
|
||||
itemData << prio::NORMAL; // Priority
|
||||
if(parent) {
|
||||
if (parent) {
|
||||
parent->appendChild(this);
|
||||
parent->updateSize();
|
||||
}
|
||||
@@ -95,14 +95,14 @@ public:
|
||||
parentItem = parent;
|
||||
m_type = FOLDER;
|
||||
// Do not display incomplete extensions
|
||||
if(name.endsWith(".!qB"))
|
||||
if (name.endsWith(".!qB"))
|
||||
name.chop(4);
|
||||
itemData << name;
|
||||
itemData << 0.; // Size
|
||||
itemData << 0.; // Progress;
|
||||
total_done = 0;
|
||||
itemData << prio::NORMAL; // Priority
|
||||
if(parent) {
|
||||
if (parent) {
|
||||
parent->appendChild(this);
|
||||
}
|
||||
}
|
||||
@@ -155,36 +155,36 @@ public:
|
||||
}
|
||||
|
||||
void setSize(qulonglong size) {
|
||||
if(getSize() == size) return;
|
||||
if (getSize() == size) return;
|
||||
itemData.replace(COL_SIZE, (qulonglong)size);
|
||||
if(parentItem)
|
||||
if (parentItem)
|
||||
parentItem->updateSize();
|
||||
}
|
||||
|
||||
void updateSize() {
|
||||
if(m_type == ROOT) return;
|
||||
if (m_type == ROOT) return;
|
||||
Q_ASSERT(m_type == FOLDER);
|
||||
qulonglong size = 0;
|
||||
foreach(TorrentFileItem* child, childItems) {
|
||||
if(child->getPriority() != prio::IGNORED)
|
||||
foreach (TorrentFileItem* child, childItems) {
|
||||
if (child->getPriority() != prio::IGNORED)
|
||||
size += child->getSize();
|
||||
}
|
||||
setSize(size);
|
||||
}
|
||||
|
||||
void setProgress(qulonglong done) {
|
||||
if(getPriority() == 0) return;
|
||||
if (getPriority() == 0) return;
|
||||
total_done = done;
|
||||
qulonglong size = getSize();
|
||||
Q_ASSERT(total_done <= size);
|
||||
qreal progress;
|
||||
if(size > 0)
|
||||
if (size > 0)
|
||||
progress = total_done/(float)size;
|
||||
else
|
||||
progress = 1.;
|
||||
Q_ASSERT(progress >= 0. && progress <= 1.);
|
||||
itemData.replace(COL_PROGRESS, progress);
|
||||
if(parentItem)
|
||||
if (parentItem)
|
||||
parentItem->updateProgress();
|
||||
}
|
||||
|
||||
@@ -193,20 +193,20 @@ public:
|
||||
}
|
||||
|
||||
qreal getProgress() const {
|
||||
if(getPriority() == 0)
|
||||
if (getPriority() == 0)
|
||||
return -1;
|
||||
qulonglong size = getSize();
|
||||
if(size > 0)
|
||||
if (size > 0)
|
||||
return total_done/(float)getSize();
|
||||
return 1.;
|
||||
}
|
||||
|
||||
void updateProgress() {
|
||||
if(m_type == ROOT) return;
|
||||
if (m_type == ROOT) return;
|
||||
Q_ASSERT(m_type == FOLDER);
|
||||
total_done = 0;
|
||||
foreach(TorrentFileItem* child, childItems) {
|
||||
if(child->getPriority() > 0)
|
||||
foreach (TorrentFileItem* child, childItems) {
|
||||
if (child->getPriority() > 0)
|
||||
total_done += child->getTotalDone();
|
||||
}
|
||||
//qDebug("Folder: total_done: %llu/%llu", total_done, getSize());
|
||||
@@ -221,17 +221,17 @@ public:
|
||||
void setPriority(int new_prio, bool update_parent=true) {
|
||||
Q_ASSERT(new_prio != prio::PARTIAL || m_type == FOLDER); // PARTIAL only applies to folders
|
||||
const int old_prio = getPriority();
|
||||
if(old_prio == new_prio) return;
|
||||
if (old_prio == new_prio) return;
|
||||
qDebug("setPriority(%s, %d)", qPrintable(getName()), new_prio);
|
||||
// Reset progress if priority is 0
|
||||
if(new_prio == 0) {
|
||||
if (new_prio == 0) {
|
||||
setProgress(0);
|
||||
}
|
||||
|
||||
itemData.replace(COL_PRIO, new_prio);
|
||||
|
||||
// Update parent
|
||||
if(update_parent && parentItem) {
|
||||
if (update_parent && parentItem) {
|
||||
qDebug("Updating parent item");
|
||||
parentItem->updateSize();
|
||||
parentItem->updateProgress();
|
||||
@@ -239,15 +239,15 @@ public:
|
||||
}
|
||||
|
||||
// Update children
|
||||
if(new_prio != prio::PARTIAL && !childItems.empty()) {
|
||||
if (new_prio != prio::PARTIAL && !childItems.empty()) {
|
||||
qDebug("Updating children items");
|
||||
foreach(TorrentFileItem* child, childItems) {
|
||||
foreach (TorrentFileItem* child, childItems) {
|
||||
// Do not update the parent since
|
||||
// the parent is causing the update
|
||||
child->setPriority(new_prio, false);
|
||||
}
|
||||
}
|
||||
if(m_type == FOLDER) {
|
||||
if (m_type == FOLDER) {
|
||||
updateSize();
|
||||
updateProgress();
|
||||
}
|
||||
@@ -255,28 +255,28 @@ public:
|
||||
|
||||
// Only non-root folders use this function
|
||||
void updatePriority() {
|
||||
if(m_type == ROOT) return;
|
||||
if (m_type == ROOT) return;
|
||||
Q_ASSERT(m_type == FOLDER);
|
||||
if(childItems.isEmpty()) return;
|
||||
if (childItems.isEmpty()) return;
|
||||
// If all children have the same priority
|
||||
// then the folder should have the same
|
||||
// priority
|
||||
const int prio = childItems.first()->getPriority();
|
||||
for(int i=1; i<childItems.size(); ++i) {
|
||||
if(childItems.at(i)->getPriority() != prio) {
|
||||
for (int i=1; i<childItems.size(); ++i) {
|
||||
if (childItems.at(i)->getPriority() != prio) {
|
||||
setPriority(prio::PARTIAL);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// All child items have the same priorrity
|
||||
// Update mine if necessary
|
||||
if(prio != getPriority())
|
||||
if (prio != getPriority())
|
||||
setPriority(prio);
|
||||
}
|
||||
|
||||
TorrentFileItem* childWithName(QString name) const {
|
||||
foreach(TorrentFileItem *child, childItems) {
|
||||
if(child->getName() == name) return child;
|
||||
foreach (TorrentFileItem *child, childItems) {
|
||||
if (child->getName() == name) return child;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -290,9 +290,9 @@ public:
|
||||
//Q_ASSERT(!childWithName(item->getName()));
|
||||
Q_ASSERT(m_type != TFILE);
|
||||
int i=0;
|
||||
for(i=0; i<childItems.size(); ++i) {
|
||||
for (i=0; i<childItems.size(); ++i) {
|
||||
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.append(item);
|
||||
@@ -313,7 +313,7 @@ public:
|
||||
}
|
||||
|
||||
QVariant data(int column) const {
|
||||
if(column == COL_PROGRESS)
|
||||
if (column == COL_PROGRESS)
|
||||
return getProgress();
|
||||
return itemData.value(column);
|
||||
}
|
||||
@@ -355,7 +355,7 @@ public:
|
||||
|
||||
void updateFilesProgress(std::vector<libtorrent::size_type> fp) {
|
||||
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);
|
||||
files_index[i]->setProgress(fp[i]);
|
||||
}
|
||||
@@ -364,7 +364,7 @@ public:
|
||||
|
||||
void updateFilesPriorities(const std::vector<int> &fprio) {
|
||||
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]);
|
||||
files_index[i]->setPriority(fprio[i]);
|
||||
}
|
||||
@@ -373,7 +373,7 @@ public:
|
||||
|
||||
std::vector<int> getFilesPriorities(unsigned int nbFiles) const {
|
||||
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());
|
||||
prio.push_back(files_index[i]->getPriority());
|
||||
}
|
||||
@@ -381,8 +381,8 @@ public:
|
||||
}
|
||||
|
||||
bool allFiltered() const {
|
||||
for(int i=0; i<rootItem->childCount(); ++i) {
|
||||
if(rootItem->child(i)->getPriority() != prio::IGNORED)
|
||||
for (int i=0; i<rootItem->childCount(); ++i) {
|
||||
if (rootItem->child(i)->getPriority() != prio::IGNORED)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -396,12 +396,12 @@ public:
|
||||
}
|
||||
|
||||
bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) {
|
||||
if(!index.isValid()) return false;
|
||||
if (!index.isValid()) return false;
|
||||
if (index.column() == 0 && role == Qt::CheckStateRole) {
|
||||
TorrentFileItem *item = static_cast<TorrentFileItem*>(index.internalPointer());
|
||||
qDebug("setData(%s, %d", qPrintable(item->getName()), value.toInt());
|
||||
if(item->getPriority() != value.toInt()) {
|
||||
if(value.toInt() == Qt::PartiallyChecked)
|
||||
if (item->getPriority() != value.toInt()) {
|
||||
if (value.toInt() == Qt::PartiallyChecked)
|
||||
item->setPriority(prio::PARTIAL);
|
||||
else if (value.toInt() == Qt::Unchecked)
|
||||
item->setPriority(prio::IGNORED);
|
||||
@@ -450,16 +450,16 @@ public:
|
||||
if (!index.isValid())
|
||||
return QVariant();
|
||||
TorrentFileItem *item = static_cast<TorrentFileItem*>(index.internalPointer());
|
||||
if(index.column() == 0 && role == Qt::DecorationRole) {
|
||||
if(item->isFolder())
|
||||
if (index.column() == 0 && role == Qt::DecorationRole) {
|
||||
if (item->isFolder())
|
||||
return IconProvider::instance()->getIcon("inode-directory");
|
||||
else
|
||||
return IconProvider::instance()->getIcon("text-plain");
|
||||
}
|
||||
if(index.column() == 0 && role == Qt::CheckStateRole) {
|
||||
if(item->data(TorrentFileItem::COL_PRIO).toInt() == prio::IGNORED)
|
||||
if (index.column() == 0 && role == Qt::CheckStateRole) {
|
||||
if (item->data(TorrentFileItem::COL_PRIO).toInt() == prio::IGNORED)
|
||||
return Qt::Unchecked;
|
||||
if(item->data(TorrentFileItem::COL_PRIO).toInt() == prio::PARTIAL)
|
||||
if (item->data(TorrentFileItem::COL_PRIO).toInt() == prio::PARTIAL)
|
||||
return Qt::PartiallyChecked;
|
||||
return Qt::Checked;
|
||||
}
|
||||
@@ -472,7 +472,7 @@ public:
|
||||
Qt::ItemFlags flags(const QModelIndex &index) const {
|
||||
if (!index.isValid())
|
||||
return 0;
|
||||
if(getType(index) == TorrentFileItem::FOLDER)
|
||||
if (getType(index) == TorrentFileItem::FOLDER)
|
||||
return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsTristate;
|
||||
return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable;
|
||||
}
|
||||
@@ -487,7 +487,7 @@ public:
|
||||
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const {
|
||||
if (parent.isValid() && parent.column() != 0)
|
||||
return QModelIndex();
|
||||
if(column >= TorrentFileItem::NB_COL)
|
||||
if (column >= TorrentFileItem::NB_COL)
|
||||
return QModelIndex();
|
||||
|
||||
TorrentFileItem *parentItem;
|
||||
@@ -497,7 +497,7 @@ public:
|
||||
else
|
||||
parentItem = static_cast<TorrentFileItem*>(parent.internalPointer());
|
||||
Q_ASSERT(parentItem);
|
||||
if(row >= parentItem->childCount())
|
||||
if (row >= parentItem->childCount())
|
||||
return QModelIndex();
|
||||
|
||||
TorrentFileItem *childItem = parentItem->child(row);
|
||||
@@ -513,7 +513,7 @@ public:
|
||||
return QModelIndex();
|
||||
|
||||
TorrentFileItem *childItem = static_cast<TorrentFileItem*>(index.internalPointer());
|
||||
if(!childItem) return QModelIndex();
|
||||
if (!childItem) return QModelIndex();
|
||||
TorrentFileItem *parentItem = childItem->parent();
|
||||
|
||||
if (parentItem == rootItem)
|
||||
@@ -539,7 +539,7 @@ public:
|
||||
void clear() {
|
||||
qDebug("clear called");
|
||||
beginResetModel();
|
||||
if(files_index) {
|
||||
if (files_index) {
|
||||
delete [] files_index;
|
||||
files_index = 0;
|
||||
}
|
||||
@@ -549,7 +549,7 @@ public:
|
||||
|
||||
void setupModelData(const libtorrent::torrent_info &t) {
|
||||
qDebug("setup model data called");
|
||||
if(t.num_files() == 0) return;
|
||||
if (t.num_files() == 0) return;
|
||||
emit layoutAboutToBeChanged();
|
||||
// Initialize files_index array
|
||||
qDebug("Torrent contains %d files", t.num_files());
|
||||
@@ -560,7 +560,7 @@ public:
|
||||
TorrentFileItem *current_parent;
|
||||
|
||||
// Iterate over files
|
||||
for(int i=0; i<t.num_files(); ++i) {
|
||||
for (int i=0; i<t.num_files(); ++i) {
|
||||
libtorrent::file_entry fentry = t.file_at(i);
|
||||
current_parent = root_folder;
|
||||
#if LIBTORRENT_VERSION_MINOR >= 16
|
||||
@@ -572,9 +572,9 @@ public:
|
||||
QStringList pathFolders = path.split("/");
|
||||
pathFolders.removeAll(".unwanted");
|
||||
pathFolders.takeLast();
|
||||
foreach(const QString &pathPart, pathFolders) {
|
||||
foreach (const QString &pathPart, pathFolders) {
|
||||
TorrentFileItem *new_parent = current_parent->childWithName(pathPart);
|
||||
if(!new_parent) {
|
||||
if (!new_parent) {
|
||||
new_parent = new TorrentFileItem(pathPart, current_parent);
|
||||
}
|
||||
current_parent = new_parent;
|
||||
@@ -588,16 +588,16 @@ public:
|
||||
|
||||
public slots:
|
||||
void selectAll() {
|
||||
for(int i=0; i<rootItem->childCount(); ++i) {
|
||||
for (int i=0; i<rootItem->childCount(); ++i) {
|
||||
TorrentFileItem *child = rootItem->child(i);
|
||||
if(child->getPriority() == prio::IGNORED)
|
||||
if (child->getPriority() == prio::IGNORED)
|
||||
child->setPriority(prio::NORMAL);
|
||||
}
|
||||
emit dataChanged(index(0,0), index(rowCount(), columnCount()));
|
||||
}
|
||||
|
||||
void selectNone() {
|
||||
for(int i=0; i<rootItem->childCount(); ++i) {
|
||||
for (int i=0; i<rootItem->childCount(); ++i) {
|
||||
rootItem->child(i)->setPriority(prio::IGNORED);
|
||||
}
|
||||
emit dataChanged(index(0,0), index(rowCount(), columnCount()));
|
||||
@@ -642,9 +642,9 @@ public:
|
||||
}
|
||||
|
||||
QModelIndex parent(const QModelIndex & child) const {
|
||||
if(!child.isValid()) return QModelIndex();
|
||||
if (!child.isValid()) return QModelIndex();
|
||||
QModelIndex sourceParent = m_model->parent(mapToSource(child));
|
||||
if(!sourceParent.isValid()) return QModelIndex();
|
||||
if (!sourceParent.isValid()) return QModelIndex();
|
||||
return mapFromSource(sourceParent);
|
||||
}
|
||||
|
||||
@@ -662,14 +662,14 @@ protected:
|
||||
|
||||
public slots:
|
||||
void selectAll() {
|
||||
for(int i=0; i<rowCount(); ++i) {
|
||||
for (int i=0; i<rowCount(); ++i) {
|
||||
setData(index(i, 0), Qt::Checked, Qt::CheckStateRole);
|
||||
}
|
||||
emit dataChanged(index(0,0), index(rowCount(), columnCount()));
|
||||
}
|
||||
|
||||
void selectNone() {
|
||||
for(int i=0; i<rowCount(); ++i) {
|
||||
for (int i=0; i<rowCount(); ++i) {
|
||||
setData(index(i, 0), Qt::Unchecked, Qt::CheckStateRole);
|
||||
}
|
||||
emit dataChanged(index(0,0), index(rowCount(), columnCount()));
|
||||
|
||||
@@ -65,7 +65,7 @@ void TorrentImportDlg::on_browseTorrentBtn_clicked()
|
||||
const QString default_dir = settings.value(QString::fromUtf8("MainWindowLastDir"), QDir::homePath()).toString();
|
||||
// Ask for a torrent file
|
||||
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);
|
||||
} else {
|
||||
ui->lineTorrent->clear();
|
||||
@@ -76,7 +76,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
|
||||
{
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
|
||||
const QString default_dir = settings.value(QString::fromUtf8("TorrentImport/LastContentDir"), QDir::homePath()).toString();
|
||||
if(t->num_files() == 1) {
|
||||
if (t->num_files() == 1) {
|
||||
// Single file torrent
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
const QString file_name = misc::fileName(misc::toQStringU(t->file_at(0).path));
|
||||
@@ -87,12 +87,12 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
|
||||
QString extension = misc::file_extension(file_name);
|
||||
qDebug("File extension is : %s", qPrintable(extension));
|
||||
QString filter;
|
||||
if(!extension.isEmpty()) {
|
||||
if (!extension.isEmpty()) {
|
||||
extension = extension.toUpper();
|
||||
filter = tr("%1 Files", "%1 is a file extension (e.g. PDF)").arg(extension)+" (*."+extension+")";
|
||||
}
|
||||
m_contentPath = QFileDialog::getOpenFileName(this, tr("Please provide the location of %1", "%1 is a file name").arg(file_name), default_dir, filter);
|
||||
if(m_contentPath.isEmpty() || !QFile(m_contentPath).exists()) {
|
||||
if (m_contentPath.isEmpty() || !QFile(m_contentPath).exists()) {
|
||||
m_contentPath = QString::null;
|
||||
ui->importBtn->setEnabled(false);
|
||||
ui->checkSkipCheck->setEnabled(false);
|
||||
@@ -106,7 +106,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
|
||||
#endif
|
||||
// Check file size
|
||||
const qint64 file_size = QFile(m_contentPath).size();
|
||||
if(t->file_at(0).size == file_size) {
|
||||
if (t->file_at(0).size == file_size) {
|
||||
qDebug("The file size matches, allowing fast seeding...");
|
||||
ui->checkSkipCheck->setEnabled(true);
|
||||
} else {
|
||||
@@ -117,7 +117,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
|
||||
// Handle file renaming
|
||||
QStringList parts = m_contentPath.replace("\\", "/").split("/");
|
||||
QString new_file_name = parts.takeLast();
|
||||
if(new_file_name != file_name) {
|
||||
if (new_file_name != file_name) {
|
||||
qDebug("The file has been renamed");
|
||||
QStringList new_parts = m_filesPath.first().split("/");
|
||||
new_parts.replace(new_parts.count()-1, new_file_name);
|
||||
@@ -128,7 +128,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
|
||||
// multiple files torrent
|
||||
m_contentPath = QFileDialog::getExistingDirectory(this, tr("Please point to the location of the torrent: %1").arg(misc::toQStringU(t->name())),
|
||||
default_dir);
|
||||
if(m_contentPath.isEmpty() || !QDir(m_contentPath).exists()) {
|
||||
if (m_contentPath.isEmpty() || !QDir(m_contentPath).exists()) {
|
||||
m_contentPath = QString::null;
|
||||
ui->importBtn->setEnabled(false);
|
||||
ui->checkSkipCheck->setEnabled(false);
|
||||
@@ -143,13 +143,13 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
|
||||
bool size_mismatch = false;
|
||||
QDir content_dir(m_contentPath);
|
||||
// Check file sizes
|
||||
for(int i=0; i<t->num_files(); ++i) {
|
||||
for (int i=0; i<t->num_files(); ++i) {
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
const QString rel_path = misc::toQStringU(t->file_at(i).path);
|
||||
#else
|
||||
const QString rel_path = misc::toQStringU(t->file_at(i).path.string());
|
||||
#endif
|
||||
if(QFile(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))).size() != t->file_at(i).size) {
|
||||
if (QFile(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))).size() != t->file_at(i).size) {
|
||||
qDebug("%s is %lld",
|
||||
qPrintable(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))), (long long int) QFile(QDir::cleanPath(content_dir.absoluteFilePath(rel_path))).size());
|
||||
qDebug("%s is %lld",
|
||||
@@ -158,7 +158,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(size_mismatch) {
|
||||
if (size_mismatch) {
|
||||
qDebug("The file size does not match, forbidding fast seeding...");
|
||||
ui->checkSkipCheck->setChecked(false);
|
||||
ui->checkSkipCheck->setEnabled(false);
|
||||
@@ -193,14 +193,14 @@ void TorrentImportDlg::importTorrent()
|
||||
{
|
||||
qDebug() << Q_FUNC_INFO << "ENTER";
|
||||
TorrentImportDlg dlg;
|
||||
if(dlg.exec()) {
|
||||
if (dlg.exec()) {
|
||||
qDebug() << "Loading the torrent file...";
|
||||
boost::intrusive_ptr<libtorrent::torrent_info> t = dlg.torrent();
|
||||
if(!t->is_valid())
|
||||
if (!t->is_valid())
|
||||
return;
|
||||
QString torrent_path = dlg.getTorrentPath();
|
||||
QString content_path = dlg.getContentPath();
|
||||
if(torrent_path.isEmpty() || content_path.isEmpty() || !QFile(torrent_path).exists()) {
|
||||
if (torrent_path.isEmpty() || content_path.isEmpty() || !QFile(torrent_path).exists()) {
|
||||
qWarning() << "Incorrect input, aborting." << torrent_path << content_path;
|
||||
return;
|
||||
}
|
||||
@@ -225,7 +225,7 @@ void TorrentImportDlg::loadTorrent(const QString &torrent_path)
|
||||
// Load the torrent file
|
||||
try {
|
||||
t = new torrent_info(torrent_path.toUtf8().constData());
|
||||
if(!t->is_valid() || t->num_files() == 0)
|
||||
if (!t->is_valid() || t->num_files() == 0)
|
||||
throw std::exception();
|
||||
} catch(std::exception&) {
|
||||
ui->browseContentBtn->setEnabled(false);
|
||||
@@ -251,7 +251,7 @@ void TorrentImportDlg::initializeFilesPath()
|
||||
{
|
||||
m_filesPath.clear();
|
||||
// Loads files path in the torrent
|
||||
for(int i=0; i<t->num_files(); ++i) {
|
||||
for (int i=0; i<t->num_files(); ++i) {
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
m_filesPath << misc::toQStringU(t->file_at(i).path).replace("\\", "/");
|
||||
#else
|
||||
|
||||
@@ -53,7 +53,7 @@ public:
|
||||
static void deleteTempData(QString hash) {
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume"));
|
||||
QHash<QString, QVariant> all_data = settings.value("torrents-tmp").toHash();
|
||||
if(all_data.contains(hash)) {
|
||||
if (all_data.contains(hash)) {
|
||||
all_data.remove(hash);
|
||||
settings.setValue("torrents-tmp", all_data);
|
||||
}
|
||||
@@ -161,7 +161,7 @@ public:
|
||||
const QHash<QString, QVariant> all_data = settings.value("torrents-tmp").toHash();
|
||||
const QHash<QString, QVariant> data = all_data.value(hash).toHash();
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -207,8 +207,8 @@ public:
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume"));
|
||||
const QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
|
||||
QHash<QString, QVariant>::ConstIterator it;
|
||||
for(it = all_data.constBegin(); it != all_data.constEnd(); it++) {
|
||||
if(it.value().toHash().value("max_ratio", USE_GLOBAL_RATIO).toReal() >= 0) {
|
||||
for (it = all_data.constBegin(); it != all_data.constEnd(); it++) {
|
||||
if (it.value().toHash().value("max_ratio", USE_GLOBAL_RATIO).toReal() >= 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -219,7 +219,7 @@ public:
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume"));
|
||||
QHash<QString, QVariant> all_data = settings.value("torrents").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();
|
||||
all_data[hash] = 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> data = all_data.value(hash).toHash();
|
||||
QDateTime dt = data.value("add_date").toDateTime();
|
||||
if(!dt.isValid()) {
|
||||
if (!dt.isValid()) {
|
||||
setAddedDate(hash);
|
||||
dt = QDateTime::currentDateTime();
|
||||
}
|
||||
@@ -290,7 +290,7 @@ public:
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume"));
|
||||
QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
|
||||
QHash<QString, QVariant> data = all_data[h.hash()].toHash();
|
||||
if(h.is_seed())
|
||||
if (h.is_seed())
|
||||
data["seed_date"] = QDateTime::currentDateTime();
|
||||
else
|
||||
data.remove("seed_date");
|
||||
@@ -308,7 +308,7 @@ public:
|
||||
static void deletePersistentData(QString hash) {
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent-resume"));
|
||||
QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
|
||||
if(all_data.contains(hash)) {
|
||||
if (all_data.contains(hash)) {
|
||||
all_data.remove(hash);
|
||||
settings.setValue("torrents", all_data);
|
||||
}
|
||||
@@ -322,12 +322,12 @@ public:
|
||||
QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
|
||||
QHash<QString, QVariant> data = all_data.value(h.hash()).toHash();
|
||||
data["is_magnet"] = is_magnet;
|
||||
if(is_magnet) {
|
||||
if (is_magnet) {
|
||||
data["magnet_uri"] = misc::toQString(make_magnet_uri(h));
|
||||
}
|
||||
data["seed"] = h.is_seed();
|
||||
data["priority"] = h.queue_position();
|
||||
if(save_path.isEmpty()) {
|
||||
if (save_path.isEmpty()) {
|
||||
qDebug("TorrentPersistantData: save path is %s", qPrintable(h.save_path()));
|
||||
data["save_path"] = h.save_path();
|
||||
} else {
|
||||
@@ -394,11 +394,11 @@ public:
|
||||
QHash<QString, QVariant> all_data = settings.value("torrents").toHash();
|
||||
QHash<QString, QVariant> data = all_data[h.hash()].toHash();
|
||||
bool was_seed = data.value("seed", false).toBool();
|
||||
if(was_seed != h.is_seed()) {
|
||||
if (was_seed != h.is_seed()) {
|
||||
data["seed"] = !was_seed;
|
||||
all_data[h.hash()] = data;
|
||||
settings.setValue("torrents", all_data);
|
||||
if(!was_seed) {
|
||||
if (!was_seed) {
|
||||
// Save completion date
|
||||
saveSeedDate(h);
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ struct QPeer {
|
||||
|
||||
libtorrent::entry toEntry(bool no_peer_id) const {
|
||||
libtorrent::entry::dictionary_type peer_map;
|
||||
if(!no_peer_id)
|
||||
if (!no_peer_id)
|
||||
peer_map["id"] = libtorrent::entry(peer_id.toStdString());
|
||||
peer_map["ip"] = libtorrent::entry(ip.toStdString());
|
||||
peer_map["port"] = libtorrent::entry(port);
|
||||
|
||||
@@ -48,7 +48,7 @@ QTracker::QTracker(QObject *parent) :
|
||||
}
|
||||
|
||||
QTracker::~QTracker() {
|
||||
if(isListening()) {
|
||||
if (isListening()) {
|
||||
qDebug("Shutting down the embedded tracker...");
|
||||
close();
|
||||
}
|
||||
@@ -69,8 +69,8 @@ bool QTracker::start()
|
||||
{
|
||||
const int listen_port = Preferences().getTrackerPort();
|
||||
//
|
||||
if(isListening()) {
|
||||
if(serverPort() == listen_port) {
|
||||
if (isListening()) {
|
||||
if (serverPort() == listen_port) {
|
||||
// Already listening on the right port, just return
|
||||
return true;
|
||||
}
|
||||
@@ -88,19 +88,19 @@ void QTracker::readRequest()
|
||||
QByteArray input = socket->readAll();
|
||||
//qDebug("QTracker: Raw request:\n%s", input.data());
|
||||
QHttpRequestHeader http_request(input);
|
||||
if(!http_request.isValid()) {
|
||||
if (!http_request.isValid()) {
|
||||
qDebug("QTracker: Invalid HTTP Request:\n %s", qPrintable(http_request.toString()));
|
||||
respondInvalidRequest(socket, 100, "Invalid request type");
|
||||
return;
|
||||
}
|
||||
//qDebug("QTracker received the following request:\n%s", qPrintable(parser.toString()));
|
||||
// Request is correct, is it a GET request?
|
||||
if(http_request.method() != "GET") {
|
||||
if (http_request.method() != "GET") {
|
||||
qDebug("QTracker: Unsupported HTTP request: %s", qPrintable(http_request.method()));
|
||||
respondInvalidRequest(socket, 100, "Invalid request type");
|
||||
return;
|
||||
}
|
||||
if(!http_request.path().startsWith("/announce", Qt::CaseInsensitive)) {
|
||||
if (!http_request.path().startsWith("/announce", Qt::CaseInsensitive)) {
|
||||
qDebug("QTracker: Unrecognized path: %s", qPrintable(http_request.path()));
|
||||
respondInvalidRequest(socket, 100, "Invalid request type");
|
||||
return;
|
||||
@@ -134,82 +134,82 @@ void QTracker::respondToAnnounceRequest(QTcpSocket *socket,
|
||||
// IP
|
||||
annonce_req.peer.ip = socket->peerAddress().toString();
|
||||
// 1. Get info_hash
|
||||
if(!get_parameters.contains("info_hash")) {
|
||||
if (!get_parameters.contains("info_hash")) {
|
||||
qDebug("QTracker: Missing info_hash");
|
||||
respondInvalidRequest(socket, 101, "Missing info_hash");
|
||||
return;
|
||||
}
|
||||
annonce_req.info_hash = get_parameters.value("info_hash");
|
||||
// info_hash cannot be longer than 20 bytes
|
||||
/*if(annonce_req.info_hash.toAscii().length() > 20) {
|
||||
/*if (annonce_req.info_hash.toAscii().length() > 20) {
|
||||
qDebug("QTracker: Info_hash is not 20 byte long: %s (%d)", qPrintable(annonce_req.info_hash), annonce_req.info_hash.toAscii().length());
|
||||
respondInvalidRequest(socket, 150, "Invalid infohash");
|
||||
return;
|
||||
}*/
|
||||
// 2. Get peer ID
|
||||
if(!get_parameters.contains("peer_id")) {
|
||||
if (!get_parameters.contains("peer_id")) {
|
||||
qDebug("QTracker: Missing peer_id");
|
||||
respondInvalidRequest(socket, 102, "Missing peer_id");
|
||||
return;
|
||||
}
|
||||
annonce_req.peer.peer_id = get_parameters.value("peer_id");
|
||||
// peer_id cannot be longer than 20 bytes
|
||||
/*if(annonce_req.peer.peer_id.length() > 20) {
|
||||
/*if (annonce_req.peer.peer_id.length() > 20) {
|
||||
qDebug("QTracker: peer_id is not 20 byte long: %s", qPrintable(annonce_req.peer.peer_id));
|
||||
respondInvalidRequest(socket, 151, "Invalid peerid");
|
||||
return;
|
||||
}*/
|
||||
// 3. Get port
|
||||
if(!get_parameters.contains("port")) {
|
||||
if (!get_parameters.contains("port")) {
|
||||
qDebug("QTracker: Missing port");
|
||||
respondInvalidRequest(socket, 103, "Missing port");
|
||||
return;
|
||||
}
|
||||
bool ok = false;
|
||||
annonce_req.peer.port = get_parameters.value("port").toInt(&ok);
|
||||
if(!ok || annonce_req.peer.port < 1 || annonce_req.peer.port > 65535) {
|
||||
if (!ok || annonce_req.peer.port < 1 || annonce_req.peer.port > 65535) {
|
||||
qDebug("QTracker: Invalid port number (%d)", annonce_req.peer.port);
|
||||
respondInvalidRequest(socket, 103, "Missing port");
|
||||
return;
|
||||
}
|
||||
// 4. Get event
|
||||
annonce_req.event = "";
|
||||
if(get_parameters.contains("event")) {
|
||||
if (get_parameters.contains("event")) {
|
||||
annonce_req.event = get_parameters.value("event");
|
||||
qDebug("QTracker: event is %s", qPrintable(annonce_req.event));
|
||||
}
|
||||
// 5. Get numwant
|
||||
annonce_req.numwant = 50;
|
||||
if(get_parameters.contains("numwant")) {
|
||||
if (get_parameters.contains("numwant")) {
|
||||
int tmp = get_parameters.value("numwant").toInt();
|
||||
if(tmp > 0) {
|
||||
if (tmp > 0) {
|
||||
qDebug("QTracker: numwant=%d", tmp);
|
||||
annonce_req.numwant = tmp;
|
||||
}
|
||||
}
|
||||
// 6. no_peer_id (extension)
|
||||
annonce_req.no_peer_id = false;
|
||||
if(get_parameters.contains("no_peer_id")) {
|
||||
if (get_parameters.contains("no_peer_id")) {
|
||||
annonce_req.no_peer_id = true;
|
||||
}
|
||||
// 7. TODO: support "compact" extension
|
||||
// Done parsing, now let's reply
|
||||
if(m_torrents.contains(annonce_req.info_hash)) {
|
||||
if(annonce_req.event == "stopped") {
|
||||
if (m_torrents.contains(annonce_req.info_hash)) {
|
||||
if (annonce_req.event == "stopped") {
|
||||
qDebug("QTracker: Peer stopped downloading, deleting it from the list");
|
||||
m_torrents[annonce_req.info_hash].remove(annonce_req.peer.qhash());
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Unknown torrent
|
||||
if(m_torrents.size() == MAX_TORRENTS) {
|
||||
if (m_torrents.size() == MAX_TORRENTS) {
|
||||
// Reached max size, remove a random torrent
|
||||
m_torrents.erase(m_torrents.begin());
|
||||
}
|
||||
}
|
||||
// Register the user
|
||||
PeerList peers = m_torrents.value(annonce_req.info_hash);
|
||||
if(peers.size() == MAX_PEERS_PER_TORRENT) {
|
||||
if (peers.size() == MAX_PEERS_PER_TORRENT) {
|
||||
// Too many peers, remove a random one
|
||||
peers.erase(peers.begin());
|
||||
}
|
||||
@@ -226,8 +226,8 @@ void QTracker::ReplyWithPeerList(QTcpSocket *socket, const TrackerAnnounceReques
|
||||
reply_dict["interval"] = entry(ANNOUNCE_INTERVAL);
|
||||
QList<QPeer> peers = m_torrents.value(annonce_req.info_hash).values();
|
||||
entry::list_type peer_list;
|
||||
foreach(const QPeer & p, peers) {
|
||||
//if(p != annonce_req.peer)
|
||||
foreach (const QPeer & p, peers) {
|
||||
//if (p != annonce_req.peer)
|
||||
peer_list.push_back(p.toEntry(annonce_req.no_peer_id));
|
||||
}
|
||||
reply_dict["peers"] = entry(peer_list);
|
||||
|
||||
@@ -77,7 +77,7 @@ public:
|
||||
case TorrentModelItem::TR_SEEDS:
|
||||
case TorrentModelItem::TR_PEERS: {
|
||||
QString display = QString::number(index.data().toLongLong());
|
||||
if(index.data(Qt::UserRole).toLongLong() > 0) {
|
||||
if (index.data(Qt::UserRole).toLongLong() > 0) {
|
||||
// Scrape was successful, we have total values
|
||||
display += " ("+QString::number(index.data(Qt::UserRole).toLongLong())+")";
|
||||
}
|
||||
@@ -132,7 +132,7 @@ public:
|
||||
QItemDelegate::drawBackground(painter, opt, index);
|
||||
const qlonglong limit = index.data().toLongLong();
|
||||
opt.displayAlignment = Qt::AlignRight;
|
||||
if(limit > 0)
|
||||
if (limit > 0)
|
||||
QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::number(limit/1024., 'f', 1) + " " + tr("KiB/s", "KiB/second (.i.e per second)"));
|
||||
else
|
||||
QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8("∞"));
|
||||
@@ -142,7 +142,7 @@ public:
|
||||
QItemDelegate::drawBackground(painter, opt, index);
|
||||
QString txt = misc::userFriendlyDuration(index.data().toLongLong());
|
||||
qlonglong seeding_time = index.data(Qt::UserRole).toLongLong();
|
||||
if(seeding_time > 0)
|
||||
if (seeding_time > 0)
|
||||
txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(misc::userFriendlyDuration(seeding_time))+")";
|
||||
QItemDelegate::drawDisplay(painter, opt, opt.rect, txt);
|
||||
break;
|
||||
@@ -156,7 +156,7 @@ public:
|
||||
QItemDelegate::drawBackground(painter, opt, index);
|
||||
opt.displayAlignment = Qt::AlignRight;
|
||||
const qreal ratio = index.data().toDouble();
|
||||
if(ratio > QBtSession::MAX_RATIO)
|
||||
if (ratio > QBtSession::MAX_RATIO)
|
||||
QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::fromUtf8("∞"));
|
||||
else
|
||||
QItemDelegate::drawDisplay(painter, opt, opt.rect, QString::number(ratio, 'f', 2));
|
||||
@@ -164,7 +164,7 @@ public:
|
||||
}
|
||||
case TorrentModelItem::TR_PRIORITY: {
|
||||
const int priority = index.data().toInt();
|
||||
if(priority >= 0) {
|
||||
if (priority >= 0) {
|
||||
opt.displayAlignment = Qt::AlignRight;
|
||||
QItemDelegate::paint(painter, opt, index);
|
||||
} else {
|
||||
@@ -179,7 +179,7 @@ public:
|
||||
qreal progress = index.data().toDouble()*100.;
|
||||
// We don't want to display 100% unless
|
||||
// the torrent is really complete
|
||||
if(progress > 99.94 && progress < 100.)
|
||||
if (progress > 99.94 && progress < 100.)
|
||||
progress = 99.9;
|
||||
newopt.rect = opt.rect;
|
||||
newopt.text = QString::number(progress, 'f', 1)+"%";
|
||||
|
||||
@@ -67,8 +67,8 @@ public:
|
||||
// Redefine addItem() to make sure the list stays sorted
|
||||
void addItem(QListWidgetItem *it) {
|
||||
Q_ASSERT(count() >= 2);
|
||||
for(int i=2; i<count(); ++i) {
|
||||
if(item(i)->text().localeAwareCompare(it->text()) >= 0) {
|
||||
for (int i=2; i<count(); ++i) {
|
||||
if (item(i)->text().localeAwareCompare(it->text()) >= 0) {
|
||||
insertItem(i, it);
|
||||
return;
|
||||
}
|
||||
@@ -87,8 +87,8 @@ public:
|
||||
|
||||
int rowFromLabel(QString label) const {
|
||||
Q_ASSERT(!label.isEmpty());
|
||||
for(int i=2; i<count(); ++i) {
|
||||
if(label == labelFromRow(i)) return i;
|
||||
for (int i=2; i<count(); ++i) {
|
||||
if (label == labelFromRow(i)) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
@@ -98,9 +98,9 @@ signals:
|
||||
|
||||
protected:
|
||||
void dragMoveEvent(QDragMoveEvent *event) {
|
||||
if(itemAt(event->pos()) && row(itemAt(event->pos())) > 0) {
|
||||
if(itemHover) {
|
||||
if(itemHover != itemAt(event->pos())) {
|
||||
if (itemAt(event->pos()) && row(itemAt(event->pos())) > 0) {
|
||||
if (itemHover) {
|
||||
if (itemHover != itemAt(event->pos())) {
|
||||
setItemHover(false);
|
||||
itemHover = itemAt(event->pos());
|
||||
setItemHover(true);
|
||||
@@ -111,7 +111,7 @@ protected:
|
||||
}
|
||||
event->acceptProposedAction();
|
||||
} else {
|
||||
if(itemHover)
|
||||
if (itemHover)
|
||||
setItemHover(false);
|
||||
event->ignore();
|
||||
}
|
||||
@@ -119,7 +119,7 @@ protected:
|
||||
|
||||
void dropEvent(QDropEvent *event) {
|
||||
qDebug("Drop Event in labels list");
|
||||
if(itemAt(event->pos())) {
|
||||
if (itemAt(event->pos())) {
|
||||
emit torrentDropped(row(itemAt(event->pos())));
|
||||
}
|
||||
event->ignore();
|
||||
@@ -129,7 +129,7 @@ protected:
|
||||
}
|
||||
|
||||
void dragLeaveEvent(QDragLeaveEvent*) {
|
||||
if(itemHover)
|
||||
if (itemHover)
|
||||
setItemHover(false);
|
||||
// Select current item again
|
||||
currentItem()->setSelected(true);
|
||||
@@ -137,7 +137,7 @@ protected:
|
||||
|
||||
void setItemHover(bool hover) {
|
||||
Q_ASSERT(itemHover);
|
||||
if(hover) {
|
||||
if (hover) {
|
||||
itemHover->setData(Qt::DecorationRole, IconProvider::instance()->getIcon("folder-documents.png"));
|
||||
itemHover->setSelected(true);
|
||||
//setCurrentItem(itemHover);
|
||||
@@ -271,7 +271,7 @@ public:
|
||||
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
|
||||
statusFilters->setCurrentRow(settings.value("TransferListFilters/selectedFilterIndex", 0).toInt());
|
||||
const QStringList label_list = Preferences().getTorrentLabels();
|
||||
foreach(const QString &label, label_list) {
|
||||
foreach (const QString &label, label_list) {
|
||||
customLabels.insert(label, 0);
|
||||
qDebug("Creating label QListWidgetItem: %s", qPrintable(label));
|
||||
QListWidgetItem *newLabel = new QListWidgetItem();
|
||||
@@ -294,7 +294,7 @@ protected slots:
|
||||
|
||||
void torrentDropped(int row) {
|
||||
Q_ASSERT(row > 0);
|
||||
if(row == 1) {
|
||||
if (row == 1) {
|
||||
transferList->setSelectionLabel("");
|
||||
} else {
|
||||
transferList->setSelectionLabel(labelFilters->labelFromRow(row));
|
||||
@@ -303,7 +303,7 @@ protected slots:
|
||||
|
||||
void addLabel(QString label) {
|
||||
label = misc::toValidFileSystemName(label.trimmed());
|
||||
if(label.isEmpty() || customLabels.contains(label)) return;
|
||||
if (label.isEmpty() || customLabels.contains(label)) return;
|
||||
QListWidgetItem *newLabel = new QListWidgetItem();
|
||||
newLabel->setText(label + " (0)");
|
||||
newLabel->setData(Qt::DecorationRole, IconProvider::instance()->getIcon("inode-directory"));
|
||||
@@ -315,7 +315,7 @@ protected slots:
|
||||
void showLabelMenu(QPoint) {
|
||||
QMenu labelMenu(labelFilters);
|
||||
QAction *removeAct = 0;
|
||||
if(!labelFilters->selectedItems().empty() && labelFilters->row(labelFilters->selectedItems().first()) > 1)
|
||||
if (!labelFilters->selectedItems().empty() && labelFilters->row(labelFilters->selectedItems().first()) > 1)
|
||||
removeAct = labelMenu.addAction(IconProvider::instance()->getIcon("list-remove"), tr("Remove label"));
|
||||
QAction *addAct = labelMenu.addAction(IconProvider::instance()->getIcon("list-add"), tr("Add label..."));
|
||||
labelMenu.addSeparator();
|
||||
@@ -324,24 +324,24 @@ protected slots:
|
||||
QAction *deleteTorrentsAct = labelMenu.addAction(IconProvider::instance()->getIcon("edit-delete"), tr("Delete torrents"));
|
||||
QAction *act = 0;
|
||||
act = labelMenu.exec(QCursor::pos());
|
||||
if(act) {
|
||||
if(act == removeAct) {
|
||||
if (act) {
|
||||
if (act == removeAct) {
|
||||
removeSelectedLabel();
|
||||
return;
|
||||
}
|
||||
if(act == deleteTorrentsAct) {
|
||||
if (act == deleteTorrentsAct) {
|
||||
transferList->deleteVisibleTorrents();
|
||||
return;
|
||||
}
|
||||
if(act == startAct) {
|
||||
if (act == startAct) {
|
||||
transferList->startVisibleTorrents();
|
||||
return;
|
||||
}
|
||||
if(act == pauseAct) {
|
||||
if (act == pauseAct) {
|
||||
transferList->pauseVisibleTorrents();
|
||||
return;
|
||||
}
|
||||
if(act == addAct) {
|
||||
if (act == addAct) {
|
||||
bool ok;
|
||||
QString label = "";
|
||||
bool invalid;
|
||||
@@ -349,7 +349,7 @@ protected slots:
|
||||
invalid = false;
|
||||
label = QInputDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, label, &ok);
|
||||
if (ok && !label.isEmpty()) {
|
||||
if(misc::isValidFileSystemName(label)) {
|
||||
if (misc::isValidFileSystemName(label)) {
|
||||
addLabel(label);
|
||||
} else {
|
||||
QMessageBox::warning(this, tr("Invalid label name"), tr("Please don't use any special characters in the label name."));
|
||||
@@ -395,8 +395,8 @@ protected slots:
|
||||
void torrentChangedLabel(TorrentModelItem *torrentItem, QString old_label, QString new_label) {
|
||||
Q_UNUSED(torrentItem);
|
||||
qDebug("Torrent label changed from %s to %s", qPrintable(old_label), qPrintable(new_label));
|
||||
if(!old_label.isEmpty()) {
|
||||
if(customLabels.contains(old_label)) {
|
||||
if (!old_label.isEmpty()) {
|
||||
if (customLabels.contains(old_label)) {
|
||||
const int new_count = customLabels.value(old_label, 0) - 1;
|
||||
Q_ASSERT(new_count >= 0);
|
||||
customLabels.insert(old_label, new_count);
|
||||
@@ -406,8 +406,8 @@ protected slots:
|
||||
}
|
||||
--nb_labeled;
|
||||
}
|
||||
if(!new_label.isEmpty()) {
|
||||
if(!customLabels.contains(new_label))
|
||||
if (!new_label.isEmpty()) {
|
||||
if (!customLabels.contains(new_label))
|
||||
addLabel(new_label);
|
||||
const int new_count = customLabels.value(new_label, 0) + 1;
|
||||
Q_ASSERT(new_count >= 1);
|
||||
@@ -423,8 +423,8 @@ protected slots:
|
||||
void handleNewTorrent(TorrentModelItem* torrentItem) {
|
||||
QString label = torrentItem->data(TorrentModelItem::TR_LABEL).toString();
|
||||
qDebug("New torrent was added with label: %s", qPrintable(label));
|
||||
if(!label.isEmpty()) {
|
||||
if(!customLabels.contains(label)) {
|
||||
if (!label.isEmpty()) {
|
||||
if (!customLabels.contains(label)) {
|
||||
addLabel(label);
|
||||
}
|
||||
// Update label counter
|
||||
@@ -448,7 +448,7 @@ protected slots:
|
||||
void torrentAboutToBeDeleted(TorrentModelItem* torrentItem) {
|
||||
Q_ASSERT(torrentItem);
|
||||
QString label = torrentItem->data(TorrentModelItem::TR_LABEL).toString();
|
||||
if(!label.isEmpty()) {
|
||||
if (!label.isEmpty()) {
|
||||
// Update label counter
|
||||
const int new_count = customLabels.value(label, 0) - 1;
|
||||
customLabels.insert(label, new_count);
|
||||
|
||||
@@ -108,7 +108,7 @@ TransferListWidget::TransferListWidget(QWidget *parent, MainWindow *main_window,
|
||||
setDragDropMode(QAbstractItemView::DragOnly);
|
||||
|
||||
// Default hidden columns
|
||||
if(!column_loaded) {
|
||||
if (!column_loaded) {
|
||||
setColumnHidden(TorrentModelItem::TR_PRIORITY, true);
|
||||
setColumnHidden(TorrentModelItem::TR_ADD_DATE, true);
|
||||
setColumnHidden(TorrentModelItem::TR_SEED_DATE, true);
|
||||
@@ -165,9 +165,9 @@ inline QString TransferListWidget::getHashFromRow(int row) const {
|
||||
|
||||
inline QModelIndex TransferListWidget::mapToSource(const QModelIndex &index) const {
|
||||
Q_ASSERT(index.isValid());
|
||||
if(index.model() == nameFilterModel)
|
||||
if (index.model() == nameFilterModel)
|
||||
return labelFilterModel->mapToSource(statusFilterModel->mapToSource(nameFilterModel->mapToSource(index)));
|
||||
if(index.model() == statusFilterModel)
|
||||
if (index.model() == statusFilterModel)
|
||||
return labelFilterModel->mapToSource(statusFilterModel->mapToSource(index));
|
||||
return labelFilterModel->mapToSource(index);
|
||||
}
|
||||
@@ -188,9 +188,9 @@ void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) {
|
||||
const int row = mapToSource(index).row();
|
||||
const QString hash = getHashFromRow(row);
|
||||
QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
int action;
|
||||
if(h.is_seed()) {
|
||||
if (h.is_seed()) {
|
||||
action = Preferences().getActionOnDblClOnTorrentFn();
|
||||
} else {
|
||||
action = Preferences().getActionOnDblClOnTorrentDl();
|
||||
@@ -198,7 +198,7 @@ void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) {
|
||||
|
||||
switch(action) {
|
||||
case TOGGLE_PAUSE:
|
||||
if(h.is_paused()) {
|
||||
if (h.is_paused()) {
|
||||
h.resume();
|
||||
} else {
|
||||
h.pause();
|
||||
@@ -213,7 +213,7 @@ void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) {
|
||||
QStringList TransferListWidget::getSelectedTorrentsHashes() const {
|
||||
QStringList hashes;
|
||||
const QModelIndexList selectedIndexes = selectionModel()->selectedRows();
|
||||
foreach(const QModelIndex &index, selectedIndexes) {
|
||||
foreach (const QModelIndex &index, selectedIndexes) {
|
||||
hashes << getHashFromRow(mapToSource(index).row());
|
||||
}
|
||||
return hashes;
|
||||
@@ -221,22 +221,22 @@ QStringList TransferListWidget::getSelectedTorrentsHashes() const {
|
||||
|
||||
void TransferListWidget::setSelectedTorrentsLocation() {
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
if(hashes.isEmpty()) return;
|
||||
if (hashes.isEmpty()) return;
|
||||
QString dir;
|
||||
const QDir saveDir(TorrentPersistentData::getSavePath(hashes.first()));
|
||||
qDebug("Old save path is %s", qPrintable(saveDir.absolutePath()));
|
||||
dir = QFileDialog::getExistingDirectory(this, tr("Choose save path"), saveDir.absolutePath(),
|
||||
QFileDialog::DontConfirmOverwrite|QFileDialog::ShowDirsOnly|QFileDialog::HideNameFilterDetails);
|
||||
if(!dir.isNull()) {
|
||||
if (!dir.isNull()) {
|
||||
qDebug("New path is %s", qPrintable(dir));
|
||||
// Check if savePath exists
|
||||
QDir savePath(misc::expandPath(dir));
|
||||
qDebug("New path after clean up is %s", qPrintable(savePath.absolutePath()));
|
||||
foreach(const QString & hash, hashes) {
|
||||
foreach (const QString & hash, hashes) {
|
||||
// Actually move storage
|
||||
QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(!BTSession->useTemporaryFolder() || h.is_seed()) {
|
||||
if(!savePath.exists()) savePath.mkpath(savePath.absolutePath());
|
||||
if (!BTSession->useTemporaryFolder() || h.is_seed()) {
|
||||
if (!savePath.exists()) savePath.mkpath(savePath.absolutePath());
|
||||
h.move_storage(savePath.absolutePath());
|
||||
} else {
|
||||
TorrentPersistentData::saveSavePath(h.hash(), savePath.absolutePath());
|
||||
@@ -248,79 +248,79 @@ void TransferListWidget::setSelectedTorrentsLocation() {
|
||||
|
||||
void TransferListWidget::startSelectedTorrents() {
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
BTSession->resumeTorrent(hash);
|
||||
}
|
||||
}
|
||||
|
||||
void TransferListWidget::startVisibleTorrents() {
|
||||
QStringList hashes;
|
||||
for(int i=0; i<nameFilterModel->rowCount(); ++i) {
|
||||
for (int i=0; i<nameFilterModel->rowCount(); ++i) {
|
||||
const int row = mapToSource(nameFilterModel->index(i, 0)).row();
|
||||
hashes << getHashFromRow(row);
|
||||
}
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
BTSession->resumeTorrent(hash);
|
||||
}
|
||||
}
|
||||
|
||||
void TransferListWidget::pauseSelectedTorrents() {
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
BTSession->pauseTorrent(hash);
|
||||
}
|
||||
}
|
||||
|
||||
void TransferListWidget::pauseVisibleTorrents() {
|
||||
QStringList hashes;
|
||||
for(int i=0; i<nameFilterModel->rowCount(); ++i) {
|
||||
for (int i=0; i<nameFilterModel->rowCount(); ++i) {
|
||||
const int row = mapToSource(nameFilterModel->index(i, 0)).row();
|
||||
hashes << getHashFromRow(row);
|
||||
}
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
BTSession->pauseTorrent(hash);
|
||||
}
|
||||
}
|
||||
|
||||
void TransferListWidget::deleteSelectedTorrents() {
|
||||
if(main_window->getCurrentTabWidget() != this) return;
|
||||
if (main_window->getCurrentTabWidget() != this) return;
|
||||
const QStringList& hashes = getSelectedTorrentsHashes();
|
||||
if(hashes.empty()) return;
|
||||
if (hashes.empty()) return;
|
||||
bool delete_local_files = false;
|
||||
if(Preferences().confirmTorrentDeletion() &&
|
||||
if (Preferences().confirmTorrentDeletion() &&
|
||||
!DeletionConfirmationDlg::askForDeletionConfirmation(&delete_local_files))
|
||||
return;
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
BTSession->deleteTorrent(hash, delete_local_files);
|
||||
}
|
||||
}
|
||||
|
||||
void TransferListWidget::deleteVisibleTorrents() {
|
||||
if(nameFilterModel->rowCount() <= 0) return;
|
||||
if (nameFilterModel->rowCount() <= 0) return;
|
||||
bool delete_local_files = false;
|
||||
if(Preferences().confirmTorrentDeletion() &&
|
||||
if (Preferences().confirmTorrentDeletion() &&
|
||||
!DeletionConfirmationDlg::askForDeletionConfirmation(&delete_local_files))
|
||||
return;
|
||||
QStringList hashes;
|
||||
for(int i=0; i<nameFilterModel->rowCount(); ++i) {
|
||||
for (int i=0; i<nameFilterModel->rowCount(); ++i) {
|
||||
const int row = mapToSource(nameFilterModel->index(i, 0)).row();
|
||||
hashes << getHashFromRow(row);
|
||||
}
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
BTSession->deleteTorrent(hash, delete_local_files);
|
||||
}
|
||||
}
|
||||
|
||||
void TransferListWidget::increasePrioSelectedTorrents() {
|
||||
qDebug() << Q_FUNC_INFO;
|
||||
if(main_window->getCurrentTabWidget() != this) return;
|
||||
if (main_window->getCurrentTabWidget() != this) return;
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
std::priority_queue<QPair<int, QTorrentHandle>, std::vector<QPair<int, QTorrentHandle> >, std::greater<QPair<int, QTorrentHandle> > > torrent_queue;
|
||||
// Sort torrents by priority
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
try {
|
||||
QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(!h.is_seed()) {
|
||||
if (!h.is_seed()) {
|
||||
torrent_queue.push(qMakePair(h.queue_position(), h));
|
||||
}
|
||||
}catch(invalid_handle&){}
|
||||
@@ -337,14 +337,14 @@ void TransferListWidget::increasePrioSelectedTorrents() {
|
||||
|
||||
void TransferListWidget::decreasePrioSelectedTorrents() {
|
||||
qDebug() << Q_FUNC_INFO;
|
||||
if(main_window->getCurrentTabWidget() != this) return;
|
||||
if (main_window->getCurrentTabWidget() != this) return;
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
std::priority_queue<QPair<int, QTorrentHandle>, std::vector<QPair<int, QTorrentHandle> >, std::less<QPair<int, QTorrentHandle> > > torrent_queue;
|
||||
// Sort torrents by priority
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
try {
|
||||
QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(!h.is_seed()) {
|
||||
if (!h.is_seed()) {
|
||||
torrent_queue.push(qMakePair(h.queue_position(), h));
|
||||
}
|
||||
}catch(invalid_handle&){}
|
||||
@@ -360,22 +360,22 @@ void TransferListWidget::decreasePrioSelectedTorrents() {
|
||||
}
|
||||
|
||||
void TransferListWidget::topPrioSelectedTorrents() {
|
||||
if(main_window->getCurrentTabWidget() != this) return;
|
||||
if (main_window->getCurrentTabWidget() != this) return;
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(h.is_valid() && !h.is_seed()) {
|
||||
if (h.is_valid() && !h.is_seed()) {
|
||||
h.queue_position_top();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void TransferListWidget::bottomPrioSelectedTorrents() {
|
||||
if(main_window->getCurrentTabWidget() != this) return;
|
||||
if (main_window->getCurrentTabWidget() != this) return;
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(h.is_valid() && !h.is_seed()) {
|
||||
if (h.is_valid() && !h.is_seed()) {
|
||||
h.queue_position_bottom();
|
||||
}
|
||||
}
|
||||
@@ -384,9 +384,9 @@ void TransferListWidget::bottomPrioSelectedTorrents() {
|
||||
void TransferListWidget::copySelectedMagnetURIs() const {
|
||||
QStringList magnet_uris;
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
const QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(h.is_valid() && h.has_metadata())
|
||||
if (h.is_valid() && h.has_metadata())
|
||||
magnet_uris << misc::toQString(make_magnet_uri(h.get_torrent_info()));
|
||||
}
|
||||
qApp->clipboard()->setText(magnet_uris.join("\n"));
|
||||
@@ -400,12 +400,12 @@ void TransferListWidget::hidePriorityColumn(bool hide) {
|
||||
void TransferListWidget::openSelectedTorrentsFolder() const {
|
||||
QStringList pathsList;
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
const QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(h.is_valid()) {
|
||||
if (h.is_valid()) {
|
||||
const QString savePath = h.save_path();
|
||||
qDebug("Opening path at %s", qPrintable(savePath));
|
||||
if(!pathsList.contains(savePath)) {
|
||||
if (!pathsList.contains(savePath)) {
|
||||
pathsList.append(savePath);
|
||||
QDesktopServices::openUrl(QUrl::fromLocalFile(savePath));
|
||||
}
|
||||
@@ -415,9 +415,9 @@ void TransferListWidget::openSelectedTorrentsFolder() const {
|
||||
|
||||
void TransferListWidget::previewSelectedTorrents() {
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
const QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(h.is_valid() && h.has_metadata()) {
|
||||
if (h.is_valid() && h.has_metadata()) {
|
||||
new PreviewSelect(this, h);
|
||||
}
|
||||
}
|
||||
@@ -428,28 +428,28 @@ void TransferListWidget::setDlLimitSelectedTorrents() {
|
||||
bool first = true;
|
||||
bool all_same_limit = true;
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
const QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(h.is_valid() && !h.is_seed()) {
|
||||
if (h.is_valid() && !h.is_seed()) {
|
||||
selected_torrents << h;
|
||||
// Determine current limit for selected torrents
|
||||
if(first) {
|
||||
if (first) {
|
||||
first = false;
|
||||
} else {
|
||||
if(all_same_limit && h.download_limit() != selected_torrents.first().download_limit())
|
||||
if (all_same_limit && h.download_limit() != selected_torrents.first().download_limit())
|
||||
all_same_limit = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(selected_torrents.empty()) return;
|
||||
if (selected_torrents.empty()) return;
|
||||
|
||||
bool ok=false;
|
||||
int default_limit = -1;
|
||||
if(all_same_limit)
|
||||
if (all_same_limit)
|
||||
default_limit = selected_torrents.first().download_limit();
|
||||
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Download Speed Limiting"), default_limit, Preferences().getGlobalDownloadLimit()*1024.);
|
||||
if(ok) {
|
||||
foreach(const QTorrentHandle &h, selected_torrents) {
|
||||
if (ok) {
|
||||
foreach (const QTorrentHandle &h, selected_torrents) {
|
||||
qDebug("Applying download speed limit of %ld Kb/s to torrent %s", (long)(new_limit/1024.), qPrintable(h.hash()));
|
||||
BTSession->setDownloadLimit(h.hash(), new_limit);
|
||||
}
|
||||
@@ -461,28 +461,28 @@ void TransferListWidget::setUpLimitSelectedTorrents() {
|
||||
bool first = true;
|
||||
bool all_same_limit = true;
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
const QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(h.is_valid()) {
|
||||
if (h.is_valid()) {
|
||||
selected_torrents << h;
|
||||
// Determine current limit for selected torrents
|
||||
if(first) {
|
||||
if (first) {
|
||||
first = false;
|
||||
} else {
|
||||
if(all_same_limit && h.upload_limit() != selected_torrents.first().upload_limit())
|
||||
if (all_same_limit && h.upload_limit() != selected_torrents.first().upload_limit())
|
||||
all_same_limit = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(selected_torrents.empty()) return;
|
||||
if (selected_torrents.empty()) return;
|
||||
|
||||
bool ok=false;
|
||||
int default_limit = -1;
|
||||
if(all_same_limit)
|
||||
if (all_same_limit)
|
||||
default_limit = selected_torrents.first().upload_limit();
|
||||
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Upload Speed Limiting"), default_limit, Preferences().getGlobalUploadLimit()*1024.);
|
||||
if(ok) {
|
||||
foreach(const QTorrentHandle &h, selected_torrents) {
|
||||
if (ok) {
|
||||
foreach (const QTorrentHandle &h, selected_torrents) {
|
||||
qDebug("Applying upload speed limit of %ld Kb/s to torrent %s", (long)(new_limit/1024.), qPrintable(h.hash()));
|
||||
BTSession->setUploadLimit(h.hash(), new_limit);
|
||||
}
|
||||
@@ -514,7 +514,7 @@ void TransferListWidget::setMaxRatioSelectedTorrents() {
|
||||
|
||||
void TransferListWidget::recheckSelectedTorrents() {
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
BTSession->recheckTorrent(hash);
|
||||
}
|
||||
}
|
||||
@@ -524,8 +524,8 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&){
|
||||
QMenu hideshowColumn(this);
|
||||
hideshowColumn.setTitle(tr("Column visibility"));
|
||||
QList<QAction*> actions;
|
||||
for(int i=0; i < listModel->columnCount(); ++i) {
|
||||
if(!BTSession->isQueueingEnabled() && i == TorrentModelItem::TR_PRIORITY) {
|
||||
for (int i=0; i < listModel->columnCount(); ++i) {
|
||||
if (!BTSession->isQueueingEnabled() && i == TorrentModelItem::TR_PRIORITY) {
|
||||
actions.append(0);
|
||||
continue;
|
||||
}
|
||||
@@ -536,21 +536,21 @@ void TransferListWidget::displayDLHoSMenu(const QPoint&){
|
||||
}
|
||||
// Call menu
|
||||
QAction *act = hideshowColumn.exec(QCursor::pos());
|
||||
if(act) {
|
||||
if (act) {
|
||||
int col = actions.indexOf(act);
|
||||
Q_ASSERT(col >= 0);
|
||||
qDebug("Toggling column %d visibility", col);
|
||||
setColumnHidden(col, !isColumnHidden(col));
|
||||
if(!isColumnHidden(col) && columnWidth(col) <= 5)
|
||||
if (!isColumnHidden(col) && columnWidth(col) <= 5)
|
||||
setColumnWidth(col, 100);
|
||||
}
|
||||
}
|
||||
|
||||
void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const {
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(h.is_valid() && h.has_metadata()) {
|
||||
if (h.is_valid() && h.has_metadata()) {
|
||||
h.super_seeding(!h.super_seeding());
|
||||
}
|
||||
}
|
||||
@@ -558,12 +558,12 @@ void TransferListWidget::toggleSelectedTorrentsSuperSeeding() const {
|
||||
|
||||
void TransferListWidget::toggleSelectedTorrentsSequentialDownload() const {
|
||||
const QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(h.is_valid() && h.has_metadata()) {
|
||||
if (h.is_valid() && h.has_metadata()) {
|
||||
bool was_sequential = h.is_sequential_download();
|
||||
h.set_sequential_download(!was_sequential);
|
||||
if(!was_sequential)
|
||||
if (!was_sequential)
|
||||
h.prioritize_first_last_piece(true);
|
||||
}
|
||||
}
|
||||
@@ -571,9 +571,9 @@ void TransferListWidget::toggleSelectedTorrentsSequentialDownload() const {
|
||||
|
||||
void TransferListWidget::toggleSelectedFirstLastPiecePrio() const {
|
||||
QStringList hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(h.is_valid() && h.has_metadata()) {
|
||||
if (h.is_valid() && h.has_metadata()) {
|
||||
h.prioritize_first_last_piece(!h.first_last_piece_first());
|
||||
}
|
||||
}
|
||||
@@ -587,7 +587,7 @@ void TransferListWidget::askNewLabelForSelection() {
|
||||
invalid = false;
|
||||
const QString label = QInputDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, "", &ok);
|
||||
if (ok && !label.isEmpty()) {
|
||||
if(misc::isValidFileSystemName(label)) {
|
||||
if (misc::isValidFileSystemName(label)) {
|
||||
setSelectionLabel(label);
|
||||
} else {
|
||||
QMessageBox::warning(this, tr("Invalid label name"), tr("Please don't use any special characters in the label name."));
|
||||
@@ -599,11 +599,11 @@ void TransferListWidget::askNewLabelForSelection() {
|
||||
|
||||
void TransferListWidget::renameSelectedTorrent() {
|
||||
const QModelIndexList selectedIndexes = selectionModel()->selectedRows();
|
||||
if(selectedIndexes.size() != 1) return;
|
||||
if(!selectedIndexes.first().isValid()) return;
|
||||
if (selectedIndexes.size() != 1) return;
|
||||
if (!selectedIndexes.first().isValid()) return;
|
||||
const QString hash = getHashFromRow(mapToSource(selectedIndexes.first()).row());
|
||||
const QTorrentHandle h = BTSession->getTorrentHandle(hash);
|
||||
if(!h.is_valid()) return;
|
||||
if (!h.is_valid()) return;
|
||||
// Ask for a new Name
|
||||
bool ok;
|
||||
const QString name = QInputDialog::getText(this, tr("Rename"), tr("New name:"), QLineEdit::Normal, h.name(), &ok);
|
||||
@@ -615,7 +615,7 @@ void TransferListWidget::renameSelectedTorrent() {
|
||||
|
||||
void TransferListWidget::setSelectionLabel(QString label) {
|
||||
const QStringList& hashes = getSelectedTorrentsHashes();
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
Q_ASSERT(!hash.isEmpty());
|
||||
const int row = getRowFromHash(hash);
|
||||
const QString old_label = listModel->data(listModel->index(row, TorrentModelItem::TR_LABEL)).toString();
|
||||
@@ -627,8 +627,8 @@ void TransferListWidget::setSelectionLabel(QString label) {
|
||||
}
|
||||
|
||||
void TransferListWidget::removeLabelFromRows(QString label) {
|
||||
for(int i=0; i<listModel->rowCount(); ++i) {
|
||||
if(listModel->data(listModel->index(i, TorrentModelItem::TR_LABEL)) == label) {
|
||||
for (int i=0; i<listModel->rowCount(); ++i) {
|
||||
if (listModel->data(listModel->index(i, TorrentModelItem::TR_LABEL)) == label) {
|
||||
const QString hash = getHashFromRow(i);
|
||||
listModel->setData(listModel->index(i, TorrentModelItem::TR_LABEL), "", Qt::DisplayRole);
|
||||
// Update save path if necessary
|
||||
@@ -694,63 +694,63 @@ void TransferListWidget::displayListMenu(const QPoint&) {
|
||||
bool first = true;
|
||||
QTorrentHandle h;
|
||||
qDebug("Displaying menu");
|
||||
foreach(const QModelIndex &index, selectedIndexes) {
|
||||
foreach (const QModelIndex &index, selectedIndexes) {
|
||||
// Get the file name
|
||||
QString hash = getHashFromRow(mapToSource(index).row());
|
||||
// Get handle and pause the torrent
|
||||
h = BTSession->getTorrentHandle(hash);
|
||||
if(!h.is_valid()) continue;
|
||||
if(h.has_metadata())
|
||||
if (!h.is_valid()) continue;
|
||||
if (h.has_metadata())
|
||||
one_has_metadata = true;
|
||||
if(!h.is_seed()) {
|
||||
if (!h.is_seed()) {
|
||||
one_not_seed = true;
|
||||
if(h.has_metadata()) {
|
||||
if(first) {
|
||||
if (h.has_metadata()) {
|
||||
if (first) {
|
||||
sequential_download_mode = h.is_sequential_download();
|
||||
prioritize_first_last = h.first_last_piece_first();
|
||||
} else {
|
||||
if(sequential_download_mode != h.is_sequential_download()) {
|
||||
if (sequential_download_mode != h.is_sequential_download()) {
|
||||
all_same_sequential_download_mode = false;
|
||||
}
|
||||
if(prioritize_first_last != h.first_last_piece_first()) {
|
||||
if (prioritize_first_last != h.first_last_piece_first()) {
|
||||
all_same_prio_firstlast = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
if(!one_not_seed && all_same_super_seeding && h.has_metadata()) {
|
||||
if(first) {
|
||||
if (!one_not_seed && all_same_super_seeding && h.has_metadata()) {
|
||||
if (first) {
|
||||
super_seeding_mode = h.super_seeding();
|
||||
} else {
|
||||
if(super_seeding_mode != h.super_seeding()) {
|
||||
if (super_seeding_mode != h.super_seeding()) {
|
||||
all_same_super_seeding = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if(h.is_paused()) {
|
||||
if(!has_start) {
|
||||
if (h.is_paused()) {
|
||||
if (!has_start) {
|
||||
listMenu.addAction(&actionStart);
|
||||
has_start = true;
|
||||
}
|
||||
}else{
|
||||
if(!has_pause) {
|
||||
if (!has_pause) {
|
||||
listMenu.addAction(&actionPause);
|
||||
has_pause = true;
|
||||
}
|
||||
}
|
||||
if(h.has_metadata() && BTSession->isFilePreviewPossible(hash) && !has_preview) {
|
||||
if (h.has_metadata() && BTSession->isFilePreviewPossible(hash) && !has_preview) {
|
||||
has_preview = true;
|
||||
}
|
||||
first = false;
|
||||
if(has_pause && has_start && has_preview && one_not_seed) break;
|
||||
if (has_pause && has_start && has_preview && one_not_seed) break;
|
||||
}
|
||||
listMenu.addSeparator();
|
||||
listMenu.addAction(&actionDelete);
|
||||
listMenu.addSeparator();
|
||||
listMenu.addAction(&actionSetTorrentPath);
|
||||
if(selectedIndexes.size() == 1)
|
||||
if (selectedIndexes.size() == 1)
|
||||
listMenu.addAction(&actionRename);
|
||||
// Label Menu
|
||||
QStringList customLabels = getCustomLabels();
|
||||
@@ -760,44 +760,44 @@ void TransferListWidget::displayListMenu(const QPoint&) {
|
||||
labelActions << labelMenu->addAction(IconProvider::instance()->getIcon("list-add"), tr("New...", "New label..."));
|
||||
labelActions << labelMenu->addAction(IconProvider::instance()->getIcon("edit-clear"), tr("Reset", "Reset label"));
|
||||
labelMenu->addSeparator();
|
||||
foreach(const QString &label, customLabels) {
|
||||
foreach (const QString &label, customLabels) {
|
||||
labelActions << labelMenu->addAction(IconProvider::instance()->getIcon("inode-directory"), label);
|
||||
}
|
||||
listMenu.addSeparator();
|
||||
if(one_not_seed)
|
||||
if (one_not_seed)
|
||||
listMenu.addAction(&actionSet_download_limit);
|
||||
listMenu.addAction(&actionSet_max_ratio);
|
||||
listMenu.addAction(&actionSet_upload_limit);
|
||||
if(!one_not_seed && all_same_super_seeding && one_has_metadata) {
|
||||
if (!one_not_seed && all_same_super_seeding && one_has_metadata) {
|
||||
actionSuper_seeding_mode.setChecked(super_seeding_mode);
|
||||
listMenu.addAction(&actionSuper_seeding_mode);
|
||||
}
|
||||
listMenu.addSeparator();
|
||||
bool added_preview_action = false;
|
||||
if(has_preview) {
|
||||
if (has_preview) {
|
||||
listMenu.addAction(&actionPreview_file);
|
||||
added_preview_action = true;
|
||||
}
|
||||
if(one_not_seed && one_has_metadata) {
|
||||
if(all_same_sequential_download_mode) {
|
||||
if (one_not_seed && one_has_metadata) {
|
||||
if (all_same_sequential_download_mode) {
|
||||
actionSequential_download.setChecked(sequential_download_mode);
|
||||
listMenu.addAction(&actionSequential_download);
|
||||
added_preview_action = true;
|
||||
}
|
||||
if(all_same_prio_firstlast) {
|
||||
if (all_same_prio_firstlast) {
|
||||
actionFirstLastPiece_prio.setChecked(prioritize_first_last);
|
||||
listMenu.addAction(&actionFirstLastPiece_prio);
|
||||
added_preview_action = true;
|
||||
}
|
||||
}
|
||||
if(added_preview_action)
|
||||
if (added_preview_action)
|
||||
listMenu.addSeparator();
|
||||
if(one_has_metadata) {
|
||||
if (one_has_metadata) {
|
||||
listMenu.addAction(&actionForce_recheck);
|
||||
listMenu.addSeparator();
|
||||
}
|
||||
listMenu.addAction(&actionOpen_destination_folder);
|
||||
if(BTSession->isQueueingEnabled() && one_not_seed) {
|
||||
if (BTSession->isQueueingEnabled() && one_not_seed) {
|
||||
listMenu.addSeparator();
|
||||
QMenu *prioMenu = listMenu.addMenu(tr("Priority"));
|
||||
prioMenu->addAction(&actionTopPriority);
|
||||
@@ -806,22 +806,22 @@ void TransferListWidget::displayListMenu(const QPoint&) {
|
||||
prioMenu->addAction(&actionBottomPriority);
|
||||
}
|
||||
listMenu.addSeparator();
|
||||
if(one_has_metadata)
|
||||
if (one_has_metadata)
|
||||
listMenu.addAction(&actionCopy_magnet_link);
|
||||
// Call menu
|
||||
QAction *act = 0;
|
||||
act = listMenu.exec(QCursor::pos());
|
||||
if(act) {
|
||||
if (act) {
|
||||
// Parse label actions only (others have slots assigned)
|
||||
int i = labelActions.indexOf(act);
|
||||
if(i >= 0) {
|
||||
if (i >= 0) {
|
||||
// Label action
|
||||
if(i == 0) {
|
||||
if (i == 0) {
|
||||
// New Label
|
||||
askNewLabelForSelection();
|
||||
} else {
|
||||
QString label = "";
|
||||
if(i > 1)
|
||||
if (i > 1)
|
||||
label = customLabels.at(i-2);
|
||||
// Update Label
|
||||
setSelectionLabel(label);
|
||||
@@ -833,7 +833,7 @@ void TransferListWidget::displayListMenu(const QPoint&) {
|
||||
void TransferListWidget::currentChanged(const QModelIndex& current, const QModelIndex&) {
|
||||
qDebug("CURRENT CHANGED");
|
||||
QTorrentHandle h;
|
||||
if(current.isValid()) {
|
||||
if (current.isValid()) {
|
||||
const int row = mapToSource(current).row();
|
||||
h = BTSession->getTorrentHandle(getHashFromRow(row));
|
||||
// Scroll Fix
|
||||
@@ -843,11 +843,11 @@ void TransferListWidget::currentChanged(const QModelIndex& current, const QModel
|
||||
}
|
||||
|
||||
void TransferListWidget::applyLabelFilter(QString label) {
|
||||
if(label == "all") {
|
||||
if (label == "all") {
|
||||
labelFilterModel->setFilterRegExp(QRegExp());
|
||||
return;
|
||||
}
|
||||
if(label == "none") {
|
||||
if (label == "none") {
|
||||
labelFilterModel->setFilterRegExp(QRegExp("^$"));
|
||||
return;
|
||||
}
|
||||
@@ -884,7 +884,7 @@ void TransferListWidget::applyStatusFilter(int f) {
|
||||
statusFilterModel->setFilterRegExp(QRegExp());
|
||||
}
|
||||
// Select first item if nothing is selected
|
||||
if(selectionModel()->selectedRows(0).empty() && nameFilterModel->rowCount() > 0) {
|
||||
if (selectionModel()->selectedRows(0).empty() && nameFilterModel->rowCount() > 0) {
|
||||
qDebug("Nothing is selected, selecting first row: %s", qPrintable(nameFilterModel->index(0, TorrentModelItem::TR_NAME).data().toString()));
|
||||
selectionModel()->setCurrentIndex(nameFilterModel->index(0, TorrentModelItem::TR_NAME), QItemSelectionModel::SelectCurrent|QItemSelectionModel::Rows);
|
||||
}
|
||||
@@ -900,7 +900,7 @@ bool TransferListWidget::loadSettings()
|
||||
{
|
||||
QIniSettings settings("qBittorrent", "qBittorrent");
|
||||
bool ok = header()->restoreState(settings.value("TransferList/HeaderState").toByteArray());
|
||||
if(!ok) {
|
||||
if (!ok) {
|
||||
header()->resizeSection(0, 200); // Default
|
||||
}
|
||||
return ok;
|
||||
|
||||
@@ -58,23 +58,23 @@ QList<QVariantMap> EventManager::getEventList() const {
|
||||
QList<QVariantMap> EventManager::getPropTrackersInfo(QString hash) const {
|
||||
QList<QVariantMap> trackersInfo;
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(h.is_valid()) {
|
||||
if (h.is_valid()) {
|
||||
QHash<QString, TrackerInfos> trackers_data = QBtSession::instance()->getTrackersInfo(hash);
|
||||
std::vector<announce_entry> vect_trackers = h.trackers();
|
||||
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;
|
||||
QString tracker_url = misc::toQString(it->url);
|
||||
tracker["url"] = tracker_url;
|
||||
TrackerInfos data = trackers_data.value(tracker_url, TrackerInfos(tracker_url));
|
||||
QString error_message = data.last_message.trimmed();
|
||||
if(it->verified) {
|
||||
if (it->verified) {
|
||||
tracker["status"] = tr("Working");
|
||||
} else {
|
||||
if(it->updating && it->fails == 0) {
|
||||
if (it->updating && it->fails == 0) {
|
||||
tracker["status"] = tr("Updating...");
|
||||
} else {
|
||||
if(it->fails > 0) {
|
||||
if (it->fails > 0) {
|
||||
tracker["status"] = tr("Not working");
|
||||
} else {
|
||||
tracker["status"] = tr("Not contacted yet");
|
||||
@@ -92,21 +92,21 @@ QList<QVariantMap> EventManager::getPropTrackersInfo(QString hash) const {
|
||||
QList<QVariantMap> EventManager::getPropFilesInfo(QString hash) const {
|
||||
QList<QVariantMap> files;
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(!h.is_valid() || !h.has_metadata()) return files;
|
||||
if (!h.is_valid() || !h.has_metadata()) return files;
|
||||
std::vector<int> priorities = h.file_priorities();
|
||||
std::vector<size_type> 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;
|
||||
file["name"] = h.filename_at(i);
|
||||
libtorrent::size_type size = h.filesize_at(i);
|
||||
file["size"] = misc::friendlyUnit((double)size);
|
||||
if(size > 0)
|
||||
if (size > 0)
|
||||
file["progress"] = fp[i]/(double)size;
|
||||
else
|
||||
file["progress"] = 1.; // Empty file...
|
||||
file["priority"] = priorities[i];
|
||||
if(i == 0)
|
||||
if (i == 0)
|
||||
file["is_seed"] = h.is_seed();
|
||||
files << file;
|
||||
}
|
||||
@@ -116,11 +116,11 @@ QList<QVariantMap> EventManager::getPropFilesInfo(QString hash) const {
|
||||
void EventManager::setGlobalPreferences(QVariantMap m) {
|
||||
// UI
|
||||
Preferences pref;
|
||||
if(m.contains("locale")) {
|
||||
if (m.contains("locale")) {
|
||||
QString locale = m["locale"].toString();
|
||||
if(pref.getLocale() != locale) {
|
||||
if (pref.getLocale() != locale) {
|
||||
QTranslator *translator = new QTranslator;
|
||||
if(translator->load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){
|
||||
if (translator->load(QString::fromUtf8(":/lang/qbittorrent_") + locale)){
|
||||
qDebug("%s locale recognized, using translation.", qPrintable(locale));
|
||||
}else{
|
||||
qDebug("%s locale unrecognized, using default (en_GB).", qPrintable(locale));
|
||||
@@ -132,184 +132,184 @@ void EventManager::setGlobalPreferences(QVariantMap m) {
|
||||
}
|
||||
}
|
||||
// Downloads
|
||||
if(m.contains("save_path"))
|
||||
if (m.contains("save_path"))
|
||||
pref.setSavePath(m["save_path"].toString());
|
||||
if(m.contains("temp_path_enabled"))
|
||||
if (m.contains("temp_path_enabled"))
|
||||
pref.setTempPathEnabled(m["temp_path_enabled"].toBool());
|
||||
if(m.contains("temp_path"))
|
||||
if (m.contains("temp_path"))
|
||||
pref.setTempPath(m["temp_path"].toString());
|
||||
if(m.contains("scan_dirs") && m.contains("download_in_scan_dirs")) {
|
||||
if (m.contains("scan_dirs") && m.contains("download_in_scan_dirs")) {
|
||||
QVariantList download_at_path_tmp = m["download_in_scan_dirs"].toList();
|
||||
QList<bool> download_at_path;
|
||||
foreach(QVariant var, download_at_path_tmp) {
|
||||
foreach (QVariant var, download_at_path_tmp) {
|
||||
download_at_path << var.toBool();
|
||||
}
|
||||
QStringList old_folders = pref.getScanDirs();
|
||||
QStringList new_folders = m["scan_dirs"].toStringList();
|
||||
if(download_at_path.size() == new_folders.size()) {
|
||||
if (download_at_path.size() == new_folders.size()) {
|
||||
pref.setScanDirs(new_folders);
|
||||
pref.setDownloadInScanDirs(download_at_path);
|
||||
foreach(const QString &old_folder, old_folders) {
|
||||
foreach (const QString &old_folder, old_folders) {
|
||||
// Update deleted folders
|
||||
if(!new_folders.contains(old_folder)) {
|
||||
if (!new_folders.contains(old_folder)) {
|
||||
QBtSession::instance()->getScanFoldersModel()->removePath(old_folder);
|
||||
}
|
||||
}
|
||||
int i = 0;
|
||||
foreach(const QString &new_folder, new_folders) {
|
||||
foreach (const QString &new_folder, new_folders) {
|
||||
qDebug("New watched folder: %s", qPrintable(new_folder));
|
||||
// Update new folders
|
||||
if(!old_folders.contains(new_folder)) {
|
||||
if (!old_folders.contains(new_folder)) {
|
||||
QBtSession::instance()->getScanFoldersModel()->addPath(new_folder, download_at_path.at(i));
|
||||
}
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(m.contains("export_dir"))
|
||||
if (m.contains("export_dir"))
|
||||
pref.setExportDir(m["export_dir"].toString());
|
||||
if(m.contains("mail_notification_enabled"))
|
||||
if (m.contains("mail_notification_enabled"))
|
||||
pref.setMailNotificationEnabled(m["mail_notification_enabled"].toBool());
|
||||
if(m.contains("mail_notification_email"))
|
||||
if (m.contains("mail_notification_email"))
|
||||
pref.setMailNotificationEmail(m["mail_notification_email"].toString());
|
||||
if(m.contains("mail_notification_smtp"))
|
||||
if (m.contains("mail_notification_smtp"))
|
||||
pref.setMailNotificationSMTP(m["mail_notification_smtp"].toString());
|
||||
if(m.contains("mail_notification_ssl_enabled"))
|
||||
if (m.contains("mail_notification_ssl_enabled"))
|
||||
pref.setMailNotificationSMTPSSL(m["mail_notification_ssl_enabled"].toBool());
|
||||
if(m.contains("mail_notification_auth_enabled"))
|
||||
if (m.contains("mail_notification_auth_enabled"))
|
||||
pref.setMailNotificationSMTPAuth(m["mail_notification_auth_enabled"].toBool());
|
||||
if(m.contains("mail_notification_username"))
|
||||
if (m.contains("mail_notification_username"))
|
||||
pref.setMailNotificationSMTPUsername(m["mail_notification_username"].toString());
|
||||
if(m.contains("mail_notification_password"))
|
||||
if (m.contains("mail_notification_password"))
|
||||
pref.setMailNotificationSMTPPassword(m["mail_notification_password"].toString());
|
||||
if(m.contains("autorun_enabled"))
|
||||
if (m.contains("autorun_enabled"))
|
||||
pref.setAutoRunEnabled(m["autorun_enabled"].toBool());
|
||||
if(m.contains("autorun_program"))
|
||||
if (m.contains("autorun_program"))
|
||||
pref.setAutoRunProgram(m["autorun_program"].toString());
|
||||
if(m.contains("preallocate_all"))
|
||||
if (m.contains("preallocate_all"))
|
||||
pref.preAllocateAllFiles(m["preallocate_all"].toBool());
|
||||
if(m.contains("queueing_enabled"))
|
||||
if (m.contains("queueing_enabled"))
|
||||
pref.setQueueingSystemEnabled(m["queueing_enabled"].toBool());
|
||||
if(m.contains("max_active_downloads"))
|
||||
if (m.contains("max_active_downloads"))
|
||||
pref.setMaxActiveDownloads(m["max_active_downloads"].toInt());
|
||||
if(m.contains("max_active_torrents"))
|
||||
if (m.contains("max_active_torrents"))
|
||||
pref.setMaxActiveTorrents(m["max_active_torrents"].toInt());
|
||||
if(m.contains("max_active_uploads"))
|
||||
if (m.contains("max_active_uploads"))
|
||||
pref.setMaxActiveUploads(m["max_active_uploads"].toInt());
|
||||
if(m.contains("dont_count_slow_torrents"))
|
||||
if (m.contains("dont_count_slow_torrents"))
|
||||
pref.setIgnoreSlowTorrentsForQueueing(m["dont_count_slow_torrents"].toBool());
|
||||
if(m.contains("incomplete_files_ext"))
|
||||
if (m.contains("incomplete_files_ext"))
|
||||
pref.useIncompleteFilesExtension(m["incomplete_files_ext"].toBool());
|
||||
// Connection
|
||||
if(m.contains("listen_port"))
|
||||
if (m.contains("listen_port"))
|
||||
pref.setSessionPort(m["listen_port"].toInt());
|
||||
if(m.contains("upnp"))
|
||||
if (m.contains("upnp"))
|
||||
pref.setUPnPEnabled(m["upnp"].toBool());
|
||||
if(m.contains("dl_limit"))
|
||||
if (m.contains("dl_limit"))
|
||||
pref.setGlobalDownloadLimit(m["dl_limit"].toInt());
|
||||
if(m.contains("up_limit"))
|
||||
if (m.contains("up_limit"))
|
||||
pref.setGlobalUploadLimit(m["up_limit"].toInt());
|
||||
if(m.contains("max_connec"))
|
||||
if (m.contains("max_connec"))
|
||||
pref.setMaxConnecs(m["max_connec"].toInt());
|
||||
if(m.contains("max_connec_per_torrent"))
|
||||
if (m.contains("max_connec_per_torrent"))
|
||||
pref.setMaxConnecsPerTorrent(m["max_connec_per_torrent"].toInt());
|
||||
if(m.contains("max_uploads_per_torrent"))
|
||||
if (m.contains("max_uploads_per_torrent"))
|
||||
pref.setMaxUploadsPerTorrent(m["max_uploads_per_torrent"].toInt());
|
||||
#if LIBTORRENT_VERSION_MINOR >= 16
|
||||
if(m.contains("enable_utp"))
|
||||
if (m.contains("enable_utp"))
|
||||
pref.setuTPEnabled(m["enable_utp"].toBool());
|
||||
if(m.contains("limit_utp_rate"))
|
||||
if (m.contains("limit_utp_rate"))
|
||||
pref.setuTPRateLimited(m["limit_utp_rate"].toBool());
|
||||
#endif
|
||||
if(m.contains("limit_tcp_overhead"))
|
||||
if (m.contains("limit_tcp_overhead"))
|
||||
pref.includeOverheadInLimits(m["limit_tcp_overhead"].toBool());
|
||||
if(m.contains("alt_dl_limit"))
|
||||
if (m.contains("alt_dl_limit"))
|
||||
pref.setAltGlobalDownloadLimit(m["alt_dl_limit"].toInt());
|
||||
if(m.contains("alt_up_limit"))
|
||||
if (m.contains("alt_up_limit"))
|
||||
pref.setAltGlobalUploadLimit(m["alt_up_limit"].toInt());
|
||||
if(m.contains("scheduler_enabled"))
|
||||
if (m.contains("scheduler_enabled"))
|
||||
pref.setSchedulerEnabled(m["scheduler_enabled"].toBool());
|
||||
if(m.contains("schedule_from_hour") && m.contains("schedule_from_min")) {
|
||||
if (m.contains("schedule_from_hour") && m.contains("schedule_from_min")) {
|
||||
pref.setSchedulerStartTime(QTime(m["schedule_from_hour"].toInt(),
|
||||
m["schedule_from_min"].toInt()));
|
||||
}
|
||||
if(m.contains("schedule_to_hour") && m.contains("schedule_to_min")) {
|
||||
if (m.contains("schedule_to_hour") && m.contains("schedule_to_min")) {
|
||||
pref.setSchedulerEndTime(QTime(m["schedule_to_hour"].toInt(),
|
||||
m["schedule_to_min"].toInt()));
|
||||
}
|
||||
if(m.contains("scheduler_days"))
|
||||
if (m.contains("scheduler_days"))
|
||||
pref.setSchedulerDays(scheduler_days(m["scheduler_days"].toInt()));
|
||||
// Bittorrent
|
||||
if(m.contains("dht"))
|
||||
if (m.contains("dht"))
|
||||
pref.setDHTEnabled(m["dht"].toBool());
|
||||
if(m.contains("dhtSameAsBT"))
|
||||
if (m.contains("dhtSameAsBT"))
|
||||
pref.setDHTPortSameAsBT(m["dhtSameAsBT"].toBool());
|
||||
if(m.contains("dht_port"))
|
||||
if (m.contains("dht_port"))
|
||||
pref.setDHTPort(m["dht_port"].toInt());
|
||||
if(m.contains("pex"))
|
||||
if (m.contains("pex"))
|
||||
pref.setPeXEnabled(m["pex"].toBool());
|
||||
qDebug("Pex support: %d", (int)m["pex"].toBool());
|
||||
if(m.contains("lsd"))
|
||||
if (m.contains("lsd"))
|
||||
pref.setLSDEnabled(m["lsd"].toBool());
|
||||
if(m.contains("encryption"))
|
||||
if (m.contains("encryption"))
|
||||
pref.setEncryptionSetting(m["encryption"].toInt());
|
||||
#if LIBTORRENT_VERSION_MINOR >= 16
|
||||
if(m.contains("anonymous_mode"))
|
||||
if (m.contains("anonymous_mode"))
|
||||
pref.enableAnonymousMode(m["anonymous_mode"].toBool());
|
||||
#endif
|
||||
// Proxy
|
||||
if(m.contains("proxy_type"))
|
||||
if (m.contains("proxy_type"))
|
||||
pref.setProxyType(m["proxy_type"].toInt());
|
||||
if(m.contains("proxy_ip"))
|
||||
if (m.contains("proxy_ip"))
|
||||
pref.setProxyIp(m["proxy_ip"].toString());
|
||||
if(m.contains("proxy_port"))
|
||||
if (m.contains("proxy_port"))
|
||||
pref.setProxyPort(m["proxy_port"].toUInt());
|
||||
if(m.contains("proxy_peer_connections"))
|
||||
if (m.contains("proxy_peer_connections"))
|
||||
pref.setProxyPeerConnections(m["proxy_peer_connections"].toBool());
|
||||
if(m.contains("proxy_auth_enabled"))
|
||||
if (m.contains("proxy_auth_enabled"))
|
||||
pref.setProxyAuthEnabled(m["proxy_auth_enabled"].toBool());
|
||||
if(m.contains("proxy_username"))
|
||||
if (m.contains("proxy_username"))
|
||||
pref.setProxyUsername(m["proxy_username"].toString());
|
||||
if(m.contains("proxy_password"))
|
||||
if (m.contains("proxy_password"))
|
||||
pref.setProxyPassword(m["proxy_password"].toString());
|
||||
// IP Filter
|
||||
if(m.contains("ip_filter_enabled"))
|
||||
if (m.contains("ip_filter_enabled"))
|
||||
pref.setFilteringEnabled(m["ip_filter_enabled"].toBool());
|
||||
if(m.contains("ip_filter_path"))
|
||||
if (m.contains("ip_filter_path"))
|
||||
pref.setFilter(m["ip_filter_path"].toString());
|
||||
// Web UI
|
||||
if(m.contains("web_ui_port"))
|
||||
if (m.contains("web_ui_port"))
|
||||
pref.setWebUiPort(m["web_ui_port"].toUInt());
|
||||
if(m.contains("web_ui_username"))
|
||||
if (m.contains("web_ui_username"))
|
||||
pref.setWebUiUsername(m["web_ui_username"].toString());
|
||||
if(m.contains("web_ui_password"))
|
||||
if (m.contains("web_ui_password"))
|
||||
pref.setWebUiPassword(m["web_ui_password"].toString());
|
||||
if(m.contains("bypass_local_auth"))
|
||||
if (m.contains("bypass_local_auth"))
|
||||
pref.setWebUiLocalAuthEnabled(!m["bypass_local_auth"].toBool());
|
||||
if(m.contains("use_https"))
|
||||
if (m.contains("use_https"))
|
||||
pref.setWebUiHttpsEnabled(m["use_https"].toBool());
|
||||
#ifndef QT_NO_OPENSSL
|
||||
if(m.contains("ssl_key")) {
|
||||
if (m.contains("ssl_key")) {
|
||||
QByteArray raw_key = m["ssl_key"].toString().toAscii();
|
||||
if (!QSslKey(raw_key, QSsl::Rsa).isNull())
|
||||
pref.setWebUiHttpsKey(raw_key);
|
||||
}
|
||||
if(m.contains("ssl_cert")) {
|
||||
if (m.contains("ssl_cert")) {
|
||||
QByteArray raw_cert = m["ssl_cert"].toString().toAscii();
|
||||
if (!QSslCertificate(raw_cert).isNull())
|
||||
pref.setWebUiHttpsCertificate(raw_cert);
|
||||
}
|
||||
#endif
|
||||
// Dyndns
|
||||
if(m.contains("dyndns_enabled"))
|
||||
if (m.contains("dyndns_enabled"))
|
||||
pref.setDynDNSEnabled(m["dyndns_enabled"].toBool());
|
||||
if(m.contains("dyndns_service"))
|
||||
if (m.contains("dyndns_service"))
|
||||
pref.setDynDNSService(m["dyndns_service"].toInt());
|
||||
if(m.contains("dyndns_username"))
|
||||
if (m.contains("dyndns_username"))
|
||||
pref.setDynDNSUsername(m["dyndns_username"].toString());
|
||||
if(m.contains("dyndns_password"))
|
||||
if (m.contains("dyndns_password"))
|
||||
pref.setDynDNSPassword(m["dyndns_password"].toString());
|
||||
if(m.contains("dyndns_domain"))
|
||||
if (m.contains("dyndns_domain"))
|
||||
pref.setDynDomainName(m["dyndns_domain"].toString());
|
||||
// Reload preferences
|
||||
QBtSession::instance()->configureSession();
|
||||
@@ -326,7 +326,7 @@ QVariantMap EventManager::getGlobalPreferences() const {
|
||||
data["temp_path"] = pref.getTempPath();
|
||||
data["scan_dirs"] = pref.getScanDirs();
|
||||
QVariantList var_list;
|
||||
foreach(bool b, pref.getDownloadInScanDirs()) {
|
||||
foreach (bool b, pref.getDownloadInScanDirs()) {
|
||||
var_list << b;
|
||||
}
|
||||
data["download_in_scan_dirs"] = var_list;
|
||||
@@ -412,10 +412,10 @@ QVariantMap EventManager::getGlobalPreferences() const {
|
||||
QVariantMap EventManager::getPropGeneralInfo(QString hash) const {
|
||||
QVariantMap data;
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(h.is_valid() && h.has_metadata()) {
|
||||
if (h.is_valid() && h.has_metadata()) {
|
||||
// Save path
|
||||
QString p = TorrentPersistentData::getSavePath(hash);
|
||||
if(p.isEmpty()) p = h.save_path();
|
||||
if (p.isEmpty()) p = h.save_path();
|
||||
data["save_path"] = p;
|
||||
// Creation date
|
||||
data["creation_date"] = h.creation_date();
|
||||
@@ -426,23 +426,23 @@ QVariantMap EventManager::getPropGeneralInfo(QString hash) const {
|
||||
data["total_wasted"] = QVariant(misc::friendlyUnit(h.total_failed_bytes()+h.total_redundant_bytes()));
|
||||
data["total_uploaded"] = QVariant(misc::friendlyUnit(h.all_time_upload()) + " ("+misc::friendlyUnit(h.total_payload_upload())+" "+tr("this session")+")");
|
||||
data["total_downloaded"] = QVariant(misc::friendlyUnit(h.all_time_download()) + " ("+misc::friendlyUnit(h.total_payload_download())+" "+tr("this session")+")");
|
||||
if(h.upload_limit() <= 0)
|
||||
if (h.upload_limit() <= 0)
|
||||
data["up_limit"] = QString::fromUtf8("∞");
|
||||
else
|
||||
data["up_limit"] = QVariant(misc::friendlyUnit(h.upload_limit())+tr("/s", "/second (i.e. per second)"));
|
||||
if(h.download_limit() <= 0)
|
||||
if (h.download_limit() <= 0)
|
||||
data["dl_limit"] = QString::fromUtf8("∞");
|
||||
else
|
||||
data["dl_limit"] = QVariant(misc::friendlyUnit(h.download_limit())+tr("/s", "/second (i.e. per second)"));
|
||||
QString elapsed_txt = misc::userFriendlyDuration(h.active_time());
|
||||
if(h.is_seed()) {
|
||||
if (h.is_seed()) {
|
||||
elapsed_txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(misc::userFriendlyDuration(h.seeding_time()))+")";
|
||||
}
|
||||
data["time_elapsed"] = elapsed_txt;
|
||||
data["nb_connections"] = QVariant(QString::number(h.num_connections())+" ("+tr("%1 max", "e.g. 10 max").arg(QString::number(h.connections_limit()))+")");
|
||||
// Update ratio info
|
||||
qreal ratio = QBtSession::instance()->getRealRatio(h.hash());
|
||||
if(ratio > 100.)
|
||||
if (ratio > 100.)
|
||||
data["share_ratio"] = QString::fromUtf8("∞");
|
||||
else
|
||||
data["share_ratio"] = QString(QByteArray::number(ratio, 'f', 1));
|
||||
@@ -465,18 +465,18 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h)
|
||||
QString hash = h.hash();
|
||||
QVariantMap event;
|
||||
event["eta"] = QVariant(QString::fromUtf8("∞"));
|
||||
if(h.is_paused()) {
|
||||
if(h.has_error()) {
|
||||
if (h.is_paused()) {
|
||||
if (h.has_error()) {
|
||||
event["state"] = QVariant("error");
|
||||
} else {
|
||||
if(h.is_seed())
|
||||
if (h.is_seed())
|
||||
event["state"] = QVariant("pausedUP");
|
||||
else
|
||||
event["state"] = QVariant("pausedDL");
|
||||
}
|
||||
} else {
|
||||
if(QBtSession::instance()->isQueueingEnabled() && h.is_queued()) {
|
||||
if(h.is_seed())
|
||||
if (QBtSession::instance()->isQueueingEnabled() && h.is_queued()) {
|
||||
if (h.is_seed())
|
||||
event["state"] = QVariant("queuedUP");
|
||||
else
|
||||
event["state"] = QVariant("queuedDL");
|
||||
@@ -485,7 +485,7 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h)
|
||||
{
|
||||
case torrent_status::finished:
|
||||
case torrent_status::seeding:
|
||||
if(h.upload_payload_rate() > 0) {
|
||||
if (h.upload_payload_rate() > 0) {
|
||||
event["state"] = QVariant("uploading");
|
||||
} else {
|
||||
event["state"] = QVariant("stalledUP");
|
||||
@@ -495,7 +495,7 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h)
|
||||
case torrent_status::checking_files:
|
||||
case torrent_status::queued_for_checking:
|
||||
case torrent_status::checking_resume_data:
|
||||
if(h.is_seed()) {
|
||||
if (h.is_seed()) {
|
||||
event["state"] = QVariant("checkingUP");
|
||||
} else {
|
||||
event["state"] = QVariant("checkingDL");
|
||||
@@ -503,7 +503,7 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h)
|
||||
break;
|
||||
case torrent_status::downloading:
|
||||
case torrent_status::downloading_metadata:
|
||||
if(h.download_payload_rate() > 0)
|
||||
if (h.download_payload_rate() > 0)
|
||||
event["state"] = QVariant("downloading");
|
||||
else
|
||||
event["state"] = QVariant("stalledDL");
|
||||
@@ -519,8 +519,8 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h)
|
||||
event["size"] = QVariant(misc::friendlyUnit(h.actual_size()));
|
||||
event["progress"] = QVariant((double)h.progress());
|
||||
event["dlspeed"] = QVariant(tr("%1/s", "e.g. 120 KiB/s").arg(misc::friendlyUnit(h.download_payload_rate())));
|
||||
if(QBtSession::instance()->isQueueingEnabled()) {
|
||||
if(h.queue_position() >= 0)
|
||||
if (QBtSession::instance()->isQueueingEnabled()) {
|
||||
if (h.queue_position() >= 0)
|
||||
event["priority"] = QVariant(QString::number(h.queue_position()));
|
||||
else
|
||||
event["priority"] = "*";
|
||||
@@ -529,16 +529,16 @@ void EventManager::modifiedTorrent(const QTorrentHandle& h)
|
||||
}
|
||||
event["upspeed"] = QVariant(tr("%1/s", "e.g. 120 KiB/s").arg(misc::friendlyUnit(h.upload_payload_rate())));
|
||||
QString seeds = QString::number(h.num_seeds());
|
||||
if(h.num_complete() > 0)
|
||||
if (h.num_complete() > 0)
|
||||
seeds += " ("+QString::number(h.num_complete())+")";
|
||||
event["num_seeds"] = QVariant(seeds);
|
||||
QString leechs = QString::number(h.num_peers()-h.num_seeds());
|
||||
if(h.num_incomplete() > 0)
|
||||
if (h.num_incomplete() > 0)
|
||||
leechs += " ("+QString::number(h.num_incomplete())+")";
|
||||
event["num_leechs"] = QVariant(leechs);
|
||||
event["seed"] = QVariant(h.is_seed());
|
||||
qreal ratio = QBtSession::instance()->getRealRatio(hash);
|
||||
if(ratio > 100.)
|
||||
if (ratio > 100.)
|
||||
event["ratio"] = QString::fromUtf8("∞");
|
||||
else
|
||||
event["ratio"] = QVariant(QString::number(ratio, 'f', 1));
|
||||
|
||||
@@ -120,7 +120,7 @@ void HttpConnection::read() {
|
||||
m_parser.writeMessage(message);
|
||||
}
|
||||
|
||||
if(m_parser.isError()) {
|
||||
if (m_parser.isError()) {
|
||||
qDebug() << Q_FUNC_INFO << "message parsing error";
|
||||
m_generator.setStatusLine(400, "Bad Request");
|
||||
write();
|
||||
@@ -150,7 +150,7 @@ void HttpConnection::translateDocument(QString& data) {
|
||||
found = false;
|
||||
|
||||
i = regex.indexIn(data, i);
|
||||
if(i >= 0) {
|
||||
if (i >= 0) {
|
||||
//qDebug("Found translatable string: %s", regex.cap(1).toUtf8().data());
|
||||
QByteArray word = regex.cap(1).toLocal8Bit();
|
||||
|
||||
@@ -173,20 +173,20 @@ void HttpConnection::translateDocument(QString& data) {
|
||||
}
|
||||
|
||||
void HttpConnection::respond() {
|
||||
if((m_socket->peerAddress() != QHostAddress::LocalHost
|
||||
if ((m_socket->peerAddress() != QHostAddress::LocalHost
|
||||
&& m_socket->peerAddress() != QHostAddress::LocalHostIPv6)
|
||||
|| m_httpserver->isLocalAuthEnabled()) {
|
||||
// Authentication
|
||||
const QString peer_ip = m_socket->peerAddress().toString();
|
||||
const int nb_fail = m_httpserver->NbFailedAttemptsForIp(peer_ip);
|
||||
if(nb_fail >= MAX_AUTH_FAILED_ATTEMPTS) {
|
||||
if (nb_fail >= MAX_AUTH_FAILED_ATTEMPTS) {
|
||||
m_generator.setStatusLine(403, "Forbidden");
|
||||
m_generator.setMessage(tr("Your IP address has been banned after too many failed authentication attempts."));
|
||||
write();
|
||||
return;
|
||||
}
|
||||
QString auth = m_parser.header().value("Authorization");
|
||||
if(auth.isEmpty()) {
|
||||
if (auth.isEmpty()) {
|
||||
// Return unauthorized header
|
||||
qDebug("Auth is Empty...");
|
||||
m_generator.setStatusLine(401, "Unauthorized");
|
||||
@@ -211,10 +211,10 @@ void HttpConnection::respond() {
|
||||
}
|
||||
QString url = m_parser.url();
|
||||
// Favicon
|
||||
if(url.endsWith("favicon.ico")) {
|
||||
if (url.endsWith("favicon.ico")) {
|
||||
qDebug("Returning favicon");
|
||||
QFile favicon(":/Icons/skin/qbittorrent16.png");
|
||||
if(favicon.open(QIODevice::ReadOnly)) {
|
||||
if (favicon.open(QIODevice::ReadOnly)) {
|
||||
QByteArray data = favicon.readAll();
|
||||
favicon.close();
|
||||
m_generator.setStatusLine(200, "OK");
|
||||
@@ -242,28 +242,28 @@ void HttpConnection::respond() {
|
||||
respondJson();
|
||||
return;
|
||||
}
|
||||
if(list.size() > 2) {
|
||||
if(list[1] == "propertiesGeneral") {
|
||||
if (list.size() > 2) {
|
||||
if (list[1] == "propertiesGeneral") {
|
||||
const QString& hash = list[2];
|
||||
respondGenPropertiesJson(hash);
|
||||
return;
|
||||
}
|
||||
if(list[1] == "propertiesTrackers") {
|
||||
if (list[1] == "propertiesTrackers") {
|
||||
const QString& hash = list[2];
|
||||
respondTrackersPropertiesJson(hash);
|
||||
return;
|
||||
}
|
||||
if(list[1] == "propertiesFiles") {
|
||||
if (list[1] == "propertiesFiles") {
|
||||
const QString& hash = list[2];
|
||||
respondFilesPropertiesJson(hash);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if(list[1] == "preferences") {
|
||||
if (list[1] == "preferences") {
|
||||
respondPreferencesJson();
|
||||
return;
|
||||
} else {
|
||||
if(list[1] == "transferInfo") {
|
||||
if (list[1] == "transferInfo") {
|
||||
respondGlobalTransferInfoJson();
|
||||
return;
|
||||
}
|
||||
@@ -281,7 +281,7 @@ void HttpConnection::respond() {
|
||||
|
||||
// Icons from theme
|
||||
qDebug() << "list[0]" << list[0];
|
||||
if(list[0] == "theme" && list.size() == 2) {
|
||||
if (list[0] == "theme" && list.size() == 2) {
|
||||
#ifdef DISABLE_GUI
|
||||
url = ":/Icons/oxygen/"+list[1]+".png";
|
||||
#else
|
||||
@@ -292,14 +292,14 @@ void HttpConnection::respond() {
|
||||
if (list[0] == "images") {
|
||||
list[0] = "Icons";
|
||||
} else {
|
||||
if(list.last().endsWith(".html"))
|
||||
if (list.last().endsWith(".html"))
|
||||
list.prepend("html");
|
||||
list.prepend("webui");
|
||||
}
|
||||
url = ":/" + list.join("/");
|
||||
}
|
||||
QFile file(url);
|
||||
if(!file.open(QIODevice::ReadOnly)) {
|
||||
if (!file.open(QIODevice::ReadOnly)) {
|
||||
qDebug("File %s was not found!", qPrintable(url));
|
||||
respondNotFound();
|
||||
return;
|
||||
@@ -314,7 +314,7 @@ void HttpConnection::respond() {
|
||||
file.close();
|
||||
|
||||
// Translate the page
|
||||
if(ext == "html" || (ext == "js" && !list.last().startsWith("excanvas"))) {
|
||||
if (ext == "html" || (ext == "js" && !list.last().startsWith("excanvas"))) {
|
||||
QString dataStr = QString::fromUtf8(data.constData());
|
||||
translateDocument(dataStr);
|
||||
if (url.endsWith("about.html")) {
|
||||
@@ -391,17 +391,17 @@ void HttpConnection::respondGlobalTransferInfoJson() {
|
||||
}
|
||||
|
||||
void HttpConnection::respondCommand(const QString& command) {
|
||||
if(command == "download") {
|
||||
if (command == "download") {
|
||||
QString urls = m_parser.post("urls");
|
||||
QStringList list = urls.split('\n');
|
||||
foreach(QString url, list){
|
||||
foreach (QString url, list){
|
||||
url = url.trimmed();
|
||||
if(!url.isEmpty()){
|
||||
if(url.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
if (!url.isEmpty()){
|
||||
if (url.startsWith("bc://bt/", Qt::CaseInsensitive)) {
|
||||
qDebug("Converting bc link to magnet link");
|
||||
url = misc::bcLinkToMagnet(url);
|
||||
}
|
||||
if(url.startsWith("magnet:", Qt::CaseInsensitive)) {
|
||||
if (url.startsWith("magnet:", Qt::CaseInsensitive)) {
|
||||
emit MagnetReadyToBeDownloaded(url);
|
||||
} else {
|
||||
qDebug("Downloading url: %s", (const char*)url.toLocal8Bit());
|
||||
@@ -412,14 +412,14 @@ void HttpConnection::respondCommand(const QString& command) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(command == "addTrackers") {
|
||||
if (command == "addTrackers") {
|
||||
QString hash = m_parser.post("hash");
|
||||
if(!hash.isEmpty()) {
|
||||
if (!hash.isEmpty()) {
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(h.is_valid() && h.has_metadata()) {
|
||||
if (h.is_valid() && h.has_metadata()) {
|
||||
QString urls = m_parser.post("urls");
|
||||
QStringList list = urls.split('\n');
|
||||
foreach(const QString& url, list) {
|
||||
foreach (const QString& url, list) {
|
||||
announce_entry e(url.toStdString());
|
||||
h.add_tracker(e);
|
||||
}
|
||||
@@ -427,7 +427,7 @@ void HttpConnection::respondCommand(const QString& command) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(command == "upload") {
|
||||
if (command == "upload") {
|
||||
qDebug() << Q_FUNC_INFO << "upload";
|
||||
// Get a unique filename
|
||||
QTemporaryFile *tmpfile = new QTemporaryFile (QDir::temp().absoluteFilePath("qBT-XXXXXX.torrent"));
|
||||
@@ -454,35 +454,35 @@ void HttpConnection::respondCommand(const QString& command) {
|
||||
write();
|
||||
return;
|
||||
}
|
||||
if(command == "resumeall") {
|
||||
if (command == "resumeall") {
|
||||
emit resumeAllTorrents();
|
||||
return;
|
||||
}
|
||||
if(command == "pauseall") {
|
||||
if (command == "pauseall") {
|
||||
emit pauseAllTorrents();
|
||||
return;
|
||||
}
|
||||
if(command == "resume") {
|
||||
if (command == "resume") {
|
||||
emit resumeTorrent(m_parser.post("hash"));
|
||||
return;
|
||||
}
|
||||
if(command == "setPreferences") {
|
||||
if (command == "setPreferences") {
|
||||
QString json_str = m_parser.post("json");
|
||||
EventManager* manager = m_httpserver->eventManager();
|
||||
manager->setGlobalPreferences(json::fromJson(json_str));
|
||||
return;
|
||||
}
|
||||
if(command == "setFilePrio") {
|
||||
if (command == "setFilePrio") {
|
||||
QString hash = m_parser.post("hash");
|
||||
int file_id = m_parser.post("id").toInt();
|
||||
int priority = m_parser.post("priority").toInt();
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(h.is_valid() && h.has_metadata()) {
|
||||
if (h.is_valid() && h.has_metadata()) {
|
||||
h.file_priority(file_id, priority);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(command == "getGlobalUpLimit") {
|
||||
if (command == "getGlobalUpLimit") {
|
||||
m_generator.setStatusLine(200, "OK");
|
||||
m_generator.setContentTypeByExt("html");
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
@@ -493,7 +493,7 @@ void HttpConnection::respondCommand(const QString& command) {
|
||||
write();
|
||||
return;
|
||||
}
|
||||
if(command == "getGlobalDlLimit") {
|
||||
if (command == "getGlobalDlLimit") {
|
||||
m_generator.setStatusLine(200, "OK");
|
||||
m_generator.setContentTypeByExt("html");
|
||||
#if LIBTORRENT_VERSION_MINOR > 15
|
||||
@@ -504,10 +504,10 @@ void HttpConnection::respondCommand(const QString& command) {
|
||||
write();
|
||||
return;
|
||||
}
|
||||
if(command == "getTorrentUpLimit") {
|
||||
if (command == "getTorrentUpLimit") {
|
||||
QString hash = m_parser.post("hash");
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(h.is_valid()) {
|
||||
if (h.is_valid()) {
|
||||
m_generator.setStatusLine(200, "OK");
|
||||
m_generator.setContentTypeByExt("html");
|
||||
m_generator.setMessage(QString::number(h.upload_limit()));
|
||||
@@ -515,10 +515,10 @@ void HttpConnection::respondCommand(const QString& command) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(command == "getTorrentDlLimit") {
|
||||
if (command == "getTorrentDlLimit") {
|
||||
QString hash = m_parser.post("hash");
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(h.is_valid()) {
|
||||
if (h.is_valid()) {
|
||||
m_generator.setStatusLine(200, "OK");
|
||||
m_generator.setContentTypeByExt("html");
|
||||
m_generator.setMessage(QString::number(h.download_limit()));
|
||||
@@ -526,81 +526,81 @@ void HttpConnection::respondCommand(const QString& command) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(command == "setTorrentUpLimit") {
|
||||
if (command == "setTorrentUpLimit") {
|
||||
QString hash = m_parser.post("hash");
|
||||
qlonglong limit = m_parser.post("limit").toLongLong();
|
||||
if(limit == 0) limit = -1;
|
||||
if (limit == 0) limit = -1;
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(h.is_valid()) {
|
||||
if (h.is_valid()) {
|
||||
h.set_upload_limit(limit);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(command == "setTorrentDlLimit") {
|
||||
if (command == "setTorrentDlLimit") {
|
||||
QString hash = m_parser.post("hash");
|
||||
qlonglong limit = m_parser.post("limit").toLongLong();
|
||||
if(limit == 0) limit = -1;
|
||||
if (limit == 0) limit = -1;
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(h.is_valid()) {
|
||||
if (h.is_valid()) {
|
||||
h.set_download_limit(limit);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(command == "setGlobalUpLimit") {
|
||||
if (command == "setGlobalUpLimit") {
|
||||
qlonglong limit = m_parser.post("limit").toLongLong();
|
||||
if(limit == 0) limit = -1;
|
||||
if (limit == 0) limit = -1;
|
||||
QBtSession::instance()->setUploadRateLimit(limit);
|
||||
Preferences().setGlobalUploadLimit(limit/1024.);
|
||||
return;
|
||||
}
|
||||
if(command == "setGlobalDlLimit") {
|
||||
if (command == "setGlobalDlLimit") {
|
||||
qlonglong limit = m_parser.post("limit").toLongLong();
|
||||
if(limit == 0) limit = -1;
|
||||
if (limit == 0) limit = -1;
|
||||
QBtSession::instance()->setDownloadRateLimit(limit);
|
||||
Preferences().setGlobalDownloadLimit(limit/1024.);
|
||||
return;
|
||||
}
|
||||
if(command == "pause") {
|
||||
if (command == "pause") {
|
||||
emit pauseTorrent(m_parser.post("hash"));
|
||||
return;
|
||||
}
|
||||
if(command == "delete") {
|
||||
if (command == "delete") {
|
||||
QStringList hashes = m_parser.post("hashes").split("|");
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
emit deleteTorrent(hash, false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(command == "deletePerm") {
|
||||
if (command == "deletePerm") {
|
||||
QStringList hashes = m_parser.post("hashes").split("|");
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
emit deleteTorrent(hash, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(command == "increasePrio") {
|
||||
if (command == "increasePrio") {
|
||||
increaseTorrentsPriority(m_parser.post("hashes").split("|"));
|
||||
return;
|
||||
}
|
||||
if(command == "decreasePrio") {
|
||||
if (command == "decreasePrio") {
|
||||
decreaseTorrentsPriority(m_parser.post("hashes").split("|"));
|
||||
return;
|
||||
}
|
||||
if(command == "topPrio") {
|
||||
foreach(const QString &hash, m_parser.post("hashes").split("|")) {
|
||||
if (command == "topPrio") {
|
||||
foreach (const QString &hash, m_parser.post("hashes").split("|")) {
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(h.is_valid()) h.queue_position_top();
|
||||
if (h.is_valid()) h.queue_position_top();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(command == "bottomPrio") {
|
||||
foreach(const QString &hash, m_parser.post("hashes").split("|")) {
|
||||
if (command == "bottomPrio") {
|
||||
foreach (const QString &hash, m_parser.post("hashes").split("|")) {
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(h.is_valid()) h.queue_position_bottom();
|
||||
if (h.is_valid()) h.queue_position_bottom();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(command == "recheck"){
|
||||
if (command == "recheck"){
|
||||
QBtSession::instance()->recheckTorrent(m_parser.post("hash"));
|
||||
return;
|
||||
}
|
||||
@@ -612,10 +612,10 @@ void HttpConnection::decreaseTorrentsPriority(const QStringList &hashes) {
|
||||
std::vector<QPair<int, QTorrentHandle> >,
|
||||
std::less<QPair<int, QTorrentHandle> > > torrent_queue;
|
||||
// Sort torrents by priority
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
try {
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(!h.is_seed()) {
|
||||
if (!h.is_seed()) {
|
||||
torrent_queue.push(qMakePair(h.queue_position(), h));
|
||||
}
|
||||
}catch(invalid_handle&){}
|
||||
@@ -637,10 +637,10 @@ void HttpConnection::increaseTorrentsPriority(const QStringList &hashes)
|
||||
std::vector<QPair<int, QTorrentHandle> >,
|
||||
std::greater<QPair<int, QTorrentHandle> > > torrent_queue;
|
||||
// Sort torrents by priority
|
||||
foreach(const QString &hash, hashes) {
|
||||
foreach (const QString &hash, hashes) {
|
||||
try {
|
||||
QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
|
||||
if(!h.is_seed()) {
|
||||
if (!h.is_seed()) {
|
||||
torrent_queue.push(qMakePair(h.queue_position(), h));
|
||||
}
|
||||
}catch(invalid_handle&){}
|
||||
|
||||
@@ -87,7 +87,7 @@ void HttpRequestParser::writeMessage(const QByteArray& ba) {
|
||||
qDebug() << Q_FUNC_INFO << "m_data.size(): " << m_data.size();
|
||||
|
||||
// Parse POST data
|
||||
if(m_header.contentType() == "application/x-www-form-urlencoded") {
|
||||
if (m_header.contentType() == "application/x-www-form-urlencoded") {
|
||||
QUrl url;
|
||||
url.setEncodedQuery(m_data);
|
||||
QListIterator<QPair<QString, QString> > i(url.queryItems());
|
||||
|
||||
@@ -42,23 +42,23 @@ void HttpResponseGenerator::setMessage(const QString& message) {
|
||||
}
|
||||
|
||||
void HttpResponseGenerator::setContentTypeByExt(const QString& ext) {
|
||||
if(ext == "css") {
|
||||
if (ext == "css") {
|
||||
setContentType("text/css");
|
||||
return;
|
||||
}
|
||||
if(ext == "gif") {
|
||||
if (ext == "gif") {
|
||||
setContentType("image/gif");
|
||||
return;
|
||||
}
|
||||
if(ext == "htm" || ext == "html") {
|
||||
if (ext == "htm" || ext == "html") {
|
||||
setContentType("text/html");
|
||||
return;
|
||||
}
|
||||
if(ext == "js") {
|
||||
if (ext == "js") {
|
||||
setContentType("text/javascript");
|
||||
return;
|
||||
}
|
||||
if(ext == "png") {
|
||||
if (ext == "png") {
|
||||
setContentType("image/x-png");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ int HttpServer::NbFailedAttemptsForIp(const QString& ip) const {
|
||||
void HttpServer::increaseNbFailedAttemptsForIp(const QString& ip) {
|
||||
const int nb_fail = m_clientFailedAttempts.value(ip, 0) + 1;
|
||||
m_clientFailedAttempts.insert(ip, nb_fail);
|
||||
if(nb_fail == MAX_AUTH_FAILED_ATTEMPTS) {
|
||||
if (nb_fail == MAX_AUTH_FAILED_ATTEMPTS) {
|
||||
// Max number of failed attempts reached
|
||||
// Start ban period
|
||||
UnbanTimer* ubantimer = new UnbanTimer(ip, this);
|
||||
@@ -112,9 +112,9 @@ HttpServer::HttpServer(int msec, QObject* parent) : QTcpServer(parent),
|
||||
// Add torrents
|
||||
std::vector<torrent_handle> torrents = QBtSession::instance()->getTorrents();
|
||||
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);
|
||||
if(h.is_valid())
|
||||
if (h.is_valid())
|
||||
m_eventManager->addedTorrent(h);
|
||||
}
|
||||
|
||||
@@ -217,9 +217,9 @@ void HttpServer::handleNewConnection(QTcpSocket *socket)
|
||||
void HttpServer::onTimer() {
|
||||
std::vector<torrent_handle> torrents = QBtSession::instance()->getTorrents();
|
||||
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);
|
||||
if(h.is_valid())
|
||||
if (h.is_valid())
|
||||
m_eventManager->modifiedTorrent(h);
|
||||
}
|
||||
}
|
||||
@@ -245,28 +245,28 @@ bool HttpServer::isAuthorized(const QByteArray& auth,
|
||||
//qDebug("AUTH string is %s", auth.data());
|
||||
// Get user name
|
||||
QRegExp regex_user(".*username=\"([^\"]+)\".*"); // Must be a quoted string
|
||||
if(regex_user.indexIn(auth) < 0) return false;
|
||||
if (regex_user.indexIn(auth) < 0) return false;
|
||||
QString prop_user = regex_user.cap(1);
|
||||
//qDebug("AUTH: Proposed username is %s, real username is %s", prop_user.toLocal8Bit().data(), username.data());
|
||||
if(prop_user != m_username) {
|
||||
if (prop_user != m_username) {
|
||||
// User name is invalid, we can reject already
|
||||
qDebug("AUTH-PROB: Username is invalid");
|
||||
return false;
|
||||
}
|
||||
// Get realm
|
||||
QRegExp regex_realm(".*realm=\"([^\"]+)\".*"); // Must be a quoted string
|
||||
if(regex_realm.indexIn(auth) < 0) {
|
||||
if (regex_realm.indexIn(auth) < 0) {
|
||||
qDebug("AUTH-PROB: Missing realm");
|
||||
return false;
|
||||
}
|
||||
QByteArray prop_realm = regex_realm.cap(1).toLocal8Bit();
|
||||
if(prop_realm != QBT_REALM) {
|
||||
if (prop_realm != QBT_REALM) {
|
||||
qDebug("AUTH-PROB: Wrong realm");
|
||||
return false;
|
||||
}
|
||||
// get nonce
|
||||
QRegExp regex_nonce(".*nonce=[\"]?([\\w=]+)[\"]?.*");
|
||||
if(regex_nonce.indexIn(auth) < 0) {
|
||||
if (regex_nonce.indexIn(auth) < 0) {
|
||||
qDebug("AUTH-PROB: missing nonce");
|
||||
return false;
|
||||
}
|
||||
@@ -274,7 +274,7 @@ bool HttpServer::isAuthorized(const QByteArray& auth,
|
||||
//qDebug("prop nonce is: %s", prop_nonce.data());
|
||||
// get uri
|
||||
QRegExp regex_uri(".*uri=\"([^\"]+)\".*");
|
||||
if(regex_uri.indexIn(auth) < 0) {
|
||||
if (regex_uri.indexIn(auth) < 0) {
|
||||
qDebug("AUTH-PROB: Missing uri");
|
||||
return false;
|
||||
}
|
||||
@@ -282,7 +282,7 @@ bool HttpServer::isAuthorized(const QByteArray& auth,
|
||||
//qDebug("prop uri is: %s", prop_uri.data());
|
||||
// get response
|
||||
QRegExp regex_response(".*response=[\"]?([\\w=]+)[\"]?.*");
|
||||
if(regex_response.indexIn(auth) < 0) {
|
||||
if (regex_response.indexIn(auth) < 0) {
|
||||
qDebug("AUTH-PROB: Missing response");
|
||||
return false;
|
||||
}
|
||||
@@ -293,25 +293,25 @@ bool HttpServer::isAuthorized(const QByteArray& auth,
|
||||
md5_ha2.addData(method.toLocal8Bit() + ":" + prop_uri);
|
||||
QByteArray ha2 = md5_ha2.result().toHex();
|
||||
QByteArray response = "";
|
||||
if(auth.contains("qop=")) {
|
||||
if (auth.contains("qop=")) {
|
||||
QCryptographicHash md5_ha(QCryptographicHash::Md5);
|
||||
// Get nc
|
||||
QRegExp regex_nc(".*nc=[\"]?([\\w=]+)[\"]?.*");
|
||||
if(regex_nc.indexIn(auth) < 0) {
|
||||
if (regex_nc.indexIn(auth) < 0) {
|
||||
qDebug("AUTH-PROB: qop but missing nc");
|
||||
return false;
|
||||
}
|
||||
QByteArray prop_nc = regex_nc.cap(1).toLocal8Bit();
|
||||
//qDebug("prop nc is: %s", prop_nc.data());
|
||||
QRegExp regex_cnonce(".*cnonce=[\"]?([\\w=]+)[\"]?.*");
|
||||
if(regex_cnonce.indexIn(auth) < 0) {
|
||||
if (regex_cnonce.indexIn(auth) < 0) {
|
||||
qDebug("AUTH-PROB: qop but missing cnonce");
|
||||
return false;
|
||||
}
|
||||
QByteArray prop_cnonce = regex_cnonce.cap(1).toLocal8Bit();
|
||||
//qDebug("prop cnonce is: %s", prop_cnonce.data());
|
||||
QRegExp regex_qop(".*qop=[\"]?(\\w+)[\"]?.*");
|
||||
if(regex_qop.indexIn(auth) < 0) {
|
||||
if (regex_qop.indexIn(auth) < 0) {
|
||||
qDebug("AUTH-PROB: missing qop");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ namespace json {
|
||||
case QVariant::StringList:
|
||||
case QVariant::List: {
|
||||
QStringList strList;
|
||||
foreach(const QVariant &var, v.toList()) {
|
||||
foreach (const QVariant &var, v.toList()) {
|
||||
strList << toJson(var);
|
||||
}
|
||||
return "["+strList.join(",")+"]";
|
||||
@@ -59,7 +59,7 @@ namespace json {
|
||||
case QVariant::String: {
|
||||
QString s = v.value<QString>();
|
||||
QString result = "\"";
|
||||
for(int i=0; i<s.size(); ++i) {
|
||||
for (int i=0; i<s.size(); ++i) {
|
||||
const QChar ch = s[i];
|
||||
switch(ch.toAscii())
|
||||
{
|
||||
@@ -109,39 +109,39 @@ namespace json {
|
||||
QVariantMap fromJson(const QString& json) {
|
||||
qDebug("JSON is %s", qPrintable(json));
|
||||
QVariantMap m;
|
||||
if(json.startsWith("{") && json.endsWith("}")) {
|
||||
if (json.startsWith("{") && json.endsWith("}")) {
|
||||
QStringList couples;
|
||||
QString tmp = "";
|
||||
bool in_list = false;
|
||||
foreach(const QChar &c, json.mid(1, json.length()-2)) {
|
||||
if(c == ',' && !in_list) {
|
||||
foreach (const QChar &c, json.mid(1, json.length()-2)) {
|
||||
if (c == ',' && !in_list) {
|
||||
couples << tmp;
|
||||
tmp = "";
|
||||
} else {
|
||||
if(c == '[')
|
||||
if (c == '[')
|
||||
in_list = true;
|
||||
else if(c == ']')
|
||||
else if (c == ']')
|
||||
in_list = false;
|
||||
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(":");
|
||||
if(parts.size() != 2) continue;
|
||||
if (parts.size() != 2) continue;
|
||||
QString key = parts.first();
|
||||
if(key.startsWith("\"") && key.endsWith("\"")) {
|
||||
if (key.startsWith("\"") && key.endsWith("\"")) {
|
||||
key = key.mid(1, key.length()-2);
|
||||
}
|
||||
QString value_str = parts.last();
|
||||
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);
|
||||
QStringList list_elems = value_str.split(",", QString::SkipEmptyParts);
|
||||
QVariantList varlist;
|
||||
foreach(const QString &list_val, list_elems) {
|
||||
if(list_val.startsWith("\"") && list_val.endsWith("\"")) {
|
||||
foreach (const QString &list_val, list_elems) {
|
||||
if (list_val.startsWith("\"") && list_val.endsWith("\"")) {
|
||||
varlist << list_val.mid(1, list_val.length()-2).replace("\\n", "\n");
|
||||
} else {
|
||||
varlist << list_val.toInt();
|
||||
@@ -149,7 +149,7 @@ namespace json {
|
||||
}
|
||||
value = varlist;
|
||||
} 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 = value_str;
|
||||
} else {
|
||||
@@ -170,10 +170,10 @@ namespace json {
|
||||
|
||||
QString toJson(const QList<QVariantMap>& v) {
|
||||
QStringList res;
|
||||
foreach(QVariantMap m, v) {
|
||||
foreach (QVariantMap m, v) {
|
||||
QStringList vlist;
|
||||
QVariantMap::ConstIterator it;
|
||||
for(it = m.constBegin(); it != m.constEnd(); it++) {
|
||||
for (it = m.constBegin(); it != m.constEnd(); it++) {
|
||||
vlist << toJson(it.key())+":"+toJson(it.value());
|
||||
}
|
||||
res << "{"+vlist.join(",")+"}";
|
||||
|
||||
Reference in New Issue
Block a user