Migrate everything to use the new Preferences class and not access directly the qbittorrent.ini file.

This commit is contained in:
sledgehammer999 2014-07-05 15:44:13 +03:00
parent da6ce859c0
commit d8d95d2195
44 changed files with 748 additions and 908 deletions

View file

@ -34,7 +34,6 @@
#include "torrentcontentmodel.h" #include "torrentcontentmodel.h"
#include "torrentcontentfiltermodel.h" #include "torrentcontentfiltermodel.h"
#include "preferences.h" #include "preferences.h"
#include "qinisettings.h"
#include "torrentpersistentdata.h" #include "torrentpersistentdata.h"
#include "qbtsession.h" #include "qbtsession.h"
#include "iconprovider.h" #include "iconprovider.h"
@ -64,10 +63,9 @@ AddNewTorrentDialog::AddNewTorrentDialog(QWidget *parent) :
ui->lblMetaLoading->setVisible(false); ui->lblMetaLoading->setVisible(false);
ui->progMetaLoading->setVisible(false); ui->progMetaLoading->setVisible(false);
QIniSettings settings; Preferences* const pref = Preferences::instance();
Preferences pref; ui->start_torrent_cb->setChecked(!pref->addTorrentsInPause());
ui->start_torrent_cb->setChecked(!pref.addTorrentsInPause()); ui->save_path_combo->addItem(fsutils::toNativePath(pref->getSavePath()), pref->getSavePath());
ui->save_path_combo->addItem(fsutils::toNativePath(pref.getSavePath()), pref.getSavePath());
loadSavePathHistory(); loadSavePathHistory();
ui->save_path_combo->insertSeparator(ui->save_path_combo->count()); ui->save_path_combo->insertSeparator(ui->save_path_combo->count());
ui->save_path_combo->addItem(tr("Other...", "Other save path...")); ui->save_path_combo->addItem(tr("Other...", "Other save path..."));
@ -75,7 +73,7 @@ AddNewTorrentDialog::AddNewTorrentDialog(QWidget *parent) :
ui->default_save_path_cb->setVisible(false); // Default path is selected by default ui->default_save_path_cb->setVisible(false); // Default path is selected by default
// Load labels // Load labels
const QStringList customLabels = settings.value("TransferListFilters/customLabels", QStringList()).toStringList(); const QStringList customLabels = pref->getTorrentLabels();
ui->label_combo->addItem(""); ui->label_combo->addItem("");
foreach (const QString& label, customLabels) { foreach (const QString& label, customLabels) {
ui->label_combo->addItem(label); ui->label_combo->addItem(label);
@ -101,27 +99,25 @@ AddNewTorrentDialog::~AddNewTorrentDialog()
void AddNewTorrentDialog::loadState() void AddNewTorrentDialog::loadState()
{ {
QIniSettings settings; const Preferences* const pref = Preferences::instance();
settings.beginGroup(QString::fromUtf8("AddNewTorrentDialog")); m_headerState = pref->getAddNewTorrentDialogState();
m_headerState = settings.value("treeHeaderState").toByteArray(); int width = pref->getAddNewTorrentDialogWidth();
int width = settings.value("width", -1).toInt();
if (width >= 0) { if (width >= 0) {
QRect geo = geometry(); QRect geo = geometry();
geo.setWidth(width); geo.setWidth(width);
setGeometry(geo); setGeometry(geo);
} }
ui->adv_button->setChecked(settings.value("expanded", false).toBool()); ui->adv_button->setChecked(pref->getAddNewTorrentDialogExpanded());
} }
void AddNewTorrentDialog::saveState() void AddNewTorrentDialog::saveState()
{ {
QIniSettings settings; Preferences* const pref = Preferences::instance();
settings.beginGroup(QString::fromUtf8("AddNewTorrentDialog"));
if (m_contentModel) if (m_contentModel)
settings.setValue("treeHeaderState", ui->content_tree->header()->saveState()); pref->setAddNewTorrentDialogState(ui->content_tree->header()->saveState());
settings.setValue("y", pos().y()); pref->setAddNewTorrentDialogPos(pos().y());
settings.setValue("width", width()); pref->setAddNewTorrentDialogWidth(width());
settings.setValue("expanded", ui->adv_button->isChecked()); pref->setAddNewTorrentDialogExpanded(ui->adv_button->isChecked());
} }
void AddNewTorrentDialog::showTorrent(const QString &torrent_path, const QString& from_url) void AddNewTorrentDialog::showTorrent(const QString &torrent_path, const QString& from_url)
@ -140,8 +136,8 @@ void AddNewTorrentDialog::showMagnet(const QString& link)
void AddNewTorrentDialog::showEvent(QShowEvent *event) { void AddNewTorrentDialog::showEvent(QShowEvent *event) {
QDialog::showEvent(event); QDialog::showEvent(event);
Preferences pref; Preferences* const pref = Preferences::instance();
if (!pref.AdditionDialogFront()) if (!pref->additionDialogFront())
return; return;
activateWindow(); activateWindow();
raise(); raise();
@ -229,8 +225,7 @@ bool AddNewTorrentDialog::loadMagnet(const QString &magnet_uri)
QString torrent_name = misc::magnetUriToName(m_url); QString torrent_name = misc::magnetUriToName(m_url);
setWindowTitle(torrent_name.isEmpty() ? tr("Magnet link") : torrent_name); setWindowTitle(torrent_name.isEmpty() ? tr("Magnet link") : torrent_name);
QIniSettings settings; showAdvancedSettings(Preferences::instance()->getAddNewTorrentDialogExpanded());
showAdvancedSettings(settings.value("AddNewTorrentDialog/expanded").toBool());
// Set dialog position // Set dialog position
setdialogPosition(); setdialogPosition();
@ -246,9 +241,9 @@ bool AddNewTorrentDialog::loadMagnet(const QString &magnet_uri)
void AddNewTorrentDialog::saveSavePathHistory() const void AddNewTorrentDialog::saveSavePathHistory() const
{ {
QDir selected_save_path(ui->save_path_combo->itemData(ui->save_path_combo->currentIndex()).toString()); QDir selected_save_path(ui->save_path_combo->itemData(ui->save_path_combo->currentIndex()).toString());
QIniSettings settings; Preferences* const pref = Preferences::instance();
// Get current history // Get current history
QStringList history = settings.value("TorrentAdditionDlg/save_path_history").toStringList(); QStringList history = pref->getAddNewTorrentDialogPathHistory();
QList<QDir> history_dirs; QList<QDir> history_dirs;
foreach(const QString dir, history) foreach(const QString dir, history)
history_dirs << QDir(dir); history_dirs << QDir(dir);
@ -259,7 +254,7 @@ void AddNewTorrentDialog::saveSavePathHistory() const
if (history.size() > 8) if (history.size() > 8)
history.removeFirst(); history.removeFirst();
// Save history // Save history
settings.setValue("TorrentAdditionDlg/save_path_history", history); pref->setAddNewTorrentDialogPathHistory(history);
} }
} }
@ -307,7 +302,7 @@ void AddNewTorrentDialog::updateDiskSpaceLabel()
void AddNewTorrentDialog::onSavePathChanged(int index) void AddNewTorrentDialog::onSavePathChanged(int index)
{ {
static int old_index = 0; static int old_index = 0;
Preferences pref; Preferences* const pref = Preferences::instance();
if (index == (ui->save_path_combo->count() - 1)) { if (index == (ui->save_path_combo->count() - 1)) {
disconnect(ui->save_path_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(onSavePathChanged(int))); disconnect(ui->save_path_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(onSavePathChanged(int)));
@ -354,7 +349,7 @@ void AddNewTorrentDialog::onSavePathChanged(int index)
} }
// Toggle default save path setting checkbox visibility // Toggle default save path setting checkbox visibility
ui->default_save_path_cb->setChecked(false); ui->default_save_path_cb->setChecked(false);
ui->default_save_path_cb->setVisible(QDir(ui->save_path_combo->itemData(ui->save_path_combo->currentIndex()).toString()) != pref.getSavePath()); ui->default_save_path_cb->setVisible(QDir(ui->save_path_combo->itemData(ui->save_path_combo->currentIndex()).toString()) != pref->getSavePath());
relayout(); relayout();
// Remember index // Remember index
old_index = ui->save_path_combo->currentIndex(); old_index = ui->save_path_combo->currentIndex();
@ -475,8 +470,7 @@ void AddNewTorrentDialog::setdialogPosition()
qApp->processEvents(); qApp->processEvents();
QPoint center(misc::screenCenter(this)); QPoint center(misc::screenCenter(this));
// Adjust y // Adjust y
QIniSettings settings; int y = Preferences::instance()->getAddNewTorrentDialogPos();
int y = settings.value("AddNewTorrentDialog/y", -1).toInt();
if (y >= 0) { if (y >= 0) {
center.setY(y); center.setY(y);
} else { } else {
@ -489,10 +483,9 @@ void AddNewTorrentDialog::setdialogPosition()
void AddNewTorrentDialog::loadSavePathHistory() void AddNewTorrentDialog::loadSavePathHistory()
{ {
QIniSettings settings; QDir default_save_path(Preferences::instance()->getSavePath());
QDir default_save_path(Preferences().getSavePath());
// Load save path history // Load save path history
QStringList raw_path_history = settings.value("TorrentAdditionDlg/save_path_history").toStringList(); QStringList raw_path_history = Preferences::instance()->getAddNewTorrentDialogPathHistory();
foreach (const QString &sp, raw_path_history) { foreach (const QString &sp, raw_path_history) {
if (QDir(sp) != default_save_path) if (QDir(sp) != default_save_path)
ui->save_path_combo->addItem(fsutils::toNativePath(sp), sp); ui->save_path_combo->addItem(fsutils::toNativePath(sp), sp);
@ -545,7 +538,7 @@ void AddNewTorrentDialog::accept()
if (m_isMagnet) if (m_isMagnet)
disconnect(this, SLOT(updateMetadata(const QTorrentHandle&))); disconnect(this, SLOT(updateMetadata(const QTorrentHandle&)));
Preferences pref; Preferences* const pref = Preferences::instance();
// Save Temporary data about torrent // Save Temporary data about torrent
QString save_path = ui->save_path_combo->itemData(ui->save_path_combo->currentIndex()).toString(); QString save_path = ui->save_path_combo->itemData(ui->save_path_combo->currentIndex()).toString();
TorrentTempData::setSavePath(m_hash, save_path); TorrentTempData::setSavePath(m_hash, save_path);
@ -553,7 +546,7 @@ void AddNewTorrentDialog::accept()
// TODO: Check if destination actually exists // TODO: Check if destination actually exists
TorrentTempData::setSeedingMode(m_hash, true); TorrentTempData::setSeedingMode(m_hash, true);
} }
pref.addTorrentsInPause(!ui->start_torrent_cb->isChecked()); pref->addTorrentsInPause(!ui->start_torrent_cb->isChecked());
// Label // Label
const QString label = ui->label_combo->currentText(); const QString label = ui->label_combo->currentText();
@ -576,10 +569,10 @@ void AddNewTorrentDialog::accept()
saveSavePathHistory(); saveSavePathHistory();
// Save settings // Save settings
pref.useAdditionDialog(!ui->never_show_cb->isChecked()); pref->useAdditionDialog(!ui->never_show_cb->isChecked());
if (ui->default_save_path_cb->isChecked()) { if (ui->default_save_path_cb->isChecked()) {
pref.setSavePath(ui->save_path_combo->itemData(ui->save_path_combo->currentIndex()).toString()); pref->setSavePath(ui->save_path_combo->itemData(ui->save_path_combo->currentIndex()).toString());
QBtSession::instance()->setDefaultSavePath(pref.getSavePath()); QBtSession::instance()->setDefaultSavePath(pref->getSavePath());
} }
QDialog::accept(); QDialog::accept();
} }
@ -671,8 +664,7 @@ void AddNewTorrentDialog::setupTreeview() {
} }
} }
QIniSettings settings; showAdvancedSettings(Preferences::instance()->getAddNewTorrentDialogExpanded());
showAdvancedSettings(settings.value("AddNewTorrentDialog/expanded").toBool());
// Set dialog position // Set dialog position
setdialogPosition(); setdialogPosition();
} }

View file

@ -35,6 +35,7 @@
#include "ui_confirmdeletiondlg.h" #include "ui_confirmdeletiondlg.h"
#include "preferences.h" #include "preferences.h"
#include "iconprovider.h" #include "iconprovider.h"
#include "misc.h"
class DeletionConfirmationDlg : public QDialog, private Ui::confirmDeletionDlg { class DeletionConfirmationDlg : public QDialog, private Ui::confirmDeletionDlg {
Q_OBJECT Q_OBJECT
@ -52,7 +53,7 @@ class DeletionConfirmationDlg : public QDialog, private Ui::confirmDeletionDlg {
rememberBtn->setIcon(IconProvider::instance()->getIcon("object-locked")); rememberBtn->setIcon(IconProvider::instance()->getIcon("object-locked"));
move(misc::screenCenter(this)); move(misc::screenCenter(this));
checkPermDelete->setChecked(Preferences().deleteTorrentFilesAsDefault()); checkPermDelete->setChecked(Preferences::instance()->deleteTorrentFilesAsDefault());
connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState())); connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState()));
buttonBox->setFocus(); buttonBox->setFocus();
} }
@ -72,11 +73,11 @@ class DeletionConfirmationDlg : public QDialog, private Ui::confirmDeletionDlg {
private slots: private slots:
void updateRememberButtonState() { void updateRememberButtonState() {
rememberBtn->setEnabled(checkPermDelete->isChecked() != Preferences().deleteTorrentFilesAsDefault()); rememberBtn->setEnabled(checkPermDelete->isChecked() != Preferences::instance()->deleteTorrentFilesAsDefault());
} }
void on_rememberBtn_clicked() { void on_rememberBtn_clicked() {
Preferences().setDeleteTorrentFilesAsDefault(checkPermDelete->isChecked()); Preferences::instance()->setDeleteTorrentFilesAsDefault(checkPermDelete->isChecked());
rememberBtn->setEnabled(false); rememberBtn->setEnabled(false);
} }
}; };

View file

@ -43,9 +43,9 @@ DNSUpdater::DNSUpdater(QObject *parent) :
updateCredentials(); updateCredentials();
// Load saved settings from previous session // Load saved settings from previous session
QIniSettings settings; const Preferences* const pref = Preferences::instance();
m_lastIPCheckTime = settings.value("DNSUpdater/lastUpdateTime").toDateTime(); m_lastIPCheckTime = pref->getDNSLastUpd();
m_lastIP = QHostAddress(settings.value("DNSUpdater/lastIP").toString()); m_lastIP = QHostAddress(pref->getDNSLastIP());
// Start IP checking timer // Start IP checking timer
m_ipCheckTimer.setInterval(IP_CHECK_INTERVAL_MS); m_ipCheckTimer.setInterval(IP_CHECK_INTERVAL_MS);
@ -61,9 +61,9 @@ DNSUpdater::DNSUpdater(QObject *parent) :
DNSUpdater::~DNSUpdater() { DNSUpdater::~DNSUpdater() {
// Save lastupdate time and last ip // Save lastupdate time and last ip
QIniSettings settings; Preferences* const pref = Preferences::instance();
settings.setValue("DNSUpdater/lastUpdateTime", m_lastIPCheckTime); pref->setDNSLastUpd(m_lastIPCheckTime);
settings.setValue("DNSUpdater/lastIP", m_lastIP.toString()); pref->setDNSLastIP(m_lastIP.toString());
} }
void DNSUpdater::checkPublicIP() void DNSUpdater::checkPublicIP()
@ -234,15 +234,15 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
void DNSUpdater::updateCredentials() void DNSUpdater::updateCredentials()
{ {
if (m_state == FATAL) return; if (m_state == FATAL) return;
Preferences pref; Preferences* const pref = Preferences::instance();
bool change = false; bool change = false;
// Get DNS service information // Get DNS service information
if (m_service != pref.getDynDNSService()) { if (m_service != pref->getDynDNSService()) {
m_service = pref.getDynDNSService(); m_service = pref->getDynDNSService();
change = true; change = true;
} }
if (m_domain != pref.getDynDomainName()) { if (m_domain != pref->getDynDomainName()) {
m_domain = pref.getDynDomainName(); m_domain = pref->getDynDomainName();
QRegExp domain_regex("^(?:(?!\\d|-)[a-zA-Z0-9\\-]{1,63}\\.)+[a-zA-Z]{2,}$"); QRegExp domain_regex("^(?:(?!\\d|-)[a-zA-Z0-9\\-]{1,63}\\.)+[a-zA-Z]{2,}$");
if (domain_regex.indexIn(m_domain) < 0) { if (domain_regex.indexIn(m_domain) < 0) {
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied domain name is invalid."), QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied domain name is invalid."),
@ -254,8 +254,8 @@ void DNSUpdater::updateCredentials()
} }
change = true; change = true;
} }
if (m_username != pref.getDynDNSUsername()) { if (m_username != pref->getDynDNSUsername()) {
m_username = pref.getDynDNSUsername(); m_username = pref->getDynDNSUsername();
if (m_username.length() < 4) { if (m_username.length() < 4) {
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied username is too short."), QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied username is too short."),
"red"); "red");
@ -266,8 +266,8 @@ void DNSUpdater::updateCredentials()
} }
change = true; change = true;
} }
if (m_password != pref.getDynDNSPassword()) { if (m_password != pref->getDynDNSPassword()) {
m_password = pref.getDynDNSPassword(); m_password = pref->getDynDNSPassword();
if (m_password.length() < 4) { if (m_password.length() < 4) {
QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied password is too short."), QBtSession::instance()->addConsoleMessage(tr("Dynamic DNS error: supplied password is too short."),
"red"); "red");

View file

@ -33,13 +33,12 @@
#include <QNetworkRequest> #include <QNetworkRequest>
#include <QNetworkProxy> #include <QNetworkProxy>
#include <QNetworkCookieJar> #include <QNetworkCookieJar>
#include <QDebug>
#include "downloadthread.h" #include "downloadthread.h"
#include "preferences.h" #include "preferences.h"
#ifndef DISABLE_GUI
#include "rsssettings.h"
#endif
#include "qinisettings.h" #include "qinisettings.h"
#include "fs_utils.h"
#include <zlib.h> #include <zlib.h>
/** Download Thread **/ /** Download Thread **/
@ -221,13 +220,13 @@ void DownloadThread::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal)
void DownloadThread::applyProxySettings() { void DownloadThread::applyProxySettings() {
QNetworkProxy proxy; QNetworkProxy proxy;
const Preferences pref; const Preferences* const pref = Preferences::instance();
if (pref.isProxyEnabled()) { if (pref->isProxyEnabled()) {
// Proxy enabled // Proxy enabled
proxy.setHostName(pref.getProxyIp()); proxy.setHostName(pref->getProxyIp());
proxy.setPort(pref.getProxyPort()); proxy.setPort(pref->getProxyPort());
// Default proxy type is HTTP, we must change if it is SOCKS5 // Default proxy type is HTTP, we must change if it is SOCKS5
const int proxy_type = pref.getProxyType(); const int proxy_type = pref->getProxyType();
if (proxy_type == Proxy::SOCKS5 || proxy_type == Proxy::SOCKS5_PW) { if (proxy_type == Proxy::SOCKS5 || proxy_type == Proxy::SOCKS5_PW) {
qDebug() << Q_FUNC_INFO << "using SOCKS proxy"; qDebug() << Q_FUNC_INFO << "using SOCKS proxy";
proxy.setType(QNetworkProxy::Socks5Proxy); proxy.setType(QNetworkProxy::Socks5Proxy);
@ -236,10 +235,10 @@ void DownloadThread::applyProxySettings() {
proxy.setType(QNetworkProxy::HttpProxy); proxy.setType(QNetworkProxy::HttpProxy);
} }
// Authentication? // Authentication?
if (pref.isProxyAuthEnabled()) { if (pref->isProxyAuthEnabled()) {
qDebug("Proxy requires authentication, authenticating"); qDebug("Proxy requires authentication, authenticating");
proxy.setUser(pref.getProxyUsername()); proxy.setUser(pref->getProxyUsername());
proxy.setPassword(pref.getProxyPassword()); proxy.setPassword(pref->getProxyPassword());
} }
} else { } else {
proxy.setType(QNetworkProxy::NoProxy); proxy.setType(QNetworkProxy::NoProxy);

View file

@ -33,8 +33,11 @@
#include <QObject> #include <QObject>
#include <QCoreApplication> #include <QCoreApplication>
#include <QDebug>
#include "preferences.h" #include "preferences.h"
#include "qbtsession.h" #include "qbtsession.h"
#include "fs_utils.h"
#include "misc.h"
class HeadlessLoader: public QObject { class HeadlessLoader: public QObject {
Q_OBJECT Q_OBJECT
@ -42,9 +45,9 @@ class HeadlessLoader: public QObject {
public: public:
HeadlessLoader(const QStringList &torrentCmdLine) { HeadlessLoader(const QStringList &torrentCmdLine) {
connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(shutdownCleanUp()), Qt::DirectConnection); connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(shutdownCleanUp()), Qt::DirectConnection);
Preferences pref; Preferences* const pref = Preferences::instance();
// Enable Web UI // Enable Web UI
pref.setWebUiEnabled(true); pref->setWebUiEnabled(true);
// Instanciate Bittorrent Object // Instanciate Bittorrent Object
connect(QBtSession::instance(), SIGNAL(newConsoleMessage(QString)), this, SLOT(displayConsoleMessage(QString))); connect(QBtSession::instance(), SIGNAL(newConsoleMessage(QString)), this, SLOT(displayConsoleMessage(QString)));
// Resume unfinished torrents // Resume unfinished torrents
@ -53,10 +56,10 @@ public:
processParams(torrentCmdLine); processParams(torrentCmdLine);
// Display some information to the user // Display some information to the user
std::cout << std::endl << "******** " << qPrintable(tr("Information")) << " ********" << std::endl; std::cout << std::endl << "******** " << qPrintable(tr("Information")) << " ********" << std::endl;
std::cout << qPrintable(tr("To control qBittorrent, access the Web UI at http://localhost:%1").arg(QString::number(pref.getWebUiPort()))) << std::endl; std::cout << qPrintable(tr("To control qBittorrent, access the Web UI at http://localhost:%1").arg(QString::number(pref->getWebUiPort()))) << std::endl;
std::cout << qPrintable(tr("The Web UI administrator user name is: %1").arg(pref.getWebUiUsername())) << std::endl; std::cout << qPrintable(tr("The Web UI administrator user name is: %1").arg(pref->getWebUiUsername())) << std::endl;
qDebug() << "Password:" << pref.getWebUiPassword(); qDebug() << "Password:" << pref->getWebUiPassword();
if (pref.getWebUiPassword() == "32fe0bd2bb001911bb8bcfe23fc92b63") { if (pref->getWebUiPassword() == "32fe0bd2bb001911bb8bcfe23fc92b63") {
std::cout << qPrintable(tr("The Web UI administrator password is still the default one: %1").arg("adminadmin")) << std::endl; std::cout << qPrintable(tr("The Web UI administrator password is still the default one: %1").arg("adminadmin")) << std::endl;
std::cout << qPrintable(tr("This is a security risk, please consider changing your password from program preferences.")) << std::endl; std::cout << qPrintable(tr("This is a security risk, please consider changing your password from program preferences.")) << std::endl;
} }
@ -64,8 +67,8 @@ public:
public slots: public slots:
void shutdownCleanUp() { void shutdownCleanUp() {
Preferences().sync();
QBtSession::drop(); QBtSession::drop();
Preferences::drop();
} }
// Call this function to exit qBittorrent headless loader // Call this function to exit qBittorrent headless loader

View file

@ -31,12 +31,17 @@
#include "iconprovider.h" #include "iconprovider.h"
#include "preferences.h" #include "preferences.h"
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
#include <QDir>
#include <QFile>
#endif
IconProvider* IconProvider::m_instance = 0; IconProvider* IconProvider::m_instance = 0;
IconProvider::IconProvider() IconProvider::IconProvider()
{ {
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
m_useSystemTheme = Preferences().useSystemIconTheme(); m_useSystemTheme = Preferences::instance()->useSystemIconTheme();
#endif #endif
} }

View file

@ -32,6 +32,7 @@
#include <QTranslator> #include <QTranslator>
#include <QFile> #include <QFile>
#include <QLibraryInfo> #include <QLibraryInfo>
#include <QDebug>
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
#if defined(QBT_STATIC_QT) #if defined(QBT_STATIC_QT)
@ -62,7 +63,6 @@ Q_IMPORT_PLUGIN(qico)
#endif #endif
#include "preferences.h" #include "preferences.h"
#include "qinisettings.h"
#if defined(Q_OS_UNIX) #if defined(Q_OS_UNIX)
#include <signal.h> #include <signal.h>
#include <execinfo.h> #include <execinfo.h>
@ -96,7 +96,7 @@ public:
std::cout << '\t' << prg_name << " -d | --daemon: " << qPrintable(tr("run in daemon-mode (background)")) << std::endl; std::cout << '\t' << prg_name << " -d | --daemon: " << qPrintable(tr("run in daemon-mode (background)")) << std::endl;
#endif #endif
std::cout << '\t' << prg_name << " --help: " << qPrintable(tr("displays this help message")) << std::endl; std::cout << '\t' << prg_name << " --help: " << qPrintable(tr("displays this help message")) << std::endl;
std::cout << '\t' << prg_name << " --webui-port=x: " << qPrintable(tr("changes the webui port (current: %1)").arg(QString::number(Preferences().getWebUiPort()))) << std::endl; std::cout << '\t' << prg_name << " --webui-port=x: " << qPrintable(tr("changes the webui port (current: %1)").arg(QString::number(Preferences::instance()->getWebUiPort()))) << std::endl;
std::cout << '\t' << prg_name << " " << qPrintable(tr("[files or urls]: downloads the torrents passed by the user (optional)")) << std::endl; std::cout << '\t' << prg_name << " " << qPrintable(tr("[files or urls]: downloads the torrents passed by the user (optional)")) << std::endl;
} }
}; };
@ -106,8 +106,8 @@ class LegalNotice: public QObject {
public: public:
static bool userAgreesWithNotice() { static bool userAgreesWithNotice() {
QIniSettings settings; Preferences* const pref = Preferences::instance();
if (settings.value(QString::fromUtf8("LegalNotice/Accepted"), false).toBool()) // Already accepted once if (pref->getAcceptedLegal()) // Already accepted once
return true; return true;
#ifdef DISABLE_GUI #ifdef DISABLE_GUI
std::cout << std::endl << "*** " << qPrintable(tr("Legal Notice")) << " ***" << std::endl; std::cout << std::endl << "*** " << qPrintable(tr("Legal Notice")) << " ***" << std::endl;
@ -116,7 +116,7 @@ public:
char ret = getchar(); // Read pressed key char ret = getchar(); // Read pressed key
if (ret == 'y' || ret == 'Y') { if (ret == 'y' || ret == 'Y') {
// Save the answer // Save the answer
settings.setValue(QString::fromUtf8("LegalNotice/Accepted"), true); pref->setAcceptedLegal(true);
return true; return true;
} }
return false; return false;
@ -131,7 +131,7 @@ public:
msgBox.exec(); msgBox.exec();
if (msgBox.clickedButton() == agree_button) { if (msgBox.clickedButton() == agree_button) {
// Save the answer // Save the answer
settings.setValue(QString::fromUtf8("LegalNotice/Accepted"), true); pref->setAcceptedLegal(true);
return true; return true;
} }
return false; return false;
@ -249,7 +249,7 @@ int main(int argc, char *argv[]) {
} }
srand(time(0)); srand(time(0));
Preferences pref; Preferences* const pref = Preferences::instance();
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
bool no_splash = false; bool no_splash = false;
#else #else
@ -260,12 +260,12 @@ int main(int argc, char *argv[]) {
#endif #endif
// Load translation // Load translation
QString locale = pref.getLocale(); QString locale = pref->getLocale();
QTranslator qtTranslator; QTranslator qtTranslator;
QTranslator translator; QTranslator translator;
if (locale.isEmpty()) { if (locale.isEmpty()) {
locale = QLocale::system().name(); locale = QLocale::system().name();
pref.setLocale(locale); pref->setLocale(locale);
} }
if (qtTranslator.load( if (qtTranslator.load(
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
@ -317,7 +317,7 @@ int main(int argc, char *argv[]) {
bool ok = false; bool ok = false;
int new_port = parts.last().toInt(&ok); int new_port = parts.last().toInt(&ok);
if (ok && new_port > 0 && new_port <= 65535) { if (ok && new_port > 0 && new_port <= 65535) {
Preferences().setWebUiPort(new_port); Preferences::instance()->setWebUiPort(new_port);
} }
} }
} }
@ -328,7 +328,7 @@ int main(int argc, char *argv[]) {
} }
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
if (pref.isSlashScreenDisabled()) { if (pref->isSlashScreenDisabled()) {
no_splash = true; no_splash = true;
} }
QSplashScreen *splash = 0; QSplashScreen *splash = 0;

View file

@ -45,6 +45,7 @@
#include <QShortcut> #include <QShortcut>
#include <QScrollBar> #include <QScrollBar>
#include <QMimeData> #include <QMimeData>
#include <QCryptographicHash>
#include "mainwindow.h" #include "mainwindow.h"
#include "transferlistwidget.h" #include "transferlistwidget.h"
@ -67,9 +68,7 @@
#include "propertieswidget.h" #include "propertieswidget.h"
#include "statusbar.h" #include "statusbar.h"
#include "hidabletabwidget.h" #include "hidabletabwidget.h"
#include "qinisettings.h"
#include "torrentimportdlg.h" #include "torrentimportdlg.h"
#include "rsssettings.h"
#include "torrentmodel.h" #include "torrentmodel.h"
#include "executionlog.h" #include "executionlog.h"
#include "iconprovider.h" #include "iconprovider.h"
@ -102,15 +101,15 @@ using namespace libtorrent;
MainWindow::MainWindow(QWidget *parent, const QStringList& torrentCmdLine) : QMainWindow(parent), m_posInitialized(false), force_exit(false) { MainWindow::MainWindow(QWidget *parent, const QStringList& torrentCmdLine) : QMainWindow(parent), m_posInitialized(false), force_exit(false) {
setupUi(this); setupUi(this);
Preferences pref; Preferences* const pref = Preferences::instance();
ui_locked = pref.isUILocked(); ui_locked = pref->isUILocked();
setWindowTitle(QString("qBittorrent %1").arg(QString::fromUtf8(VERSION))); setWindowTitle(QString("qBittorrent %1").arg(QString::fromUtf8(VERSION)));
displaySpeedInTitle = pref.speedInTitleBar(); displaySpeedInTitle = pref->speedInTitleBar();
// Clean exit on log out // Clean exit on log out
connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(shutdownCleanUp()), Qt::DirectConnection); connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(shutdownCleanUp()), Qt::DirectConnection);
// Setting icons // Setting icons
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
if (Preferences().useSystemIconTheme()) if (Preferences::instance()->useSystemIconTheme())
setWindowIcon(QIcon::fromTheme("qbittorrent", QIcon(QString::fromUtf8(":/Icons/skin/qbittorrent32.png")))); setWindowIcon(QIcon::fromTheme("qbittorrent", QIcon(QString::fromUtf8(":/Icons/skin/qbittorrent32.png"))));
else else
#endif #endif
@ -245,11 +244,11 @@ MainWindow::MainWindow(QWidget *parent, const QStringList& torrentCmdLine) : QMa
#endif #endif
// View settings // View settings
actionTop_tool_bar->setChecked(pref.isToolbarDisplayed()); actionTop_tool_bar->setChecked(pref->isToolbarDisplayed());
actionSpeed_in_title_bar->setChecked(pref.speedInTitleBar()); actionSpeed_in_title_bar->setChecked(pref->speedInTitleBar());
actionRSS_Reader->setChecked(RssSettings().isRSSEnabled()); actionRSS_Reader->setChecked(pref->isRSSEnabled());
actionSearch_engine->setChecked(pref.isSearchEnabled()); actionSearch_engine->setChecked(pref->isSearchEnabled());
actionExecution_Logs->setChecked(pref.isExecutionLogEnabled()); actionExecution_Logs->setChecked(pref->isExecutionLogEnabled());
displaySearchTab(actionSearch_engine->isChecked()); displaySearchTab(actionSearch_engine->isChecked());
displayRSSTab(actionRSS_Reader->isChecked()); displayRSSTab(actionRSS_Reader->isChecked());
on_actionExecution_Logs_triggered(actionExecution_Logs->isChecked()); on_actionExecution_Logs_triggered(actionExecution_Logs->isChecked());
@ -263,15 +262,15 @@ MainWindow::MainWindow(QWidget *parent, const QStringList& torrentCmdLine) : QMa
autoShutdownGroup->addAction(actionAutoSuspend_system); autoShutdownGroup->addAction(actionAutoSuspend_system);
autoShutdownGroup->addAction(actionAutoHibernate_system); autoShutdownGroup->addAction(actionAutoHibernate_system);
#if (!defined(Q_OS_UNIX) || defined(Q_OS_MAC)) || defined(QT_DBUS_LIB) #if (!defined(Q_OS_UNIX) || defined(Q_OS_MAC)) || defined(QT_DBUS_LIB)
actionAutoShutdown_system->setChecked(pref.shutdownWhenDownloadsComplete()); actionAutoShutdown_system->setChecked(pref->shutdownWhenDownloadsComplete());
actionAutoSuspend_system->setChecked(pref.suspendWhenDownloadsComplete()); actionAutoSuspend_system->setChecked(pref->suspendWhenDownloadsComplete());
actionAutoHibernate_system->setChecked(pref.hibernateWhenDownloadsComplete()); actionAutoHibernate_system->setChecked(pref->hibernateWhenDownloadsComplete());
#else #else
actionAutoShutdown_system->setDisabled(true); actionAutoShutdown_system->setDisabled(true);
actionAutoSuspend_system->setDisabled(true); actionAutoSuspend_system->setDisabled(true);
actionAutoHibernate_system->setDisabled(true); actionAutoHibernate_system->setDisabled(true);
#endif #endif
actionAutoExit_qBittorrent->setChecked(pref.shutdownqBTWhenDownloadsComplete()); actionAutoExit_qBittorrent->setChecked(pref->shutdownqBTWhenDownloadsComplete());
if (!autoShutdownGroup->checkedAction()) if (!autoShutdownGroup->checkedAction())
actionAutoShutdown_Disabled->setChecked(true); actionAutoShutdown_Disabled->setChecked(true);
@ -280,7 +279,7 @@ MainWindow::MainWindow(QWidget *parent, const QStringList& torrentCmdLine) : QMa
readSettings(); readSettings();
if (systrayIcon) { if (systrayIcon) {
if (!(pref.startMinimized() || ui_locked)) { if (!(pref->startMinimized() || ui_locked)) {
show(); show();
activateWindow(); activateWindow();
raise(); raise();
@ -309,14 +308,14 @@ MainWindow::MainWindow(QWidget *parent, const QStringList& torrentCmdLine) : QMa
qDebug("GUI Built"); qDebug("GUI Built");
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
if (!pref.neverCheckFileAssoc() && (!Preferences::isTorrentFileAssocSet() || !Preferences::isMagnetLinkAssocSet())) { if (!pref->neverCheckFileAssoc() && (!Preferences::isTorrentFileAssocSet() || !Preferences::isMagnetLinkAssocSet())) {
if (QMessageBox::question(0, tr("Torrent file association"), if (QMessageBox::question(0, tr("Torrent file association"),
tr("qBittorrent is not the default application to open torrent files or Magnet links.\nDo you want to associate qBittorrent to torrent files and Magnet links?"), tr("qBittorrent is not the default application to open torrent files or Magnet links.\nDo you want to associate qBittorrent to torrent files and Magnet links?"),
QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) {
Preferences::setTorrentFileAssoc(true); Preferences::setTorrentFileAssoc(true);
Preferences::setMagnetLinkAssoc(true); Preferences::setMagnetLinkAssoc(true);
} else { } else {
pref.setNeverCheckFileAssoc(); pref->setNeverCheckFileAssoc();
} }
} }
#endif #endif
@ -326,7 +325,7 @@ MainWindow::MainWindow(QWidget *parent, const QStringList& torrentCmdLine) : QMa
// Make sure the Window is visible if we don't have a tray icon // Make sure the Window is visible if we don't have a tray icon
if (!systrayIcon) { if (!systrayIcon) {
if (pref.startMinimized()) { if (pref->startMinimized()) {
showMinimized(); showMinimized();
} else { } else {
show(); show();
@ -390,12 +389,12 @@ void MainWindow::shutdownCleanUp() {
delete switchTransferShortcut; delete switchTransferShortcut;
delete switchRSSShortcut; delete switchRSSShortcut;
IconProvider::drop(); IconProvider::drop();
Preferences().sync(); Preferences::drop();
qDebug("Finished GUI destruction"); qDebug("Finished GUI destruction");
} }
void MainWindow::defineUILockPassword() { void MainWindow::defineUILockPassword() {
QString old_pass_md5 = Preferences().getUILockPasswordMD5(); QString old_pass_md5 = Preferences::instance()->getUILockPasswordMD5();
if (old_pass_md5.isNull()) old_pass_md5 = ""; if (old_pass_md5.isNull()) old_pass_md5 = "";
bool ok = false; bool ok = false;
QString new_clear_password = AutoExpandableDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, old_pass_md5, &ok); QString new_clear_password = AutoExpandableDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, old_pass_md5, &ok);
@ -406,7 +405,7 @@ void MainWindow::defineUILockPassword() {
return; return;
} }
if (new_clear_password != old_pass_md5) { if (new_clear_password != old_pass_md5) {
Preferences().setUILockPassword(new_clear_password); Preferences::instance()->setUILockPassword(new_clear_password);
} }
QMessageBox::information(this, tr("Password update"), tr("The UI lock password has been successfully updated")); QMessageBox::information(this, tr("Password update"), tr("The UI lock password has been successfully updated"));
} }
@ -415,22 +414,22 @@ void MainWindow::defineUILockPassword() {
void MainWindow::clearUILockPassword() { void MainWindow::clearUILockPassword() {
QMessageBox::StandardButton answer = QMessageBox::question(this, tr("Clear the password"), tr("Are you sure you want to clear the password?"), QMessageBox::Yes|QMessageBox::No, QMessageBox::No); QMessageBox::StandardButton answer = QMessageBox::question(this, tr("Clear the password"), tr("Are you sure you want to clear the password?"), QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
if (answer == QMessageBox::Yes) if (answer == QMessageBox::Yes)
Preferences().clearUILockPassword(); Preferences::instance()->clearUILockPassword();
} }
void MainWindow::on_actionLock_qBittorrent_triggered() { void MainWindow::on_actionLock_qBittorrent_triggered() {
Preferences pref; Preferences* const pref = Preferences::instance();
// Check if there is a password // Check if there is a password
if (pref.getUILockPasswordMD5().isEmpty()) { if (pref->getUILockPasswordMD5().isEmpty()) {
// Ask for a password // Ask for a password
bool ok = false; bool ok = false;
QString clear_password = AutoExpandableDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok); QString clear_password = AutoExpandableDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok);
if (!ok) return; if (!ok) return;
pref.setUILockPassword(clear_password); pref->setUILockPassword(clear_password);
} }
// Lock the interface // Lock the interface
ui_locked = true; ui_locked = true;
pref.setUILocked(true); pref->setUILocked(true);
myTrayIconMenu->setEnabled(false); myTrayIconMenu->setEnabled(false);
hide(); hide();
} }
@ -496,30 +495,27 @@ void MainWindow::tab_changed(int new_tab) {
} }
void MainWindow::writeSettings() { void MainWindow::writeSettings() {
QIniSettings settings; Preferences* const pref = Preferences::instance();
settings.beginGroup(QString::fromUtf8("MainWindow")); pref->setMainGeometry(saveGeometry());
settings.setValue("geometry", saveGeometry());
// Splitter size // Splitter size
settings.setValue(QString::fromUtf8("vsplitterState"), vSplitter->saveState()); pref->setMainVSplitterState(vSplitter->saveState());
settings.endGroup();
properties->saveSettings(); properties->saveSettings();
} }
void MainWindow::readSettings() { void MainWindow::readSettings() {
QIniSettings settings; const Preferences* const pref = Preferences::instance();
settings.beginGroup(QString::fromUtf8("MainWindow")); const QByteArray mainGeo = pref->getMainGeometry();
if (settings.contains("geometry")) { if (!mainGeo.isEmpty()) {
if (restoreGeometry(settings.value("geometry").toByteArray())) if (restoreGeometry(mainGeo))
m_posInitialized = true; m_posInitialized = true;
} }
const QByteArray splitterState = settings.value("vsplitterState").toByteArray(); const QByteArray splitterState = pref->getMainVSplitterState();
if (splitterState.isEmpty()) { if (splitterState.isEmpty()) {
// Default sizes // Default sizes
vSplitter->setSizes(QList<int>() << 120 << vSplitter->width()-120); vSplitter->setSizes(QList<int>() << 120 << vSplitter->width()-120);
} else { } else {
vSplitter->restoreState(splitterState); vSplitter->restoreState(splitterState);
} }
settings.endGroup();
} }
void MainWindow::balloonClicked() { void MainWindow::balloonClicked() {
@ -595,8 +591,8 @@ void MainWindow::displayRSSTab() const {
// End of keyboard shortcuts slots // End of keyboard shortcuts slots
void MainWindow::askRecursiveTorrentDownloadConfirmation(const QTorrentHandle &h) { void MainWindow::askRecursiveTorrentDownloadConfirmation(const QTorrentHandle &h) {
Preferences pref; Preferences* const pref = Preferences::instance();
if (pref.recursiveDownloadDisabled()) return; if (pref->recursiveDownloadDisabled()) return;
// Get Torrent name // Get Torrent name
QString torrent_name; QString torrent_name;
try { try {
@ -615,7 +611,7 @@ void MainWindow::askRecursiveTorrentDownloadConfirmation(const QTorrentHandle &h
return; return;
} }
if (confirmBox.clickedButton() == never) { if (confirmBox.clickedButton() == never) {
pref.disableRecursiveDownload(); pref->disableRecursiveDownload();
} }
} }
@ -633,9 +629,9 @@ void MainWindow::on_actionSet_global_upload_limit_triggered() {
qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.); qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.);
QBtSession::instance()->setUploadRateLimit(new_limit); QBtSession::instance()->setUploadRateLimit(new_limit);
if (new_limit <= 0) if (new_limit <= 0)
Preferences().setGlobalUploadLimit(-1); Preferences::instance()->setGlobalUploadLimit(-1);
else else
Preferences().setGlobalUploadLimit(new_limit/1024.); Preferences::instance()->setGlobalUploadLimit(new_limit/1024.);
} }
} }
@ -648,9 +644,9 @@ void MainWindow::on_actionSet_global_download_limit_triggered() {
qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.); qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.);
QBtSession::instance()->setDownloadRateLimit(new_limit); QBtSession::instance()->setDownloadRateLimit(new_limit);
if (new_limit <= 0) if (new_limit <= 0)
Preferences().setGlobalDownloadLimit(-1); Preferences::instance()->setGlobalDownloadLimit(-1);
else else
Preferences().setGlobalDownloadLimit(new_limit/1024.); Preferences::instance()->setGlobalDownloadLimit(new_limit/1024.);
} }
} }
@ -684,14 +680,14 @@ bool MainWindow::unlockUI() {
bool ok = false; bool ok = false;
QString clear_password = AutoExpandableDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok); QString clear_password = AutoExpandableDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok);
if (!ok) return false; if (!ok) return false;
Preferences pref; Preferences* const pref = Preferences::instance();
QString real_pass_md5 = pref.getUILockPasswordMD5(); QString real_pass_md5 = pref->getUILockPasswordMD5();
QCryptographicHash md5(QCryptographicHash::Md5); QCryptographicHash md5(QCryptographicHash::Md5);
md5.addData(clear_password.toLocal8Bit()); md5.addData(clear_password.toLocal8Bit());
QString password_md5 = md5.result().toHex(); QString password_md5 = md5.result().toHex();
if (real_pass_md5 == password_md5) { if (real_pass_md5 == password_md5) {
ui_locked = false; ui_locked = false;
pref.setUILocked(false); pref->setUILocked(false);
myTrayIconMenu->setEnabled(true); myTrayIconMenu->setEnabled(true);
return true; return true;
} }
@ -763,14 +759,14 @@ void MainWindow::showEvent(QShowEvent *e) {
// Called when we close the program // Called when we close the program
void MainWindow::closeEvent(QCloseEvent *e) { void MainWindow::closeEvent(QCloseEvent *e) {
Preferences pref; Preferences* const pref = Preferences::instance();
const bool goToSystrayOnExit = pref.closeToTray(); const bool goToSystrayOnExit = pref->closeToTray();
if (!force_exit && systrayIcon && goToSystrayOnExit && !this->isHidden()) { if (!force_exit && systrayIcon && goToSystrayOnExit && !this->isHidden()) {
hide(); hide();
e->accept(); e->accept();
return; return;
} }
if (pref.confirmOnExit() && QBtSession::instance()->hasActiveTorrents()) { if (pref->confirmOnExit() && QBtSession::instance()->hasActiveTorrents()) {
if (e->spontaneous() || force_exit) { if (e->spontaneous() || force_exit) {
if (!isVisible()) if (!isVisible())
show(); show();
@ -790,7 +786,7 @@ void MainWindow::closeEvent(QCloseEvent *e) {
} }
if (confirmBox.clickedButton() == alwaysBtn) { if (confirmBox.clickedButton() == alwaysBtn) {
// Remember choice // Remember choice
Preferences().setConfirmOnExit(false); Preferences::instance()->setConfirmOnExit(false);
} }
} }
} }
@ -823,7 +819,7 @@ bool MainWindow::event(QEvent * e) {
//Now check to see if the window is minimised //Now check to see if the window is minimised
if (isMinimized()) { if (isMinimized()) {
qDebug("minimisation"); qDebug("minimisation");
if (systrayIcon && Preferences().minimizeToTray()) { if (systrayIcon && Preferences::instance()->minimizeToTray()) {
qDebug("Has active window: %d", (int)(qApp->activeWindow() != 0)); qDebug("Has active window: %d", (int)(qApp->activeWindow() != 0));
// Check if there is a modal window // Check if there is a modal window
bool has_modal_window = false; bool has_modal_window = false;
@ -851,7 +847,7 @@ bool MainWindow::event(QEvent * e) {
qDebug("MAC: new toolbar visibility is %d", !actionTop_tool_bar->isChecked()); qDebug("MAC: new toolbar visibility is %d", !actionTop_tool_bar->isChecked());
actionTop_tool_bar->toggle(); actionTop_tool_bar->toggle();
Preferences().setToolbarDisplayed(actionTop_tool_bar->isChecked()); Preferences::instance()->setToolbarDisplayed(actionTop_tool_bar->isChecked());
return ret; return ret;
} }
#endif #endif
@ -879,8 +875,8 @@ void MainWindow::dropEvent(QDropEvent *event) {
files = event->mimeData()->text().split(QString::fromUtf8("\n")); files = event->mimeData()->text().split(QString::fromUtf8("\n"));
} }
// Add file to download list // Add file to download list
Preferences pref; Preferences* const pref = Preferences::instance();
const bool useTorrentAdditionDialog = pref.useAdditionDialog(); const bool useTorrentAdditionDialog = pref->useAdditionDialog();
foreach (QString file, files) { foreach (QString file, files) {
qDebug("Dropped file %s on download list", qPrintable(file)); qDebug("Dropped file %s on download list", qPrintable(file));
if (misc::isUrl(file)) { if (misc::isUrl(file)) {
@ -926,17 +922,16 @@ void MainWindow::dragEnterEvent(QDragEnterEvent *event) {
// Display a dialog to allow user to add // Display a dialog to allow user to add
// torrents to download list // torrents to download list
void MainWindow::on_actionOpen_triggered() { void MainWindow::on_actionOpen_triggered() {
Preferences pref; Preferences* const pref = Preferences::instance();
QIniSettings settings;
// Open File Open Dialog // Open File Open Dialog
// Note: it is possible to select more than one file // Note: it is possible to select more than one file
const QStringList pathsList = QFileDialog::getOpenFileNames(0, const QStringList pathsList = QFileDialog::getOpenFileNames(0,
tr("Open Torrent Files"), settings.value(QString::fromUtf8("MainWindowLastDir"), QDir::homePath()).toString(), tr("Open Torrent Files"), pref->getMainLastDir(),
tr("Torrent Files")+QString::fromUtf8(" (*.torrent)")); tr("Torrent Files")+QString::fromUtf8(" (*.torrent)"));
if (!pathsList.empty()) { if (!pathsList.empty()) {
const uint listSize = pathsList.size(); const uint listSize = pathsList.size();
for (uint i=0; i<listSize; ++i) { for (uint i=0; i<listSize; ++i) {
if (pref.useAdditionDialog()) if (pref->useAdditionDialog())
AddNewTorrentDialog::showTorrent(pathsList.at(i)); AddNewTorrentDialog::showTorrent(pathsList.at(i));
else else
QBtSession::instance()->addTorrent(pathsList.at(i)); QBtSession::instance()->addTorrent(pathsList.at(i));
@ -944,7 +939,7 @@ void MainWindow::on_actionOpen_triggered() {
// Save last dir to remember it // Save last dir to remember it
QStringList top_dir = fsutils::fromNativePath(pathsList.at(0)).split("/"); QStringList top_dir = fsutils::fromNativePath(pathsList.at(0)).split("/");
top_dir.removeLast(); top_dir.removeLast();
settings.setValue(QString::fromUtf8("MainWindowLastDir"), fsutils::fromNativePath(top_dir.join("/"))); pref->setMainLastDir(fsutils::fromNativePath(top_dir.join("/")));
} }
} }
@ -957,8 +952,8 @@ void MainWindow::processParams(const QString& params_str) {
} }
void MainWindow::processParams(const QStringList& params) { void MainWindow::processParams(const QStringList& params) {
Preferences pref; Preferences* const pref = Preferences::instance();
const bool useTorrentAdditionDialog = pref.useAdditionDialog(); const bool useTorrentAdditionDialog = pref->useAdditionDialog();
foreach (QString param, params) { foreach (QString param, params) {
param = param.trimmed(); param = param.trimmed();
if (misc::isUrl(param)) { if (misc::isUrl(param)) {
@ -998,16 +993,16 @@ void MainWindow::addTorrent(QString path) {
} }
void MainWindow::processDownloadedFiles(QString path, QString url) { void MainWindow::processDownloadedFiles(QString path, QString url) {
Preferences pref; Preferences* const pref = Preferences::instance();
if (pref.useAdditionDialog()) if (pref->useAdditionDialog())
AddNewTorrentDialog::showTorrent(path, url); AddNewTorrentDialog::showTorrent(path, url);
else else
QBtSession::instance()->addTorrent(path, false, url); QBtSession::instance()->addTorrent(path, false, url);
} }
void MainWindow::processNewMagnetLink(const QString& link) { void MainWindow::processNewMagnetLink(const QString& link) {
Preferences pref; Preferences* const pref = Preferences::instance();
if (pref.useAdditionDialog()) if (pref->useAdditionDialog())
AddNewTorrentDialog::showMagnet(link); AddNewTorrentDialog::showMagnet(link);
else else
QBtSession::instance()->addMagnetUri(link); QBtSession::instance()->addMagnetUri(link);
@ -1020,8 +1015,8 @@ void MainWindow::optionsSaved() {
// Load program preferences // Load program preferences
void MainWindow::loadPreferences(bool configure_session) { void MainWindow::loadPreferences(bool configure_session) {
QBtSession::instance()->addConsoleMessage(tr("Options were saved successfully.")); QBtSession::instance()->addConsoleMessage(tr("Options were saved successfully."));
const Preferences pref; const Preferences* const pref = Preferences::instance();
const bool newSystrayIntegration = pref.systrayIntegration(); const bool newSystrayIntegration = pref->systrayIntegration();
actionLock_qBittorrent->setVisible(newSystrayIntegration); actionLock_qBittorrent->setVisible(newSystrayIntegration);
if (newSystrayIntegration != (systrayIcon!=0)) { if (newSystrayIntegration != (systrayIcon!=0)) {
if (newSystrayIntegration) { if (newSystrayIntegration) {
@ -1050,7 +1045,7 @@ void MainWindow::loadPreferences(bool configure_session) {
systrayIcon->setIcon(getSystrayIcon()); systrayIcon->setIcon(getSystrayIcon());
} }
// General // General
if (pref.isToolbarDisplayed()) { if (pref->isToolbarDisplayed()) {
toolBar->setVisible(true); toolBar->setVisible(true);
} else { } else {
// Clear search filter before hiding the top toolbar // Clear search filter before hiding the top toolbar
@ -1058,7 +1053,7 @@ void MainWindow::loadPreferences(bool configure_session) {
toolBar->setVisible(false); toolBar->setVisible(false);
} }
if (pref.preventFromSuspend()) if (pref->preventFromSuspend())
{ {
preventTimer->start(PREVENT_SUSPEND_INTERVAL); preventTimer->start(PREVENT_SUSPEND_INTERVAL);
} }
@ -1068,14 +1063,14 @@ void MainWindow::loadPreferences(bool configure_session) {
m_pwr->setActivityState(false); m_pwr->setActivityState(false);
} }
const uint new_refreshInterval = pref.getRefreshInterval(); const uint new_refreshInterval = pref->getRefreshInterval();
transferList->setRefreshInterval(new_refreshInterval); transferList->setRefreshInterval(new_refreshInterval);
transferList->setAlternatingRowColors(pref.useAlternatingRowColors()); transferList->setAlternatingRowColors(pref->useAlternatingRowColors());
properties->getFilesList()->setAlternatingRowColors(pref.useAlternatingRowColors()); properties->getFilesList()->setAlternatingRowColors(pref->useAlternatingRowColors());
properties->getTrackerList()->setAlternatingRowColors(pref.useAlternatingRowColors()); properties->getTrackerList()->setAlternatingRowColors(pref->useAlternatingRowColors());
properties->getPeerList()->setAlternatingRowColors(pref.useAlternatingRowColors()); properties->getPeerList()->setAlternatingRowColors(pref->useAlternatingRowColors());
// Queueing System // Queueing System
if (pref.isQueueingSystemEnabled()) { if (pref->isQueueingSystemEnabled()) {
if (!actionDecreasePriority->isVisible()) { if (!actionDecreasePriority->isVisible()) {
transferList->hidePriorityColumn(false); transferList->hidePriorityColumn(false);
actionDecreasePriority->setVisible(true); actionDecreasePriority->setVisible(true);
@ -1098,14 +1093,14 @@ void MainWindow::loadPreferences(bool configure_session) {
// Icon provider // Icon provider
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
IconProvider::instance()->useSystemIconTheme(pref.useSystemIconTheme()); IconProvider::instance()->useSystemIconTheme(pref->useSystemIconTheme());
#endif #endif
if (configure_session) if (configure_session)
QBtSession::instance()->configureSession(); QBtSession::instance()->configureSession();
#if defined(Q_OS_WIN) || defined(Q_OS_MAC) #if defined(Q_OS_WIN) || defined(Q_OS_MAC)
if (pref.isUpdateCheckEnabled()) if (pref->isUpdateCheckEnabled())
checkProgramUpdate(); checkProgramUpdate();
else else
programUpdateTimer.stop(); programUpdateTimer.stop();
@ -1157,7 +1152,7 @@ void MainWindow::updateGUI() {
} }
void MainWindow::showNotificationBaloon(QString title, QString msg) const { void MainWindow::showNotificationBaloon(QString title, QString msg) const {
if (!Preferences().useProgramNotification()) return; if (!Preferences::instance()->useProgramNotification()) return;
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) && defined(QT_DBUS_LIB) #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) && defined(QT_DBUS_LIB)
org::freedesktop::Notifications notifications("org.freedesktop.Notifications", org::freedesktop::Notifications notifications("org.freedesktop.Notifications",
"/org/freedesktop/Notifications", "/org/freedesktop/Notifications",
@ -1190,8 +1185,8 @@ void MainWindow::showNotificationBaloon(QString title, QString msg) const {
*****************************************************/ *****************************************************/
void MainWindow::downloadFromURLList(const QStringList& url_list) { void MainWindow::downloadFromURLList(const QStringList& url_list) {
Preferences pref; Preferences* const pref = Preferences::instance();
const bool useTorrentAdditionDialog = pref.useAdditionDialog(); const bool useTorrentAdditionDialog = pref->useAdditionDialog();
foreach (QString url, url_list) { foreach (QString url, url_list) {
if (url.startsWith("bc://bt/", Qt::CaseInsensitive)) { if (url.startsWith("bc://bt/", Qt::CaseInsensitive)) {
qDebug("Converting bc link to magnet link"); qDebug("Converting bc link to magnet link");
@ -1238,7 +1233,7 @@ void MainWindow::createSystrayDelayed() {
delete systrayCreator; delete systrayCreator;
// Disable it in program preferences to // Disable it in program preferences to
// avoid trying at earch startup // avoid trying at earch startup
Preferences().setSystrayIntegration(false); Preferences::instance()->setSystrayIntegration(false);
} }
} }
} }
@ -1263,7 +1258,7 @@ QMenu* MainWindow::getTrayIconMenu() {
myTrayIconMenu->addAction(actionOpen); myTrayIconMenu->addAction(actionOpen);
//myTrayIconMenu->addAction(actionDownload_from_URL); //myTrayIconMenu->addAction(actionDownload_from_URL);
myTrayIconMenu->addSeparator(); myTrayIconMenu->addSeparator();
const bool isAltBWEnabled = Preferences().isAltBandwidthEnabled(); const bool isAltBWEnabled = Preferences::instance()->isAltBandwidthEnabled();
updateAltSpeedsBtn(isAltBWEnabled); updateAltSpeedsBtn(isAltBWEnabled);
actionUse_alternative_speed_limits->setChecked(isAltBWEnabled); actionUse_alternative_speed_limits->setChecked(isAltBWEnabled);
myTrayIconMenu->addAction(actionUse_alternative_speed_limits); myTrayIconMenu->addAction(actionUse_alternative_speed_limits);
@ -1304,12 +1299,12 @@ void MainWindow::on_actionOptions_triggered() {
void MainWindow::on_actionTop_tool_bar_triggered() { void MainWindow::on_actionTop_tool_bar_triggered() {
bool is_visible = static_cast<QAction*>(sender())->isChecked(); bool is_visible = static_cast<QAction*>(sender())->isChecked();
toolBar->setVisible(is_visible); toolBar->setVisible(is_visible);
Preferences().setToolbarDisplayed(is_visible); Preferences::instance()->setToolbarDisplayed(is_visible);
} }
void MainWindow::on_actionSpeed_in_title_bar_triggered() { void MainWindow::on_actionSpeed_in_title_bar_triggered() {
displaySpeedInTitle = static_cast<QAction*>(sender())->isChecked(); displaySpeedInTitle = static_cast<QAction*>(sender())->isChecked();
Preferences().showSpeedInTitleBar(displaySpeedInTitle); Preferences::instance()->showSpeedInTitleBar(displaySpeedInTitle);
if (displaySpeedInTitle) if (displaySpeedInTitle)
updateGUI(); updateGUI();
else else
@ -1317,12 +1312,12 @@ void MainWindow::on_actionSpeed_in_title_bar_triggered() {
} }
void MainWindow::on_actionRSS_Reader_triggered() { void MainWindow::on_actionRSS_Reader_triggered() {
RssSettings().setRSSEnabled(actionRSS_Reader->isChecked()); Preferences::instance()->setRSSEnabled(actionRSS_Reader->isChecked());
displayRSSTab(actionRSS_Reader->isChecked()); displayRSSTab(actionRSS_Reader->isChecked());
} }
void MainWindow::on_actionSearch_engine_triggered() { void MainWindow::on_actionSearch_engine_triggered() {
Preferences().setSearchEnabled(actionSearch_engine->isChecked()); Preferences::instance()->setSearchEnabled(actionSearch_engine->isChecked());
displaySearchTab(actionSearch_engine->isChecked()); displaySearchTab(actionSearch_engine->isChecked());
} }
@ -1370,7 +1365,7 @@ void MainWindow::handleUpdateCheckFinished(bool update_available, QString new_ve
actionCheck_for_updates->setText(tr("Check for updates")); actionCheck_for_updates->setText(tr("Check for updates"));
actionCheck_for_updates->setToolTip(tr("Check for program updates")); actionCheck_for_updates->setToolTip(tr("Check for program updates"));
// Don't bother the user again in this session if he chose to ignore the update // Don't bother the user again in this session if he chose to ignore the update
if (Preferences().isUpdateCheckEnabled() && answer == QMessageBox::Yes) if (Preferences::instance()->isUpdateCheckEnabled() && answer == QMessageBox::Yes)
programUpdateTimer.start(); programUpdateTimer.start();
} }
#endif #endif
@ -1402,30 +1397,30 @@ void MainWindow::on_actionExecution_Logs_triggered(bool checked)
if (m_executionLog) if (m_executionLog)
delete m_executionLog; delete m_executionLog;
} }
Preferences().setExecutionLogEnabled(checked); Preferences::instance()->setExecutionLogEnabled(checked);
} }
void MainWindow::on_actionAutoExit_qBittorrent_toggled(bool enabled) void MainWindow::on_actionAutoExit_qBittorrent_toggled(bool enabled)
{ {
qDebug() << Q_FUNC_INFO << enabled; qDebug() << Q_FUNC_INFO << enabled;
Preferences().setShutdownqBTWhenDownloadsComplete(enabled); Preferences::instance()->setShutdownqBTWhenDownloadsComplete(enabled);
} }
void MainWindow::on_actionAutoSuspend_system_toggled(bool enabled) void MainWindow::on_actionAutoSuspend_system_toggled(bool enabled)
{ {
qDebug() << Q_FUNC_INFO << enabled; qDebug() << Q_FUNC_INFO << enabled;
Preferences().setSuspendWhenDownloadsComplete(enabled); Preferences::instance()->setSuspendWhenDownloadsComplete(enabled);
} }
void MainWindow::on_actionAutoHibernate_system_toggled(bool enabled) { void MainWindow::on_actionAutoHibernate_system_toggled(bool enabled) {
qDebug() << Q_FUNC_INFO << enabled; qDebug() << Q_FUNC_INFO << enabled;
Preferences().setHibernateWhenDownloadsComplete(enabled); Preferences::instance()->setHibernateWhenDownloadsComplete(enabled);
} }
void MainWindow::on_actionAutoShutdown_system_toggled(bool enabled) void MainWindow::on_actionAutoShutdown_system_toggled(bool enabled)
{ {
qDebug() << Q_FUNC_INFO << enabled; qDebug() << Q_FUNC_INFO << enabled;
Preferences().setShutdownWhenDownloadsComplete(enabled); Preferences::instance()->setShutdownWhenDownloadsComplete(enabled);
} }
void MainWindow::checkForActiveTorrents() void MainWindow::checkForActiveTorrents()
@ -1436,7 +1431,7 @@ void MainWindow::checkForActiveTorrents()
QIcon MainWindow::getSystrayIcon() const QIcon MainWindow::getSystrayIcon() const
{ {
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
TrayIcon::Style style = Preferences().trayIconStyle(); TrayIcon::Style style = Preferences::instance()->trayIconStyle();
switch(style) { switch(style) {
case TrayIcon::MONO_DARK: case TrayIcon::MONO_DARK:
return QIcon(":/Icons/skin/qbittorrent_mono_dark.png"); return QIcon(":/Icons/skin/qbittorrent_mono_dark.png");
@ -1448,7 +1443,7 @@ QIcon MainWindow::getSystrayIcon() const
#endif #endif
QIcon icon; QIcon icon;
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
if (Preferences().useSystemIconTheme()) { if (Preferences::instance()->useSystemIconTheme()) {
icon = QIcon::fromTheme("qbittorrent"); icon = QIcon::fromTheme("qbittorrent");
} }
#endif #endif

View file

@ -67,57 +67,57 @@ public:
public slots: public slots:
void saveAdvancedSettings() { void saveAdvancedSettings() {
Preferences pref; Preferences* const pref = Preferences::instance();
// Disk write cache // Disk write cache
pref.setDiskCacheSize(spin_cache.value()); pref->setDiskCacheSize(spin_cache.value());
pref.setDiskCacheTTL(spin_cache_ttl.value()); pref->setDiskCacheTTL(spin_cache_ttl.value());
// Outgoing ports // Outgoing ports
pref.setOutgoingPortsMin(outgoing_ports_min.value()); pref->setOutgoingPortsMin(outgoing_ports_min.value());
pref.setOutgoingPortsMax(outgoing_ports_max.value()); pref->setOutgoingPortsMax(outgoing_ports_max.value());
// Ignore limits on LAN // Ignore limits on LAN
pref.ignoreLimitsOnLAN(cb_ignore_limits_lan.isChecked()); pref->ignoreLimitsOnLAN(cb_ignore_limits_lan.isChecked());
// Recheck torrents on completion // Recheck torrents on completion
pref.recheckTorrentsOnCompletion(cb_recheck_completed.isChecked()); pref->recheckTorrentsOnCompletion(cb_recheck_completed.isChecked());
// Transfer list refresh interval // Transfer list refresh interval
pref.setRefreshInterval(spin_list_refresh.value()); pref->setRefreshInterval(spin_list_refresh.value());
// Peer resolution // Peer resolution
pref.resolvePeerCountries(cb_resolve_countries.isChecked()); pref->resolvePeerCountries(cb_resolve_countries.isChecked());
pref.resolvePeerHostNames(cb_resolve_hosts.isChecked()); pref->resolvePeerHostNames(cb_resolve_hosts.isChecked());
// Max Half-Open connections // Max Half-Open connections
pref.setMaxHalfOpenConnections(spin_maxhalfopen.value()); pref->setMaxHalfOpenConnections(spin_maxhalfopen.value());
// Super seeding // Super seeding
pref.enableSuperSeeding(cb_super_seeding.isChecked()); pref->enableSuperSeeding(cb_super_seeding.isChecked());
// Network interface // Network interface
if (combo_iface.currentIndex() == 0) { if (combo_iface.currentIndex() == 0) {
// All interfaces (default) // All interfaces (default)
pref.setNetworkInterface(QString::null); pref->setNetworkInterface(QString::null);
pref.setNetworkInterfaceName(QString::null); pref->setNetworkInterfaceName(QString::null);
} else { } else {
pref.setNetworkInterface(combo_iface.itemData(combo_iface.currentIndex()).toString()); pref->setNetworkInterface(combo_iface.itemData(combo_iface.currentIndex()).toString());
pref.setNetworkInterfaceName(combo_iface.currentText()); pref->setNetworkInterfaceName(combo_iface.currentText());
} }
// Network address // Network address
QHostAddress addr(txt_network_address.text().trimmed()); QHostAddress addr(txt_network_address.text().trimmed());
if (addr.isNull()) if (addr.isNull())
pref.setNetworkAddress(""); pref->setNetworkAddress("");
else else
pref.setNetworkAddress(addr.toString()); pref->setNetworkAddress(addr.toString());
// Program notification // Program notification
pref.useProgramNotification(cb_program_notifications.isChecked()); pref->useProgramNotification(cb_program_notifications.isChecked());
// Tracker // Tracker
pref.setTrackerEnabled(cb_tracker_status.isChecked()); pref->setTrackerEnabled(cb_tracker_status.isChecked());
pref.setTrackerPort(spin_tracker_port.value()); pref->setTrackerPort(spin_tracker_port.value());
#if defined(Q_OS_WIN) || defined(Q_OS_MAC) #if defined(Q_OS_WIN) || defined(Q_OS_MAC)
pref.setUpdateCheckEnabled(cb_update_check.isChecked()); pref->setUpdateCheckEnabled(cb_update_check.isChecked());
#endif #endif
// Icon theme // Icon theme
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
pref.useSystemIconTheme(cb_use_icon_theme.isChecked()); pref->useSystemIconTheme(cb_use_icon_theme.isChecked());
#endif #endif
pref.setConfirmTorrentDeletion(cb_confirm_torrent_deletion.isChecked()); pref->setConfirmTorrentDeletion(cb_confirm_torrent_deletion.isChecked());
// Tracker exchange // Tracker exchange
pref.setTrackerExchangeEnabled(cb_enable_tracker_ext.isChecked()); pref->setTrackerExchangeEnabled(cb_enable_tracker_ext.isChecked());
pref.setAnnounceToAllTrackers(cb_announce_all_trackers.isChecked()); pref->setAnnounceToAllTrackers(cb_announce_all_trackers.isChecked());
} }
signals: signals:
@ -167,58 +167,58 @@ private slots:
void loadAdvancedSettings() void loadAdvancedSettings()
{ {
const Preferences pref; const Preferences* const pref = Preferences::instance();
// Disk write cache // Disk write cache
spin_cache.setMinimum(0); spin_cache.setMinimum(0);
spin_cache.setMaximum(2048); spin_cache.setMaximum(2048);
spin_cache.setValue(pref.diskCacheSize()); spin_cache.setValue(pref->diskCacheSize());
updateCacheSpinSuffix(spin_cache.value()); updateCacheSpinSuffix(spin_cache.value());
setRow(DISK_CACHE, tr("Disk write cache size"), &spin_cache); setRow(DISK_CACHE, tr("Disk write cache size"), &spin_cache);
// Disk cache expiry // Disk cache expiry
spin_cache_ttl.setMinimum(15); spin_cache_ttl.setMinimum(15);
spin_cache_ttl.setMaximum(600); spin_cache_ttl.setMaximum(600);
spin_cache_ttl.setValue(pref.diskCacheTTL()); spin_cache_ttl.setValue(pref->diskCacheTTL());
spin_cache_ttl.setSuffix(tr(" s", " seconds")); spin_cache_ttl.setSuffix(tr(" s", " seconds"));
setRow(DISK_CACHE_TTL, tr("Disk cache expiry interval"), &spin_cache_ttl); setRow(DISK_CACHE_TTL, tr("Disk cache expiry interval"), &spin_cache_ttl);
// Outgoing port Min // Outgoing port Min
outgoing_ports_min.setMinimum(0); outgoing_ports_min.setMinimum(0);
outgoing_ports_min.setMaximum(65535); outgoing_ports_min.setMaximum(65535);
outgoing_ports_min.setValue(pref.outgoingPortsMin()); outgoing_ports_min.setValue(pref->outgoingPortsMin());
setRow(OUTGOING_PORT_MIN, tr("Outgoing ports (Min) [0: Disabled]"), &outgoing_ports_min); setRow(OUTGOING_PORT_MIN, tr("Outgoing ports (Min) [0: Disabled]"), &outgoing_ports_min);
// Outgoing port Min // Outgoing port Min
outgoing_ports_max.setMinimum(0); outgoing_ports_max.setMinimum(0);
outgoing_ports_max.setMaximum(65535); outgoing_ports_max.setMaximum(65535);
outgoing_ports_max.setValue(pref.outgoingPortsMax()); outgoing_ports_max.setValue(pref->outgoingPortsMax());
setRow(OUTGOING_PORT_MAX, tr("Outgoing ports (Max) [0: Disabled]"), &outgoing_ports_max); setRow(OUTGOING_PORT_MAX, tr("Outgoing ports (Max) [0: Disabled]"), &outgoing_ports_max);
// Ignore transfer limits on local network // Ignore transfer limits on local network
cb_ignore_limits_lan.setChecked(pref.ignoreLimitsOnLAN()); cb_ignore_limits_lan.setChecked(pref->ignoreLimitsOnLAN());
setRow(IGNORE_LIMIT_LAN, tr("Ignore transfer limits on local network"), &cb_ignore_limits_lan); setRow(IGNORE_LIMIT_LAN, tr("Ignore transfer limits on local network"), &cb_ignore_limits_lan);
// Recheck completed torrents // Recheck completed torrents
cb_recheck_completed.setChecked(pref.recheckTorrentsOnCompletion()); cb_recheck_completed.setChecked(pref->recheckTorrentsOnCompletion());
setRow(RECHECK_COMPLETED, tr("Recheck torrents on completion"), &cb_recheck_completed); setRow(RECHECK_COMPLETED, tr("Recheck torrents on completion"), &cb_recheck_completed);
// Transfer list refresh interval // Transfer list refresh interval
spin_list_refresh.setMinimum(30); spin_list_refresh.setMinimum(30);
spin_list_refresh.setMaximum(99999); spin_list_refresh.setMaximum(99999);
spin_list_refresh.setValue(pref.getRefreshInterval()); spin_list_refresh.setValue(pref->getRefreshInterval());
spin_list_refresh.setSuffix(tr(" ms", " milliseconds")); spin_list_refresh.setSuffix(tr(" ms", " milliseconds"));
setRow(LIST_REFRESH, tr("Transfer list refresh interval"), &spin_list_refresh); setRow(LIST_REFRESH, tr("Transfer list refresh interval"), &spin_list_refresh);
// Resolve Peer countries // Resolve Peer countries
cb_resolve_countries.setChecked(pref.resolvePeerCountries()); cb_resolve_countries.setChecked(pref->resolvePeerCountries());
setRow(RESOLVE_COUNTRIES, tr("Resolve peer countries (GeoIP)"), &cb_resolve_countries); setRow(RESOLVE_COUNTRIES, tr("Resolve peer countries (GeoIP)"), &cb_resolve_countries);
// Resolve peer hosts // Resolve peer hosts
cb_resolve_hosts.setChecked(pref.resolvePeerHostNames()); cb_resolve_hosts.setChecked(pref->resolvePeerHostNames());
setRow(RESOLVE_HOSTS, tr("Resolve peer host names"), &cb_resolve_hosts); setRow(RESOLVE_HOSTS, tr("Resolve peer host names"), &cb_resolve_hosts);
// Max Half Open connections // Max Half Open connections
spin_maxhalfopen.setMinimum(0); spin_maxhalfopen.setMinimum(0);
spin_maxhalfopen.setMaximum(99999); spin_maxhalfopen.setMaximum(99999);
spin_maxhalfopen.setValue(pref.getMaxHalfOpenConnections()); spin_maxhalfopen.setValue(pref->getMaxHalfOpenConnections());
setRow(MAX_HALF_OPEN, tr("Maximum number of half-open connections [0: Disabled]"), &spin_maxhalfopen); setRow(MAX_HALF_OPEN, tr("Maximum number of half-open connections [0: Disabled]"), &spin_maxhalfopen);
// Super seeding // Super seeding
cb_super_seeding.setChecked(pref.isSuperSeedingEnabled()); cb_super_seeding.setChecked(pref->isSuperSeedingEnabled());
setRow(SUPER_SEEDING, tr("Strict super seeding"), &cb_super_seeding); setRow(SUPER_SEEDING, tr("Strict super seeding"), &cb_super_seeding);
// Network interface // Network interface
combo_iface.addItem(tr("Any interface", "i.e. Any network interface")); combo_iface.addItem(tr("Any interface", "i.e. Any network interface"));
const QString current_iface = pref.getNetworkInterface(); const QString current_iface = pref->getNetworkInterface();
bool interface_exists = current_iface.isEmpty(); bool interface_exists = current_iface.isEmpty();
int i = 1; int i = 1;
foreach (const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) { foreach (const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) {
@ -232,40 +232,40 @@ private slots:
} }
// Saved interface does not exist, show it anyway // Saved interface does not exist, show it anyway
if (!interface_exists) { if (!interface_exists) {
combo_iface.addItem(pref.getNetworkInterfaceName(),current_iface); combo_iface.addItem(pref->getNetworkInterfaceName(),current_iface);
combo_iface.setCurrentIndex(i); combo_iface.setCurrentIndex(i);
} }
setRow(NETWORK_IFACE, tr("Network Interface (requires restart)"), &combo_iface); setRow(NETWORK_IFACE, tr("Network Interface (requires restart)"), &combo_iface);
// Network address // Network address
txt_network_address.setText(pref.getNetworkAddress()); txt_network_address.setText(pref->getNetworkAddress());
setRow(NETWORK_ADDRESS, tr("IP Address to report to trackers (requires restart)"), &txt_network_address); setRow(NETWORK_ADDRESS, tr("IP Address to report to trackers (requires restart)"), &txt_network_address);
// Program notifications // Program notifications
cb_program_notifications.setChecked(pref.useProgramNotification()); cb_program_notifications.setChecked(pref->useProgramNotification());
setRow(PROGRAM_NOTIFICATIONS, tr("Display program on-screen notifications"), &cb_program_notifications); setRow(PROGRAM_NOTIFICATIONS, tr("Display program on-screen notifications"), &cb_program_notifications);
// Tracker State // Tracker State
cb_tracker_status.setChecked(pref.isTrackerEnabled()); cb_tracker_status.setChecked(pref->isTrackerEnabled());
setRow(TRACKER_STATUS, tr("Enable embedded tracker"), &cb_tracker_status); setRow(TRACKER_STATUS, tr("Enable embedded tracker"), &cb_tracker_status);
// Tracker port // Tracker port
spin_tracker_port.setMinimum(1); spin_tracker_port.setMinimum(1);
spin_tracker_port.setMaximum(65535); spin_tracker_port.setMaximum(65535);
spin_tracker_port.setValue(pref.getTrackerPort()); spin_tracker_port.setValue(pref->getTrackerPort());
setRow(TRACKER_PORT, tr("Embedded tracker port"), &spin_tracker_port); setRow(TRACKER_PORT, tr("Embedded tracker port"), &spin_tracker_port);
#if defined(Q_OS_WIN) || defined(Q_OS_MAC) #if defined(Q_OS_WIN) || defined(Q_OS_MAC)
cb_update_check.setChecked(pref.isUpdateCheckEnabled()); cb_update_check.setChecked(pref->isUpdateCheckEnabled());
setRow(UPDATE_CHECK, tr("Check for software updates"), &cb_update_check); setRow(UPDATE_CHECK, tr("Check for software updates"), &cb_update_check);
#endif #endif
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
cb_use_icon_theme.setChecked(pref.useSystemIconTheme()); cb_use_icon_theme.setChecked(pref->useSystemIconTheme());
setRow(USE_ICON_THEME, tr("Use system icon theme"), &cb_use_icon_theme); setRow(USE_ICON_THEME, tr("Use system icon theme"), &cb_use_icon_theme);
#endif #endif
// Torrent deletion confirmation // Torrent deletion confirmation
cb_confirm_torrent_deletion.setChecked(pref.confirmTorrentDeletion()); cb_confirm_torrent_deletion.setChecked(pref->confirmTorrentDeletion());
setRow(CONFIRM_DELETE_TORRENT, tr("Confirm torrent deletion"), &cb_confirm_torrent_deletion); setRow(CONFIRM_DELETE_TORRENT, tr("Confirm torrent deletion"), &cb_confirm_torrent_deletion);
// Tracker exchange // Tracker exchange
cb_enable_tracker_ext.setChecked(pref.trackerExchangeEnabled()); cb_enable_tracker_ext.setChecked(pref->trackerExchangeEnabled());
setRow(TRACKER_EXCHANGE, tr("Exchange trackers with other peers"), &cb_enable_tracker_ext); setRow(TRACKER_EXCHANGE, tr("Exchange trackers with other peers"), &cb_enable_tracker_ext);
// Announce to all trackers // Announce to all trackers
cb_announce_all_trackers.setChecked(pref.announceToAllTrackers()); cb_announce_all_trackers.setChecked(pref->announceToAllTrackers());
setRow(ANNOUNCE_ALL_TRACKERS, tr("Always announce to all trackers"), &cb_announce_all_trackers); setRow(ANNOUNCE_ALL_TRACKERS, tr("Always announce to all trackers"), &cb_announce_all_trackers);
} }

View file

@ -37,6 +37,7 @@
#include <QDesktopWidget> #include <QDesktopWidget>
#include <QTranslator> #include <QTranslator>
#include <QDesktopServices> #include <QDesktopServices>
#include <QDebug>
#include <libtorrent/version.hpp> #include <libtorrent/version.hpp>
@ -45,7 +46,6 @@
#include "fs_utils.h" #include "fs_utils.h"
#include "advancedsettings.h" #include "advancedsettings.h"
#include "scannedfoldersmodel.h" #include "scannedfoldersmodel.h"
#include "qinisettings.h"
#include "qbtsession.h" #include "qbtsession.h"
#include "iconprovider.h" #include "iconprovider.h"
#include "dnsupdater.h" #include "dnsupdater.h"
@ -289,14 +289,14 @@ void options_imp::changePage(QListWidgetItem *current, QListWidgetItem *previous
} }
void options_imp::loadWindowState() { void options_imp::loadWindowState() {
QIniSettings settings; const Preferences* const pref = Preferences::instance();
resize(settings.value(QString::fromUtf8("Preferences/State/size"), sizeFittingScreen()).toSize()); resize(pref->getPrefSize(sizeFittingScreen()));
QPoint p = settings.value(QString::fromUtf8("Preferences/State/pos"), QPoint()).toPoint(); QPoint p = pref->getPrefPos();
QRect scr_rect = qApp->desktop()->screenGeometry(); QRect scr_rect = qApp->desktop()->screenGeometry();
if (!p.isNull() && scr_rect.contains(p)) if (!p.isNull() && scr_rect.contains(p))
move(p); move(p);
// Load slider size // Load slider size
const QStringList sizes_str = settings.value("Preferences/State/hSplitterSizes", QStringList()).toStringList(); const QStringList sizes_str = pref->getPrefHSplitterSizes();
// Splitter size // Splitter size
QList<int> sizes; QList<int> sizes;
if (sizes_str.size() == 2) { if (sizes_str.size() == 2) {
@ -310,14 +310,14 @@ void options_imp::loadWindowState() {
} }
void options_imp::saveWindowState() const { void options_imp::saveWindowState() const {
QIniSettings settings; Preferences* const pref = Preferences::instance();
settings.setValue(QString::fromUtf8("Preferences/State/size"), size()); pref->setPrefSize(size());
settings.setValue(QString::fromUtf8("Preferences/State/pos"), pos()); pref->setPrefPos(pos());
// Splitter size // Splitter size
QStringList sizes_str; QStringList sizes_str;
sizes_str << QString::number(hsplitter->sizes().first()); sizes_str << QString::number(hsplitter->sizes().first());
sizes_str << QString::number(hsplitter->sizes().last()); sizes_str << QString::number(hsplitter->sizes().last());
settings.setValue(QString::fromUtf8("Preferences/State/hSplitterSizes"), sizes_str); pref->setPrefHSplitterSizes(sizes_str);
} }
QSize options_imp::sizeFittingScreen() const { QSize options_imp::sizeFittingScreen() const {
@ -341,10 +341,10 @@ QSize options_imp::sizeFittingScreen() const {
void options_imp::saveOptions() { void options_imp::saveOptions() {
applyButton->setEnabled(false); applyButton->setEnabled(false);
Preferences pref; Preferences* const pref = Preferences::instance();
// Load the translation // Load the translation
QString locale = getLocale(); QString locale = getLocale();
if (pref.getLocale() != locale) { if (pref->getLocale() != locale) {
QTranslator *translator = new QTranslator; QTranslator *translator = new QTranslator;
if (translator->load(QString::fromUtf8(":/lang/qbittorrent_") + locale)) { if (translator->load(QString::fromUtf8(":/lang/qbittorrent_") + locale)) {
qDebug("%s locale recognized, using translation.", qPrintable(locale)); qDebug("%s locale recognized, using translation.", qPrintable(locale));
@ -355,18 +355,18 @@ void options_imp::saveOptions() {
} }
// General preferences // General preferences
pref.setLocale(locale); pref->setLocale(locale);
pref.setAlternatingRowColors(checkAltRowColors->isChecked()); pref->setAlternatingRowColors(checkAltRowColors->isChecked());
pref.setSystrayIntegration(systrayIntegration()); pref->setSystrayIntegration(systrayIntegration());
pref.setTrayIconStyle(TrayIcon::Style(comboTrayIcon->currentIndex())); pref->setTrayIconStyle(TrayIcon::Style(comboTrayIcon->currentIndex()));
pref.setCloseToTray(closeToTray()); pref->setCloseToTray(closeToTray());
pref.setMinimizeToTray(minimizeToTray()); pref->setMinimizeToTray(minimizeToTray());
pref.setStartMinimized(startMinimized()); pref->setStartMinimized(startMinimized());
pref.setSplashScreenDisabled(isSlashScreenDisabled()); pref->setSplashScreenDisabled(isSlashScreenDisabled());
pref.setConfirmOnExit(checkProgramExitConfirm->isChecked()); pref->setConfirmOnExit(checkProgramExitConfirm->isChecked());
pref.setPreventFromSuspend(preventFromSuspend()); pref->setPreventFromSuspend(preventFromSuspend());
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
pref.setStartup(Startup()); pref->setWinStartup(WinStartup());
// Windows: file association settings // Windows: file association settings
Preferences::setTorrentFileAssoc(checkAssociateTorrents->isChecked()); Preferences::setTorrentFileAssoc(checkAssociateTorrents->isChecked());
Preferences::setMagnetLinkAssoc(checkAssociateMagnetLinks->isChecked()); Preferences::setMagnetLinkAssoc(checkAssociateMagnetLinks->isChecked());
@ -374,108 +374,111 @@ void options_imp::saveOptions() {
// End General preferences // End General preferences
// Downloads preferences // Downloads preferences
pref.setSavePath(getSavePath()); pref->setSavePath(getSavePath());
pref.setTempPathEnabled(isTempPathEnabled()); pref->setTempPathEnabled(isTempPathEnabled());
pref.setTempPath(getTempPath()); pref->setTempPath(getTempPath());
pref.setAppendTorrentLabel(checkAppendLabel->isChecked()); pref->setAppendTorrentLabel(checkAppendLabel->isChecked());
pref.useIncompleteFilesExtension(checkAppendqB->isChecked()); pref->useIncompleteFilesExtension(checkAppendqB->isChecked());
pref.preAllocateAllFiles(preAllocateAllFiles()); pref->preAllocateAllFiles(preAllocateAllFiles());
pref.useAdditionDialog(useAdditionDialog()); pref->useAdditionDialog(useAdditionDialog());
pref.AdditionDialogFront(checkAdditionDialogFront->isChecked()); pref->additionDialogFront(checkAdditionDialogFront->isChecked());
pref.addTorrentsInPause(addTorrentsInPause()); pref->addTorrentsInPause(addTorrentsInPause());
ScanFoldersModel::instance()->makePersistent(); ScanFoldersModel::instance()->makePersistent();
addedScanDirs.clear(); addedScanDirs.clear();
pref.setTorrentExportDir(getTorrentExportDir()); pref->setTorrentExportDir(getTorrentExportDir());
pref.setFinishedTorrentExportDir(getFinishedTorrentExportDir()); pref->setFinishedTorrentExportDir(getFinishedTorrentExportDir());
pref.setMailNotificationEnabled(groupMailNotification->isChecked()); pref->setMailNotificationEnabled(groupMailNotification->isChecked());
pref.setMailNotificationEmail(dest_email_txt->text()); pref->setMailNotificationEmail(dest_email_txt->text());
pref.setMailNotificationSMTP(smtp_server_txt->text()); pref->setMailNotificationSMTP(smtp_server_txt->text());
pref.setMailNotificationSMTPSSL(checkSmtpSSL->isChecked()); pref->setMailNotificationSMTPSSL(checkSmtpSSL->isChecked());
pref.setMailNotificationSMTPAuth(groupMailNotifAuth->isChecked()); pref->setMailNotificationSMTPAuth(groupMailNotifAuth->isChecked());
pref.setMailNotificationSMTPUsername(mailNotifUsername->text()); pref->setMailNotificationSMTPUsername(mailNotifUsername->text());
pref.setMailNotificationSMTPPassword(mailNotifPassword->text()); pref->setMailNotificationSMTPPassword(mailNotifPassword->text());
pref.setAutoRunEnabled(autoRunBox->isChecked()); pref->setAutoRunEnabled(autoRunBox->isChecked());
pref.setAutoRunProgram(autoRun_txt->text()); pref->setAutoRunProgram(autoRun_txt->text());
pref.setActionOnDblClOnTorrentDl(getActionOnDblClOnTorrentDl()); pref->setActionOnDblClOnTorrentDl(getActionOnDblClOnTorrentDl());
pref.setActionOnDblClOnTorrentFn(getActionOnDblClOnTorrentFn()); pref->setActionOnDblClOnTorrentFn(getActionOnDblClOnTorrentFn());
// End Downloads preferences // End Downloads preferences
// Connection preferences // Connection preferences
pref.setSessionPort(getPort()); pref->setSessionPort(getPort());
pref.setRandomPort(checkRandomPort->isChecked()); pref->setRandomPort(checkRandomPort->isChecked());
pref.setUPnPEnabled(isUPnPEnabled()); pref->setUPnPEnabled(isUPnPEnabled());
const QPair<int, int> down_up_limit = getGlobalBandwidthLimits(); const QPair<int, int> down_up_limit = getGlobalBandwidthLimits();
pref.setGlobalDownloadLimit(down_up_limit.first); pref->setGlobalDownloadLimit(down_up_limit.first);
pref.setGlobalUploadLimit(down_up_limit.second); pref->setGlobalUploadLimit(down_up_limit.second);
pref.setuTPEnabled(checkuTP->isChecked()); pref->setuTPEnabled(checkuTP->isChecked());
pref.setuTPRateLimited(checkLimituTPConnections->isChecked()); pref->setuTPRateLimited(checkLimituTPConnections->isChecked());
pref.includeOverheadInLimits(checkLimitTransportOverhead->isChecked()); pref->includeOverheadInLimits(checkLimitTransportOverhead->isChecked());
pref.setAltGlobalDownloadLimit(spinDownloadLimitAlt->value()); pref->setAltGlobalDownloadLimit(spinDownloadLimitAlt->value());
pref.setAltGlobalUploadLimit(spinUploadLimitAlt->value()); pref->setAltGlobalUploadLimit(spinUploadLimitAlt->value());
pref.setSchedulerEnabled(check_schedule->isChecked()); pref->setSchedulerEnabled(check_schedule->isChecked());
pref.setSchedulerStartTime(schedule_from->time()); pref->setSchedulerStartTime(schedule_from->time());
pref.setSchedulerEndTime(schedule_to->time()); pref->setSchedulerEndTime(schedule_to->time());
pref.setSchedulerDays((scheduler_days)schedule_days->currentIndex()); pref->setSchedulerDays((scheduler_days)schedule_days->currentIndex());
pref.setProxyType(getProxyType()); pref->setProxyType(getProxyType());
pref.setProxyIp(getProxyIp()); pref->setProxyIp(getProxyIp());
pref.setProxyPort(getProxyPort()); pref->setProxyPort(getProxyPort());
pref.setProxyPeerConnections(checkProxyPeerConnecs->isChecked()); pref->setProxyPeerConnections(checkProxyPeerConnecs->isChecked());
pref.setProxyAuthEnabled(isProxyAuthEnabled()); pref->setProxyAuthEnabled(isProxyAuthEnabled());
pref.setProxyUsername(getProxyUsername()); pref->setProxyUsername(getProxyUsername());
pref.setProxyPassword(getProxyPassword()); pref->setProxyPassword(getProxyPassword());
// End Connection preferences // End Connection preferences
// Bittorrent preferences // Bittorrent preferences
pref.setMaxConnecs(getMaxConnecs()); pref->setMaxConnecs(getMaxConnecs());
pref.setMaxConnecsPerTorrent(getMaxConnecsPerTorrent()); pref->setMaxConnecsPerTorrent(getMaxConnecsPerTorrent());
pref.setMaxUploads(getMaxUploads()); pref->setMaxUploads(getMaxUploads());
pref.setMaxUploadsPerTorrent(getMaxUploadsPerTorrent()); pref->setMaxUploadsPerTorrent(getMaxUploadsPerTorrent());
pref.setDHTEnabled(isDHTEnabled()); pref->setDHTEnabled(isDHTEnabled());
pref.setPeXEnabled(checkPeX->isChecked()); pref->setPeXEnabled(checkPeX->isChecked());
pref.setLSDEnabled(isLSDEnabled()); pref->setLSDEnabled(isLSDEnabled());
pref.setEncryptionSetting(getEncryptionSetting()); pref->setEncryptionSetting(getEncryptionSetting());
pref.enableAnonymousMode(checkAnonymousMode->isChecked()); pref->enableAnonymousMode(checkAnonymousMode->isChecked());
pref.setGlobalMaxRatio(getMaxRatio()); pref->setGlobalMaxRatio(getMaxRatio());
pref.setMaxRatioAction(comboRatioLimitAct->currentIndex()); pref->setMaxRatioAction(comboRatioLimitAct->currentIndex());
// End Bittorrent preferences // End Bittorrent preferences
// Misc preferences // Misc preferences
// * IPFilter // * IPFilter
pref.setFilteringEnabled(isFilteringEnabled()); pref->setFilteringEnabled(isFilteringEnabled());
if (isFilteringEnabled()) if (isFilteringEnabled())
pref.setFilter(textFilterPath->text()); pref->setFilter(textFilterPath->text());
// End IPFilter preferences // End IPFilter preferences
// Queueing system // Queueing system
pref.setQueueingSystemEnabled(isQueueingSystemEnabled()); pref->setQueueingSystemEnabled(isQueueingSystemEnabled());
pref.setMaxActiveDownloads(spinMaxActiveDownloads->value()); pref->setMaxActiveDownloads(spinMaxActiveDownloads->value());
pref.setMaxActiveUploads(spinMaxActiveUploads->value()); pref->setMaxActiveUploads(spinMaxActiveUploads->value());
pref.setMaxActiveTorrents(spinMaxActiveTorrents->value()); pref->setMaxActiveTorrents(spinMaxActiveTorrents->value());
pref.setIgnoreSlowTorrentsForQueueing(checkIgnoreSlowTorrentsForQueueing->isChecked()); pref->setIgnoreSlowTorrentsForQueueing(checkIgnoreSlowTorrentsForQueueing->isChecked());
// End Queueing system preferences // End Queueing system preferences
// Web UI // Web UI
pref.setWebUiEnabled(isWebUiEnabled()); pref->setWebUiEnabled(isWebUiEnabled());
if (isWebUiEnabled()) if (isWebUiEnabled())
{ {
pref.setWebUiPort(webUiPort()); pref->setWebUiPort(webUiPort());
pref.setUPnPForWebUIPort(checkWebUIUPnP->isChecked()); pref->setUPnPForWebUIPort(checkWebUIUPnP->isChecked());
pref.setWebUiHttpsEnabled(checkWebUiHttps->isChecked()); pref->setWebUiHttpsEnabled(checkWebUiHttps->isChecked());
if (checkWebUiHttps->isChecked()) if (checkWebUiHttps->isChecked())
{ {
pref.setWebUiHttpsCertificate(m_sslCert); pref->setWebUiHttpsCertificate(m_sslCert);
pref.setWebUiHttpsKey(m_sslKey); pref->setWebUiHttpsKey(m_sslKey);
} }
pref.setWebUiUsername(webUiUsername()); pref->setWebUiUsername(webUiUsername());
// FIXME: Check that the password is valid (not empty at least) // FIXME: Check that the password is valid (not empty at least)
pref.setWebUiPassword(webUiPassword()); pref->setWebUiPassword(webUiPassword());
pref.setWebUiLocalAuthEnabled(!checkBypassLocalAuth->isChecked()); pref->setWebUiLocalAuthEnabled(!checkBypassLocalAuth->isChecked());
// DynDNS // DynDNS
pref.setDynDNSEnabled(checkDynDNS->isChecked()); pref->setDynDNSEnabled(checkDynDNS->isChecked());
pref.setDynDNSService(comboDNSService->currentIndex()); pref->setDynDNSService(comboDNSService->currentIndex());
pref.setDynDomainName(domainNameTxt->text()); pref->setDynDomainName(domainNameTxt->text());
pref.setDynDNSUsername(DNSUsernameTxt->text()); pref->setDynDNSUsername(DNSUsernameTxt->text());
pref.setDynDNSPassword(DNSPasswordTxt->text()); pref->setDynDNSPassword(DNSPasswordTxt->text());
} }
// End Web UI // End Web UI
// End preferences // End preferences
// Save advanced settings // Save advanced settings
advancedSettings->saveAdvancedSettings(); advancedSettings->saveAdvancedSettings();
// Assume that user changed multiple settings
// so it's best to save immediately
pref->save();
} }
bool options_imp::isFilteringEnabled() const { bool options_imp::isFilteringEnabled() const {
@ -507,43 +510,43 @@ void options_imp::loadOptions() {
qreal floatValue; qreal floatValue;
QString strValue; QString strValue;
// General preferences // General preferences
const Preferences pref; const Preferences* const pref = Preferences::instance();
setLocale(pref.getLocale()); setLocale(pref->getLocale());
checkAltRowColors->setChecked(pref.useAlternatingRowColors()); checkAltRowColors->setChecked(pref->useAlternatingRowColors());
checkShowSystray->setChecked(pref.systrayIntegration()); checkShowSystray->setChecked(pref->systrayIntegration());
checkShowSplash->setChecked(!pref.isSlashScreenDisabled()); checkShowSplash->setChecked(!pref->isSlashScreenDisabled());
if (checkShowSystray->isChecked()) { if (checkShowSystray->isChecked()) {
checkCloseToSystray->setChecked(pref.closeToTray()); checkCloseToSystray->setChecked(pref->closeToTray());
checkMinimizeToSysTray->setChecked(pref.minimizeToTray()); checkMinimizeToSysTray->setChecked(pref->minimizeToTray());
checkStartMinimized->setChecked(pref.startMinimized()); checkStartMinimized->setChecked(pref->startMinimized());
} }
comboTrayIcon->setCurrentIndex(pref.trayIconStyle()); comboTrayIcon->setCurrentIndex(pref->trayIconStyle());
checkProgramExitConfirm->setChecked(pref.confirmOnExit()); checkProgramExitConfirm->setChecked(pref->confirmOnExit());
checkPreventFromSuspend->setChecked(pref.preventFromSuspend()); checkPreventFromSuspend->setChecked(pref->preventFromSuspend());
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
checkStartup->setChecked(pref.Startup()); checkStartup->setChecked(pref->WinStartup());
// Windows: file association settings // Windows: file association settings
checkAssociateTorrents->setChecked(Preferences::isTorrentFileAssocSet()); checkAssociateTorrents->setChecked(Preferences::isTorrentFileAssocSet());
checkAssociateMagnetLinks->setChecked(Preferences::isMagnetLinkAssocSet()); checkAssociateMagnetLinks->setChecked(Preferences::isMagnetLinkAssocSet());
#endif #endif
// End General preferences // End General preferences
// Downloads preferences // Downloads preferences
textSavePath->setText(fsutils::toNativePath(pref.getSavePath())); textSavePath->setText(fsutils::toNativePath(pref->getSavePath()));
if (pref.isTempPathEnabled()) { if (pref->isTempPathEnabled()) {
// enable // enable
checkTempFolder->setChecked(true); checkTempFolder->setChecked(true);
} else { } else {
checkTempFolder->setChecked(false); checkTempFolder->setChecked(false);
} }
textTempPath->setText(fsutils::toNativePath(pref.getTempPath())); textTempPath->setText(fsutils::toNativePath(pref->getTempPath()));
checkAppendLabel->setChecked(pref.appendTorrentLabel()); checkAppendLabel->setChecked(pref->appendTorrentLabel());
checkAppendqB->setChecked(pref.useIncompleteFilesExtension()); checkAppendqB->setChecked(pref->useIncompleteFilesExtension());
checkPreallocateAll->setChecked(pref.preAllocateAllFiles()); checkPreallocateAll->setChecked(pref->preAllocateAllFiles());
checkAdditionDialog->setChecked(pref.useAdditionDialog()); checkAdditionDialog->setChecked(pref->useAdditionDialog());
checkAdditionDialogFront->setChecked(pref.AdditionDialogFront()); checkAdditionDialogFront->setChecked(pref->additionDialogFront());
checkStartPaused->setChecked(pref.addTorrentsInPause()); checkStartPaused->setChecked(pref->addTorrentsInPause());
strValue = fsutils::toNativePath(pref.getTorrentExportDir()); strValue = fsutils::toNativePath(pref->getTorrentExportDir());
if (strValue.isEmpty()) { if (strValue.isEmpty()) {
// Disable // Disable
checkExportDir->setChecked(false); checkExportDir->setChecked(false);
@ -552,7 +555,7 @@ void options_imp::loadOptions() {
textExportDir->setText(strValue); textExportDir->setText(strValue);
} }
strValue = fsutils::toNativePath(pref.getFinishedTorrentExportDir()); strValue = fsutils::toNativePath(pref->getFinishedTorrentExportDir());
if (strValue.isEmpty()) { if (strValue.isEmpty()) {
// Disable // Disable
checkExportDirFin->setChecked(false); checkExportDirFin->setChecked(false);
@ -561,30 +564,30 @@ void options_imp::loadOptions() {
checkExportDirFin->setChecked(true); checkExportDirFin->setChecked(true);
textExportDirFin->setText(strValue); textExportDirFin->setText(strValue);
} }
groupMailNotification->setChecked(pref.isMailNotificationEnabled()); groupMailNotification->setChecked(pref->isMailNotificationEnabled());
dest_email_txt->setText(pref.getMailNotificationEmail()); dest_email_txt->setText(pref->getMailNotificationEmail());
smtp_server_txt->setText(pref.getMailNotificationSMTP()); smtp_server_txt->setText(pref->getMailNotificationSMTP());
checkSmtpSSL->setChecked(pref.getMailNotificationSMTPSSL()); checkSmtpSSL->setChecked(pref->getMailNotificationSMTPSSL());
groupMailNotifAuth->setChecked(pref.getMailNotificationSMTPAuth()); groupMailNotifAuth->setChecked(pref->getMailNotificationSMTPAuth());
mailNotifUsername->setText(pref.getMailNotificationSMTPUsername()); mailNotifUsername->setText(pref->getMailNotificationSMTPUsername());
mailNotifPassword->setText(pref.getMailNotificationSMTPPassword()); mailNotifPassword->setText(pref->getMailNotificationSMTPPassword());
autoRunBox->setChecked(pref.isAutoRunEnabled()); autoRunBox->setChecked(pref->isAutoRunEnabled());
autoRun_txt->setText(pref.getAutoRunProgram()); autoRun_txt->setText(pref->getAutoRunProgram());
intValue = pref.getActionOnDblClOnTorrentDl(); intValue = pref->getActionOnDblClOnTorrentDl();
if (intValue >= actionTorrentDlOnDblClBox->count()) if (intValue >= actionTorrentDlOnDblClBox->count())
intValue = 0; intValue = 0;
actionTorrentDlOnDblClBox->setCurrentIndex(intValue); actionTorrentDlOnDblClBox->setCurrentIndex(intValue);
intValue = pref.getActionOnDblClOnTorrentFn(); intValue = pref->getActionOnDblClOnTorrentFn();
if (intValue >= actionTorrentFnOnDblClBox->count()) if (intValue >= actionTorrentFnOnDblClBox->count())
intValue = 1; intValue = 1;
actionTorrentFnOnDblClBox->setCurrentIndex(intValue); actionTorrentFnOnDblClBox->setCurrentIndex(intValue);
// End Downloads preferences // End Downloads preferences
// Connection preferences // Connection preferences
spinPort->setValue(pref.getSessionPort()); spinPort->setValue(pref->getSessionPort());
checkUPnP->setChecked(pref.isUPnPEnabled()); checkUPnP->setChecked(pref->isUPnPEnabled());
checkRandomPort->setChecked(pref.useRandomPort()); checkRandomPort->setChecked(pref->useRandomPort());
spinPort->setDisabled(checkRandomPort->isChecked()); spinPort->setDisabled(checkRandomPort->isChecked());
intValue = pref.getGlobalDownloadLimit(); intValue = pref->getGlobalDownloadLimit();
if (intValue > 0) { if (intValue > 0) {
// Enabled // Enabled
checkDownloadLimit->setChecked(true); checkDownloadLimit->setChecked(true);
@ -595,7 +598,7 @@ void options_imp::loadOptions() {
checkDownloadLimit->setChecked(false); checkDownloadLimit->setChecked(false);
spinDownloadLimit->setEnabled(false); spinDownloadLimit->setEnabled(false);
} }
intValue = pref.getGlobalUploadLimit(); intValue = pref->getGlobalUploadLimit();
if (intValue != -1) { if (intValue != -1) {
// Enabled // Enabled
checkUploadLimit->setChecked(true); checkUploadLimit->setChecked(true);
@ -606,19 +609,19 @@ void options_imp::loadOptions() {
checkUploadLimit->setChecked(false); checkUploadLimit->setChecked(false);
spinUploadLimit->setEnabled(false); spinUploadLimit->setEnabled(false);
} }
spinUploadLimitAlt->setValue(pref.getAltGlobalUploadLimit()); spinUploadLimitAlt->setValue(pref->getAltGlobalUploadLimit());
spinDownloadLimitAlt->setValue(pref.getAltGlobalDownloadLimit()); spinDownloadLimitAlt->setValue(pref->getAltGlobalDownloadLimit());
// Options // Options
checkuTP->setChecked(pref.isuTPEnabled()); checkuTP->setChecked(pref->isuTPEnabled());
checkLimituTPConnections->setChecked(pref.isuTPRateLimited()); checkLimituTPConnections->setChecked(pref->isuTPRateLimited());
checkLimitTransportOverhead->setChecked(pref.includeOverheadInLimits()); checkLimitTransportOverhead->setChecked(pref->includeOverheadInLimits());
// Scheduler // Scheduler
check_schedule->setChecked(pref.isSchedulerEnabled()); check_schedule->setChecked(pref->isSchedulerEnabled());
schedule_from->setTime(pref.getSchedulerStartTime()); schedule_from->setTime(pref->getSchedulerStartTime());
schedule_to->setTime(pref.getSchedulerEndTime()); schedule_to->setTime(pref->getSchedulerEndTime());
schedule_days->setCurrentIndex((int)pref.getSchedulerDays()); schedule_days->setCurrentIndex((int)pref->getSchedulerDays());
intValue = pref.getProxyType(); intValue = pref->getProxyType();
switch(intValue) { switch(intValue) {
case Proxy::SOCKS4: case Proxy::SOCKS4:
comboProxyType->setCurrentIndex(1); comboProxyType->setCurrentIndex(1);
@ -637,16 +640,16 @@ void options_imp::loadOptions() {
enableProxy(comboProxyType->currentIndex()); enableProxy(comboProxyType->currentIndex());
//if (isProxyEnabled()) { //if (isProxyEnabled()) {
// Proxy is enabled, save settings // Proxy is enabled, save settings
textProxyIP->setText(pref.getProxyIp()); textProxyIP->setText(pref->getProxyIp());
spinProxyPort->setValue(pref.getProxyPort()); spinProxyPort->setValue(pref->getProxyPort());
checkProxyPeerConnecs->setChecked(pref.proxyPeerConnections()); checkProxyPeerConnecs->setChecked(pref->proxyPeerConnections());
checkProxyAuth->setChecked(pref.isProxyAuthEnabled()); checkProxyAuth->setChecked(pref->isProxyAuthEnabled());
textProxyUsername->setText(pref.getProxyUsername()); textProxyUsername->setText(pref->getProxyUsername());
textProxyPassword->setText(pref.getProxyPassword()); textProxyPassword->setText(pref->getProxyPassword());
//} //}
// End Connection preferences // End Connection preferences
// Bittorrent preferences // Bittorrent preferences
intValue = pref.getMaxConnecs(); intValue = pref->getMaxConnecs();
if (intValue > 0) { if (intValue > 0) {
// enable // enable
checkMaxConnecs->setChecked(true); checkMaxConnecs->setChecked(true);
@ -657,7 +660,7 @@ void options_imp::loadOptions() {
checkMaxConnecs->setChecked(false); checkMaxConnecs->setChecked(false);
spinMaxConnec->setEnabled(false); spinMaxConnec->setEnabled(false);
} }
intValue = pref.getMaxConnecsPerTorrent(); intValue = pref->getMaxConnecsPerTorrent();
if (intValue > 0) { if (intValue > 0) {
// enable // enable
checkMaxConnecsPerTorrent->setChecked(true); checkMaxConnecsPerTorrent->setChecked(true);
@ -668,7 +671,7 @@ void options_imp::loadOptions() {
checkMaxConnecsPerTorrent->setChecked(false); checkMaxConnecsPerTorrent->setChecked(false);
spinMaxConnecPerTorrent->setEnabled(false); spinMaxConnecPerTorrent->setEnabled(false);
} }
intValue = pref.getMaxUploads(); intValue = pref->getMaxUploads();
if (intValue > 0) { if (intValue > 0) {
// enable // enable
checkMaxUploads->setChecked(true); checkMaxUploads->setChecked(true);
@ -679,7 +682,7 @@ void options_imp::loadOptions() {
checkMaxUploads->setChecked(false); checkMaxUploads->setChecked(false);
spinMaxUploads->setEnabled(false); spinMaxUploads->setEnabled(false);
} }
intValue = pref.getMaxUploadsPerTorrent(); intValue = pref->getMaxUploadsPerTorrent();
if (intValue > 0) { if (intValue > 0) {
// enable // enable
checkMaxUploadsPerTorrent->setChecked(true); checkMaxUploadsPerTorrent->setChecked(true);
@ -690,15 +693,15 @@ void options_imp::loadOptions() {
checkMaxUploadsPerTorrent->setChecked(false); checkMaxUploadsPerTorrent->setChecked(false);
spinMaxUploadsPerTorrent->setEnabled(false); spinMaxUploadsPerTorrent->setEnabled(false);
} }
checkDHT->setChecked(pref.isDHTEnabled()); checkDHT->setChecked(pref->isDHTEnabled());
checkPeX->setChecked(pref.isPeXEnabled()); checkPeX->setChecked(pref->isPeXEnabled());
checkLSD->setChecked(pref.isLSDEnabled()); checkLSD->setChecked(pref->isLSDEnabled());
comboEncryption->setCurrentIndex(pref.getEncryptionSetting()); comboEncryption->setCurrentIndex(pref->getEncryptionSetting());
checkAnonymousMode->setChecked(pref.isAnonymousModeEnabled()); checkAnonymousMode->setChecked(pref->isAnonymousModeEnabled());
/* make sure ui matches options */ /* make sure ui matches options */
toggleAnonymousMode(checkAnonymousMode->isChecked()); toggleAnonymousMode(checkAnonymousMode->isChecked());
// Ratio limit // Ratio limit
floatValue = pref.getGlobalMaxRatio(); floatValue = pref->getGlobalMaxRatio();
if (floatValue >= 0.) { if (floatValue >= 0.) {
// Enable // Enable
checkMaxRatio->setChecked(true); checkMaxRatio->setChecked(true);
@ -711,36 +714,36 @@ void options_imp::loadOptions() {
spinMaxRatio->setEnabled(false); spinMaxRatio->setEnabled(false);
comboRatioLimitAct->setEnabled(false); comboRatioLimitAct->setEnabled(false);
} }
comboRatioLimitAct->setCurrentIndex(pref.getMaxRatioAction()); comboRatioLimitAct->setCurrentIndex(pref->getMaxRatioAction());
// End Bittorrent preferences // End Bittorrent preferences
// Misc preferences // Misc preferences
// * IP Filter // * IP Filter
checkIPFilter->setChecked(pref.isFilteringEnabled()); checkIPFilter->setChecked(pref->isFilteringEnabled());
textFilterPath->setText(fsutils::toNativePath(pref.getFilter())); textFilterPath->setText(fsutils::toNativePath(pref->getFilter()));
// End IP Filter // End IP Filter
// Queueing system preferences // Queueing system preferences
checkEnableQueueing->setChecked(pref.isQueueingSystemEnabled()); checkEnableQueueing->setChecked(pref->isQueueingSystemEnabled());
spinMaxActiveDownloads->setValue(pref.getMaxActiveDownloads()); spinMaxActiveDownloads->setValue(pref->getMaxActiveDownloads());
spinMaxActiveUploads->setValue(pref.getMaxActiveUploads()); spinMaxActiveUploads->setValue(pref->getMaxActiveUploads());
spinMaxActiveTorrents->setValue(pref.getMaxActiveTorrents()); spinMaxActiveTorrents->setValue(pref->getMaxActiveTorrents());
checkIgnoreSlowTorrentsForQueueing->setChecked(pref.ignoreSlowTorrentsForQueueing()); checkIgnoreSlowTorrentsForQueueing->setChecked(pref->ignoreSlowTorrentsForQueueing());
// End Queueing system preferences // End Queueing system preferences
// Web UI // Web UI
checkWebUi->setChecked(pref.isWebUiEnabled()); checkWebUi->setChecked(pref->isWebUiEnabled());
spinWebUiPort->setValue(pref.getWebUiPort()); spinWebUiPort->setValue(pref->getWebUiPort());
checkWebUIUPnP->setChecked(pref.useUPnPForWebUIPort()); checkWebUIUPnP->setChecked(pref->useUPnPForWebUIPort());
checkWebUiHttps->setChecked(pref.isWebUiHttpsEnabled()); checkWebUiHttps->setChecked(pref->isWebUiHttpsEnabled());
setSslCertificate(pref.getWebUiHttpsCertificate(), false); setSslCertificate(pref->getWebUiHttpsCertificate(), false);
setSslKey(pref.getWebUiHttpsKey(), false); setSslKey(pref->getWebUiHttpsKey(), false);
textWebUiUsername->setText(pref.getWebUiUsername()); textWebUiUsername->setText(pref->getWebUiUsername());
textWebUiPassword->setText(pref.getWebUiPassword()); textWebUiPassword->setText(pref->getWebUiPassword());
checkBypassLocalAuth->setChecked(!pref.isWebUiLocalAuthEnabled()); checkBypassLocalAuth->setChecked(!pref->isWebUiLocalAuthEnabled());
// Dynamic DNS // Dynamic DNS
checkDynDNS->setChecked(pref.isDynDNSEnabled()); checkDynDNS->setChecked(pref->isDynDNSEnabled());
comboDNSService->setCurrentIndex((int)pref.getDynDNSService()); comboDNSService->setCurrentIndex((int)pref->getDynDNSService());
domainNameTxt->setText(pref.getDynDomainName()); domainNameTxt->setText(pref->getDynDomainName());
DNSUsernameTxt->setText(pref.getDynDNSUsername()); DNSUsernameTxt->setText(pref->getDynDNSUsername());
DNSPasswordTxt->setText(pref.getDynDNSPassword()); DNSPasswordTxt->setText(pref->getDynDNSPassword());
// End Web UI // End Web UI
} }
@ -830,7 +833,7 @@ qreal options_imp::getMaxRatio() const {
// Return Save Path // Return Save Path
QString options_imp::getSavePath() const { QString options_imp::getSavePath() const {
if (textSavePath->text().trimmed().isEmpty()) { if (textSavePath->text().trimmed().isEmpty()) {
QString save_path = Preferences().getSavePath(); QString save_path = Preferences::instance()->getSavePath();
textSavePath->setText(fsutils::toNativePath(save_path)); textSavePath->setText(fsutils::toNativePath(save_path));
} }
return fsutils::expandPathAbs(textSavePath->text()); return fsutils::expandPathAbs(textSavePath->text());
@ -952,7 +955,7 @@ bool options_imp::isSlashScreenDisabled() const {
} }
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
bool options_imp::Startup() const { bool options_imp::WinStartup() const {
return checkStartup->isChecked(); return checkStartup->isChecked();
} }
#endif #endif
@ -1042,9 +1045,9 @@ int options_imp::getActionOnDblClOnTorrentFn() const {
} }
void options_imp::on_addScanFolderButton_clicked() { void options_imp::on_addScanFolderButton_clicked() {
Preferences pref; Preferences* const pref = Preferences::instance();
const QString dir = QFileDialog::getExistingDirectory(this, tr("Add directory to scan"), const QString dir = QFileDialog::getExistingDirectory(this, tr("Add directory to scan"),
fsutils::toNativePath(fsutils::folderName(pref.getScanDirsLastPath()))); fsutils::toNativePath(fsutils::folderName(pref->getScanDirsLastPath())));
if (!dir.isEmpty()) { if (!dir.isEmpty()) {
const ScanFoldersModel::PathStatus status = ScanFoldersModel::instance()->addPath(dir, false); const ScanFoldersModel::PathStatus status = ScanFoldersModel::instance()->addPath(dir, false);
QString error; QString error;
@ -1059,7 +1062,7 @@ void options_imp::on_addScanFolderButton_clicked() {
error = tr("Folder is not readable."); error = tr("Folder is not readable.");
break; break;
default: default:
pref.setScanDirsLastPath(dir); pref->setScanDirsLastPath(dir);
addedScanDirs << dir; addedScanDirs << dir;
scanFoldersView->resizeColumnsToContents(); scanFoldersView->resizeColumnsToContents();
enableApplyButton(); enableApplyButton();
@ -1210,9 +1213,9 @@ void options_imp::on_IpFilterRefreshBtn_clicked() {
if (m_refreshingIpFilter) return; if (m_refreshingIpFilter) return;
m_refreshingIpFilter = true; m_refreshingIpFilter = true;
// Updating program preferences // Updating program preferences
Preferences pref; Preferences* const pref = Preferences::instance();
pref.setFilteringEnabled(true); pref->setFilteringEnabled(true);
pref.setFilter(getFilter()); pref->setFilter(getFilter());
// Force refresh // Force refresh
connect(QBtSession::instance(), SIGNAL(ipFilterParsed(bool, int)), SLOT(handleIPFilterParsed(bool, int))); connect(QBtSession::instance(), SIGNAL(ipFilterParsed(bool, int)), SLOT(handleIPFilterParsed(bool, int)));
setCursor(QCursor(Qt::WaitCursor)); setCursor(QCursor(Qt::WaitCursor));

View file

@ -102,7 +102,7 @@ private:
bool isSlashScreenDisabled() const; bool isSlashScreenDisabled() const;
bool preventFromSuspend() const; bool preventFromSuspend() const;
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
bool Startup() const; bool WinStartup() const;
#endif #endif
// Downloads // Downloads
QString getSavePath() const; QString getSavePath() const;

View file

@ -45,7 +45,7 @@
PreviewSelect::PreviewSelect(QWidget* parent, QTorrentHandle h): QDialog(parent), h(h) { PreviewSelect::PreviewSelect(QWidget* parent, QTorrentHandle h): QDialog(parent), h(h) {
setupUi(this); setupUi(this);
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
Preferences pref; Preferences* const pref = Preferences::instance();
// Preview list // Preview list
previewListModel = new QStandardItemModel(0, NB_COLUMNS); previewListModel = new QStandardItemModel(0, NB_COLUMNS);
previewListModel->setHeaderData(NAME, Qt::Horizontal, tr("Name")); previewListModel->setHeaderData(NAME, Qt::Horizontal, tr("Name"));
@ -56,7 +56,7 @@ PreviewSelect::PreviewSelect(QWidget* parent, QTorrentHandle h): QDialog(parent)
listDelegate = new PreviewListDelegate(this); listDelegate = new PreviewListDelegate(this);
previewList->setItemDelegate(listDelegate); previewList->setItemDelegate(listDelegate);
previewList->header()->resizeSection(0, 200); previewList->header()->resizeSection(0, 200);
previewList->setAlternatingRowColors(pref.useAlternatingRowColors()); previewList->setAlternatingRowColors(pref->useAlternatingRowColors());
// Fill list in // Fill list in
std::vector<libtorrent::size_type> fp; std::vector<libtorrent::size_type> fp;
h.file_progress(fp); h.file_progress(fp);

View file

@ -34,6 +34,9 @@
#include <QXmlStreamReader> #include <QXmlStreamReader>
#include <QNetworkProxy> #include <QNetworkProxy>
#include <QDesktopServices> #include <QDesktopServices>
#include <QDebug>
#include <QRegExp>
#include <QStringList>
#include "programupdater.h" #include "programupdater.h"
#include "fs_utils.h" #include "fs_utils.h"
@ -47,17 +50,15 @@ const QUrl RSS_URL("http://sourceforge.net/api/file/index/project-id/163414/mtim
const QString FILE_EXT = "EXE"; const QString FILE_EXT = "EXE";
#endif #endif
using namespace libtorrent;
ProgramUpdater::ProgramUpdater(QObject *parent, bool invokedByUser) : ProgramUpdater::ProgramUpdater(QObject *parent, bool invokedByUser) :
QObject(parent), m_invokedByUser(invokedByUser) QObject(parent), m_invokedByUser(invokedByUser)
{ {
mp_manager = new QNetworkAccessManager(this); mp_manager = new QNetworkAccessManager(this);
Preferences pref; Preferences* const pref = Preferences::instance();
// Proxy support // Proxy support
if (pref.isProxyEnabled()) { if (pref->isProxyEnabled()) {
QNetworkProxy proxy; QNetworkProxy proxy;
switch(pref.getProxyType()) { switch(pref->getProxyType()) {
case Proxy::SOCKS4: case Proxy::SOCKS4:
case Proxy::SOCKS5: case Proxy::SOCKS5:
case Proxy::SOCKS5_PW: case Proxy::SOCKS5_PW:
@ -66,12 +67,12 @@ ProgramUpdater::ProgramUpdater(QObject *parent, bool invokedByUser) :
proxy.setType(QNetworkProxy::HttpProxy); proxy.setType(QNetworkProxy::HttpProxy);
break; break;
} }
proxy.setHostName(pref.getProxyIp()); proxy.setHostName(pref->getProxyIp());
proxy.setPort(pref.getProxyPort()); proxy.setPort(pref->getProxyPort());
// Proxy authentication // Proxy authentication
if (pref.isProxyAuthEnabled()) { if (pref->isProxyAuthEnabled()) {
proxy.setUser(pref.getProxyUsername()); proxy.setUser(pref->getProxyUsername());
proxy.setPassword(pref.getProxyPassword()); proxy.setPassword(pref->getProxyPassword());
} }
mp_manager->setProxy(proxy); mp_manager->setProxy(proxy);
} }

View file

@ -44,7 +44,6 @@
#include <QMenu> #include <QMenu>
#include <QClipboard> #include <QClipboard>
#include <vector> #include <vector>
#include "qinisettings.h"
using namespace libtorrent; using namespace libtorrent;
@ -84,7 +83,7 @@ PeerListWidget::PeerListWidget(PropertiesWidget *parent):
showColumn(i); showColumn(i);
hideColumn(PeerListDelegate::IP_HIDDEN); hideColumn(PeerListDelegate::IP_HIDDEN);
hideColumn(PeerListDelegate::COL_COUNT); hideColumn(PeerListDelegate::COL_COUNT);
if (!Preferences().resolvePeerCountries()) if (!Preferences::instance()->resolvePeerCountries())
hideColumn(PeerListDelegate::COUNTRY); hideColumn(PeerListDelegate::COUNTRY);
//To also migitate the above issue, we have to resize each column when //To also migitate the above issue, we have to resize each column when
//its size is 0, because explicitely 'showing' the column isn't enough //its size is 0, because explicitely 'showing' the column isn't enough
@ -119,7 +118,7 @@ PeerListWidget::~PeerListWidget()
void PeerListWidget::updatePeerHostNameResolutionState() void PeerListWidget::updatePeerHostNameResolutionState()
{ {
if (Preferences().resolvePeerHostNames()) { if (Preferences::instance()->resolvePeerHostNames()) {
if (!m_resolver) { if (!m_resolver) {
m_resolver = new ReverseResolution(this); m_resolver = new ReverseResolution(this);
connect(m_resolver, SIGNAL(ip_resolved(QString,QString)), SLOT(handleResolved(QString,QString))); connect(m_resolver, SIGNAL(ip_resolved(QString,QString)), SLOT(handleResolved(QString,QString)));
@ -133,7 +132,7 @@ void PeerListWidget::updatePeerHostNameResolutionState()
void PeerListWidget::updatePeerCountryResolutionState() void PeerListWidget::updatePeerCountryResolutionState()
{ {
if (Preferences().resolvePeerCountries() != m_displayFlags) { if (Preferences::instance()->resolvePeerCountries() != m_displayFlags) {
m_displayFlags = !m_displayFlags; m_displayFlags = !m_displayFlags;
if (m_displayFlags) if (m_displayFlags)
loadPeers(m_properties->getCurrentTorrent()); loadPeers(m_properties->getCurrentTorrent());
@ -253,7 +252,7 @@ void PeerListWidget::limitUpRateSelectedPeers(const QStringList& peer_ips)
long limit = SpeedLimitDialog::askSpeedLimit(&ok, long limit = SpeedLimitDialog::askSpeedLimit(&ok,
tr("Upload rate limiting"), tr("Upload rate limiting"),
cur_limit, cur_limit,
Preferences().getGlobalUploadLimit()*1024.); Preferences::instance()->getGlobalUploadLimit()*1024.);
if (!ok) if (!ok)
return; return;
@ -283,7 +282,7 @@ void PeerListWidget::limitDlRateSelectedPeers(const QStringList& peer_ips)
boost::asio::ip::tcp::endpoint()); boost::asio::ip::tcp::endpoint());
if (first_ep != boost::asio::ip::tcp::endpoint()) if (first_ep != boost::asio::ip::tcp::endpoint())
cur_limit = h.get_peer_download_limit(first_ep); cur_limit = h.get_peer_download_limit(first_ep);
long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Download rate limiting"), cur_limit, Preferences().getGlobalDownloadLimit()*1024.); long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Download rate limiting"), cur_limit, Preferences::instance()->getGlobalDownloadLimit()*1024.);
if (!ok) if (!ok)
return; return;
@ -316,13 +315,11 @@ void PeerListWidget::clear() {
} }
void PeerListWidget::loadSettings() { void PeerListWidget::loadSettings() {
QIniSettings settings; header()->restoreState(Preferences::instance()->getPeerListState());
header()->restoreState(settings.value("TorrentProperties/Peers/PeerListState").toByteArray());
} }
void PeerListWidget::saveSettings() const { void PeerListWidget::saveSettings() const {
QIniSettings settings; Preferences::instance()->setPeerListState(header()->saveState());
settings.setValue("TorrentProperties/Peers/PeerListState", header()->saveState());
} }
void PeerListWidget::loadPeers(const QTorrentHandle &h, bool force_hostname_resolution) { void PeerListWidget::loadPeers(const QTorrentHandle &h, bool force_hostname_resolution) {

View file

@ -52,7 +52,7 @@
#include "mainwindow.h" #include "mainwindow.h"
#include "downloadedpiecesbar.h" #include "downloadedpiecesbar.h"
#include "pieceavailabilitybar.h" #include "pieceavailabilitybar.h"
#include "qinisettings.h" #include "preferences.h"
#include "proptabbar.h" #include "proptabbar.h"
#include "iconprovider.h" #include "iconprovider.h"
#include "lineedit.h" #include "lineedit.h"
@ -268,28 +268,28 @@ void PropertiesWidget::loadTorrentInfos(const QTorrentHandle& _h)
} }
void PropertiesWidget::readSettings() { void PropertiesWidget::readSettings() {
QIniSettings settings; const Preferences* const pref = Preferences::instance();
// Restore splitter sizes // Restore splitter sizes
QStringList sizes_str = settings.value(QString::fromUtf8("TorrentProperties/SplitterSizes"), QString()).toString().split(","); QStringList sizes_str = pref->getPropSplitterSizes().split(",");
if (sizes_str.size() == 2) { if (sizes_str.size() == 2) {
slideSizes << sizes_str.first().toInt(); slideSizes << sizes_str.first().toInt();
slideSizes << sizes_str.last().toInt(); slideSizes << sizes_str.last().toInt();
QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget()); QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
hSplitter->setSizes(slideSizes); hSplitter->setSizes(slideSizes);
} }
if (!filesList->header()->restoreState(settings.value("TorrentProperties/FilesListState").toByteArray())) { if (!filesList->header()->restoreState(pref->getPropFileListState())) {
filesList->header()->resizeSection(0, 400); //Default filesList->header()->resizeSection(0, 400); //Default
} }
const int current_tab = settings.value("TorrentProperties/CurrentTab", -1).toInt(); const int current_tab = pref->getPropCurTab();
m_tabBar->setCurrentIndex(current_tab); m_tabBar->setCurrentIndex(current_tab);
if (!settings.value("TorrentProperties/Visible", false).toBool()) { if (!pref->getPropVisible()) {
setVisibility(false); setVisibility(false);
} }
} }
void PropertiesWidget::saveSettings() { void PropertiesWidget::saveSettings() {
QIniSettings settings; Preferences* const pref = Preferences::instance();
settings.setValue("TorrentProperties/Visible", state==VISIBLE); pref->setPropVisible(state==VISIBLE);
// Splitter sizes // Splitter sizes
QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget()); QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
QList<int> sizes; QList<int> sizes;
@ -299,11 +299,11 @@ void PropertiesWidget::saveSettings() {
sizes = slideSizes; sizes = slideSizes;
qDebug("Sizes: %d", sizes.size()); qDebug("Sizes: %d", sizes.size());
if (sizes.size() == 2) { if (sizes.size() == 2) {
settings.setValue(QString::fromUtf8("TorrentProperties/SplitterSizes"), QVariant(QString::number(sizes.first())+','+QString::number(sizes.last()))); pref->setPropSplitterSizes(QString::number(sizes.first())+','+QString::number(sizes.last()));
} }
settings.setValue("TorrentProperties/FilesListState", filesList->header()->saveState()); pref->setPropFileListState(filesList->header()->saveState());
// Remember current tab // Remember current tab
settings.setValue("TorrentProperties/CurrentTab", m_tabBar->currentIndex()); pref->setPropCurTab(m_tabBar->currentIndex());
} }
void PropertiesWidget::reloadPreferences() { void PropertiesWidget::reloadPreferences() {

View file

@ -43,7 +43,7 @@
#include "trackersadditiondlg.h" #include "trackersadditiondlg.h"
#include "iconprovider.h" #include "iconprovider.h"
#include "qbtsession.h" #include "qbtsession.h"
#include "qinisettings.h" #include "preferences.h"
#include "misc.h" #include "misc.h"
#include "autoexpandabledialog.h" #include "autoexpandabledialog.h"
@ -501,14 +501,12 @@ void TrackerList::showTrackerListMenu(QPoint) {
} }
void TrackerList::loadSettings() { void TrackerList::loadSettings() {
QIniSettings settings; if (!header()->restoreState(Preferences::instance()->getPropTrackerListState())) {
if (!header()->restoreState(settings.value("TorrentProperties/Trackers/TrackerListState").toByteArray())) {
setColumnWidth(0, 30); setColumnWidth(0, 30);
setColumnWidth(1, 300); setColumnWidth(1, 300);
} }
} }
void TrackerList::saveSettings() const { void TrackerList::saveSettings() const {
QIniSettings settings; Preferences::instance()->setPropTrackerListState(header()->saveState());
settings.setValue("TorrentProperties/Trackers/TrackerListState", header()->saveState());
} }

View file

@ -13,7 +13,7 @@ class BandwidthScheduler: public QTimer {
public: public:
BandwidthScheduler(QObject *parent): QTimer(parent) { BandwidthScheduler(QObject *parent): QTimer(parent) {
Q_ASSERT(Preferences().isSchedulerEnabled()); Q_ASSERT(Preferences::instance()->isSchedulerEnabled());
// Signal shot, we call start() again manually // Signal shot, we call start() again manually
setSingleShot(true); setSingleShot(true);
// Connect Signals/Slots // Connect Signals/Slots
@ -22,14 +22,14 @@ public:
public slots: public slots:
void start() { void start() {
const Preferences pref; const Preferences* const pref = Preferences::instance();
Q_ASSERT(pref.isSchedulerEnabled()); Q_ASSERT(pref->isSchedulerEnabled());
bool alt_bw_enabled = pref.isAltBandwidthEnabled(); bool alt_bw_enabled = pref->isAltBandwidthEnabled();
QTime start = pref.getSchedulerStartTime(); QTime start = pref->getSchedulerStartTime();
QTime end = pref.getSchedulerEndTime(); QTime end = pref->getSchedulerEndTime();
QTime now = QTime::currentTime(); QTime now = QTime::currentTime();
int sched_days = pref.getSchedulerDays(); int sched_days = pref->getSchedulerDays();
int day = QDateTime::currentDateTime().toLocalTime().date().dayOfWeek(); int day = QDateTime::currentDateTime().toLocalTime().date().dayOfWeek();
bool new_mode = false; bool new_mode = false;
bool reverse = false; bool reverse = false;

View file

@ -53,7 +53,6 @@
#endif #endif
#include "torrentpersistentdata.h" #include "torrentpersistentdata.h"
#include "httpserver.h" #include "httpserver.h"
#include "qinisettings.h"
#include "bandwidthscheduler.h" #include "bandwidthscheduler.h"
#include <libtorrent/version.hpp> #include <libtorrent/version.hpp>
#include <libtorrent/extensions/ut_metadata.hpp> #include <libtorrent/extensions/ut_metadata.hpp>
@ -121,7 +120,7 @@ QBtSession::QBtSession()
BigRatioTimer = new QTimer(this); BigRatioTimer = new QTimer(this);
BigRatioTimer->setInterval(10000); BigRatioTimer->setInterval(10000);
connect(BigRatioTimer, SIGNAL(timeout()), SLOT(processBigRatios())); connect(BigRatioTimer, SIGNAL(timeout()), SLOT(processBigRatios()));
Preferences pref; Preferences* const pref = Preferences::instance();;
// Creating Bittorrent session // Creating Bittorrent session
QList<int> version; QList<int> version;
version << VERSION_MAJOR; version << VERSION_MAJOR;
@ -141,9 +140,9 @@ QBtSession::QBtSession()
// Enabling plugins // Enabling plugins
//s->add_extension(&create_metadata_plugin); //s->add_extension(&create_metadata_plugin);
s->add_extension(&create_ut_metadata_plugin); s->add_extension(&create_ut_metadata_plugin);
if (pref.trackerExchangeEnabled()) if (pref->trackerExchangeEnabled())
s->add_extension(&create_lt_trackers_plugin); s->add_extension(&create_lt_trackers_plugin);
if (pref.isPeXEnabled()) { if (pref->isPeXEnabled()) {
PeXEnabled = true; PeXEnabled = true;
s->add_extension(&create_ut_pex_plugin); s->add_extension(&create_ut_pex_plugin);
} else { } else {
@ -152,8 +151,8 @@ QBtSession::QBtSession()
s->add_extension(&create_smart_ban_plugin); s->add_extension(&create_smart_ban_plugin);
m_alertDispatcher = new QAlertDispatcher(s, this); m_alertDispatcher = new QAlertDispatcher(s, this);
connect(m_alertDispatcher, SIGNAL(alertsReceived()), SLOT(readAlerts())); connect(m_alertDispatcher, SIGNAL(alertsReceived()), SLOT(readAlerts()));
appendLabelToSavePath = pref.appendTorrentLabel(); appendLabelToSavePath = pref->appendTorrentLabel();
appendqBExtension = pref.useIncompleteFilesExtension(); appendqBExtension = pref->useIncompleteFilesExtension();
connect(m_scanFolders, SIGNAL(torrentsAdded(QStringList&)), SLOT(addTorrentsFromScanFolder(QStringList&))); connect(m_scanFolders, SIGNAL(torrentsAdded(QStringList&)), SLOT(addTorrentsFromScanFolder(QStringList&)));
// Apply user settings to Bittorrent session // Apply user settings to Bittorrent session
configureSession(); configureSession();
@ -283,13 +282,13 @@ void QBtSession::setQueueingEnabled(bool enable) {
// Set BT session configuration // Set BT session configuration
void QBtSession::configureSession() { void QBtSession::configureSession() {
qDebug("Configuring session"); qDebug("Configuring session");
Preferences pref; Preferences* const pref = Preferences::instance();
if (pref.useRandomPort()) { if (pref->useRandomPort()) {
pref.setSessionPort(rand() % USHRT_MAX + 1025); pref->setSessionPort(rand() % USHRT_MAX + 1025);
} }
const unsigned short old_listenPort = getListenPort(); const unsigned short old_listenPort = getListenPort();
const unsigned short new_listenPort = pref.getSessionPort(); const unsigned short new_listenPort = pref->getSessionPort();
if (old_listenPort != new_listenPort) { if (old_listenPort != new_listenPort) {
qDebug("Session port changes in program preferences: %d -> %d", old_listenPort, new_listenPort); qDebug("Session port changes in program preferences: %d -> %d", old_listenPort, new_listenPort);
setListeningPort(new_listenPort); setListeningPort(new_listenPort);
@ -297,36 +296,36 @@ void QBtSession::configureSession() {
// Downloads // Downloads
// * Save path // * Save path
defaultSavePath = pref.getSavePath(); defaultSavePath = pref->getSavePath();
if (pref.isTempPathEnabled()) { if (pref->isTempPathEnabled()) {
setDefaultTempPath(pref.getTempPath()); setDefaultTempPath(pref->getTempPath());
} else { } else {
setDefaultTempPath(QString::null); setDefaultTempPath(QString::null);
} }
setAppendLabelToSavePath(pref.appendTorrentLabel()); setAppendLabelToSavePath(pref->appendTorrentLabel());
setAppendqBExtension(pref.useIncompleteFilesExtension()); setAppendqBExtension(pref->useIncompleteFilesExtension());
preAllocateAllFiles(pref.preAllocateAllFiles()); preAllocateAllFiles(pref->preAllocateAllFiles());
// * Torrent export directory // * Torrent export directory
const bool torrentExportEnabled = pref.isTorrentExportEnabled(); const bool torrentExportEnabled = pref->isTorrentExportEnabled();
if (m_torrentExportEnabled != torrentExportEnabled) { if (m_torrentExportEnabled != torrentExportEnabled) {
m_torrentExportEnabled = torrentExportEnabled; m_torrentExportEnabled = torrentExportEnabled;
if (m_torrentExportEnabled) { if (m_torrentExportEnabled) {
qDebug("Torrent export is enabled, exporting the current torrents"); qDebug("Torrent export is enabled, exporting the current torrents");
exportTorrentFiles(pref.getTorrentExportDir()); exportTorrentFiles(pref->getTorrentExportDir());
} }
} }
// * Finished Torrent export directory // * Finished Torrent export directory
const bool finishedTorrentExportEnabled = pref.isFinishedTorrentExportEnabled(); const bool finishedTorrentExportEnabled = pref->isFinishedTorrentExportEnabled();
if (m_finishedTorrentExportEnabled != finishedTorrentExportEnabled) if (m_finishedTorrentExportEnabled != finishedTorrentExportEnabled)
m_finishedTorrentExportEnabled = finishedTorrentExportEnabled; m_finishedTorrentExportEnabled = finishedTorrentExportEnabled;
// Connection // Connection
// * Global download limit // * Global download limit
const bool alternative_speeds = pref.isAltBandwidthEnabled(); const bool alternative_speeds = pref->isAltBandwidthEnabled();
int down_limit; int down_limit;
if (alternative_speeds) if (alternative_speeds)
down_limit = pref.getAltGlobalDownloadLimit(); down_limit = pref->getAltGlobalDownloadLimit();
else else
down_limit = pref.getGlobalDownloadLimit(); down_limit = pref->getGlobalDownloadLimit();
if (down_limit <= 0) { if (down_limit <= 0) {
// Download limit disabled // Download limit disabled
setDownloadRateLimit(-1); setDownloadRateLimit(-1);
@ -336,9 +335,9 @@ void QBtSession::configureSession() {
} }
int up_limit; int up_limit;
if (alternative_speeds) if (alternative_speeds)
up_limit = pref.getAltGlobalUploadLimit(); up_limit = pref->getAltGlobalUploadLimit();
else else
up_limit = pref.getGlobalUploadLimit(); up_limit = pref->getGlobalUploadLimit();
// * Global Upload limit // * Global Upload limit
if (up_limit <= 0) { if (up_limit <= 0) {
// Upload limit disabled // Upload limit disabled
@ -347,7 +346,7 @@ void QBtSession::configureSession() {
// Enabled // Enabled
setUploadRateLimit(up_limit*1024); setUploadRateLimit(up_limit*1024);
} }
if (pref.isSchedulerEnabled()) { if (pref->isSchedulerEnabled()) {
if (!bd_scheduler) { if (!bd_scheduler) {
bd_scheduler = new BandwidthScheduler(this); bd_scheduler = new BandwidthScheduler(this);
connect(bd_scheduler, SIGNAL(switchToAlternativeMode(bool)), this, SLOT(useAlternativeSpeedsLimit(bool))); connect(bd_scheduler, SIGNAL(switchToAlternativeMode(bool)), this, SLOT(useAlternativeSpeedsLimit(bool)));
@ -359,7 +358,7 @@ void QBtSession::configureSession() {
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
// Resolve countries // Resolve countries
qDebug("Loading country resolution settings"); qDebug("Loading country resolution settings");
const bool new_resolv_countries = pref.resolvePeerCountries(); const bool new_resolv_countries = pref->resolvePeerCountries();
if (resolve_countries != new_resolv_countries) { if (resolve_countries != new_resolv_countries) {
qDebug("in country resolution settings"); qDebug("in country resolution settings");
resolve_countries = new_resolv_countries; resolve_countries = new_resolv_countries;
@ -381,7 +380,7 @@ void QBtSession::configureSession() {
} }
#endif #endif
// * UPnP / NAT-PMP // * UPnP / NAT-PMP
if (pref.isUPnPEnabled()) { if (pref->isUPnPEnabled()) {
enableUPnP(true); enableUPnP(true);
addConsoleMessage(tr("UPnP / NAT-PMP support [ON]"), QString::fromUtf8("blue")); addConsoleMessage(tr("UPnP / NAT-PMP support [ON]"), QString::fromUtf8("blue"));
} else { } else {
@ -404,24 +403,24 @@ void QBtSession::configureSession() {
sessionSettings.stop_tracker_timeout = 1; sessionSettings.stop_tracker_timeout = 1;
//sessionSettings.announce_to_all_trackers = true; //sessionSettings.announce_to_all_trackers = true;
sessionSettings.auto_scrape_interval = 1200; // 20 minutes sessionSettings.auto_scrape_interval = 1200; // 20 minutes
bool announce_to_all = pref.announceToAllTrackers(); bool announce_to_all = pref->announceToAllTrackers();
sessionSettings.announce_to_all_trackers = announce_to_all; sessionSettings.announce_to_all_trackers = announce_to_all;
sessionSettings.announce_to_all_tiers = announce_to_all; sessionSettings.announce_to_all_tiers = announce_to_all;
sessionSettings.auto_scrape_min_interval = 900; // 15 minutes sessionSettings.auto_scrape_min_interval = 900; // 15 minutes
int cache_size = pref.diskCacheSize(); int cache_size = pref->diskCacheSize();
sessionSettings.cache_size = cache_size ? cache_size * 64 : -1; sessionSettings.cache_size = cache_size ? cache_size * 64 : -1;
sessionSettings.cache_expiry = pref.diskCacheTTL(); sessionSettings.cache_expiry = pref->diskCacheTTL();
qDebug() << "Using a disk cache size of" << cache_size << "MiB"; qDebug() << "Using a disk cache size of" << cache_size << "MiB";
sessionSettings.anonymous_mode = pref.isAnonymousModeEnabled(); sessionSettings.anonymous_mode = pref->isAnonymousModeEnabled();
if (sessionSettings.anonymous_mode) { if (sessionSettings.anonymous_mode) {
addConsoleMessage(tr("Anonymous mode [ON]"), "blue"); addConsoleMessage(tr("Anonymous mode [ON]"), "blue");
} else { } else {
addConsoleMessage(tr("Anonymous mode [OFF]"), "blue"); addConsoleMessage(tr("Anonymous mode [OFF]"), "blue");
} }
// Queueing System // Queueing System
if (pref.isQueueingSystemEnabled()) { if (pref->isQueueingSystemEnabled()) {
int max_downloading = pref.getMaxActiveDownloads(); int max_downloading = pref->getMaxActiveDownloads();
int max_active = pref.getMaxActiveTorrents(); int max_active = pref->getMaxActiveTorrents();
if (max_downloading > -1) if (max_downloading > -1)
sessionSettings.active_downloads = max_downloading + HiddenData::getDownloadingSize(); sessionSettings.active_downloads = max_downloading + HiddenData::getDownloadingSize();
else else
@ -439,8 +438,8 @@ void QBtSession::configureSession() {
sessionSettings.active_dht_limit = max_active; sessionSettings.active_dht_limit = max_active;
sessionSettings.active_lsd_limit = max_active; sessionSettings.active_lsd_limit = max_active;
} }
sessionSettings.active_seeds = pref.getMaxActiveUploads(); sessionSettings.active_seeds = pref->getMaxActiveUploads();
sessionSettings.dont_count_slow_torrents = pref.ignoreSlowTorrentsForQueueing(); sessionSettings.dont_count_slow_torrents = pref->ignoreSlowTorrentsForQueueing();
setQueueingEnabled(true); setQueueingEnabled(true);
} else { } else {
sessionSettings.active_downloads = -1; sessionSettings.active_downloads = -1;
@ -452,29 +451,29 @@ void QBtSession::configureSession() {
setQueueingEnabled(false); setQueueingEnabled(false);
} }
// Outgoing ports // Outgoing ports
sessionSettings.outgoing_ports = std::make_pair(pref.outgoingPortsMin(), pref.outgoingPortsMax()); sessionSettings.outgoing_ports = std::make_pair(pref->outgoingPortsMin(), pref->outgoingPortsMax());
// Ignore limits on LAN // Ignore limits on LAN
qDebug() << "Ignore limits on LAN" << pref.ignoreLimitsOnLAN(); qDebug() << "Ignore limits on LAN" << pref->ignoreLimitsOnLAN();
sessionSettings.ignore_limits_on_local_network = pref.ignoreLimitsOnLAN(); sessionSettings.ignore_limits_on_local_network = pref->ignoreLimitsOnLAN();
// Include overhead in transfer limits // Include overhead in transfer limits
sessionSettings.rate_limit_ip_overhead = pref.includeOverheadInLimits(); sessionSettings.rate_limit_ip_overhead = pref->includeOverheadInLimits();
// IP address to announce to trackers // IP address to announce to trackers
QString announce_ip = pref.getNetworkAddress(); QString announce_ip = pref->getNetworkAddress();
if (!announce_ip.isEmpty()) if (!announce_ip.isEmpty())
sessionSettings.announce_ip = announce_ip.toStdString(); sessionSettings.announce_ip = announce_ip.toStdString();
// Super seeding // Super seeding
sessionSettings.strict_super_seeding = pref.isSuperSeedingEnabled(); sessionSettings.strict_super_seeding = pref->isSuperSeedingEnabled();
// * Max Half-open connections // * Max Half-open connections
sessionSettings.half_open_limit = pref.getMaxHalfOpenConnections(); sessionSettings.half_open_limit = pref->getMaxHalfOpenConnections();
// * Max connections limit // * Max connections limit
sessionSettings.connections_limit = pref.getMaxConnecs(); sessionSettings.connections_limit = pref->getMaxConnecs();
// * Global max upload slots // * Global max upload slots
sessionSettings.unchoke_slots_limit = pref.getMaxUploads(); sessionSettings.unchoke_slots_limit = pref->getMaxUploads();
// uTP // uTP
sessionSettings.enable_incoming_utp = pref.isuTPEnabled(); sessionSettings.enable_incoming_utp = pref->isuTPEnabled();
sessionSettings.enable_outgoing_utp = pref.isuTPEnabled(); sessionSettings.enable_outgoing_utp = pref->isuTPEnabled();
// uTP rate limiting // uTP rate limiting
sessionSettings.rate_limit_utp = pref.isuTPRateLimited(); sessionSettings.rate_limit_utp = pref->isuTPRateLimited();
if (sessionSettings.rate_limit_utp) if (sessionSettings.rate_limit_utp)
sessionSettings.mixed_mode_algorithm = session_settings::prefer_tcp; sessionSettings.mixed_mode_algorithm = session_settings::prefer_tcp;
else else
@ -484,22 +483,22 @@ void QBtSession::configureSession() {
setSessionSettings(sessionSettings); setSessionSettings(sessionSettings);
// Bittorrent // Bittorrent
// * Max connections per torrent limit // * Max connections per torrent limit
setMaxConnectionsPerTorrent(pref.getMaxConnecsPerTorrent()); setMaxConnectionsPerTorrent(pref->getMaxConnecsPerTorrent());
// * Max uploads per torrent limit // * Max uploads per torrent limit
setMaxUploadsPerTorrent(pref.getMaxUploadsPerTorrent()); setMaxUploadsPerTorrent(pref->getMaxUploadsPerTorrent());
// * DHT // * DHT
enableDHT(pref.isDHTEnabled()); enableDHT(pref->isDHTEnabled());
// * PeX // * PeX
if (PeXEnabled) { if (PeXEnabled) {
addConsoleMessage(tr("PeX support [ON]"), QString::fromUtf8("blue")); addConsoleMessage(tr("PeX support [ON]"), QString::fromUtf8("blue"));
} else { } else {
addConsoleMessage(tr("PeX support [OFF]"), QString::fromUtf8("red")); addConsoleMessage(tr("PeX support [OFF]"), QString::fromUtf8("red"));
} }
if (PeXEnabled != pref.isPeXEnabled()) { if (PeXEnabled != pref->isPeXEnabled()) {
addConsoleMessage(tr("Restart is required to toggle PeX support"), QString::fromUtf8("red")); addConsoleMessage(tr("Restart is required to toggle PeX support"), QString::fromUtf8("red"));
} }
// * LSD // * LSD
if (pref.isLSDEnabled()) { if (pref->isLSDEnabled()) {
enableLSD(true); enableLSD(true);
addConsoleMessage(tr("Local Peer Discovery support [ON]"), QString::fromUtf8("blue")); addConsoleMessage(tr("Local Peer Discovery support [ON]"), QString::fromUtf8("blue"));
} else { } else {
@ -507,7 +506,7 @@ void QBtSession::configureSession() {
addConsoleMessage(tr("Local Peer Discovery support [OFF]"), QString::fromUtf8("blue")); addConsoleMessage(tr("Local Peer Discovery support [OFF]"), QString::fromUtf8("blue"));
} }
// * Encryption // * Encryption
const int encryptionState = pref.getEncryptionSetting(); const int encryptionState = pref->getEncryptionSetting();
// The most secure, rc4 only so that all streams and encrypted // The most secure, rc4 only so that all streams and encrypted
pe_settings encryptionSettings; pe_settings encryptionSettings;
encryptionSettings.allowed_enc_level = pe_settings::rc4; encryptionSettings.allowed_enc_level = pe_settings::rc4;
@ -530,13 +529,13 @@ void QBtSession::configureSession() {
} }
applyEncryptionSettings(encryptionSettings); applyEncryptionSettings(encryptionSettings);
// * Maximum ratio // * Maximum ratio
high_ratio_action = pref.getMaxRatioAction(); high_ratio_action = pref->getMaxRatioAction();
setGlobalMaxRatio(pref.getGlobalMaxRatio()); setGlobalMaxRatio(pref->getGlobalMaxRatio());
updateRatioTimer(); updateRatioTimer();
// Ip Filter // Ip Filter
FilterParserThread::processFilterList(s, pref.bannedIPs()); FilterParserThread::processFilterList(s, pref->bannedIPs());
if (pref.isFilteringEnabled()) { if (pref->isFilteringEnabled()) {
enableIPFilter(pref.getFilter()); enableIPFilter(pref->getFilter());
}else{ }else{
disableIPFilter(); disableIPFilter();
} }
@ -545,20 +544,20 @@ void QBtSession::configureSession() {
QTimer::singleShot(0, this, SLOT(initWebUi())); QTimer::singleShot(0, this, SLOT(initWebUi()));
// * Proxy settings // * Proxy settings
proxy_settings proxySettings; proxy_settings proxySettings;
if (pref.isProxyEnabled()) { if (pref->isProxyEnabled()) {
qDebug("Enabling P2P proxy"); qDebug("Enabling P2P proxy");
proxySettings.hostname = pref.getProxyIp().toStdString(); proxySettings.hostname = pref->getProxyIp().toStdString();
qDebug("hostname is %s", proxySettings.hostname.c_str()); qDebug("hostname is %s", proxySettings.hostname.c_str());
proxySettings.port = pref.getProxyPort(); proxySettings.port = pref->getProxyPort();
qDebug("port is %d", proxySettings.port); qDebug("port is %d", proxySettings.port);
if (pref.isProxyAuthEnabled()) { if (pref->isProxyAuthEnabled()) {
proxySettings.username = pref.getProxyUsername().toStdString(); proxySettings.username = pref->getProxyUsername().toStdString();
proxySettings.password = pref.getProxyPassword().toStdString(); proxySettings.password = pref->getProxyPassword().toStdString();
qDebug("username is %s", proxySettings.username.c_str()); qDebug("username is %s", proxySettings.username.c_str());
qDebug("password is %s", proxySettings.password.c_str()); qDebug("password is %s", proxySettings.password.c_str());
} }
} }
switch(pref.getProxyType()) { switch(pref->getProxyType()) {
case Proxy::HTTP: case Proxy::HTTP:
qDebug("type: http"); qDebug("type: http");
proxySettings.type = proxy_settings::http; proxySettings.type = proxy_settings::http;
@ -583,7 +582,7 @@ void QBtSession::configureSession() {
} }
setProxySettings(proxySettings); setProxySettings(proxySettings);
// Tracker // Tracker
if (pref.isTrackerEnabled()) { if (pref->isTrackerEnabled()) {
if (!m_tracker) { if (!m_tracker) {
m_tracker = new QTracker(this); m_tracker = new QTracker(this);
} }
@ -598,8 +597,8 @@ void QBtSession::configureSession() {
delete m_tracker; delete m_tracker;
} }
// * Scan dirs // * Scan dirs
const QStringList scan_dirs = pref.getScanDirs(); const QStringList scan_dirs = pref->getScanDirs();
QList<bool> downloadInDirList = pref.getDownloadInScanDirs(); QList<bool> downloadInDirList = pref->getDownloadInScanDirs();
while(scan_dirs.size() > downloadInDirList.size()) { while(scan_dirs.size() > downloadInDirList.size()) {
downloadInDirList << false; downloadInDirList << false;
} }
@ -613,11 +612,11 @@ void QBtSession::configureSession() {
} }
void QBtSession::initWebUi() { void QBtSession::initWebUi() {
Preferences pref; Preferences* const pref = Preferences::instance();
if (pref.isWebUiEnabled()) { if (pref->isWebUiEnabled()) {
const quint16 port = pref.getWebUiPort(); const quint16 port = pref->getWebUiPort();
const QString username = pref.getWebUiUsername(); const QString username = pref->getWebUiUsername();
const QString password = pref.getWebUiPassword(); const QString password = pref->getWebUiPassword();
if (httpServer) { if (httpServer) {
if (httpServer->serverPort() != port) { if (httpServer->serverPort() != port) {
@ -628,10 +627,10 @@ void QBtSession::initWebUi() {
} }
#ifndef QT_NO_OPENSSL #ifndef QT_NO_OPENSSL
if (pref.isWebUiHttpsEnabled()) { if (pref->isWebUiHttpsEnabled()) {
QSslCertificate cert(pref.getWebUiHttpsCertificate()); QSslCertificate cert(pref->getWebUiHttpsCertificate());
QSslKey key; QSslKey key;
const QByteArray raw_key = pref.getWebUiHttpsKey(); const QByteArray raw_key = pref->getWebUiHttpsKey();
key = QSslKey(raw_key, QSsl::Rsa); key = QSslKey(raw_key, QSsl::Rsa);
if (!cert.isNull() && !key.isNull()) if (!cert.isNull() && !key.isNull())
httpServer->enableHttps(cert, key); httpServer->enableHttps(cert, key);
@ -643,7 +642,7 @@ void QBtSession::initWebUi() {
#endif #endif
httpServer->setAuthorization(username, password); httpServer->setAuthorization(username, password);
httpServer->setlocalAuthEnabled(pref.isWebUiLocalAuthEnabled()); httpServer->setlocalAuthEnabled(pref->isWebUiLocalAuthEnabled());
if (!httpServer->isListening()) { if (!httpServer->isListening()) {
bool success = httpServer->listen(QHostAddress::Any, port); bool success = httpServer->listen(QHostAddress::Any, port);
if (success) if (success)
@ -652,7 +651,7 @@ void QBtSession::initWebUi() {
addConsoleMessage(tr("Web User Interface Error - Unable to bind Web UI to port %1").arg(port), "red"); addConsoleMessage(tr("Web User Interface Error - Unable to bind Web UI to port %1").arg(port), "red");
} }
// DynDNS // DynDNS
if (pref.isDynDNSEnabled()) { if (pref->isDynDNSEnabled()) {
if (!m_dynDNSUpdater) if (!m_dynDNSUpdater)
m_dynDNSUpdater = new DNSUpdater(this); m_dynDNSUpdater = new DNSUpdater(this);
else else
@ -676,13 +675,13 @@ void QBtSession::initWebUi() {
void QBtSession::useAlternativeSpeedsLimit(bool alternative) { void QBtSession::useAlternativeSpeedsLimit(bool alternative) {
qDebug() << Q_FUNC_INFO << alternative; qDebug() << Q_FUNC_INFO << alternative;
// Save new state to remember it on startup // Save new state to remember it on startup
Preferences pref; Preferences* const pref = Preferences::instance();
// Stop the scheduler when the user has manually changed the bandwidth mode // Stop the scheduler when the user has manually changed the bandwidth mode
if (!pref.isSchedulerEnabled()) if (!pref->isSchedulerEnabled())
delete bd_scheduler; delete bd_scheduler;
pref.setAltBandwidthEnabled(alternative); pref->setAltBandwidthEnabled(alternative);
// Apply settings to the bittorrent session // Apply settings to the bittorrent session
int down_limit = alternative ? pref.getAltGlobalDownloadLimit() : pref.getGlobalDownloadLimit(); int down_limit = alternative ? pref->getAltGlobalDownloadLimit() : pref->getGlobalDownloadLimit();
if (down_limit <= 0) { if (down_limit <= 0) {
down_limit = -1; down_limit = -1;
} else { } else {
@ -690,7 +689,7 @@ void QBtSession::useAlternativeSpeedsLimit(bool alternative) {
} }
setDownloadRateLimit(down_limit); setDownloadRateLimit(down_limit);
// Upload rate // Upload rate
int up_limit = alternative ? pref.getAltGlobalUploadLimit() : pref.getGlobalUploadLimit(); int up_limit = alternative ? pref->getAltGlobalUploadLimit() : pref->getGlobalUploadLimit();
if (up_limit <= 0) { if (up_limit <= 0) {
up_limit = -1; up_limit = -1;
} else { } else {
@ -739,7 +738,7 @@ bool QBtSession::hasDownloadingTorrents() const {
void QBtSession::banIP(QString ip) { void QBtSession::banIP(QString ip) {
FilterParserThread::processFilterList(s, QStringList(ip)); FilterParserThread::processFilterList(s, QStringList(ip));
Preferences().banIP(ip); Preferences::instance()->banIP(ip);
} }
// Delete a torrent from the session, given its hash // Delete a torrent from the session, given its hash
@ -874,11 +873,11 @@ bool QBtSession::loadFastResumeData(const QString &hash, std::vector<char> &buf)
} }
void QBtSession::loadTorrentSettings(QTorrentHandle& h) { void QBtSession::loadTorrentSettings(QTorrentHandle& h) {
Preferences pref; Preferences* const pref = Preferences::instance();
// Connections limit per torrent // Connections limit per torrent
h.set_max_connections(pref.getMaxConnecsPerTorrent()); h.set_max_connections(pref->getMaxConnecsPerTorrent());
// Uploads limit per torrent // Uploads limit per torrent
h.set_max_uploads(pref.getMaxUploadsPerTorrent()); h.set_max_uploads(pref->getMaxUploadsPerTorrent());
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
// Resolve countries // Resolve countries
h.resolve_countries(resolve_countries); h.resolve_countries(resolve_countries);
@ -889,7 +888,7 @@ QTorrentHandle QBtSession::addMagnetUri(QString magnet_uri, bool resumed, bool f
{ {
Q_UNUSED(fromScanDir); Q_UNUSED(fromScanDir);
Q_UNUSED(filePath); Q_UNUSED(filePath);
Preferences pref; Preferences* const pref = Preferences::instance();
QTorrentHandle h; QTorrentHandle h;
add_torrent_params p; add_torrent_params p;
libtorrent::error_code ec; libtorrent::error_code ec;
@ -979,11 +978,11 @@ QTorrentHandle QBtSession::addMagnetUri(QString magnet_uri, bool resumed, bool f
if (!resumed) { if (!resumed) {
loadTorrentTempData(h, savePath, true); loadTorrentTempData(h, savePath, true);
} }
if (HiddenData::hasData(hash) && pref.isQueueingSystemEnabled()) { if (HiddenData::hasData(hash) && pref->isQueueingSystemEnabled()) {
//Internally increase the queue limits to ensure that the magnet is started //Internally increase the queue limits to ensure that the magnet is started
libtorrent::session_settings sessionSettings(s->settings()); libtorrent::session_settings sessionSettings(s->settings());
int max_downloading = pref.getMaxActiveDownloads(); int max_downloading = pref->getMaxActiveDownloads();
int max_active = pref.getMaxActiveTorrents(); int max_active = pref->getMaxActiveTorrents();
if (max_downloading > -1) if (max_downloading > -1)
sessionSettings.active_downloads = max_downloading + HiddenData::getDownloadingSize(); sessionSettings.active_downloads = max_downloading + HiddenData::getDownloadingSize();
else else
@ -995,7 +994,7 @@ QTorrentHandle QBtSession::addMagnetUri(QString magnet_uri, bool resumed, bool f
s->set_settings(sessionSettings); s->set_settings(sessionSettings);
h.queue_position_top(); h.queue_position_top();
} }
if (!pref.addTorrentsInPause() || HiddenData::hasData(hash)) { if (!pref->addTorrentsInPause() || HiddenData::hasData(hash)) {
// Start torrent because it was added in paused state // Start torrent because it was added in paused state
h.resume(); h.resume();
} }
@ -1010,7 +1009,7 @@ QTorrentHandle QBtSession::addMagnetUri(QString magnet_uri, bool resumed, bool f
// Add a torrent to the Bittorrent session // Add a torrent to the Bittorrent session
QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString from_url, bool resumed) { QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString from_url, bool resumed) {
QTorrentHandle h; QTorrentHandle h;
Preferences pref; Preferences* const pref = Preferences::instance();
// Check if BT_backup directory exists // Check if BT_backup directory exists
const QDir torrentBackup(fsutils::BTBackupLocation()); const QDir torrentBackup(fsutils::BTBackupLocation());
@ -1170,7 +1169,7 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr
exportTorrentFile(h); exportTorrentFile(h);
} }
if (!fastResume && !pref.addTorrentsInPause()) { if (!fastResume && !pref->addTorrentsInPause()) {
// Start torrent because it was added in paused state // Start torrent because it was added in paused state
h.resume(); h.resume();
} }
@ -1201,7 +1200,7 @@ void QBtSession::exportTorrentFile(const QTorrentHandle& h, TorrentExportFolder
Q_ASSERT((folder == RegularTorrentExportFolder && m_torrentExportEnabled) || Q_ASSERT((folder == RegularTorrentExportFolder && m_torrentExportEnabled) ||
(folder == FinishedTorrentExportFolder && m_finishedTorrentExportEnabled)); (folder == FinishedTorrentExportFolder && m_finishedTorrentExportEnabled));
QString torrent_path = QDir(fsutils::BTBackupLocation()).absoluteFilePath(h.hash()+".torrent"); QString torrent_path = QDir(fsutils::BTBackupLocation()).absoluteFilePath(h.hash()+".torrent");
QDir exportPath(folder == RegularTorrentExportFolder ? Preferences().getTorrentExportDir() : Preferences().getFinishedTorrentExportDir()); QDir exportPath(folder == RegularTorrentExportFolder ? Preferences::instance()->getTorrentExportDir() : Preferences::instance()->getFinishedTorrentExportDir());
if (exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) { if (exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) {
QString new_torrent_path = exportPath.absoluteFilePath(h.name()+".torrent"); QString new_torrent_path = exportPath.absoluteFilePath(h.name()+".torrent");
if (QFile::exists(new_torrent_path) && fsutils::sameFiles(torrent_path, new_torrent_path)) { if (QFile::exists(new_torrent_path) && fsutils::sameFiles(torrent_path, new_torrent_path)) {
@ -1427,7 +1426,7 @@ void QBtSession::setMaxUploadsPerTorrent(int max) {
} }
void QBtSession::enableUPnP(bool b) { void QBtSession::enableUPnP(bool b) {
Preferences pref; Preferences* const pref = Preferences::instance();
if (b) { if (b) {
qDebug("Enabling UPnP / NAT-PMP"); qDebug("Enabling UPnP / NAT-PMP");
#if LIBTORRENT_VERSION_NUM < 10000 #if LIBTORRENT_VERSION_NUM < 10000
@ -1438,8 +1437,8 @@ void QBtSession::enableUPnP(bool b) {
s->start_natpmp(); s->start_natpmp();
#endif #endif
// Use UPnP/NAT-PMP for Web UI too // Use UPnP/NAT-PMP for Web UI too
if (pref.isWebUiEnabled() && pref.useUPnPForWebUIPort()) { if (pref->isWebUiEnabled() && pref->useUPnPForWebUIPort()) {
const qint16 port = pref.getWebUiPort(); const qint16 port = pref->getWebUiPort();
#if LIBTORRENT_VERSION_NUM < 10000 #if LIBTORRENT_VERSION_NUM < 10000
m_upnp->add_mapping(upnp::tcp, port, port); m_upnp->add_mapping(upnp::tcp, port, port);
m_natpmp->add_mapping(natpmp::tcp, port, port); m_natpmp->add_mapping(natpmp::tcp, port, port);
@ -1884,10 +1883,10 @@ void QBtSession::setAppendqBExtension(bool append) {
// session will listen to // session will listen to
void QBtSession::setListeningPort(int port) { void QBtSession::setListeningPort(int port) {
qDebug() << Q_FUNC_INFO << port; qDebug() << Q_FUNC_INFO << port;
Preferences pref; Preferences* const pref = Preferences::instance();
std::pair<int,int> ports(port, port); std::pair<int,int> ports(port, port);
libtorrent::error_code ec; libtorrent::error_code ec;
const QString iface_name = pref.getNetworkInterface(); const QString iface_name = pref->getNetworkInterface();
if (iface_name.isEmpty()) { if (iface_name.isEmpty()) {
addConsoleMessage(tr("qBittorrent is trying to listen on any interface port: %1", "e.g: qBittorrent is trying to listen on any interface port: TCP/6881").arg(QString::number(port)), "blue"); addConsoleMessage(tr("qBittorrent is trying to listen on any interface port: %1", "e.g: qBittorrent is trying to listen on any interface port: TCP/6881").arg(QString::number(port)), "blue");
s->listen_on(ports, ec, 0, session::listen_no_system_port); s->listen_on(ports, ec, 0, session::listen_no_system_port);
@ -2020,7 +2019,7 @@ void QBtSession::setSessionSettings(const session_settings &sessionSettings) {
void QBtSession::setProxySettings(proxy_settings proxySettings) { void QBtSession::setProxySettings(proxy_settings proxySettings) {
qDebug() << Q_FUNC_INFO; qDebug() << Q_FUNC_INFO;
proxySettings.proxy_peer_connections = Preferences().proxyPeerConnections(); proxySettings.proxy_peer_connections = Preferences::instance()->proxyPeerConnections();
s->set_proxy(proxySettings); s->set_proxy(proxySettings);
// Define environment variable // Define environment variable
@ -2074,7 +2073,7 @@ void QBtSession::recursiveTorrentDownload(const QTorrentHandle &h) {
void QBtSession::autoRunExternalProgram(const QTorrentHandle &h) { void QBtSession::autoRunExternalProgram(const QTorrentHandle &h) {
if (!h.is_valid()) return; if (!h.is_valid()) return;
QString program = Preferences().getAutoRunProgram().trimmed(); QString program = Preferences::instance()->getAutoRunProgram().trimmed();
if (program.isEmpty()) return; if (program.isEmpty()) return;
// Replace %f by torrent path // Replace %f by torrent path
QString torrent_path; QString torrent_path;
@ -2098,7 +2097,7 @@ void QBtSession::sendNotificationEmail(const QTorrentHandle &h) {
content += tr("Thank you for using qBittorrent.") + "\n"; content += tr("Thank you for using qBittorrent.") + "\n";
// Send the notification email // Send the notification email
Smtp *sender = new Smtp(this); Smtp *sender = new Smtp(this);
sender->sendMail("notification@qbittorrent.org", Preferences().getMailNotificationEmail(), tr("[qBittorrent] %1 has finished downloading").arg(h.name()), content); sender->sendMail("notification@qbittorrent.org", Preferences::instance()->getMailNotificationEmail(), tr("[qBittorrent] %1 has finished downloading").arg(h.name()), content);
} }
// Read alerts sent by the Bittorrent session // Read alerts sent by the Bittorrent session
@ -2247,37 +2246,37 @@ void QBtSession::handleTorrentFinishedAlert(libtorrent::torrent_finished_alert*
qDebug("Saving seed status"); qDebug("Saving seed status");
TorrentPersistentData::saveSeedStatus(h); TorrentPersistentData::saveSeedStatus(h);
// Recheck if the user asked to // Recheck if the user asked to
Preferences pref; Preferences* const pref = Preferences::instance();
if (pref.recheckTorrentsOnCompletion()) { if (pref->recheckTorrentsOnCompletion()) {
h.force_recheck(); h.force_recheck();
} }
qDebug("Emitting finishedTorrent() signal"); qDebug("Emitting finishedTorrent() signal");
emit finishedTorrent(h); emit finishedTorrent(h);
qDebug("Received finished alert for %s", qPrintable(h.name())); qDebug("Received finished alert for %s", qPrintable(h.name()));
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
bool will_shutdown = (pref.shutdownWhenDownloadsComplete() || bool will_shutdown = (pref->shutdownWhenDownloadsComplete() ||
pref.shutdownqBTWhenDownloadsComplete() || pref->shutdownqBTWhenDownloadsComplete() ||
pref.suspendWhenDownloadsComplete() || pref->suspendWhenDownloadsComplete() ||
pref.hibernateWhenDownloadsComplete()) pref->hibernateWhenDownloadsComplete())
&& !hasDownloadingTorrents(); && !hasDownloadingTorrents();
#else #else
bool will_shutdown = false; bool will_shutdown = false;
#endif #endif
// AutoRun program // AutoRun program
if (pref.isAutoRunEnabled()) if (pref->isAutoRunEnabled())
autoRunExternalProgram(h); autoRunExternalProgram(h);
// Move .torrent file to another folder // Move .torrent file to another folder
if (pref.isFinishedTorrentExportEnabled()) if (pref->isFinishedTorrentExportEnabled())
exportTorrentFile(h, FinishedTorrentExportFolder); exportTorrentFile(h, FinishedTorrentExportFolder);
// Mail notification // Mail notification
if (pref.isMailNotificationEnabled()) if (pref->isMailNotificationEnabled())
sendNotificationEmail(h); sendNotificationEmail(h);
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
// Auto-Shutdown // Auto-Shutdown
if (will_shutdown) { if (will_shutdown) {
bool suspend = pref.suspendWhenDownloadsComplete(); bool suspend = pref->suspendWhenDownloadsComplete();
bool hibernate = pref.hibernateWhenDownloadsComplete(); bool hibernate = pref->hibernateWhenDownloadsComplete();
bool shutdown = pref.shutdownWhenDownloadsComplete(); bool shutdown = pref->shutdownWhenDownloadsComplete();
// Confirm shutdown // Confirm shutdown
QString confirm_msg; QString confirm_msg;
if (suspend) { if (suspend) {
@ -2295,9 +2294,9 @@ void QBtSession::handleTorrentFinishedAlert(libtorrent::torrent_finished_alert*
if (suspend || hibernate || shutdown) { if (suspend || hibernate || shutdown) {
qDebug("Preparing for auto-shutdown because all downloads are complete!"); qDebug("Preparing for auto-shutdown because all downloads are complete!");
// Disabling it for next time // Disabling it for next time
pref.setShutdownWhenDownloadsComplete(false); pref->setShutdownWhenDownloadsComplete(false);
pref.setSuspendWhenDownloadsComplete(false); pref->setSuspendWhenDownloadsComplete(false);
pref.setHibernateWhenDownloadsComplete(false); pref->setHibernateWhenDownloadsComplete(false);
// Make sure preferences are synced before exiting // Make sure preferences are synced before exiting
if (suspend) if (suspend)
m_shutdownAct = SUSPEND_COMPUTER; m_shutdownAct = SUSPEND_COMPUTER;
@ -2458,16 +2457,16 @@ void QBtSession::handleStorageMovedFailedAlert(libtorrent::storage_moved_failed_
void QBtSession::handleMetadataReceivedAlert(libtorrent::metadata_received_alert* p) { void QBtSession::handleMetadataReceivedAlert(libtorrent::metadata_received_alert* p) {
QTorrentHandle h(p->handle); QTorrentHandle h(p->handle);
Preferences pref; Preferences* const pref = Preferences::instance();
if (h.is_valid()) { if (h.is_valid()) {
QString hash(h.hash()); QString hash(h.hash());
if (HiddenData::hasData(hash)) { if (HiddenData::hasData(hash)) {
HiddenData::gotMetadata(hash); HiddenData::gotMetadata(hash);
if (pref.isQueueingSystemEnabled()) { if (pref->isQueueingSystemEnabled()) {
//Internally decrease the queue limits to ensure that that other queued items aren't started //Internally decrease the queue limits to ensure that that other queued items aren't started
libtorrent::session_settings sessionSettings(s->settings()); libtorrent::session_settings sessionSettings(s->settings());
int max_downloading = pref.getMaxActiveDownloads(); int max_downloading = pref->getMaxActiveDownloads();
int max_active = pref.getMaxActiveTorrents(); int max_active = pref->getMaxActiveTorrents();
if (max_downloading > -1) if (max_downloading > -1)
sessionSettings.active_downloads = max_downloading + HiddenData::getDownloadingSize(); sessionSettings.active_downloads = max_downloading + HiddenData::getDownloadingSize();
else else
@ -2840,7 +2839,7 @@ void QBtSession::downloadUrlAndSkipDialog(QString url, QString save_path, QStrin
// Add to Bittorrent session the downloaded torrent file // Add to Bittorrent session the downloaded torrent file
void QBtSession::processDownloadedFile(QString url, QString file_path) { void QBtSession::processDownloadedFile(QString url, QString file_path) {
Preferences pref; Preferences* const pref = Preferences::instance();
const int index = url_skippingDlg.indexOf(QUrl::fromEncoded(url.toUtf8())); const int index = url_skippingDlg.indexOf(QUrl::fromEncoded(url.toUtf8()));
if (index < 0) { if (index < 0) {
// Add file to torrent download list // Add file to torrent download list
@ -2863,7 +2862,7 @@ void QBtSession::processDownloadedFile(QString url, QString file_path) {
url_skippingDlg.removeAt(index); url_skippingDlg.removeAt(index);
QTorrentHandle h = addTorrent(file_path, false, url, false); QTorrentHandle h = addTorrent(file_path, false, url, false);
// Pause torrent if necessary // Pause torrent if necessary
if (h.is_valid() && pref.addTorrentsInPause() && Preferences().useAdditionDialog()) if (h.is_valid() && pref->addTorrentsInPause() && pref->useAdditionDialog())
h.pause(); h.pause();
emit newDownloadedTorrentFromRss(url); emit newDownloadedTorrentFromRss(url);
} }
@ -2940,8 +2939,6 @@ void QBtSession::startUpTorrents() {
addTorrent(torrentBackup.path()+"/"+hash+".torrent", false, QString(), true); addTorrent(torrentBackup.path()+"/"+hash+".torrent", false, QString(), true);
} }
} }
QIniSettings settings;
settings.setValue("ported_to_new_savepath_system", true);
qDebug("Unfinished torrents resumed"); qDebug("Unfinished torrents resumed");
} }
@ -3025,17 +3022,17 @@ void QBtSession::backupPersistentData(const QString &hash, boost::shared_ptr<lib
} }
void QBtSession::unhideMagnet(const QString &hash) { void QBtSession::unhideMagnet(const QString &hash) {
Preferences pref; Preferences* const pref = Preferences::instance();
HiddenData::deleteData(hash); HiddenData::deleteData(hash);
QString save_path = getSavePath(hash, false); //appends label if necessary QString save_path = getSavePath(hash, false); //appends label if necessary
QTorrentHandle h(getTorrentHandle(hash)); QTorrentHandle h(getTorrentHandle(hash));
if (!h.is_valid()) { if (!h.is_valid()) {
if (pref.isQueueingSystemEnabled()) { if (pref->isQueueingSystemEnabled()) {
//Internally decrease the queue limits to ensure that other queued items aren't started //Internally decrease the queue limits to ensure that other queued items aren't started
libtorrent::session_settings sessionSettings(s->settings()); libtorrent::session_settings sessionSettings(s->settings());
int max_downloading = pref.getMaxActiveDownloads(); int max_downloading = pref->getMaxActiveDownloads();
int max_active = pref.getMaxActiveTorrents(); int max_active = pref->getMaxActiveTorrents();
if (max_downloading > -1) if (max_downloading > -1)
sessionSettings.active_downloads = max_downloading + HiddenData::getDownloadingSize(); sessionSettings.active_downloads = max_downloading + HiddenData::getDownloadingSize();
else else
@ -3051,11 +3048,11 @@ void QBtSession::unhideMagnet(const QString &hash) {
} }
if (!h.has_metadata()) { if (!h.has_metadata()) {
if (pref.isQueueingSystemEnabled()) { if (pref->isQueueingSystemEnabled()) {
//Internally decrease the queue limits to ensure that other queued items aren't started //Internally decrease the queue limits to ensure that other queued items aren't started
libtorrent::session_settings sessionSettings(s->settings()); libtorrent::session_settings sessionSettings(s->settings());
int max_downloading = pref.getMaxActiveDownloads(); int max_downloading = pref->getMaxActiveDownloads();
int max_active = pref.getMaxActiveTorrents(); int max_active = pref->getMaxActiveTorrents();
if (max_downloading > -1) if (max_downloading > -1)
sessionSettings.active_downloads = max_downloading + HiddenData::getDownloadingSize(); sessionSettings.active_downloads = max_downloading + HiddenData::getDownloadingSize();
else else
@ -3066,13 +3063,13 @@ void QBtSession::unhideMagnet(const QString &hash) {
sessionSettings.active_limit = max_active; sessionSettings.active_limit = max_active;
s->set_settings(sessionSettings); s->set_settings(sessionSettings);
} }
if (pref.addTorrentsInPause()) if (pref->addTorrentsInPause())
h.pause(); h.pause();
} }
h.queue_position_bottom(); h.queue_position_bottom();
loadTorrentTempData(h, h.save_path(), !h.has_metadata()); //TempData are deleted by a call to TorrentPersistentData::saveTorrentPersistentData() loadTorrentTempData(h, h.save_path(), !h.has_metadata()); //TempData are deleted by a call to TorrentPersistentData::saveTorrentPersistentData()
if (!pref.addTorrentsInPause()) if (!pref->addTorrentsInPause())
h.resume(); h.resume();
h.move_storage(save_path); h.move_storage(save_path);

View file

@ -413,7 +413,7 @@ void QTorrentHandle::resume() const {
const QString torrent_hash = hash(); const QString torrent_hash = hash();
bool has_persistant_error = TorrentPersistentData::hasError(torrent_hash); bool has_persistant_error = TorrentPersistentData::hasError(torrent_hash);
TorrentPersistentData::setErrorState(torrent_hash, false); TorrentPersistentData::setErrorState(torrent_hash, false);
bool temp_path_enabled = Preferences().isTempPathEnabled(); bool temp_path_enabled = Preferences::instance()->isTempPathEnabled();
if (has_persistant_error && temp_path_enabled) { if (has_persistant_error && temp_path_enabled) {
// Torrent was supposed to be seeding, checking again in final destination // Torrent was supposed to be seeding, checking again in final destination
qDebug("Resuming a torrent with error..."); qDebug("Resuming a torrent with error...");
@ -577,9 +577,9 @@ void QTorrentHandle::prioritize_files(const vector<int> &files) const {
// Save seed status // Save seed status
TorrentPersistentData::saveSeedStatus(*this); TorrentPersistentData::saveSeedStatus(*this);
// Move to temp folder if necessary // Move to temp folder if necessary
const Preferences pref; const Preferences* const pref = Preferences::instance();
if (pref.isTempPathEnabled()) { if (pref->isTempPathEnabled()) {
QString tmp_path = pref.getTempPath(); QString tmp_path = pref->getTempPath();
qDebug() << "tmp folder is enabled, move torrent to " << tmp_path << " from " << spath; qDebug() << "tmp folder is enabled, move torrent to " << tmp_path << " from " << spath;
move_storage(tmp_path); move_storage(tmp_path);
} }

View file

@ -35,7 +35,6 @@
#include "qbtsession.h" #include "qbtsession.h"
#include "misc.h" #include "misc.h"
#include "torrentspeedmonitor.h" #include "torrentspeedmonitor.h"
#include "qinisettings.h"
using namespace libtorrent; using namespace libtorrent;

View file

@ -6,6 +6,7 @@
#include "qbtsession.h" #include "qbtsession.h"
#include "qinisettings.h" #include "qinisettings.h"
#include "preferences.h"
TorrentStatistics::TorrentStatistics(QBtSession* session, QObject* parent) TorrentStatistics::TorrentStatistics(QBtSession* session, QObject* parent)
: QObject(parent) : QObject(parent)
@ -65,13 +66,16 @@ void TorrentStatistics::loadStats() {
// This code reads the data from there, writes it to the new file, and removes the keys // This code reads the data from there, writes it to the new file, and removes the keys
// from the old file. This code should be removed after some time has passed. // from the old file. This code should be removed after some time has passed.
// e.g. When we reach v3.3.0 // e.g. When we reach v3.3.0
QIniSettings s_old; // Don't forget to remove:
// 1. Preferences::getStats()
// 2. Preferences::removeStats()
// 3. #include "preferences.h"
Preferences* const pref = Preferences::instance();
QIniSettings s("qBittorrent", "qBittorrent-data"); QIniSettings s("qBittorrent", "qBittorrent-data");
QVariantHash v; QVariantHash v = pref->getStats();
// Let's test if the qbittorrent.ini holds the key // Let's test if the qbittorrent.ini holds the key
if (s_old.contains("Stats/AllStats")) { if (!v.isEmpty()) {
v = s_old.value("Stats/AllStats").toHash();
m_dirty = true; m_dirty = true;
// If the user has used qbt > 3.1.5 and then reinstalled/used // If the user has used qbt > 3.1.5 and then reinstalled/used
@ -91,6 +95,6 @@ void TorrentStatistics::loadStats() {
if (m_dirty) { if (m_dirty) {
saveStats(); saveStats();
s_old.remove("Stats/AllStats"); pref->removeStats();
} }
} }

View file

@ -36,14 +36,13 @@
#include "automatedrssdownloader.h" #include "automatedrssdownloader.h"
#include "ui_automatedrssdownloader.h" #include "ui_automatedrssdownloader.h"
#include "rsssettings.h"
#include "rssdownloadrulelist.h" #include "rssdownloadrulelist.h"
#include "preferences.h" #include "preferences.h"
#include "qinisettings.h"
#include "rssmanager.h" #include "rssmanager.h"
#include "rssfeed.h" #include "rssfeed.h"
#include "iconprovider.h" #include "iconprovider.h"
#include "autoexpandabledialog.h" #include "autoexpandabledialog.h"
#include "fs_utils.h"
AutomatedRssDownloader::AutomatedRssDownloader(const QWeakPointer<RssManager>& manager, QWidget *parent) : AutomatedRssDownloader::AutomatedRssDownloader(const QWeakPointer<RssManager>& manager, QWidget *parent) :
QDialog(parent), QDialog(parent),
@ -119,21 +118,21 @@ AutomatedRssDownloader::~AutomatedRssDownloader()
void AutomatedRssDownloader::loadSettings() void AutomatedRssDownloader::loadSettings()
{ {
// load dialog geometry // load dialog geometry
QIniSettings settings; const Preferences* const pref = Preferences::instance();
restoreGeometry(settings.value("RssFeedDownloader/geometry").toByteArray()); restoreGeometry(pref->getRssGeometry());
ui->checkEnableDownloader->setChecked(RssSettings().isRssDownloadingEnabled()); ui->checkEnableDownloader->setChecked(pref->isRssDownloadingEnabled());
ui->hsplitter->restoreState(settings.value("RssFeedDownloader/hsplitterSizes").toByteArray()); ui->hsplitter->restoreState(pref->getRssHSplitterSizes());
// Display download rules // Display download rules
loadRulesList(); loadRulesList();
} }
void AutomatedRssDownloader::saveSettings() void AutomatedRssDownloader::saveSettings()
{ {
RssSettings().setRssDownloadingEnabled(ui->checkEnableDownloader->isChecked()); Preferences::instance()->setRssDownloadingEnabled(ui->checkEnableDownloader->isChecked());
// Save dialog geometry // Save dialog geometry
QIniSettings settings; Preferences* const pref = Preferences::instance();
settings.setValue("RssFeedDownloader/geometry", saveGeometry()); pref->setRssGeometry(saveGeometry());
settings.setValue("RssFeedDownloader/hsplitterSizes", ui->hsplitter->saveState()); pref->setRssHSplitterSizes(ui->hsplitter->saveState());
} }
void AutomatedRssDownloader::loadRulesList() void AutomatedRssDownloader::loadRulesList()
@ -157,9 +156,9 @@ void AutomatedRssDownloader::loadRulesList()
void AutomatedRssDownloader::loadFeedList() void AutomatedRssDownloader::loadFeedList()
{ {
const RssSettings settings; const Preferences* const pref = Preferences::instance();
const QStringList feed_aliases = settings.getRssFeedsAliases(); const QStringList feed_aliases = pref->getRssFeedsAliases();
const QStringList feed_urls = settings.getRssFeedsUrls(); const QStringList feed_urls = pref->getRssFeedsUrls();
QStringList existing_urls; QStringList existing_urls;
for (int i=0; i<feed_aliases.size(); ++i) { for (int i=0; i<feed_aliases.size(); ++i) {
QString feed_url = feed_urls.at(i); QString feed_url = feed_urls.at(i);
@ -275,7 +274,7 @@ RssDownloadRulePtr AutomatedRssDownloader::getCurrentRule() const
void AutomatedRssDownloader::initLabelCombobox() void AutomatedRssDownloader::initLabelCombobox()
{ {
// Load custom labels // Load custom labels
const QStringList customLabels = Preferences().getTorrentLabels(); const QStringList customLabels = Preferences::instance()->getTorrentLabels();
foreach (const QString& label, customLabels) { foreach (const QString& label, customLabels) {
ui->comboLabel->addItem(label); ui->comboLabel->addItem(label);
} }
@ -309,7 +308,7 @@ void AutomatedRssDownloader::saveEditedRule()
rule->setLabel(ui->comboLabel->currentText()); rule->setLabel(ui->comboLabel->currentText());
// Save new label // Save new label
if (!rule->label().isEmpty()) if (!rule->label().isEmpty())
Preferences().addTorrentLabel(rule->label()); Preferences::instance()->addTorrentLabel(rule->label());
//rule->setRssFeeds(getSelectedFeeds()); //rule->setRssFeeds(getSelectedFeeds());
// Save it // Save it
m_editableRuleList->saveRule(rule); m_editableRuleList->saveRule(rule);

View file

@ -9,7 +9,6 @@ HEADERS += $$PWD/rss_imp.h \
$$PWD/rssfile.h \ $$PWD/rssfile.h \
$$PWD/rssarticle.h \ $$PWD/rssarticle.h \
$$PWD/automatedrssdownloader.h \ $$PWD/automatedrssdownloader.h \
$$PWD/rsssettings.h \
$$PWD/rssdownloadrule.h \ $$PWD/rssdownloadrule.h \
$$PWD/rssdownloadrulelist.h \ $$PWD/rssdownloadrulelist.h \
$$PWD/cookiesdlg.h \ $$PWD/cookiesdlg.h \

View file

@ -35,6 +35,7 @@
#include <QString> #include <QString>
#include <QClipboard> #include <QClipboard>
#include <QDragMoveEvent> #include <QDragMoveEvent>
#include <QDebug>
#include "rss_imp.h" #include "rss_imp.h"
#include "feedlistwidget.h" #include "feedlistwidget.h"
@ -47,7 +48,6 @@
#include "rssarticle.h" #include "rssarticle.h"
#include "rssparser.h" #include "rssparser.h"
#include "rssfeed.h" #include "rssfeed.h"
#include "rsssettings.h"
#include "automatedrssdownloader.h" #include "automatedrssdownloader.h"
#include "iconprovider.h" #include "iconprovider.h"
#include "autoexpandabledialog.h" #include "autoexpandabledialog.h"
@ -134,11 +134,11 @@ void RSSImp::on_actionManage_cookies_triggered()
qDebug("RSS Feed hostname is: %s", qPrintable(feed_hostname)); qDebug("RSS Feed hostname is: %s", qPrintable(feed_hostname));
Q_ASSERT(!feed_hostname.isEmpty()); Q_ASSERT(!feed_hostname.isEmpty());
bool ok = false; bool ok = false;
RssSettings settings; Preferences* const pref = Preferences::instance();
QList<QByteArray> raw_cookies = CookiesDlg::askForCookies(this, settings.getHostNameCookies(feed_hostname), &ok); QList<QByteArray> raw_cookies = CookiesDlg::askForCookies(this, pref->getHostNameCookies(feed_hostname), &ok);
if (ok) { if (ok) {
qDebug() << "Settings cookies for host name: " << feed_hostname; qDebug() << "Settings cookies for host name: " << feed_hostname;
settings.setHostNameCookies(feed_hostname, raw_cookies); pref->setHostNameCookies(feed_hostname, raw_cookies);
} }
} }
@ -283,10 +283,7 @@ void RSSImp::deleteSelectedItems()
void RSSImp::loadFoldersOpenState() void RSSImp::loadFoldersOpenState()
{ {
QIniSettings settings; QStringList open_folders = Preferences::instance()->getRssOpenFolders();
settings.beginGroup("Rss");
QStringList open_folders = settings.value("open_folders", QStringList()).toStringList();
settings.endGroup();
foreach (const QString& var_path, open_folders) { foreach (const QString& var_path, open_folders) {
QStringList path = var_path.split("\\"); QStringList path = var_path.split("\\");
QTreeWidgetItem* parent = 0; QTreeWidgetItem* parent = 0;
@ -322,10 +319,7 @@ void RSSImp::saveFoldersOpenState()
qDebug("saving open folder: %s", qPrintable(path)); qDebug("saving open folder: %s", qPrintable(path));
open_folders << path; open_folders << path;
} }
QIniSettings settings; Preferences::instance()->setRssOpenFolders(open_folders);
settings.beginGroup("Rss");
settings.setValue("open_folders", open_folders);
settings.endGroup();
} }
// refresh all streams by a button // refresh all streams by a button
@ -351,7 +345,7 @@ void RSSImp::downloadSelectedTorrents()
// Load possible cookies // Load possible cookies
QString feed_url = m_feedList->getItemID(m_feedList->selectedItems().first()); QString feed_url = m_feedList->getItemID(m_feedList->selectedItems().first());
QString feed_hostname = QUrl::fromEncoded(feed_url.toUtf8()).host(); QString feed_hostname = QUrl::fromEncoded(feed_url.toUtf8()).host();
QList<QNetworkCookie> cookies = RssSettings().getHostNameQNetworkCookies(feed_hostname); QList<QNetworkCookie> cookies = Preferences::instance()->getHostNameQNetworkCookies(feed_hostname);
qDebug("Loaded %d cookies for RSS item\n", cookies.size()); qDebug("Loaded %d cookies for RSS item\n", cookies.size());
QBtSession::instance()->downloadFromUrl(torrentLink, cookies); QBtSession::instance()->downloadFromUrl(torrentLink, cookies);
} }
@ -583,20 +577,20 @@ void RSSImp::refreshTextBrowser()
void RSSImp::saveSlidersPosition() void RSSImp::saveSlidersPosition()
{ {
// Remember sliders positions // Remember sliders positions
QIniSettings settings; Preferences* const pref = Preferences::instance();
settings.setValue("rss/splitter_h", splitter_h->saveState()); pref->setRssHSplitterState(splitter_h->saveState());
settings.setValue("rss/splitter_v", splitter_v->saveState()); pref->setRssVSplitterState(splitter_v->saveState());
qDebug("Splitters position saved"); qDebug("Splitters position saved");
} }
void RSSImp::restoreSlidersPosition() void RSSImp::restoreSlidersPosition()
{ {
QIniSettings settings; const Preferences* const pref = Preferences::instance();
QByteArray pos_h = settings.value("rss/splitter_h", QByteArray()).toByteArray(); QByteArray pos_h = pref->getRssHSplitterState();
if (!pos_h.isNull()) { if (!pos_h.isNull()) {
splitter_h->restoreState(pos_h); splitter_h->restoreState(pos_h);
} }
QByteArray pos_v = settings.value("rss/splitter_v", QByteArray()).toByteArray(); QByteArray pos_v = pref->getRssVSplitterState();
if (!pos_v.isNull()) { if (!pos_v.isNull()) {
splitter_v->restoreState(pos_v); splitter_v->restoreState(pos_v);
} }
@ -756,7 +750,7 @@ void RSSImp::on_settingsButton_clicked()
{ {
RssSettingsDlg dlg(this); RssSettingsDlg dlg(this);
if (dlg.exec()) if (dlg.exec())
updateRefreshInterval(RssSettings().getRSSRefreshInterval()); updateRefreshInterval(Preferences::instance()->getRSSRefreshInterval());
} }
void RSSImp::on_rssDownloaderBtn_clicked() void RSSImp::on_rssDownloaderBtn_clicked()

View file

@ -30,12 +30,13 @@
#include <QRegExp> #include <QRegExp>
#include <QDebug> #include <QDebug>
#include <QDir>
#include "rssdownloadrule.h" #include "rssdownloadrule.h"
#include "preferences.h" #include "preferences.h"
#include "qinisettings.h"
#include "rssfeed.h" #include "rssfeed.h"
#include "rssarticle.h" #include "rssarticle.h"
#include "fs_utils.h"
RssDownloadRule::RssDownloadRule(): m_enabled(false), m_useRegex(false) RssDownloadRule::RssDownloadRule(): m_enabled(false), m_useRegex(false)
{ {
@ -112,7 +113,7 @@ bool RssDownloadRule::operator==(const RssDownloadRule &other) const {
void RssDownloadRule::setSavePath(const QString &save_path) void RssDownloadRule::setSavePath(const QString &save_path)
{ {
if (!save_path.isEmpty() && QDir(save_path) != QDir(Preferences().getSavePath())) if (!save_path.isEmpty() && QDir(save_path) != QDir(Preferences::instance()->getSavePath()))
m_savePath = fsutils::fromNativePath(save_path); m_savePath = fsutils::fromNativePath(save_path);
else else
m_savePath = QString(); m_savePath = QString();

View file

@ -33,7 +33,7 @@
#include <QDebug> #include <QDebug>
#include "rssdownloadrulelist.h" #include "rssdownloadrulelist.h"
#include "rsssettings.h" #include "preferences.h"
#include "qinisettings.h" #include "qinisettings.h"
RssDownloadRuleList::RssDownloadRuleList() RssDownloadRuleList::RssDownloadRuleList()
@ -43,7 +43,7 @@ RssDownloadRuleList::RssDownloadRuleList()
RssDownloadRulePtr RssDownloadRuleList::findMatchingRule(const QString &feed_url, const QString &article_title) const RssDownloadRulePtr RssDownloadRuleList::findMatchingRule(const QString &feed_url, const QString &article_title) const
{ {
Q_ASSERT(RssSettings().isRssDownloadingEnabled()); Q_ASSERT(Preferences::instance()->isRssDownloadingEnabled());
QStringList rule_names = m_feedRules.value(feed_url); QStringList rule_names = m_feedRules.value(feed_url);
foreach (const QString &rule_name, rule_names) { foreach (const QString &rule_name, rule_names) {
RssDownloadRulePtr rule = m_rules[rule_name]; RssDownloadRulePtr rule = m_rules[rule_name];

View file

@ -33,7 +33,8 @@
#include "rssmanager.h" #include "rssmanager.h"
#include "qbtsession.h" #include "qbtsession.h"
#include "rssfolder.h" #include "rssfolder.h"
#include "rsssettings.h" #include "preferences.h"
#include "qinisettings.h"
#include "rssarticle.h" #include "rssarticle.h"
#include "rssparser.h" #include "rssparser.h"
#include "misc.h" #include "misc.h"
@ -116,7 +117,7 @@ void RssFeed::loadItemsFromDisk()
void RssFeed::addArticle(const RssArticlePtr& article) { void RssFeed::addArticle(const RssArticlePtr& article) {
int lbIndex = -1; int lbIndex = -1;
int max_articles = RssSettings().getRSSMaxArticlesPerFeed(); int max_articles = Preferences::instance()->getRSSMaxArticlesPerFeed();
if (!m_articles.contains(article->guid())) { if (!m_articles.contains(article->guid())) {
markAsDirty(); markAsDirty();
@ -139,7 +140,7 @@ void RssFeed::addArticle(const RssArticlePtr& article) {
} }
// Check if article was inserted at the end of the list and will break max_articles limit // Check if article was inserted at the end of the list and will break max_articles limit
if (RssSettings().isRssDownloadingEnabled()) { if (Preferences::instance()->isRssDownloadingEnabled()) {
if (lbIndex < max_articles && !article->isRead()) if (lbIndex < max_articles && !article->isRead())
downloadArticleTorrentIfMatching(m_manager->downloadRules(), article); downloadArticleTorrentIfMatching(m_manager->downloadRules(), article);
} }
@ -147,7 +148,7 @@ void RssFeed::addArticle(const RssArticlePtr& article) {
else { else {
// m_articles.contains(article->guid()) // m_articles.contains(article->guid())
// Try to download skipped articles // Try to download skipped articles
if (RssSettings().isRssDownloadingEnabled()) { if (Preferences::instance()->isRssDownloadingEnabled()) {
RssArticlePtr skipped = m_articles.value(article->guid(), RssArticlePtr()); RssArticlePtr skipped = m_articles.value(article->guid(), RssArticlePtr());
if (skipped) { if (skipped) {
if (!skipped->isRead()) if (!skipped->isRead())
@ -160,7 +161,7 @@ void RssFeed::addArticle(const RssArticlePtr& article) {
QList<QNetworkCookie> RssFeed::feedCookies() const QList<QNetworkCookie> RssFeed::feedCookies() const
{ {
QString feed_hostname = QUrl::fromEncoded(m_url.toUtf8()).host(); QString feed_hostname = QUrl::fromEncoded(m_url.toUtf8()).host();
return RssSettings().getHostNameQNetworkCookies(feed_hostname); return Preferences::instance()->getHostNameQNetworkCookies(feed_hostname);
} }
bool RssFeed::refresh() bool RssFeed::refresh()
@ -347,7 +348,7 @@ void RssFeed::handleFeedTitle(const QString& feedUrl, const QString& title)
void RssFeed::downloadArticleTorrentIfMatching(RssDownloadRuleList* rules, const RssArticlePtr& article) void RssFeed::downloadArticleTorrentIfMatching(RssDownloadRuleList* rules, const RssArticlePtr& article)
{ {
Q_ASSERT(RssSettings().isRssDownloadingEnabled()); Q_ASSERT(Preferences::instance()->isRssDownloadingEnabled());
RssDownloadRulePtr matching_rule = rules->findMatchingRule(m_url, article->title()); RssDownloadRulePtr matching_rule = rules->findMatchingRule(m_url, article->title());
if (!matching_rule) if (!matching_rule)
return; return;
@ -365,7 +366,7 @@ void RssFeed::downloadArticleTorrentIfMatching(RssDownloadRuleList* rules, const
void RssFeed::recheckRssItemsForDownload() void RssFeed::recheckRssItemsForDownload()
{ {
Q_ASSERT(RssSettings().isRssDownloadingEnabled()); Q_ASSERT(Preferences::instance()->isRssDownloadingEnabled());
RssDownloadRuleList* rules = m_manager->downloadRules(); RssDownloadRuleList* rules = m_manager->downloadRules();
foreach (const RssArticlePtr& article, m_articlesByDate) { foreach (const RssArticlePtr& article, m_articlesByDate) {
if (!article->isRead()) if (!article->isRead())

View file

@ -30,7 +30,7 @@
#include <QDebug> #include <QDebug>
#include "rssmanager.h" #include "rssmanager.h"
#include "rsssettings.h" #include "preferences.h"
#include "qbtsession.h" #include "qbtsession.h"
#include "rssfeed.h" #include "rssfeed.h"
#include "rssarticle.h" #include "rssarticle.h"
@ -46,7 +46,7 @@ RssManager::RssManager():
m_rssParser(new RssParser(this)) m_rssParser(new RssParser(this))
{ {
connect(&m_refreshTimer, SIGNAL(timeout()), SLOT(refresh())); connect(&m_refreshTimer, SIGNAL(timeout()), SLOT(refresh()));
m_refreshInterval = RssSettings().getRSSRefreshInterval(); m_refreshInterval = Preferences::instance()->getRSSRefreshInterval();
m_refreshTimer.start(m_refreshInterval * MSECS_PER_MIN); m_refreshTimer.start(m_refreshInterval * MSECS_PER_MIN);
} }
@ -81,9 +81,9 @@ void RssManager::updateRefreshInterval(uint val)
void RssManager::loadStreamList() void RssManager::loadStreamList()
{ {
RssSettings settings; const Preferences* const pref = Preferences::instance();
const QStringList streamsUrl = settings.getRssFeedsUrls(); const QStringList streamsUrl = pref->getRssFeedsUrls();
const QStringList aliases = settings.getRssFeedsAliases(); const QStringList aliases = pref->getRssFeedsAliases();
if (streamsUrl.size() != aliases.size()) { if (streamsUrl.size() != aliases.size()) {
std::cerr << "Corrupted Rss list, not loading it\n"; std::cerr << "Corrupted Rss list, not loading it\n";
return; return;
@ -155,9 +155,9 @@ void RssManager::saveStreamList() const
streamsUrl << stream_path; streamsUrl << stream_path;
aliases << stream->displayName(); aliases << stream->displayName();
} }
RssSettings settings; Preferences* const pref = Preferences::instance();
settings.setRssFeedsUrls(streamsUrl); pref->setRssFeedsUrls(streamsUrl);
settings.setRssFeedsAliases(aliases); pref->setRssFeedsAliases(aliases);
} }
RssDownloadRuleList* RssManager::downloadRules() const RssDownloadRuleList* RssManager::downloadRules() const

View file

@ -1,124 +0,0 @@
/*
* Bittorrent Client using Qt4 and libtorrent.
* Copyright (C) 2010 Christophe Dumez
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*
* Contact : chris@qbittorrent.org
*/
#ifndef RSSSETTINGS_H
#define RSSSETTINGS_H
#include <QStringList>
#include <QNetworkCookie>
#include "qinisettings.h"
class RssSettings: public QIniSettings{
public:
RssSettings() : QIniSettings("qBittorrent", "qBittorrent") {}
bool isRSSEnabled() const {
return value(QString::fromUtf8("Preferences/RSS/RSSEnabled"), false).toBool();
}
void setRSSEnabled(bool enabled) {
setValue(QString::fromUtf8("Preferences/RSS/RSSEnabled"), enabled);
}
unsigned int getRSSRefreshInterval() const {
return value(QString::fromUtf8("Preferences/RSS/RSSRefresh"), 5).toUInt();
}
void setRSSRefreshInterval(uint interval) {
setValue(QString::fromUtf8("Preferences/RSS/RSSRefresh"), interval);
}
int getRSSMaxArticlesPerFeed() const {
return value(QString::fromUtf8("Preferences/RSS/RSSMaxArticlesPerFeed"), 50).toInt();
}
void setRSSMaxArticlesPerFeed(int nb) {
setValue(QString::fromUtf8("Preferences/RSS/RSSMaxArticlesPerFeed"), nb);
}
bool isRssDownloadingEnabled() const {
return value("Preferences/RSS/RssDownloading", true).toBool();
}
void setRssDownloadingEnabled(bool b) {
setValue("Preferences/RSS/RssDownloading", b);
}
QStringList getRssFeedsUrls() const {
return value("Rss/streamList").toStringList();
}
void setRssFeedsUrls(const QStringList &rssFeeds) {
setValue("Rss/streamList", rssFeeds);
}
QStringList getRssFeedsAliases() const {
return value("Rss/streamAlias").toStringList();
}
void setRssFeedsAliases(const QStringList &rssAliases) {
setValue("Rss/streamAlias", rssAliases);
}
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>();
QByteArray raw_cookies = hosts_table.value(host_name).toByteArray();
return raw_cookies.split(':');
}
QList<QNetworkCookie> getHostNameQNetworkCookies(const QString& host_name) const {
QList<QNetworkCookie> cookies;
const QList<QByteArray> raw_cookies = getHostNameCookies(host_name);
foreach (const QByteArray& raw_cookie, raw_cookies) {
QList<QByteArray> cookie_parts = raw_cookie.split('=');
if (cookie_parts.size() == 2) {
qDebug("Loading cookie: %s = %s", cookie_parts.first().constData(), cookie_parts.last().constData());
cookies << QNetworkCookie(cookie_parts.first(), cookie_parts.last());
}
}
return cookies;
}
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) {
raw_cookies += cookie + ":";
}
if (raw_cookies.endsWith(":"))
raw_cookies.chop(1);
hosts_table.insert(host_name, raw_cookies);
setValue("Rss/hosts_cookies", hosts_table);
}
};
#endif // RSSSETTINGS_H

View file

@ -30,7 +30,7 @@
#include "rsssettingsdlg.h" #include "rsssettingsdlg.h"
#include "ui_rsssettingsdlg.h" #include "ui_rsssettingsdlg.h"
#include "rsssettings.h" #include "preferences.h"
RssSettingsDlg::RssSettingsDlg(QWidget *parent) : RssSettingsDlg::RssSettingsDlg(QWidget *parent) :
QDialog(parent), QDialog(parent),
@ -38,9 +38,9 @@ RssSettingsDlg::RssSettingsDlg(QWidget *parent) :
{ {
ui->setupUi(this); ui->setupUi(this);
// Load settings // Load settings
const RssSettings settings; const Preferences* const pref = Preferences::instance();
ui->spinRSSRefresh->setValue(settings.getRSSRefreshInterval()); ui->spinRSSRefresh->setValue(pref->getRSSRefreshInterval());
ui->spinRSSMaxArticlesPerFeed->setValue(settings.getRSSMaxArticlesPerFeed()); ui->spinRSSMaxArticlesPerFeed->setValue(pref->getRSSMaxArticlesPerFeed());
} }
RssSettingsDlg::~RssSettingsDlg() RssSettingsDlg::~RssSettingsDlg()
@ -51,7 +51,7 @@ RssSettingsDlg::~RssSettingsDlg()
void RssSettingsDlg::on_buttonBox_accepted() { void RssSettingsDlg::on_buttonBox_accepted() {
// Save settings // Save settings
RssSettings settings; Preferences* const pref = Preferences::instance();
settings.setRSSRefreshInterval(ui->spinRSSRefresh->value()); pref->setRSSRefreshInterval(ui->spinRSSRefresh->value());
settings.setRSSMaxArticlesPerFeed(ui->spinRSSMaxArticlesPerFeed->value()); pref->setRSSMaxArticlesPerFeed(ui->spinRSSMaxArticlesPerFeed->value());
} }

View file

@ -36,7 +36,6 @@
#include <QFileInfo> #include <QFileInfo>
#include <QString> #include <QString>
#include <QTemporaryFile> #include <QTemporaryFile>
#include "qinisettings.h"
#include "misc.h" #include "misc.h"
namespace { namespace {
@ -185,15 +184,15 @@ int ScanFoldersModel::findPathData(const QString &path) const {
} }
void ScanFoldersModel::makePersistent() { void ScanFoldersModel::makePersistent() {
Preferences pref; Preferences* const pref = Preferences::instance();
QStringList paths; QStringList paths;
QList<bool> downloadInFolderInfo; QList<bool> downloadInFolderInfo;
foreach (const PathData* pathData, m_pathList) { foreach (const PathData* pathData, m_pathList) {
paths << pathData->path; paths << pathData->path;
downloadInFolderInfo << pathData->downloadAtPath; downloadInFolderInfo << pathData->downloadAtPath;
} }
pref.setScanDirs(paths); pref->setScanDirs(paths);
pref.setDownloadInScanDirs(downloadInFolderInfo); pref->setDownloadInScanDirs(downloadInFolderInfo);
} }
ScanFoldersModel *ScanFoldersModel::m_instance = 0; ScanFoldersModel *ScanFoldersModel::m_instance = 0;

View file

@ -36,7 +36,6 @@
#include <QStringList> #include <QStringList>
class FileSystemWatcher; class FileSystemWatcher;
class QIniSettings;
class ScanFoldersModel : public QAbstractTableModel { class ScanFoldersModel : public QAbstractTableModel {
Q_OBJECT Q_OBJECT

View file

@ -54,7 +54,6 @@
#include "misc.h" #include "misc.h"
#include "preferences.h" #include "preferences.h"
#include "searchlistdelegate.h" #include "searchlistdelegate.h"
#include "qinisettings.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "iconprovider.h" #include "iconprovider.h"
#include "lineedit.h" #include "lineedit.h"
@ -301,12 +300,12 @@ void SearchEngine::propagateSectionResized(int index, int , int newsize) {
void SearchEngine::saveResultsColumnsWidth() { void SearchEngine::saveResultsColumnsWidth() {
if (all_tab.size() > 0) { if (all_tab.size() > 0) {
QTreeView* treeview = all_tab.first()->getCurrentTreeView(); QTreeView* treeview = all_tab.first()->getCurrentTreeView();
QIniSettings settings; Preferences* const pref = Preferences::instance();
QStringList width_list; QStringList width_list;
QStringList new_width_list; QStringList new_width_list;
short nbColumns = all_tab.first()->getCurrentSearchListModel()->columnCount(); short nbColumns = all_tab.first()->getCurrentSearchListModel()->columnCount();
QString line = settings.value("SearchResultsColsWidth", QString()).toString(); QString line = pref->getSearchColsWidth();
if (!line.isEmpty()) { if (!line.isEmpty()) {
width_list = line.split(' '); width_list = line.split(' ');
} }
@ -323,7 +322,7 @@ void SearchEngine::saveResultsColumnsWidth() {
new_width_list << QString::number(treeview->columnWidth(i)); new_width_list << QString::number(treeview->columnWidth(i));
} }
} }
settings.setValue("SearchResultsColsWidth", new_width_list.join(" ")); pref->setSearchColsWidth(new_width_list.join(" "));
} }
} }
@ -486,8 +485,7 @@ void SearchEngine::searchFinished(int exitcode,QProcess::ExitStatus) {
if (searchTimeout->isActive()) { if (searchTimeout->isActive()) {
searchTimeout->stop(); searchTimeout->stop();
} }
QIniSettings settings; bool useNotificationBalloons = Preferences::instance()->useProgramNotification();
bool useNotificationBalloons = settings.value("Preferences/General/NotificationBaloons", true).toBool();
if (useNotificationBalloons && mp_mainWindow->getCurrentTabWidget() != this) { if (useNotificationBalloons && mp_mainWindow->getCurrentTabWidget() != this) {
mp_mainWindow->showNotificationBaloon(tr("Search Engine"), tr("Search has finished")); mp_mainWindow->showNotificationBaloon(tr("Search Engine"), tr("Search has finished"));
} }

View file

@ -38,7 +38,7 @@
#include "searchlistdelegate.h" #include "searchlistdelegate.h"
#include "misc.h" #include "misc.h"
#include "searchengine.h" #include "searchengine.h"
#include "qinisettings.h" #include "preferences.h"
SearchTab::SearchTab(SearchEngine *parent) : QWidget(), parent(parent) SearchTab::SearchTab(SearchEngine *parent) : QWidget(), parent(parent)
{ {
@ -106,8 +106,7 @@ QHeaderView* SearchTab::header() const {
} }
bool SearchTab::loadColWidthResultsList() { bool SearchTab::loadColWidthResultsList() {
QIniSettings settings; QString line = Preferences::instance()->getSearchColsWidth();
QString line = settings.value("SearchResultsColsWidth", QString()).toString();
if (line.isEmpty()) if (line.isEmpty())
return false; return false;
QStringList width_list = line.split(' '); QStringList width_list = line.split(' ');

View file

@ -42,7 +42,7 @@
#include <QDebug> #include <QDebug>
#include "fs_utils.h" #include "fs_utils.h"
#include "qinisettings.h" #include "preferences.h"
class SearchCategories: public QObject, public QHash<QString, QString> { class SearchCategories: public QObject, public QHash<QString, QString> {
Q_OBJECT Q_OBJECT
@ -75,8 +75,7 @@ public:
full_name = engine_elem.elementsByTagName("name").at(0).toElement().text(); full_name = engine_elem.elementsByTagName("name").at(0).toElement().text();
url = engine_elem.elementsByTagName("url").at(0).toElement().text(); url = engine_elem.elementsByTagName("url").at(0).toElement().text();
supported_categories = engine_elem.elementsByTagName("categories").at(0).toElement().text().split(" "); supported_categories = engine_elem.elementsByTagName("categories").at(0).toElement().text().split(" ");
QIniSettings settings; QStringList disabled_engines = Preferences::instance()->getSearchEngDisabled();
QStringList disabled_engines = settings.value(QString::fromUtf8("SearchEngines/disabledEngines"), QStringList()).toStringList();
enabled = !disabled_engines.contains(name); enabled = !disabled_engines.contains(name);
} }
@ -88,14 +87,14 @@ public:
void setEnabled(bool _enabled) { void setEnabled(bool _enabled) {
enabled = _enabled; enabled = _enabled;
// Save to Hard disk // Save to Hard disk
QIniSettings settings; Preferences* const pref = Preferences::instance();
QStringList disabled_engines = settings.value(QString::fromUtf8("SearchEngines/disabledEngines"), QStringList()).toStringList(); QStringList disabled_engines = pref->getSearchEngDisabled();
if (enabled) { if (enabled) {
disabled_engines.removeAll(name); disabled_engines.removeAll(name);
} else { } else {
disabled_engines.append(name); disabled_engines.append(name);
} }
settings.setValue("SearchEngines/disabledEngines", disabled_engines); pref->setSearchEngDisabled(disabled_engines);
} }
}; };

View file

@ -100,7 +100,7 @@ Smtp::~Smtp() {
} }
void Smtp::sendMail(const QString &from, const QString &to, const QString &subject, const QString &body) { void Smtp::sendMail(const QString &from, const QString &to, const QString &subject, const QString &body) {
Preferences pref; Preferences* const pref = Preferences::instance();
QTextCodec* latin1 = QTextCodec::codecForName("latin1"); QTextCodec* latin1 = QTextCodec::codecForName("latin1");
message = ""; message = "";
message += encode_mime_header("Date", QDateTime::currentDateTime().toUTC().toString("ddd, d MMM yyyy hh:mm:ss UT"), latin1); message += encode_mime_header("Date", QDateTime::currentDateTime().toUTC().toString("ddd, d MMM yyyy hh:mm:ss UT"), latin1);
@ -122,19 +122,19 @@ void Smtp::sendMail(const QString &from, const QString &to, const QString &subje
this->from = from; this->from = from;
rcpt = to; rcpt = to;
// Authentication // Authentication
if (pref.getMailNotificationSMTPAuth()) { if (pref->getMailNotificationSMTPAuth()) {
username = pref.getMailNotificationSMTPUsername(); username = pref->getMailNotificationSMTPUsername();
password = pref.getMailNotificationSMTPPassword(); password = pref->getMailNotificationSMTPPassword();
} }
// Connect to SMTP server // Connect to SMTP server
#ifndef QT_NO_OPENSSL #ifndef QT_NO_OPENSSL
if (pref.getMailNotificationSMTPSSL()) { if (pref->getMailNotificationSMTPSSL()) {
socket->connectToHostEncrypted(pref.getMailNotificationSMTP(), DEFAULT_PORT_SSL); socket->connectToHostEncrypted(pref->getMailNotificationSMTP(), DEFAULT_PORT_SSL);
use_ssl = true; use_ssl = true;
} else { } else {
#endif #endif
socket->connectToHost(pref.getMailNotificationSMTP(), DEFAULT_PORT); socket->connectToHost(pref->getMailNotificationSMTP(), DEFAULT_PORT);
use_ssl = false; use_ssl = false;
#ifndef QT_NO_OPENSSL #ifndef QT_NO_OPENSSL
} }

View file

@ -51,7 +51,7 @@ class StatusBar: public QObject {
public: public:
StatusBar(QStatusBar *bar): m_bar(bar) { StatusBar(QStatusBar *bar): m_bar(bar) {
Preferences pref; Preferences* const pref = Preferences::instance();
connect(QBtSession::instance(), SIGNAL(alternativeSpeedsModeChanged(bool)), this, SLOT(updateAltSpeedsBtn(bool))); connect(QBtSession::instance(), SIGNAL(alternativeSpeedsModeChanged(bool)), this, SLOT(updateAltSpeedsBtn(bool)));
container = new QWidget(bar); container = new QWidget(bar);
layout = new QHBoxLayout(container); layout = new QHBoxLayout(container);
@ -80,7 +80,7 @@ public:
altSpeedsBtn->setFlat(true); altSpeedsBtn->setFlat(true);
altSpeedsBtn->setFocusPolicy(Qt::NoFocus); altSpeedsBtn->setFocusPolicy(Qt::NoFocus);
altSpeedsBtn->setCursor(Qt::PointingHandCursor); altSpeedsBtn->setCursor(Qt::PointingHandCursor);
updateAltSpeedsBtn(pref.isAltBandwidthEnabled()); updateAltSpeedsBtn(pref->isAltBandwidthEnabled());
connect(altSpeedsBtn, SIGNAL(clicked()), this, SLOT(toggleAlternativeSpeeds())); connect(altSpeedsBtn, SIGNAL(clicked()), this, SLOT(toggleAlternativeSpeeds()));
@ -128,7 +128,7 @@ public:
container->setFixedHeight(dlSpeedLbl->fontMetrics().height()+7); container->setFixedHeight(dlSpeedLbl->fontMetrics().height()+7);
bar->setFixedHeight(dlSpeedLbl->fontMetrics().height()+9); bar->setFixedHeight(dlSpeedLbl->fontMetrics().height()+9);
// Is DHT enabled // Is DHT enabled
DHTLbl->setVisible(pref.isDHTEnabled()); DHTLbl->setVisible(pref->isDHTEnabled());
refreshTimer = new QTimer(bar); refreshTimer = new QTimer(bar);
refreshStatusBar(); refreshStatusBar();
connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refreshStatusBar())); connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refreshStatusBar()));
@ -206,12 +206,12 @@ public slots:
} }
void toggleAlternativeSpeeds() { void toggleAlternativeSpeeds() {
Preferences pref; Preferences* const pref = Preferences::instance();
if (pref.isSchedulerEnabled()) { if (pref->isSchedulerEnabled()) {
pref.setSchedulerEnabled(false); pref->setSchedulerEnabled(false);
m_bar->showMessage(tr("Manual change of rate limits mode. The scheduler is disabled."), 5000); m_bar->showMessage(tr("Manual change of rate limits mode. The scheduler is disabled."), 5000);
} }
QBtSession::instance()->useAlternativeSpeedsLimit(!pref.isAltBandwidthEnabled()); QBtSession::instance()->useAlternativeSpeedsLimit(!pref->isAltBandwidthEnabled());
} }
void capDownloadSpeed() { void capDownloadSpeed() {
@ -219,18 +219,18 @@ public slots:
int cur_limit = QBtSession::instance()->getSession()->settings().download_rate_limit; int cur_limit = QBtSession::instance()->getSession()->settings().download_rate_limit;
long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), cur_limit); long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), cur_limit);
if (ok) { if (ok) {
Preferences pref; Preferences* const pref = Preferences::instance();
bool alt = pref.isAltBandwidthEnabled(); bool alt = pref->isAltBandwidthEnabled();
if (new_limit <= 0) { if (new_limit <= 0) {
qDebug("Setting global download rate limit to Unlimited"); qDebug("Setting global download rate limit to Unlimited");
QBtSession::instance()->setDownloadRateLimit(-1); QBtSession::instance()->setDownloadRateLimit(-1);
if (!alt) if (!alt)
pref.setGlobalDownloadLimit(-1); pref->setGlobalDownloadLimit(-1);
} else { } else {
qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.); qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.);
QBtSession::instance()->setDownloadRateLimit(new_limit); QBtSession::instance()->setDownloadRateLimit(new_limit);
if (!alt) if (!alt)
pref.setGlobalDownloadLimit(new_limit/1024.); pref->setGlobalDownloadLimit(new_limit/1024.);
} }
} }
} }
@ -240,18 +240,18 @@ public slots:
int cur_limit = QBtSession::instance()->getSession()->settings().upload_rate_limit; int cur_limit = QBtSession::instance()->getSession()->settings().upload_rate_limit;
long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), cur_limit); long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), cur_limit);
if (ok) { if (ok) {
Preferences pref; Preferences* const pref = Preferences::instance();
bool alt = pref.isAltBandwidthEnabled(); bool alt = pref->isAltBandwidthEnabled();
if (new_limit <= 0) { if (new_limit <= 0) {
qDebug("Setting global upload rate limit to Unlimited"); qDebug("Setting global upload rate limit to Unlimited");
QBtSession::instance()->setUploadRateLimit(-1); QBtSession::instance()->setUploadRateLimit(-1);
if (!alt) if (!alt)
Preferences().setGlobalUploadLimit(-1); Preferences::instance()->setGlobalUploadLimit(-1);
} else { } else {
qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.); qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.);
QBtSession::instance()->setUploadRateLimit(new_limit); QBtSession::instance()->setUploadRateLimit(new_limit);
if (!alt) if (!alt)
Preferences().setGlobalUploadLimit(new_limit/1024.); Preferences::instance()->setGlobalUploadLimit(new_limit/1024.);
} }
} }
} }

View file

@ -35,7 +35,7 @@
#include "torrentcreatordlg.h" #include "torrentcreatordlg.h"
#include "fs_utils.h" #include "fs_utils.h"
#include "misc.h" #include "misc.h"
#include "qinisettings.h" #include "preferences.h"
#include "torrentcreatorthread.h" #include "torrentcreatorthread.h"
#include "iconprovider.h" #include "iconprovider.h"
#include "qbtsession.h" #include "qbtsession.h"
@ -69,11 +69,11 @@ TorrentCreatorDlg::~TorrentCreatorDlg() {
} }
void TorrentCreatorDlg::on_addFolder_button_clicked() { void TorrentCreatorDlg::on_addFolder_button_clicked() {
QIniSettings settings; Preferences* const pref = Preferences::instance();
QString last_path = settings.value("CreateTorrent/last_add_path", QDir::homePath()).toString(); QString last_path = pref->getCreateTorLastAddPath();
QString dir = QFileDialog::getExistingDirectory(this, tr("Select a folder to add to the torrent"), last_path, QFileDialog::ShowDirsOnly); QString dir = QFileDialog::getExistingDirectory(this, tr("Select a folder to add to the torrent"), last_path, QFileDialog::ShowDirsOnly);
if (!dir.isEmpty()) { if (!dir.isEmpty()) {
settings.setValue("CreateTorrent/last_add_path", dir); pref->setCreateTorLastAddPath(dir);
textInputPath->setText(fsutils::toNativePath(dir)); textInputPath->setText(fsutils::toNativePath(dir));
// Update piece size // Update piece size
if (checkAutoPieceSize->isChecked()) if (checkAutoPieceSize->isChecked())
@ -82,11 +82,11 @@ void TorrentCreatorDlg::on_addFolder_button_clicked() {
} }
void TorrentCreatorDlg::on_addFile_button_clicked() { void TorrentCreatorDlg::on_addFile_button_clicked() {
QIniSettings settings; Preferences* const pref = Preferences::instance();
QString last_path = settings.value("CreateTorrent/last_add_path", QDir::homePath()).toString(); QString last_path = pref->getCreateTorLastAddPath();
QString file = QFileDialog::getOpenFileName(this, tr("Select a file to add to the torrent"), last_path); QString file = QFileDialog::getOpenFileName(this, tr("Select a file to add to the torrent"), last_path);
if (!file.isEmpty()) { if (!file.isEmpty()) {
settings.setValue("CreateTorrent/last_add_path", fsutils::branchPath(file)); pref->setCreateTorLastAddPath(fsutils::branchPath(file));
textInputPath->setText(fsutils::toNativePath(file)); textInputPath->setText(fsutils::toNativePath(file));
// Update piece size // Update piece size
if (checkAutoPieceSize->isChecked()) if (checkAutoPieceSize->isChecked())
@ -111,12 +111,12 @@ void TorrentCreatorDlg::on_createButton_clicked() {
if (!trackers_list->toPlainText().trimmed().isEmpty()) if (!trackers_list->toPlainText().trimmed().isEmpty())
saveTrackerList(); saveTrackerList();
QIniSettings settings; Preferences* const pref = Preferences::instance();
QString last_path = settings.value("CreateTorrent/last_save_path", QDir::homePath()).toString(); QString last_path = pref->getCreateTorLastSavePath();
QString destination = QFileDialog::getSaveFileName(this, tr("Select destination torrent file"), last_path, tr("Torrent Files")+QString::fromUtf8(" (*.torrent)")); QString destination = QFileDialog::getSaveFileName(this, tr("Select destination torrent file"), last_path, tr("Torrent Files")+QString::fromUtf8(" (*.torrent)"));
if (!destination.isEmpty()) { if (!destination.isEmpty()) {
settings.setValue("CreateTorrent/last_save_path", fsutils::branchPath(destination)); pref->setCreateTorLastSavePath(fsutils::branchPath(destination));
if (!destination.toUpper().endsWith(".TORRENT")) if (!destination.toUpper().endsWith(".TORRENT"))
destination += QString::fromUtf8(".torrent"); destination += QString::fromUtf8(".torrent");
} else { } else {
@ -243,28 +243,26 @@ void TorrentCreatorDlg::updateOptimalPieceSize()
void TorrentCreatorDlg::saveTrackerList() void TorrentCreatorDlg::saveTrackerList()
{ {
QIniSettings settings; Preferences::instance()->setCreateTorTrackers(trackers_list->toPlainText());
settings.setValue("CreateTorrent/TrackerList", trackers_list->toPlainText());
} }
void TorrentCreatorDlg::loadTrackerList() void TorrentCreatorDlg::loadTrackerList()
{ {
QIniSettings settings; trackers_list->setPlainText(Preferences::instance()->getCreateTorTrackers());
trackers_list->setPlainText(settings.value("CreateTorrent/TrackerList", "").toString());
} }
void TorrentCreatorDlg::saveSettings() void TorrentCreatorDlg::saveSettings()
{ {
QIniSettings settings; Preferences* const pref = Preferences::instance();
settings.setValue("CreateTorrent/dimensions", saveGeometry()); pref->setCreateTorGeometry(saveGeometry());
settings.setValue("CreateTorrent/IgnoreRatio", checkIgnoreShareLimits->isChecked()); pref->setCreateTorIgnoreRatio(checkIgnoreShareLimits->isChecked());
} }
void TorrentCreatorDlg::loadSettings() void TorrentCreatorDlg::loadSettings()
{ {
QIniSettings settings; const Preferences* const pref = Preferences::instance();
restoreGeometry(settings.value("CreateTorrent/dimensions").toByteArray()); restoreGeometry(pref->getCreateTorGeometry());
checkIgnoreShareLimits->setChecked(settings.value("CreateTorrent/IgnoreRatio").toBool()); checkIgnoreShareLimits->setChecked(pref->getCreateTorIgnoreRatio());
} }
void TorrentCreatorDlg::closeEvent(QCloseEvent *event) void TorrentCreatorDlg::closeEvent(QCloseEvent *event)

View file

@ -34,7 +34,7 @@
#include "torrentimportdlg.h" #include "torrentimportdlg.h"
#include "ui_torrentimportdlg.h" #include "ui_torrentimportdlg.h"
#include "qinisettings.h" #include "preferences.h"
#include "qbtsession.h" #include "qbtsession.h"
#include "torrentpersistentdata.h" #include "torrentpersistentdata.h"
#include "iconprovider.h" #include "iconprovider.h"
@ -62,8 +62,7 @@ TorrentImportDlg::~TorrentImportDlg()
void TorrentImportDlg::on_browseTorrentBtn_clicked() void TorrentImportDlg::on_browseTorrentBtn_clicked()
{ {
QIniSettings settings; const QString default_dir = Preferences::instance()->getMainLastDir();
const QString default_dir = settings.value(QString::fromUtf8("MainWindowLastDir"), QDir::homePath()).toString();
// Ask for a torrent file // Ask for a torrent file
m_torrentPath = QFileDialog::getOpenFileName(this, tr("Torrent file to import"), default_dir, tr("Torrent files (*.torrent)")); m_torrentPath = QFileDialog::getOpenFileName(this, tr("Torrent file to import"), default_dir, tr("Torrent files (*.torrent)"));
if (!m_torrentPath.isEmpty()) { if (!m_torrentPath.isEmpty()) {
@ -75,8 +74,7 @@ void TorrentImportDlg::on_browseTorrentBtn_clicked()
void TorrentImportDlg::on_browseContentBtn_clicked() void TorrentImportDlg::on_browseContentBtn_clicked()
{ {
QIniSettings settings; const QString default_dir = Preferences::instance()->getTorImportLastContentDir();
const QString default_dir = settings.value(QString::fromUtf8("TorrentImport/LastContentDir"), QDir::homePath()).toString();
if (t->num_files() == 1) { if (t->num_files() == 1) {
// Single file torrent // Single file torrent
const QString file_name = fsutils::fileName(misc::toQStringU(t->file_at(0).path)); const QString file_name = fsutils::fileName(misc::toQStringU(t->file_at(0).path));
@ -197,9 +195,9 @@ void TorrentImportDlg::importTorrent()
qDebug("Adding the torrent to the session..."); qDebug("Adding the torrent to the session...");
QBtSession::instance()->addTorrent(torrent_path); QBtSession::instance()->addTorrent(torrent_path);
// Remember the last opened folder // Remember the last opened folder
QIniSettings settings; Preferences* const pref = Preferences::instance();
settings.setValue(QString::fromUtf8("MainWindowLastDir"), fsutils::fromNativePath(torrent_path)); pref->setMainLastDir(fsutils::fromNativePath(torrent_path));
settings.setValue("TorrentImport/LastContentDir", fsutils::fromNativePath(content_path)); pref->setTorImportLastContentDir(fsutils::fromNativePath(content_path));
return; return;
} }
qDebug() << Q_FUNC_INFO << "EXIT"; qDebug() << Q_FUNC_INFO << "EXIT";
@ -253,14 +251,12 @@ bool TorrentImportDlg::skipFileChecking() const
void TorrentImportDlg::loadSettings() void TorrentImportDlg::loadSettings()
{ {
QIniSettings settings; restoreGeometry(Preferences::instance()->getTorImportGeometry());
restoreGeometry(settings.value("TorrentImportDlg/dimensions").toByteArray());
} }
void TorrentImportDlg::saveSettings() void TorrentImportDlg::saveSettings()
{ {
QIniSettings settings; Preferences::instance()->setTorImportGeometry(saveGeometry());
settings.setValue("TorrentImportDlg/dimensions", saveGeometry());
} }
void TorrentImportDlg::closeEvent(QCloseEvent *event) void TorrentImportDlg::closeEvent(QCloseEvent *event)

View file

@ -42,12 +42,14 @@
#include "qtracker.h" #include "qtracker.h"
#include "preferences.h" #include "preferences.h"
#include <vector>
using namespace libtorrent; using namespace libtorrent;
QTracker::QTracker(QObject *parent) : QTracker::QTracker(QObject *parent) :
QTcpServer(parent) QTcpServer(parent)
{ {
Q_ASSERT(Preferences().isTrackerEnabled()); Q_ASSERT(Preferences::instance()->isTrackerEnabled());
connect(this, SIGNAL(newConnection()), this, SLOT(handlePeerConnection())); connect(this, SIGNAL(newConnection()), this, SLOT(handlePeerConnection()));
} }
@ -71,7 +73,7 @@ void QTracker::handlePeerConnection()
bool QTracker::start() bool QTracker::start()
{ {
const int listen_port = Preferences().getTrackerPort(); const int listen_port = Preferences::instance()->getTrackerPort();
// //
if (isListening()) { if (isListening()) {
if (serverPort() == listen_port) { if (serverPort() == listen_port) {

View file

@ -46,7 +46,6 @@
#include "transferlistdelegate.h" #include "transferlistdelegate.h"
#include "transferlistwidget.h" #include "transferlistwidget.h"
#include "preferences.h" #include "preferences.h"
#include "qinisettings.h"
#include "torrentmodel.h" #include "torrentmodel.h"
#include "iconprovider.h" #include "iconprovider.h"
#include "fs_utils.h" #include "fs_utils.h"
@ -281,17 +280,14 @@ public:
} }
void saveSettings() const { void saveSettings() const {
QIniSettings settings; Preferences* const pref = Preferences::instance();
settings.beginGroup(QString::fromUtf8("TransferListFilters")); pref->setTransSelFilter(statusFilters->currentRow());
settings.setValue("selectedFilterIndex", QVariant(statusFilters->currentRow())); pref->setTorrentLabels(customLabels.keys());
//settings.setValue("selectedLabelIndex", QVariant(labelFilters->currentRow()));
settings.setValue("customLabels", QVariant(customLabels.keys()));
} }
void loadSettings() { void loadSettings() {
QIniSettings settings; statusFilters->setCurrentRow(Preferences::instance()->getTransSelFilter());
statusFilters->setCurrentRow(settings.value("TransferListFilters/selectedFilterIndex", 0).toInt()); const QStringList label_list = Preferences::instance()->getTorrentLabels();
const QStringList label_list = Preferences().getTorrentLabels();
foreach (const QString &label, label_list) { foreach (const QString &label, label_list) {
customLabels.insert(label, 0); customLabels.insert(label, 0);
qDebug("Creating label QListWidgetItem: %s", qPrintable(label)); qDebug("Creating label QListWidgetItem: %s", qPrintable(label));
@ -330,7 +326,7 @@ protected slots:
newLabel->setData(Qt::DecorationRole, IconProvider::instance()->getIcon("inode-directory")); newLabel->setData(Qt::DecorationRole, IconProvider::instance()->getIcon("inode-directory"));
labelFilters->addItem(newLabel); labelFilters->addItem(newLabel);
customLabels.insert(label, 0); customLabels.insert(label, 0);
Preferences().addTorrentLabel(label); Preferences::instance()->addTorrentLabel(label);
} }
void showLabelMenu(QPoint) { void showLabelMenu(QPoint) {
@ -397,7 +393,7 @@ protected slots:
// Un display filter // Un display filter
delete labelFilters->takeItem(row); delete labelFilters->takeItem(row);
// Save custom labels to remember it was deleted // Save custom labels to remember it was deleted
Preferences().removeTorrentLabel(label); Preferences::instance()->removeTorrentLabel(label);
} }
void applyLabelFilter(int row) { void applyLabelFilter(int row) {

View file

@ -57,7 +57,6 @@
#include "torrentmodel.h" #include "torrentmodel.h"
#include "deletionconfirmationdlg.h" #include "deletionconfirmationdlg.h"
#include "propertieswidget.h" #include "propertieswidget.h"
#include "qinisettings.h"
#include "iconprovider.h" #include "iconprovider.h"
#include "fs_utils.h" #include "fs_utils.h"
#include "autoexpandabledialog.h" #include "autoexpandabledialog.h"
@ -208,12 +207,6 @@ inline QModelIndex TransferListWidget::mapFromSource(const QModelIndex &index) c
return nameFilterModel->mapFromSource(statusFilterModel->mapFromSource(labelFilterModel->mapFromSource(index))); return nameFilterModel->mapFromSource(statusFilterModel->mapFromSource(labelFilterModel->mapFromSource(index)));
} }
QStringList TransferListWidget::getCustomLabels() const {
QIniSettings settings;
return settings.value("TransferListFilters/customLabels", QStringList()).toStringList();
}
void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) { void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) {
const int row = mapToSource(index).row(); const int row = mapToSource(index).row();
const QString hash = getHashFromRow(row); const QString hash = getHashFromRow(row);
@ -221,9 +214,9 @@ void TransferListWidget::torrentDoubleClicked(const QModelIndex& index) {
if (!h.is_valid()) return; if (!h.is_valid()) return;
int action; int action;
if (h.is_seed()) { if (h.is_seed()) {
action = Preferences().getActionOnDblClOnTorrentFn(); action = Preferences::instance()->getActionOnDblClOnTorrentFn();
} else { } else {
action = Preferences().getActionOnDblClOnTorrentDl(); action = Preferences::instance()->getActionOnDblClOnTorrentDl();
} }
switch(action) { switch(action) {
@ -318,7 +311,7 @@ void TransferListWidget::deleteSelectedTorrents() {
if (hashes.empty()) return; if (hashes.empty()) return;
QTorrentHandle torrent = BTSession->getTorrentHandle(hashes[0]); QTorrentHandle torrent = BTSession->getTorrentHandle(hashes[0]);
bool delete_local_files = false; bool delete_local_files = false;
if (Preferences().confirmTorrentDeletion() && if (Preferences::instance()->confirmTorrentDeletion() &&
!DeletionConfirmationDlg::askForDeletionConfirmation(delete_local_files, hashes.size(), torrent.name())) !DeletionConfirmationDlg::askForDeletionConfirmation(delete_local_files, hashes.size(), torrent.name()))
return; return;
foreach (const QString &hash, hashes) { foreach (const QString &hash, hashes) {
@ -330,7 +323,7 @@ void TransferListWidget::deleteVisibleTorrents() {
if (nameFilterModel->rowCount() <= 0) return; if (nameFilterModel->rowCount() <= 0) return;
QTorrentHandle torrent = BTSession->getTorrentHandle(getHashFromRow(0)); QTorrentHandle torrent = BTSession->getTorrentHandle(getHashFromRow(0));
bool delete_local_files = false; bool delete_local_files = false;
if (Preferences().confirmTorrentDeletion() && if (Preferences::instance()->confirmTorrentDeletion() &&
!DeletionConfirmationDlg::askForDeletionConfirmation(delete_local_files, nameFilterModel->rowCount(), torrent.name())) !DeletionConfirmationDlg::askForDeletionConfirmation(delete_local_files, nameFilterModel->rowCount(), torrent.name()))
return; return;
QStringList hashes; QStringList hashes;
@ -479,7 +472,7 @@ void TransferListWidget::setDlLimitSelectedTorrents() {
int default_limit = -1; int default_limit = -1;
if (all_same_limit) if (all_same_limit)
default_limit = selected_torrents.first().download_limit(); default_limit = selected_torrents.first().download_limit();
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Download Speed Limiting"), default_limit, Preferences().getGlobalDownloadLimit()*1024.); const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Download Speed Limiting"), default_limit, Preferences::instance()->getGlobalDownloadLimit()*1024.);
if (ok) { if (ok) {
foreach (const QTorrentHandle &h, selected_torrents) { foreach (const QTorrentHandle &h, selected_torrents) {
qDebug("Applying download speed limit of %ld Kb/s to torrent %s", (long)(new_limit/1024.), qPrintable(h.hash())); qDebug("Applying download speed limit of %ld Kb/s to torrent %s", (long)(new_limit/1024.), qPrintable(h.hash()));
@ -512,7 +505,7 @@ void TransferListWidget::setUpLimitSelectedTorrents() {
int default_limit = -1; int default_limit = -1;
if (all_same_limit) if (all_same_limit)
default_limit = selected_torrents.first().upload_limit(); default_limit = selected_torrents.first().upload_limit();
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Upload Speed Limiting"), default_limit, Preferences().getGlobalUploadLimit()*1024.); const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Torrent Upload Speed Limiting"), default_limit, Preferences::instance()->getGlobalUploadLimit()*1024.);
if (ok) { if (ok) {
foreach (const QTorrentHandle &h, selected_torrents) { foreach (const QTorrentHandle &h, selected_torrents) {
qDebug("Applying upload speed limit of %ld Kb/s to torrent %s", (long)(new_limit/1024.), qPrintable(h.hash())); qDebug("Applying upload speed limit of %ld Kb/s to torrent %s", (long)(new_limit/1024.), qPrintable(h.hash()));
@ -811,7 +804,7 @@ void TransferListWidget::displayListMenu(const QPoint&) {
if (selectedIndexes.size() == 1) if (selectedIndexes.size() == 1)
listMenu.addAction(&actionRename); listMenu.addAction(&actionRename);
// Label Menu // Label Menu
QStringList customLabels = getCustomLabels(); QStringList customLabels = Preferences::instance()->getTorrentLabels();
customLabels.sort(); customLabels.sort();
QList<QAction*> labelActions; QList<QAction*> labelActions;
QMenu *labelMenu = listMenu.addMenu(IconProvider::instance()->getIcon("view-categories"), tr("Label")); QMenu *labelMenu = listMenu.addMenu(IconProvider::instance()->getIcon("view-categories"), tr("Label"));
@ -949,14 +942,12 @@ void TransferListWidget::applyStatusFilter(int f) {
void TransferListWidget::saveSettings() void TransferListWidget::saveSettings()
{ {
QIniSettings settings; Preferences::instance()->setTransHeaderState(header()->saveState());
settings.setValue("TransferList/HeaderState", header()->saveState());
} }
bool TransferListWidget::loadSettings() bool TransferListWidget::loadSettings()
{ {
QIniSettings settings; bool ok = header()->restoreState(Preferences::instance()->getTransHeaderState());
bool ok = header()->restoreState(settings.value("TransferList/HeaderState").toByteArray());
if (!ok) { if (!ok) {
header()->resizeSection(0, 200); // Default header()->resizeSection(0, 200); // Default
} }

View file

@ -92,7 +92,6 @@ protected:
QString getHashFromRow(int row) const; QString getHashFromRow(int row) const;
QModelIndex mapToSource(const QModelIndex &index) const; QModelIndex mapToSource(const QModelIndex &index) const;
QModelIndex mapFromSource(const QModelIndex &index) const; QModelIndex mapFromSource(const QModelIndex &index) const;
QStringList getCustomLabels() const;
void saveSettings(); void saveSettings();
bool loadSettings(); bool loadSettings();
QStringList getSelectedTorrentsHashes() const; QStringList getSelectedTorrentsHashes() const;

View file

@ -42,7 +42,7 @@ UpDownRatioDlg::UpDownRatioDlg(bool useDefault, qreal initialValue,
ui->useDefaultButton->setChecked(true); ui->useDefaultButton->setChecked(true);
} else if (initialValue == -1) { } else if (initialValue == -1) {
ui->noLimitButton->setChecked(true); ui->noLimitButton->setChecked(true);
initialValue = Preferences().getGlobalMaxRatio(); initialValue = Preferences::instance()->getGlobalMaxRatio();
} else { } else {
ui->torrentLimitButton->setChecked(true); ui->torrentLimitButton->setChecked(true);
} }