1
0
mirror of https://github.com/d47081/qBittorrent.git synced 2025-01-25 14:04:23 +00:00

Importance code refactoring related to the "preferences" code - Greatly improves performance

This commit is contained in:
Christophe Dumez 2010-11-16 20:34:31 +00:00
parent a640b08414
commit e5032a52c4
26 changed files with 976 additions and 1142 deletions

View File

@ -58,51 +58,53 @@ public:
public slots: public slots:
void saveAdvancedSettings() { void saveAdvancedSettings() {
Preferences pref;
// Disk write cache // Disk write cache
Preferences::setDiskCacheSize(spin_cache->value()); pref.setDiskCacheSize(spin_cache->value());
// Outgoing ports // Outgoing ports
Preferences::setOutgoingPortsMin(outgoing_ports_min->value()); pref.setOutgoingPortsMin(outgoing_ports_min->value());
Preferences::setOutgoingPortsMax(outgoing_ports_max->value()); pref.setOutgoingPortsMax(outgoing_ports_max->value());
// Ignore limits on LAN // Ignore limits on LAN
Preferences::ignoreLimitsOnLAN(cb_ignore_limits_lan->isChecked()); pref.ignoreLimitsOnLAN(cb_ignore_limits_lan->isChecked());
// Include protocol overhead in transfer limits // Include protocol overhead in transfer limits
Preferences::includeOverheadInLimits(cb_count_overhead->isChecked()); pref.includeOverheadInLimits(cb_count_overhead->isChecked());
// Recheck torrents on completion // Recheck torrents on completion
Preferences::recheckTorrentsOnCompletion(cb_recheck_completed->isChecked()); pref.recheckTorrentsOnCompletion(cb_recheck_completed->isChecked());
// Transfer list refresh interval // Transfer list refresh interval
Preferences::setRefreshInterval(spin_list_refresh->value()); pref.setRefreshInterval(spin_list_refresh->value());
// Peer resolution // Peer resolution
Preferences::resolvePeerCountries(cb_resolve_countries->isChecked()); pref.resolvePeerCountries(cb_resolve_countries->isChecked());
Preferences::resolvePeerHostNames(cb_resolve_hosts->isChecked()); pref.resolvePeerHostNames(cb_resolve_hosts->isChecked());
// Max Half-Open connections // Max Half-Open connections
Preferences::setMaxHalfOpenConnections(spin_maxhalfopen->value()); pref.setMaxHalfOpenConnections(spin_maxhalfopen->value());
#if LIBTORRENT_VERSION_MINOR > 14 #if LIBTORRENT_VERSION_MINOR > 14
// Super seeding // Super seeding
Preferences::enableSuperSeeding(cb_super_seeding->isChecked()); pref.enableSuperSeeding(cb_super_seeding->isChecked());
#endif #endif
// Network interface // Network interface
if(combo_iface->currentIndex() == 0) { if(combo_iface->currentIndex() == 0) {
// All interfaces (default) // All interfaces (default)
Preferences::setNetworkInterface(QString::null); pref.setNetworkInterface(QString::null);
} else { } else {
Preferences::setNetworkInterface(combo_iface->currentText()); pref.setNetworkInterface(combo_iface->currentText());
} }
// Program notification // Program notification
Preferences::useProgramNotification(cb_program_notifications->isChecked()); pref.useProgramNotification(cb_program_notifications->isChecked());
// Tracker // Tracker
Preferences::setTrackerEnabled(cb_tracker_status->isChecked()); pref.setTrackerEnabled(cb_tracker_status->isChecked());
Preferences::setTrackerPort(spin_tracker_port->value()); pref.setTrackerPort(spin_tracker_port->value());
} }
protected slots: protected slots:
void loadAdvancedSettings() { void loadAdvancedSettings() {
const Preferences pref;
// Disk write cache // Disk write cache
setItem(DISK_CACHE, PROPERTY, new QTableWidgetItem(tr("Disk write cache size"))); setItem(DISK_CACHE, PROPERTY, new QTableWidgetItem(tr("Disk write cache size")));
spin_cache = new QSpinBox(); spin_cache = new QSpinBox();
connect(spin_cache, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged())); connect(spin_cache, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged()));
spin_cache->setMinimum(1); spin_cache->setMinimum(1);
spin_cache->setMaximum(200); spin_cache->setMaximum(200);
spin_cache->setValue(Preferences::diskCacheSize()); spin_cache->setValue(pref.diskCacheSize());
spin_cache->setSuffix(tr(" MiB")); spin_cache->setSuffix(tr(" MiB"));
setCellWidget(DISK_CACHE, VALUE, spin_cache); setCellWidget(DISK_CACHE, VALUE, spin_cache);
// Outgoing port Min // Outgoing port Min
@ -111,7 +113,7 @@ protected slots:
connect(outgoing_ports_min, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged())); connect(outgoing_ports_min, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged()));
outgoing_ports_min->setMinimum(0); outgoing_ports_min->setMinimum(0);
outgoing_ports_min->setMaximum(65535); outgoing_ports_min->setMaximum(65535);
outgoing_ports_min->setValue(Preferences::outgoingPortsMin()); outgoing_ports_min->setValue(pref.outgoingPortsMin());
setCellWidget(OUTGOING_PORT_MIN, VALUE, outgoing_ports_min); setCellWidget(OUTGOING_PORT_MIN, VALUE, outgoing_ports_min);
// Outgoing port Min // Outgoing port Min
setItem(OUTGOING_PORT_MAX, PROPERTY, new QTableWidgetItem(tr("Outgoing ports (Max) [0: Disabled]"))); setItem(OUTGOING_PORT_MAX, PROPERTY, new QTableWidgetItem(tr("Outgoing ports (Max) [0: Disabled]")));
@ -119,25 +121,25 @@ protected slots:
connect(outgoing_ports_max, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged())); connect(outgoing_ports_max, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged()));
outgoing_ports_max->setMinimum(0); outgoing_ports_max->setMinimum(0);
outgoing_ports_max->setMaximum(65535); outgoing_ports_max->setMaximum(65535);
outgoing_ports_max->setValue(Preferences::outgoingPortsMax()); outgoing_ports_max->setValue(pref.outgoingPortsMax());
setCellWidget(OUTGOING_PORT_MAX, VALUE, outgoing_ports_max); setCellWidget(OUTGOING_PORT_MAX, VALUE, outgoing_ports_max);
// Ignore transfer limits on local network // Ignore transfer limits on local network
setItem(IGNORE_LIMIT_LAN, PROPERTY, new QTableWidgetItem(tr("Ignore transfer limits on local network"))); setItem(IGNORE_LIMIT_LAN, PROPERTY, new QTableWidgetItem(tr("Ignore transfer limits on local network")));
cb_ignore_limits_lan = new QCheckBox(); cb_ignore_limits_lan = new QCheckBox();
connect(cb_ignore_limits_lan, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged())); connect(cb_ignore_limits_lan, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged()));
cb_ignore_limits_lan->setChecked(Preferences::ignoreLimitsOnLAN()); cb_ignore_limits_lan->setChecked(pref.ignoreLimitsOnLAN());
setCellWidget(IGNORE_LIMIT_LAN, VALUE, cb_ignore_limits_lan); setCellWidget(IGNORE_LIMIT_LAN, VALUE, cb_ignore_limits_lan);
// Consider protocol overhead in transfer limits // Consider protocol overhead in transfer limits
setItem(COUNT_OVERHEAD, PROPERTY, new QTableWidgetItem(tr("Include TCP/IP overhead in transfer limits"))); setItem(COUNT_OVERHEAD, PROPERTY, new QTableWidgetItem(tr("Include TCP/IP overhead in transfer limits")));
cb_count_overhead = new QCheckBox(); cb_count_overhead = new QCheckBox();
connect(cb_count_overhead, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged())); connect(cb_count_overhead, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged()));
cb_count_overhead->setChecked(Preferences::includeOverheadInLimits()); cb_count_overhead->setChecked(pref.includeOverheadInLimits());
setCellWidget(COUNT_OVERHEAD, VALUE, cb_count_overhead); setCellWidget(COUNT_OVERHEAD, VALUE, cb_count_overhead);
// Recheck completed torrents // Recheck completed torrents
setItem(RECHECK_COMPLETED, PROPERTY, new QTableWidgetItem(tr("Recheck torrents on completion"))); setItem(RECHECK_COMPLETED, PROPERTY, new QTableWidgetItem(tr("Recheck torrents on completion")));
cb_recheck_completed = new QCheckBox(); cb_recheck_completed = new QCheckBox();
connect(cb_recheck_completed, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged())); connect(cb_recheck_completed, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged()));
cb_recheck_completed->setChecked(Preferences::recheckTorrentsOnCompletion()); cb_recheck_completed->setChecked(pref.recheckTorrentsOnCompletion());
setCellWidget(RECHECK_COMPLETED, VALUE, cb_recheck_completed); setCellWidget(RECHECK_COMPLETED, VALUE, cb_recheck_completed);
// Transfer list refresh interval // Transfer list refresh interval
setItem(LIST_REFRESH, PROPERTY, new QTableWidgetItem(tr("Transfer list refresh interval"))); setItem(LIST_REFRESH, PROPERTY, new QTableWidgetItem(tr("Transfer list refresh interval")));
@ -145,20 +147,20 @@ protected slots:
connect(spin_list_refresh, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged())); connect(spin_list_refresh, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged()));
spin_list_refresh->setMinimum(30); spin_list_refresh->setMinimum(30);
spin_list_refresh->setMaximum(99999); spin_list_refresh->setMaximum(99999);
spin_list_refresh->setValue(Preferences::getRefreshInterval()); spin_list_refresh->setValue(pref.getRefreshInterval());
spin_list_refresh->setSuffix(tr(" ms", " milliseconds")); spin_list_refresh->setSuffix(tr(" ms", " milliseconds"));
setCellWidget(LIST_REFRESH, VALUE, spin_list_refresh); setCellWidget(LIST_REFRESH, VALUE, spin_list_refresh);
// Resolve Peer countries // Resolve Peer countries
setItem(RESOLVE_COUNTRIES, PROPERTY, new QTableWidgetItem(tr("Resolve peer countries (GeoIP)"))); setItem(RESOLVE_COUNTRIES, PROPERTY, new QTableWidgetItem(tr("Resolve peer countries (GeoIP)")));
cb_resolve_countries = new QCheckBox(); cb_resolve_countries = new QCheckBox();
connect(cb_resolve_countries, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged())); connect(cb_resolve_countries, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged()));
cb_resolve_countries->setChecked(Preferences::resolvePeerCountries()); cb_resolve_countries->setChecked(pref.resolvePeerCountries());
setCellWidget(RESOLVE_COUNTRIES, VALUE, cb_resolve_countries); setCellWidget(RESOLVE_COUNTRIES, VALUE, cb_resolve_countries);
// Resolve peer hosts // Resolve peer hosts
setItem(RESOLVE_HOSTS, PROPERTY, new QTableWidgetItem(tr("Resolve peer host names"))); setItem(RESOLVE_HOSTS, PROPERTY, new QTableWidgetItem(tr("Resolve peer host names")));
cb_resolve_hosts = new QCheckBox(); cb_resolve_hosts = new QCheckBox();
connect(cb_resolve_hosts, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged())); connect(cb_resolve_hosts, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged()));
cb_resolve_hosts->setChecked(Preferences::resolvePeerHostNames()); cb_resolve_hosts->setChecked(pref.resolvePeerHostNames());
setCellWidget(RESOLVE_HOSTS, VALUE, cb_resolve_hosts); setCellWidget(RESOLVE_HOSTS, VALUE, cb_resolve_hosts);
// Max Half Open connections // Max Half Open connections
setItem(MAX_HALF_OPEN, PROPERTY, new QTableWidgetItem(tr("Maximum number of half-open connections [0: Disabled]"))); setItem(MAX_HALF_OPEN, PROPERTY, new QTableWidgetItem(tr("Maximum number of half-open connections [0: Disabled]")));
@ -166,14 +168,14 @@ protected slots:
connect(spin_maxhalfopen, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged())); connect(spin_maxhalfopen, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged()));
spin_maxhalfopen->setMinimum(0); spin_maxhalfopen->setMinimum(0);
spin_maxhalfopen->setMaximum(99999); spin_maxhalfopen->setMaximum(99999);
spin_maxhalfopen->setValue(Preferences::getMaxHalfOpenConnections()); spin_maxhalfopen->setValue(pref.getMaxHalfOpenConnections());
setCellWidget(MAX_HALF_OPEN, VALUE, spin_maxhalfopen); setCellWidget(MAX_HALF_OPEN, VALUE, spin_maxhalfopen);
// Super seeding // Super seeding
setItem(SUPER_SEEDING, PROPERTY, new QTableWidgetItem(tr("Strict super seeding"))); setItem(SUPER_SEEDING, PROPERTY, new QTableWidgetItem(tr("Strict super seeding")));
cb_super_seeding = new QCheckBox(); cb_super_seeding = new QCheckBox();
connect(cb_super_seeding, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged())); connect(cb_super_seeding, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged()));
#if LIBTORRENT_VERSION_MINOR > 14 #if LIBTORRENT_VERSION_MINOR > 14
cb_super_seeding->setChecked(Preferences::isSuperSeedingEnabled()); cb_super_seeding->setChecked(pref.isSuperSeedingEnabled());
#else #else
cb_super_seeding->setEnabled(false); cb_super_seeding->setEnabled(false);
#endif #endif
@ -182,7 +184,7 @@ protected slots:
setItem(NETWORK_IFACE, PROPERTY, new QTableWidgetItem(tr("Network Interface (requires restart)"))); setItem(NETWORK_IFACE, PROPERTY, new QTableWidgetItem(tr("Network Interface (requires restart)")));
combo_iface = new QComboBox; combo_iface = new QComboBox;
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 = Preferences::getNetworkInterface(); const QString current_iface = pref.getNetworkInterface();
int i = 1; int i = 1;
foreach(const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) { foreach(const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) {
if(iface.name() == "lo") continue; if(iface.name() == "lo") continue;
@ -197,13 +199,13 @@ protected slots:
setItem(PROGRAM_NOTIFICATIONS, PROPERTY, new QTableWidgetItem(tr("Display program notification balloons"))); setItem(PROGRAM_NOTIFICATIONS, PROPERTY, new QTableWidgetItem(tr("Display program notification balloons")));
cb_program_notifications = new QCheckBox(); cb_program_notifications = new QCheckBox();
connect(cb_program_notifications, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged())); connect(cb_program_notifications, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged()));
cb_program_notifications->setChecked(Preferences::useProgramNotification()); cb_program_notifications->setChecked(pref.useProgramNotification());
setCellWidget(PROGRAM_NOTIFICATIONS, VALUE, cb_program_notifications); setCellWidget(PROGRAM_NOTIFICATIONS, VALUE, cb_program_notifications);
// Tracker State // Tracker State
setItem(TRACKER_STATUS, PROPERTY, new QTableWidgetItem(tr("Enable embedded tracker"))); setItem(TRACKER_STATUS, PROPERTY, new QTableWidgetItem(tr("Enable embedded tracker")));
cb_tracker_status = new QCheckBox(); cb_tracker_status = new QCheckBox();
connect(cb_tracker_status, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged())); connect(cb_tracker_status, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged()));
cb_tracker_status->setChecked(Preferences::isTrackerEnabled()); cb_tracker_status->setChecked(pref.isTrackerEnabled());
setCellWidget(TRACKER_STATUS, VALUE, cb_tracker_status); setCellWidget(TRACKER_STATUS, VALUE, cb_tracker_status);
// Tracker port // Tracker port
setItem(TRACKER_PORT, PROPERTY, new QTableWidgetItem(tr("Embedded tracker port"))); setItem(TRACKER_PORT, PROPERTY, new QTableWidgetItem(tr("Embedded tracker port")));
@ -211,7 +213,7 @@ protected slots:
connect(spin_tracker_port, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged())); connect(spin_tracker_port, SIGNAL(valueChanged(int)), this, SLOT(emitSettingsChanged()));
spin_tracker_port->setMinimum(1); spin_tracker_port->setMinimum(1);
spin_tracker_port->setMaximum(65535); spin_tracker_port->setMaximum(65535);
spin_tracker_port->setValue(Preferences::getTrackerPort()); spin_tracker_port->setValue(pref.getTrackerPort());
setCellWidget(TRACKER_PORT, VALUE, spin_tracker_port); setCellWidget(TRACKER_PORT, VALUE, spin_tracker_port);
} }

View File

@ -43,7 +43,7 @@ class DeletionConfirmationDlg : public QDialog, private Ui::confirmDeletionDlg {
DeletionConfirmationDlg(QWidget *parent=0): QDialog(parent) { DeletionConfirmationDlg(QWidget *parent=0): QDialog(parent) {
setupUi(this); setupUi(this);
move(misc::screenCenter(this)); move(misc::screenCenter(this));
checkPermDelete->setChecked(Preferences::deleteTorrentFilesAsDefault()); checkPermDelete->setChecked(Preferences().deleteTorrentFilesAsDefault());
connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState())); connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState()));
buttonBox->setFocus(); buttonBox->setFocus();
} }
@ -63,11 +63,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().deleteTorrentFilesAsDefault());
} }
void on_rememberBtn_clicked() { void on_rememberBtn_clicked() {
Preferences::setDeleteTorrentFilesAsDefault(checkPermDelete->isChecked()); Preferences().setDeleteTorrentFilesAsDefault(checkPermDelete->isChecked());
rememberBtn->setEnabled(false); rememberBtn->setEnabled(false);
} }
}; };

View File

@ -37,6 +37,7 @@
#include "downloadthread.h" #include "downloadthread.h"
#include "preferences.h" #include "preferences.h"
#include "rsssettings.h"
#include "qinisettings.h" #include "qinisettings.h"
/** Download Thread **/ /** Download Thread **/
@ -99,7 +100,7 @@ void downloadThread::processDlFinished(QNetworkReply* reply) {
} }
void downloadThread::loadCookies(const QString &host_name, QString url) { void downloadThread::loadCookies(const QString &host_name, QString url) {
const QList<QByteArray> raw_cookies = Preferences::getHostNameCookies(host_name); const QList<QByteArray> raw_cookies = RssSettings::getHostNameCookies(host_name);
QNetworkCookieJar *cookie_jar = networkManager.cookieJar(); QNetworkCookieJar *cookie_jar = networkManager.cookieJar();
QList<QNetworkCookie> cookies; QList<QNetworkCookie> cookies;
qDebug("Loading cookies for host name: %s", qPrintable(host_name)); qDebug("Loading cookies for host name: %s", qPrintable(host_name));

View File

@ -41,8 +41,9 @@ class HeadlessLoader: public QObject {
public: public:
HeadlessLoader(QStringList torrentCmdLine) { HeadlessLoader(QStringList torrentCmdLine) {
Preferences pref;
// Enable Web UI // Enable Web UI
Preferences::setWebUiEnabled(true); pref.setWebUiEnabled(true);
// Instanciate Bittorrent Object // Instanciate Bittorrent Object
BTSession = QBtSession::instance(); BTSession = QBtSession::instance();
connect(BTSession, SIGNAL(newConsoleMessage(QString)), this, SLOT(displayConsoleMessage(QString))); connect(BTSession, SIGNAL(newConsoleMessage(QString)), this, SLOT(displayConsoleMessage(QString)));
@ -52,9 +53,9 @@ 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(Preferences::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(Preferences::getWebUiUsername())) << std::endl; std::cout << qPrintable(tr("The Web UI administrator user name is: %1").arg(pref.getWebUiUsername())) << std::endl;
if(Preferences::getWebUiPassword() == "f6fdffe48c908deb0f4c3bd36c032e72") { if(pref.getWebUiPassword() == "f6fdffe48c908deb0f4c3bd36c032e72") {
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;
} }

View File

@ -74,7 +74,7 @@ public:
std::cout << '\t' << prg_name << " --no-splash: " << qPrintable(tr("disable splash screen")) << std::endl; std::cout << '\t' << prg_name << " --no-splash: " << qPrintable(tr("disable splash screen")) << 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().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;
} }
}; };
@ -154,7 +154,7 @@ void useStyle(QString style){
if(!style.isEmpty()) { if(!style.isEmpty()) {
QApplication::setStyle(QStyleFactory::create(style)); QApplication::setStyle(QStyleFactory::create(style));
} }
Preferences::setStyle(QApplication::style()->objectName()); Preferences().setStyle(QApplication::style()->objectName());
} }
#endif #endif
@ -240,7 +240,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().setWebUiPort(new_port);
} }
} }
} }

View File

@ -93,9 +93,10 @@ using namespace libtorrent;
// Constructor // Constructor
MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent), force_exit(false) { MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent), force_exit(false) {
setupUi(this); setupUi(this);
ui_locked = Preferences::isUILocked(); Preferences pref;
ui_locked = pref.isUILocked();
setWindowTitle(tr("qBittorrent %1", "e.g: qBittorrent v0.x").arg(QString::fromUtf8(VERSION))); setWindowTitle(tr("qBittorrent %1", "e.g: qBittorrent v0.x").arg(QString::fromUtf8(VERSION)));
displaySpeedInTitle = Preferences::speedInTitleBar(); displaySpeedInTitle = pref.speedInTitleBar();
// Clean exit on log out // Clean exit on log out
connect(static_cast<SessionApplication*>(qApp), SIGNAL(sessionIsShuttingDown()), this, SLOT(deleteBTSession())); connect(static_cast<SessionApplication*>(qApp), SIGNAL(sessionIsShuttingDown()), this, SLOT(deleteBTSession()));
// Setting icons // Setting icons
@ -204,14 +205,14 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo
#endif #endif
// View settings // View settings
actionTop_tool_bar->setChecked(Preferences::isToolbarDisplayed()); actionTop_tool_bar->setChecked(pref.isToolbarDisplayed());
actionSpeed_in_title_bar->setChecked(Preferences::speedInTitleBar()); actionSpeed_in_title_bar->setChecked(pref.speedInTitleBar());
actionRSS_Reader->setChecked(RssSettings::isRSSEnabled()); actionRSS_Reader->setChecked(RssSettings::isRSSEnabled());
actionSearch_engine->setChecked(Preferences::isSearchEnabled()); actionSearch_engine->setChecked(pref.isSearchEnabled());
displaySearchTab(actionSearch_engine->isChecked()); displaySearchTab(actionSearch_engine->isChecked());
displayRSSTab(actionRSS_Reader->isChecked()); displayRSSTab(actionRSS_Reader->isChecked());
actionShutdown_when_downloads_complete->setChecked(Preferences::shutdownWhenDownloadsComplete()); actionShutdown_when_downloads_complete->setChecked(pref.shutdownWhenDownloadsComplete());
actionShutdown_qBittorrent_when_downloads_complete->setChecked(Preferences::shutdownqBTWhenDownloadsComplete()); actionShutdown_qBittorrent_when_downloads_complete->setChecked(pref.shutdownqBTWhenDownloadsComplete());
show(); show();
@ -225,7 +226,7 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo
if(ui_locked) { if(ui_locked) {
hide(); hide();
} else { } else {
if(Preferences::startMinimized()) if(pref.startMinimized())
showMinimized(); showMinimized();
} }
@ -244,13 +245,13 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo
qDebug("GUI Built"); qDebug("GUI Built");
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
if(!Preferences::neverCheckFileAssoc() && !Preferences::isFileAssocOk()) { if(!pref.neverCheckFileAssoc() && !Preferences::isFileAssocOk()) {
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::setFileAssoc(); Preferences::setFileAssoc();
} else { } else {
Preferences::setNeverCheckFileAssoc(); pref.setNeverCheckFileAssoc();
} }
} }
#endif #endif
@ -338,30 +339,31 @@ MainWindow::~MainWindow() {
} }
void MainWindow::defineUILockPassword() { void MainWindow::defineUILockPassword() {
QString old_pass_md5 = Preferences::getUILockPasswordMD5(); QString old_pass_md5 = Preferences().getUILockPasswordMD5();
if(old_pass_md5.isNull()) old_pass_md5 = ""; if(old_pass_md5.isNull()) old_pass_md5 = "";
bool ok = false; bool ok = false;
QString new_clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, old_pass_md5, &ok); QString new_clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, old_pass_md5, &ok);
if(ok) { if(ok) {
if(new_clear_password != old_pass_md5) { if(new_clear_password != old_pass_md5) {
Preferences::setUILockPassword(new_clear_password); Preferences().setUILockPassword(new_clear_password);
} }
QMessageBox::information(this, tr("Password update"), tr("The UI lock password has been successfully updated")); QMessageBox::information(this, tr("Password update"), tr("The UI lock password has been successfully updated"));
} }
} }
void MainWindow::on_actionLock_qBittorrent_triggered() { void MainWindow::on_actionLock_qBittorrent_triggered() {
Preferences pref;
// Check if there is a password // Check if there is a password
if(Preferences::getUILockPasswordMD5().isEmpty()) { if(pref.getUILockPasswordMD5().isEmpty()) {
// Ask for a password // Ask for a password
bool ok = false; bool ok = false;
QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok); QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok);
if(!ok) return; if(!ok) return;
Preferences::setUILockPassword(clear_password); pref.setUILockPassword(clear_password);
} }
// Lock the interface // Lock the interface
ui_locked = true; ui_locked = true;
Preferences::setUILocked(true); pref.setUILocked(true);
myTrayIconMenu->setEnabled(false); myTrayIconMenu->setEnabled(false);
hide(); hide();
} }
@ -527,7 +529,8 @@ void MainWindow::balloonClicked() {
} }
void MainWindow::askRecursiveTorrentDownloadConfirmation(QTorrentHandle &h) { void MainWindow::askRecursiveTorrentDownloadConfirmation(QTorrentHandle &h) {
if(Preferences::recursiveDownloadDisabled()) return; Preferences pref;
if(pref.recursiveDownloadDisabled()) return;
QMessageBox confirmBox(QMessageBox::Question, tr("Recursive download confirmation"), tr("The torrent %1 contains torrent files, do you want to proceed with their download?").arg(h.name())); QMessageBox confirmBox(QMessageBox::Question, tr("Recursive download confirmation"), tr("The torrent %1 contains torrent files, do you want to proceed with their download?").arg(h.name()));
QPushButton *yes = confirmBox.addButton(tr("Yes"), QMessageBox::YesRole); QPushButton *yes = confirmBox.addButton(tr("Yes"), QMessageBox::YesRole);
/*QPushButton *no = */confirmBox.addButton(tr("No"), QMessageBox::NoRole); /*QPushButton *no = */confirmBox.addButton(tr("No"), QMessageBox::NoRole);
@ -539,7 +542,7 @@ void MainWindow::askRecursiveTorrentDownloadConfirmation(QTorrentHandle &h) {
return; return;
} }
if(confirmBox.clickedButton() == never) { if(confirmBox.clickedButton() == never) {
Preferences::disableRecursiveDownload(); pref.disableRecursiveDownload();
} }
} }
@ -556,9 +559,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.);
BTSession->getSession()->set_upload_rate_limit(new_limit); BTSession->getSession()->set_upload_rate_limit(new_limit);
if(new_limit <= 0) if(new_limit <= 0)
Preferences::setGlobalUploadLimit(-1); Preferences().setGlobalUploadLimit(-1);
else else
Preferences::setGlobalUploadLimit(new_limit/1024.); Preferences().setGlobalUploadLimit(new_limit/1024.);
} }
} }
@ -578,9 +581,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.);
BTSession->getSession()->set_download_rate_limit(new_limit); BTSession->getSession()->set_download_rate_limit(new_limit);
if(new_limit <= 0) if(new_limit <= 0)
Preferences::setGlobalDownloadLimit(-1); Preferences().setGlobalDownloadLimit(-1);
else else
Preferences::setGlobalDownloadLimit(new_limit/1024.); Preferences().setGlobalDownloadLimit(new_limit/1024.);
} }
} }
@ -607,13 +610,14 @@ bool MainWindow::unlockUI() {
bool ok = false; bool ok = false;
QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok); QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok);
if(!ok) return false; if(!ok) return false;
QString real_pass_md5 = Preferences::getUILockPasswordMD5(); Preferences pref;
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;
Preferences::setUILocked(false); pref.setUILocked(false);
myTrayIconMenu->setEnabled(true); myTrayIconMenu->setEnabled(true);
return true; return true;
} }
@ -701,7 +705,7 @@ void MainWindow::closeEvent(QCloseEvent *e) {
} }
if(confirmBox.clickedButton() == alwaysBtn) { if(confirmBox.clickedButton() == alwaysBtn) {
// Remember choice // Remember choice
Preferences::setConfirmOnExit(false); Preferences().setConfirmOnExit(false);
} }
} }
} }
@ -734,8 +738,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");
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); if(systrayIcon && Preferences().minimizeToTray()) {
if(systrayIcon && settings.value(QString::fromUtf8("Preferences/General/MinimizeToTray"), false).toBool()) {
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;
@ -763,7 +766,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().setToolbarDisplayed(actionTop_tool_bar->isChecked());
return ret; return ret;
} }
#endif #endif
@ -923,7 +926,8 @@ void MainWindow::optionsSaved() {
// Load program preferences // Load program preferences
void MainWindow::loadPreferences(bool configure_session) { void MainWindow::loadPreferences(bool configure_session) {
BTSession->addConsoleMessage(tr("Options were saved successfully.")); BTSession->addConsoleMessage(tr("Options were saved successfully."));
const bool newSystrayIntegration = Preferences::systrayIntegration(); const Preferences pref;
const bool newSystrayIntegration = pref.systrayIntegration();
actionLock_qBittorrent->setEnabled(newSystrayIntegration); actionLock_qBittorrent->setEnabled(newSystrayIntegration);
if(newSystrayIntegration != (systrayIcon!=0)) { if(newSystrayIntegration != (systrayIcon!=0)) {
if(newSystrayIntegration) { if(newSystrayIntegration) {
@ -948,7 +952,7 @@ void MainWindow::loadPreferences(bool configure_session) {
} }
} }
// General // General
if(Preferences::isToolbarDisplayed()) { if(pref.isToolbarDisplayed()) {
toolBar->setVisible(true); toolBar->setVisible(true);
toolBar->layout()->setSpacing(7); toolBar->layout()->setSpacing(7);
} else { } else {
@ -956,14 +960,14 @@ void MainWindow::loadPreferences(bool configure_session) {
search_filter->clear(); search_filter->clear();
toolBar->setVisible(false); toolBar->setVisible(false);
} }
const uint new_refreshInterval = Preferences::getRefreshInterval(); const uint new_refreshInterval = pref.getRefreshInterval();
transferList->setRefreshInterval(new_refreshInterval); transferList->setRefreshInterval(new_refreshInterval);
transferList->setAlternatingRowColors(Preferences::useAlternatingRowColors()); transferList->setAlternatingRowColors(pref.useAlternatingRowColors());
properties->getFilesList()->setAlternatingRowColors(Preferences::useAlternatingRowColors()); properties->getFilesList()->setAlternatingRowColors(pref.useAlternatingRowColors());
properties->getTrackerList()->setAlternatingRowColors(Preferences::useAlternatingRowColors()); properties->getTrackerList()->setAlternatingRowColors(pref.useAlternatingRowColors());
properties->getPeerList()->setAlternatingRowColors(Preferences::useAlternatingRowColors()); properties->getPeerList()->setAlternatingRowColors(pref.useAlternatingRowColors());
// Queueing System // Queueing System
if(Preferences::isQueueingSystemEnabled()) { if(pref.isQueueingSystemEnabled()) {
if(!actionDecreasePriority->isVisible()) { if(!actionDecreasePriority->isVisible()) {
transferList->hidePriorityColumn(false); transferList->hidePriorityColumn(false);
actionDecreasePriority->setVisible(true); actionDecreasePriority->setVisible(true);
@ -1035,7 +1039,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().useProgramNotification()) return;
#ifdef WITH_LIBNOTIFY #ifdef WITH_LIBNOTIFY
if (notify_init ("summary-body")) { if (notify_init ("summary-body")) {
NotifyNotification* notification; NotifyNotification* notification;
@ -1108,7 +1112,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().setSystrayIntegration(false);
} }
} }
} }
@ -1125,8 +1129,9 @@ QMenu* MainWindow::getTrayIconMenu() {
myTrayIconMenu->addAction(actionOpen); myTrayIconMenu->addAction(actionOpen);
myTrayIconMenu->addAction(actionDownload_from_URL); myTrayIconMenu->addAction(actionDownload_from_URL);
myTrayIconMenu->addSeparator(); myTrayIconMenu->addSeparator();
updateAltSpeedsBtn(Preferences::isAltBandwidthEnabled()); const bool isAltBWEnabled = Preferences().isAltBandwidthEnabled();
actionUse_alternative_speed_limits->setChecked(Preferences::isAltBandwidthEnabled()); updateAltSpeedsBtn(isAltBWEnabled);
actionUse_alternative_speed_limits->setChecked(isAltBWEnabled);
myTrayIconMenu->addAction(actionUse_alternative_speed_limits); myTrayIconMenu->addAction(actionUse_alternative_speed_limits);
myTrayIconMenu->addAction(actionSet_global_download_limit); myTrayIconMenu->addAction(actionSet_global_download_limit);
myTrayIconMenu->addAction(actionSet_global_upload_limit); myTrayIconMenu->addAction(actionSet_global_upload_limit);
@ -1169,22 +1174,22 @@ 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().setToolbarDisplayed(is_visible);
} }
void MainWindow::on_actionShutdown_when_downloads_complete_triggered() { void MainWindow::on_actionShutdown_when_downloads_complete_triggered() {
bool is_checked = static_cast<QAction*>(sender())->isChecked(); bool is_checked = static_cast<QAction*>(sender())->isChecked();
Preferences::setShutdownWhenDownloadsComplete(is_checked); Preferences().setShutdownWhenDownloadsComplete(is_checked);
} }
void MainWindow::on_actionShutdown_qBittorrent_when_downloads_complete_triggered() { void MainWindow::on_actionShutdown_qBittorrent_when_downloads_complete_triggered() {
bool is_checked = static_cast<QAction*>(sender())->isChecked(); bool is_checked = static_cast<QAction*>(sender())->isChecked();
Preferences::setShutdownqBTWhenDownloadsComplete(is_checked); Preferences().setShutdownqBTWhenDownloadsComplete(is_checked);
} }
void MainWindow::on_actionSpeed_in_title_bar_triggered() { void MainWindow::on_actionSpeed_in_title_bar_triggered() {
displaySpeedInTitle = static_cast<QAction*>(sender())->isChecked(); displaySpeedInTitle = static_cast<QAction*>(sender())->isChecked();
Preferences::showSpeedInTitleBar(displaySpeedInTitle); Preferences().showSpeedInTitleBar(displaySpeedInTitle);
if(displaySpeedInTitle) if(displaySpeedInTitle)
updateGUI(); updateGUI();
else else
@ -1197,7 +1202,7 @@ void MainWindow::on_actionRSS_Reader_triggered() {
} }
void MainWindow::on_actionSearch_engine_triggered() { void MainWindow::on_actionSearch_engine_triggered() {
Preferences::setSearchEnabled(actionSearch_engine->isChecked()); Preferences().setSearchEnabled(actionSearch_engine->isChecked());
displaySearchTab(actionSearch_engine->isChecked()); displaySearchTab(actionSearch_engine->isChecked());
} }

View File

@ -346,12 +346,12 @@ QSize options_imp::sizeFittingScreen() {
void options_imp::saveOptions(){ void options_imp::saveOptions(){
applyButton->setEnabled(false); applyButton->setEnabled(false);
QIniSettings settings("qBittorrent", "qBittorrent"); Preferences pref;
// Apply style // Apply style
useStyle(); useStyle();
// Load the translation // Load the translation
QString locale = getLocale(); QString locale = getLocale();
if(Preferences::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));
@ -361,149 +361,117 @@ void options_imp::saveOptions(){
qApp->installTranslator(translator); qApp->installTranslator(translator);
} }
settings.beginGroup("Preferences");
// General preferences // General preferences
settings.beginGroup("General"); pref.setLocale(locale);
settings.setValue(QString::fromUtf8("Locale"), locale); pref.setStyle(getStyle());
settings.setValue(QString::fromUtf8("Style"), getStyle()); pref.setAlternatingRowColors(checkAltRowColors->isChecked());
settings.setValue(QString::fromUtf8("AlternatingRowColors"), checkAltRowColors->isChecked()); pref.setSystrayIntegration(systrayIntegration());
settings.setValue(QString::fromUtf8("SystrayEnabled"), systrayIntegration()); pref.setCloseToTray(closeToTray());
settings.setValue(QString::fromUtf8("CloseToTray"), closeToTray()); pref.setMinimizeToTray(minimizeToTray());
settings.setValue(QString::fromUtf8("MinimizeToTray"), minimizeToTray()); pref.setStartMinimized(startMinimized());
settings.setValue(QString::fromUtf8("StartMinimized"), startMinimized()); pref.setSplashScreenDisabled(isSlashScreenDisabled());
settings.setValue(QString::fromUtf8("NoSplashScreen"), isSlashScreenDisabled());
// End General preferences // End General preferences
settings.endGroup();
// Downloads preferences // Downloads preferences
settings.beginGroup("Downloads");
QString save_path = getSavePath(); QString save_path = getSavePath();
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
save_path = save_path.replace("\\", "/"); save_path = save_path.replace("\\", "/");
#endif #endif
settings.setValue(QString::fromUtf8("SavePath"), save_path); pref.setSavePath(save_path);
settings.setValue(QString::fromUtf8("TempPathEnabled"), isTempPathEnabled()); pref.setTempPathEnabled(isTempPathEnabled());
QString temp_path = getTempPath(); QString temp_path = getTempPath();
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
temp_path = temp_path.replace("\\", "/"); temp_path = temp_path.replace("\\", "/");
#endif #endif
settings.setValue(QString::fromUtf8("TempPath"), temp_path); pref.setTempPath(temp_path);
settings.setValue(QString::fromUtf8("AppendLabel"), checkAppendLabel->isChecked()); pref.setAppendTorrentLabel(checkAppendLabel->isChecked());
#if LIBTORRENT_VERSION_MINOR > 14 #if LIBTORRENT_VERSION_MINOR > 14
settings.setValue(QString::fromUtf8("UseIncompleteExtension"), checkAppendqB->isChecked()); pref.useIncompleteFilesExtension(checkAppendqB->isChecked());
#endif #endif
settings.setValue(QString::fromUtf8("PreAllocation"), preAllocateAllFiles()); pref.preAllocateAllFiles(preAllocateAllFiles());
settings.setValue(QString::fromUtf8("AdditionDialog"), useAdditionDialog()); pref.useAdditionDialog(useAdditionDialog());
settings.setValue(QString::fromUtf8("StartInPause"), addTorrentsInPause()); pref.addTorrentsInPause(addTorrentsInPause());
ScanFoldersModel::instance()->makePersistent(settings); ScanFoldersModel::instance()->makePersistent(pref);
addedScanDirs.clear(); addedScanDirs.clear();
QString export_dir = getExportDir(); QString export_dir = getExportDir();
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
export_dir = export_dir.replace("\\", "/"); export_dir = export_dir.replace("\\", "/");
#endif #endif
Preferences::setExportDir(export_dir); pref.setExportDir(export_dir);
Preferences::setMailNotificationEnabled(groupMailNotification->isChecked()); pref.setMailNotificationEnabled(groupMailNotification->isChecked());
Preferences::setMailNotificationEmail(dest_email_txt->text()); pref.setMailNotificationEmail(dest_email_txt->text());
Preferences::setMailNotificationSMTP(smtp_server_txt->text()); pref.setMailNotificationSMTP(smtp_server_txt->text());
Preferences::setAutoRunEnabled(autoRunBox->isChecked()); pref.setAutoRunEnabled(autoRunBox->isChecked());
Preferences::setAutoRunProgram(autoRun_txt->text()); pref.setAutoRunProgram(autoRun_txt->text());
settings.setValue(QString::fromUtf8("DblClOnTorDl"), getActionOnDblClOnTorrentDl()); pref.setActionOnDblClOnTorrentDl(getActionOnDblClOnTorrentDl());
settings.setValue(QString::fromUtf8("DblClOnTorFn"), getActionOnDblClOnTorrentFn()); pref.setActionOnDblClOnTorrentFn(getActionOnDblClOnTorrentFn());
// End Downloads preferences // End Downloads preferences
settings.endGroup();
// Connection preferences // Connection preferences
settings.beginGroup("Connection"); pref.setSessionPort(getPort());
settings.setValue(QString::fromUtf8("PortRangeMin"), getPort()); pref.setUPnPEnabled(isUPnPEnabled());
settings.setValue(QString::fromUtf8("UPnP"), isUPnPEnabled()); pref.setNATPMPEnabled(isNATPMPEnabled());
settings.setValue(QString::fromUtf8("NAT-PMP"), isNATPMPEnabled()); pref.setGlobalDownloadLimit(getGlobalBandwidthLimits().first);
settings.setValue(QString::fromUtf8("GlobalDLLimit"), getGlobalBandwidthLimits().first); pref.setGlobalUploadLimit(getGlobalBandwidthLimits().second);
settings.setValue(QString::fromUtf8("GlobalUPLimit"), getGlobalBandwidthLimits().second); pref.setAltGlobalDownloadLimit(spinDownloadLimitAlt->value());
Preferences::setAltGlobalDownloadLimit(spinDownloadLimitAlt->value()); pref.setAltGlobalUploadLimit(spinUploadLimitAlt->value());
Preferences::setAltGlobalUploadLimit(spinUploadLimitAlt->value()); pref.setSchedulerEnabled(check_schedule->isChecked());
Preferences::setSchedulerEnabled(check_schedule->isChecked()); pref.setSchedulerStartTime(schedule_from->time());
Preferences::setSchedulerStartTime(schedule_from->time()); pref.setSchedulerEndTime(schedule_to->time());
Preferences::setSchedulerEndTime(schedule_to->time()); pref.setSchedulerDays((scheduler_days)schedule_days->currentIndex());
Preferences::setSchedulerDays((scheduler_days)schedule_days->currentIndex()); pref.setPeerProxyType(getPeerProxyType());
settings.setValue(QString::fromUtf8("ProxyType"), getPeerProxyType()); pref.setPeerProxyIp(getPeerProxyIp());
//if(isProxyEnabled()) { pref.setPeerProxyPort(getPeerProxyPort());
settings.beginGroup("Proxy"); pref.setPeerProxyAuthEnabled(isPeerProxyAuthEnabled());
// Proxy is enabled, save settings pref.setPeerProxyUsername(getPeerProxyUsername());
settings.setValue(QString::fromUtf8("IP"), getPeerProxyIp()); pref.setPeerProxyPassword(getPeerProxyPassword());
settings.setValue(QString::fromUtf8("Port"), getPeerProxyPort()); pref.setHTTPProxyType(getHTTPProxyType());
settings.setValue(QString::fromUtf8("Authentication"), isPeerProxyAuthEnabled()); pref.setHTTPProxyIp(getHTTPProxyIp());
//if(isProxyAuthEnabled()) { pref.setHTTPProxyPort(getHTTPProxyPort());
// Credentials pref.setHTTPProxyAuthEnabled(isHTTPProxyAuthEnabled());
settings.setValue(QString::fromUtf8("Username"), getPeerProxyUsername()); pref.setHTTPProxyUsername(getHTTPProxyUsername());
settings.setValue(QString::fromUtf8("Password"), getPeerProxyPassword()); pref.setHTTPProxyPassword(getHTTPProxyPassword());
//}
settings.endGroup(); // End Proxy
//}
settings.setValue(QString::fromUtf8("HTTPProxyType"), getHTTPProxyType());
//if(isHTTPProxyEnabled()) {
settings.beginGroup("HTTPProxy");
// Proxy is enabled, save settings
settings.setValue(QString::fromUtf8("IP"), getHTTPProxyIp());
settings.setValue(QString::fromUtf8("Port"), getHTTPProxyPort());
settings.setValue(QString::fromUtf8("Authentication"), isHTTPProxyAuthEnabled());
//if(isHTTPProxyAuthEnabled()) {
// Credentials
settings.setValue(QString::fromUtf8("Username"), getHTTPProxyUsername());
settings.setValue(QString::fromUtf8("Password"), getHTTPProxyPassword());
//}
settings.endGroup(); // End HTTPProxy
//}
// End Connection preferences // End Connection preferences
settings.endGroup();
// Bittorrent preferences // Bittorrent preferences
settings.beginGroup("Bittorrent"); pref.setMaxConnecs(getMaxConnecs());
settings.setValue(QString::fromUtf8("MaxConnecs"), getMaxConnecs()); pref.setMaxConnecsPerTorrent(getMaxConnecsPerTorrent());
settings.setValue(QString::fromUtf8("MaxConnecsPerTorrent"), getMaxConnecsPerTorrent()); pref.setMaxUploadsPerTorrent(getMaxUploadsPerTorrent());
settings.setValue(QString::fromUtf8("MaxUploadsPerTorrent"), getMaxUploadsPerTorrent()); pref.setDHTEnabled(isDHTEnabled());
settings.setValue(QString::fromUtf8("DHT"), isDHTEnabled()); pref.setPeXEnabled(checkPeX->isChecked());
settings.setValue(QString::fromUtf8("PeX"), checkPeX->isChecked()); pref.setDHTPortSameAsBT(isDHTPortSameAsBT());
settings.setValue(QString::fromUtf8("sameDHTPortAsBT"), isDHTPortSameAsBT()); pref.setDHTPort(getDHTPort());
settings.setValue(QString::fromUtf8("DHTPort"), getDHTPort()); pref.setLSDEnabled(isLSDEnabled());
settings.setValue(QString::fromUtf8("LSD"), isLSDEnabled()); pref.setEncryptionSetting(getEncryptionSetting());
settings.setValue(QString::fromUtf8("Encryption"), getEncryptionSetting()); pref.setMaxRatio(getMaxRatio());
Preferences::setMaxRatio(getMaxRatio()); pref.setMaxRatioAction(comboRatioLimitAct->currentIndex());
Preferences::setMaxRatioAction(comboRatioLimitAct->currentIndex());
// End Bittorrent preferences // End Bittorrent preferences
settings.endGroup();
// Misc preferences // Misc preferences
// * IPFilter // * IPFilter
settings.beginGroup("IPFilter"); pref.setFilteringEnabled(isFilteringEnabled());
settings.setValue(QString::fromUtf8("Enabled"), isFilteringEnabled());
if(isFilteringEnabled()){ if(isFilteringEnabled()){
QString filter_path = textFilterPath->text(); QString filter_path = textFilterPath->text();
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
filter_path = filter_path.replace("\\", "/"); filter_path = filter_path.replace("\\", "/");
#endif #endif
settings.setValue(QString::fromUtf8("File"), filter_path); pref.setFilter(filter_path);
} }
// End IPFilter preferences // End IPFilter preferences
settings.endGroup();
// Queueing system // Queueing system
settings.beginGroup("Queueing"); pref.setQueueingSystemEnabled(isQueueingSystemEnabled());
settings.setValue(QString::fromUtf8("QueueingEnabled"), isQueueingSystemEnabled()); pref.setMaxActiveDownloads(spinMaxActiveDownloads->value());
settings.setValue(QString::fromUtf8("MaxActiveDownloads"), spinMaxActiveDownloads->value()); pref.setMaxActiveUploads(spinMaxActiveUploads->value());
settings.setValue(QString::fromUtf8("MaxActiveUploads"), spinMaxActiveUploads->value()); pref.setMaxActiveTorrents(spinMaxActiveTorrents->value());
settings.setValue(QString::fromUtf8("MaxActiveTorrents"), spinMaxActiveTorrents->value());
// End Queueing system preferences // End Queueing system preferences
settings.endGroup();
// Web UI // Web UI
settings.beginGroup("WebUI"); pref.setWebUiEnabled(isWebUiEnabled());
settings.setValue("Enabled", isWebUiEnabled());
if(isWebUiEnabled()) if(isWebUiEnabled())
{ {
settings.setValue("Port", webUiPort()); pref.setWebUiPort(webUiPort());
settings.setValue("Username", 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)
Preferences::setWebUiPassword(webUiPassword()); pref.setWebUiPassword(webUiPassword());
} }
// End Web UI // End Web UI
settings.endGroup();
// End preferences // End preferences
settings.endGroup();
// Save advanced settings // Save advanced settings
advancedSettings->saveAdvancedSettings(); advancedSettings->saveAdvancedSettings();
} }
@ -570,46 +538,47 @@ void options_imp::loadOptions(){
float floatValue; float floatValue;
QString strValue; QString strValue;
// General preferences // General preferences
setLocale(Preferences::getLocale()); const Preferences pref;
setStyle(Preferences::getStyle()); setLocale(pref.getLocale());
checkAltRowColors->setChecked(Preferences::useAlternatingRowColors()); setStyle(pref.getStyle());
checkShowSystray->setChecked(Preferences::systrayIntegration()); checkAltRowColors->setChecked(pref.useAlternatingRowColors());
checkShowSplash->setChecked(!Preferences::isSlashScreenDisabled()); checkShowSystray->setChecked(pref.systrayIntegration());
checkShowSplash->setChecked(!pref.isSlashScreenDisabled());
if(!checkShowSystray->isChecked()) { if(!checkShowSystray->isChecked()) {
disableSystrayOptions(); disableSystrayOptions();
} else { } else {
enableSystrayOptions(); enableSystrayOptions();
checkCloseToSystray->setChecked(Preferences::closeToTray()); checkCloseToSystray->setChecked(pref.closeToTray());
checkMinimizeToSysTray->setChecked(Preferences::minimizeToTray()); checkMinimizeToSysTray->setChecked(pref.minimizeToTray());
checkStartMinimized->setChecked(Preferences::startMinimized()); checkStartMinimized->setChecked(pref.startMinimized());
} }
// End General preferences // End General preferences
// Downloads preferences // Downloads preferences
QString save_path = Preferences::getSavePath(); QString save_path = pref.getSavePath();
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
save_path = save_path.replace("/", "\\"); save_path = save_path.replace("/", "\\");
#endif #endif
textSavePath->setText(save_path); textSavePath->setText(save_path);
if(Preferences::isTempPathEnabled()) { if(pref.isTempPathEnabled()) {
// enable // enable
checkTempFolder->setChecked(true); checkTempFolder->setChecked(true);
} else { } else {
checkTempFolder->setChecked(false); checkTempFolder->setChecked(false);
} }
QString temp_path = Preferences::getTempPath(); QString temp_path = pref.getTempPath();
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
temp_path = temp_path.replace("/", "\\"); temp_path = temp_path.replace("/", "\\");
#endif #endif
textTempPath->setText(temp_path); textTempPath->setText(temp_path);
checkAppendLabel->setChecked(Preferences::appendTorrentLabel()); checkAppendLabel->setChecked(pref.appendTorrentLabel());
#if LIBTORRENT_VERSION_MINOR > 14 #if LIBTORRENT_VERSION_MINOR > 14
checkAppendqB->setChecked(Preferences::useIncompleteFilesExtension()); checkAppendqB->setChecked(pref.useIncompleteFilesExtension());
#endif #endif
checkPreallocateAll->setChecked(Preferences::preAllocateAllFiles()); checkPreallocateAll->setChecked(pref.preAllocateAllFiles());
checkAdditionDialog->setChecked(Preferences::useAdditionDialog()); checkAdditionDialog->setChecked(pref.useAdditionDialog());
checkStartPaused->setChecked(Preferences::addTorrentsInPause()); checkStartPaused->setChecked(pref.addTorrentsInPause());
strValue = Preferences::getExportDir(); strValue = pref.getExportDir();
if(strValue.isEmpty()) { if(strValue.isEmpty()) {
// Disable // Disable
checkExportDir->setChecked(false); checkExportDir->setChecked(false);
@ -621,25 +590,25 @@ void options_imp::loadOptions(){
#endif #endif
textExportDir->setText(strValue); textExportDir->setText(strValue);
} }
groupMailNotification->setChecked(Preferences::isMailNotificationEnabled()); groupMailNotification->setChecked(pref.isMailNotificationEnabled());
dest_email_txt->setText(Preferences::getMailNotificationEmail()); dest_email_txt->setText(pref.getMailNotificationEmail());
smtp_server_txt->setText(Preferences::getMailNotificationSMTP()); smtp_server_txt->setText(pref.getMailNotificationSMTP());
autoRunBox->setChecked(Preferences::isAutoRunEnabled()); autoRunBox->setChecked(pref.isAutoRunEnabled());
autoRun_txt->setText(Preferences::getAutoRunProgram()); autoRun_txt->setText(pref.getAutoRunProgram());
intValue = Preferences::getActionOnDblClOnTorrentDl(); intValue = pref.getActionOnDblClOnTorrentDl();
if(intValue >= actionTorrentDlOnDblClBox->count()) if(intValue >= actionTorrentDlOnDblClBox->count())
intValue = 0; intValue = 0;
actionTorrentDlOnDblClBox->setCurrentIndex(intValue); actionTorrentDlOnDblClBox->setCurrentIndex(intValue);
intValue = Preferences::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(Preferences::getSessionPort()); spinPort->setValue(pref.getSessionPort());
checkUPnP->setChecked(Preferences::isUPnPEnabled()); checkUPnP->setChecked(pref.isUPnPEnabled());
checkNATPMP->setChecked(Preferences::isNATPMPEnabled()); checkNATPMP->setChecked(pref.isNATPMPEnabled());
intValue = Preferences::getGlobalDownloadLimit(); intValue = pref.getGlobalDownloadLimit();
if(intValue > 0) { if(intValue > 0) {
// Enabled // Enabled
checkDownloadLimit->setChecked(true); checkDownloadLimit->setChecked(true);
@ -650,7 +619,7 @@ void options_imp::loadOptions(){
checkDownloadLimit->setChecked(false); checkDownloadLimit->setChecked(false);
spinDownloadLimit->setEnabled(false); spinDownloadLimit->setEnabled(false);
} }
intValue = Preferences::getGlobalUploadLimit(); intValue = pref.getGlobalUploadLimit();
if(intValue != -1) { if(intValue != -1) {
// Enabled // Enabled
checkUploadLimit->setChecked(true); checkUploadLimit->setChecked(true);
@ -661,15 +630,15 @@ void options_imp::loadOptions(){
checkUploadLimit->setChecked(false); checkUploadLimit->setChecked(false);
spinUploadLimit->setEnabled(false); spinUploadLimit->setEnabled(false);
} }
spinUploadLimitAlt->setValue(Preferences::getAltGlobalUploadLimit()); spinUploadLimitAlt->setValue(pref.getAltGlobalUploadLimit());
spinDownloadLimitAlt->setValue(Preferences::getAltGlobalDownloadLimit()); spinDownloadLimitAlt->setValue(pref.getAltGlobalDownloadLimit());
// Scheduler // Scheduler
check_schedule->setChecked(Preferences::isSchedulerEnabled()); check_schedule->setChecked(pref.isSchedulerEnabled());
schedule_from->setTime(Preferences::getSchedulerStartTime()); schedule_from->setTime(pref.getSchedulerStartTime());
schedule_to->setTime(Preferences::getSchedulerEndTime()); schedule_to->setTime(pref.getSchedulerEndTime());
schedule_days->setCurrentIndex((int)Preferences::getSchedulerDays()); schedule_days->setCurrentIndex((int)pref.getSchedulerDays());
intValue = Preferences::getPeerProxyType(); intValue = pref.getPeerProxyType();
switch(intValue) { switch(intValue) {
case Proxy::SOCKS4: case Proxy::SOCKS4:
comboProxyType->setCurrentIndex(1); comboProxyType->setCurrentIndex(1);
@ -688,14 +657,14 @@ void options_imp::loadOptions(){
enablePeerProxy(comboProxyType->currentIndex()); enablePeerProxy(comboProxyType->currentIndex());
//if(isProxyEnabled()) { //if(isProxyEnabled()) {
// Proxy is enabled, save settings // Proxy is enabled, save settings
textProxyIP->setText(Preferences::getPeerProxyIp()); textProxyIP->setText(pref.getPeerProxyIp());
spinProxyPort->setValue(Preferences::getPeerProxyPort()); spinProxyPort->setValue(pref.getPeerProxyPort());
checkProxyAuth->setChecked(Preferences::isPeerProxyAuthEnabled()); checkProxyAuth->setChecked(pref.isPeerProxyAuthEnabled());
textProxyUsername->setText(Preferences::getPeerProxyUsername()); textProxyUsername->setText(pref.getPeerProxyUsername());
textProxyPassword->setText(Preferences::getPeerProxyPassword()); textProxyPassword->setText(pref.getPeerProxyPassword());
enablePeerProxyAuth(checkProxyAuth->isChecked()); enablePeerProxyAuth(checkProxyAuth->isChecked());
//} //}
intValue = Preferences::getHTTPProxyType(); intValue = pref.getHTTPProxyType();
switch(intValue) { switch(intValue) {
case Proxy::HTTP: case Proxy::HTTP:
case Proxy::HTTP_PW: case Proxy::HTTP_PW:
@ -709,16 +678,16 @@ void options_imp::loadOptions(){
comboProxyType_http->setCurrentIndex(0); comboProxyType_http->setCurrentIndex(0);
} }
enableHTTPProxy(comboProxyType_http->currentIndex()); enableHTTPProxy(comboProxyType_http->currentIndex());
textProxyUsername_http->setText(Preferences::getHTTPProxyUsername()); textProxyUsername_http->setText(pref.getHTTPProxyUsername());
textProxyPassword_http->setText(Preferences::getHTTPProxyPassword()); textProxyPassword_http->setText(pref.getHTTPProxyPassword());
textProxyIP_http->setText(Preferences::getHTTPProxyIp()); textProxyIP_http->setText(pref.getHTTPProxyIp());
spinProxyPort_http->setValue(Preferences::getHTTPProxyPort()); spinProxyPort_http->setValue(pref.getHTTPProxyPort());
checkProxyAuth_http->setChecked(Preferences::isHTTPProxyAuthEnabled()); checkProxyAuth_http->setChecked(pref.isHTTPProxyAuthEnabled());
enableHTTPProxyAuth(checkProxyAuth_http->isChecked()); enableHTTPProxyAuth(checkProxyAuth_http->isChecked());
// End HTTPProxy // End HTTPProxy
// End Connection preferences // End Connection preferences
// Bittorrent preferences // Bittorrent preferences
intValue = Preferences::getMaxConnecs(); intValue = pref.getMaxConnecs();
if(intValue > 0) { if(intValue > 0) {
// enable // enable
checkMaxConnecs->setChecked(true); checkMaxConnecs->setChecked(true);
@ -729,7 +698,7 @@ void options_imp::loadOptions(){
checkMaxConnecs->setChecked(false); checkMaxConnecs->setChecked(false);
spinMaxConnec->setEnabled(false); spinMaxConnec->setEnabled(false);
} }
intValue = Preferences::getMaxConnecsPerTorrent(); intValue = pref.getMaxConnecsPerTorrent();
if(intValue > 0) { if(intValue > 0) {
// enable // enable
checkMaxConnecsPerTorrent->setChecked(true); checkMaxConnecsPerTorrent->setChecked(true);
@ -740,7 +709,7 @@ void options_imp::loadOptions(){
checkMaxConnecsPerTorrent->setChecked(false); checkMaxConnecsPerTorrent->setChecked(false);
spinMaxConnecPerTorrent->setEnabled(false); spinMaxConnecPerTorrent->setEnabled(false);
} }
intValue = Preferences::getMaxUploadsPerTorrent(); intValue = pref.getMaxUploadsPerTorrent();
if(intValue > 0) { if(intValue > 0) {
// enable // enable
checkMaxUploadsPerTorrent->setChecked(true); checkMaxUploadsPerTorrent->setChecked(true);
@ -751,14 +720,14 @@ void options_imp::loadOptions(){
checkMaxUploadsPerTorrent->setChecked(false); checkMaxUploadsPerTorrent->setChecked(false);
spinMaxUploadsPerTorrent->setEnabled(false); spinMaxUploadsPerTorrent->setEnabled(false);
} }
checkDHT->setChecked(Preferences::isDHTEnabled()); checkDHT->setChecked(pref.isDHTEnabled());
checkDifferentDHTPort->setChecked(!Preferences::isDHTPortSameAsBT()); checkDifferentDHTPort->setChecked(!pref.isDHTPortSameAsBT());
spinDHTPort->setValue(Preferences::getDHTPort()); spinDHTPort->setValue(pref.getDHTPort());
checkPeX->setChecked(Preferences::isPeXEnabled()); checkPeX->setChecked(pref.isPeXEnabled());
checkLSD->setChecked(Preferences::isLSDEnabled()); checkLSD->setChecked(pref.isLSDEnabled());
comboEncryption->setCurrentIndex(Preferences::getEncryptionSetting()); comboEncryption->setCurrentIndex(pref.getEncryptionSetting());
// Ratio limit // Ratio limit
floatValue = Preferences::getMaxRatio(); floatValue = pref.getMaxRatio();
if(floatValue >= 0.) { if(floatValue >= 0.) {
// Enable // Enable
checkMaxRatio->setChecked(true); checkMaxRatio->setChecked(true);
@ -771,24 +740,24 @@ void options_imp::loadOptions(){
spinMaxRatio->setEnabled(false); spinMaxRatio->setEnabled(false);
comboRatioLimitAct->setEnabled(false); comboRatioLimitAct->setEnabled(false);
} }
comboRatioLimitAct->setCurrentIndex(Preferences::getMaxRatioAction()); comboRatioLimitAct->setCurrentIndex(pref.getMaxRatioAction());
// End Bittorrent preferences // End Bittorrent preferences
// Misc preferences // Misc preferences
// * IP Filter // * IP Filter
checkIPFilter->setChecked(Preferences::isFilteringEnabled()); checkIPFilter->setChecked(pref.isFilteringEnabled());
textFilterPath->setText(Preferences::getFilter()); textFilterPath->setText(pref.getFilter());
// End IP Filter // End IP Filter
// Queueing system preferences // Queueing system preferences
checkEnableQueueing->setChecked(Preferences::isQueueingSystemEnabled()); checkEnableQueueing->setChecked(pref.isQueueingSystemEnabled());
spinMaxActiveDownloads->setValue(Preferences::getMaxActiveDownloads()); spinMaxActiveDownloads->setValue(pref.getMaxActiveDownloads());
spinMaxActiveUploads->setValue(Preferences::getMaxActiveUploads()); spinMaxActiveUploads->setValue(pref.getMaxActiveUploads());
spinMaxActiveTorrents->setValue(Preferences::getMaxActiveTorrents()); spinMaxActiveTorrents->setValue(pref.getMaxActiveTorrents());
// End Queueing system preferences // End Queueing system preferences
// Web UI // Web UI
checkWebUi->setChecked(Preferences::isWebUiEnabled()); checkWebUi->setChecked(pref.isWebUiEnabled());
spinWebUiPort->setValue(Preferences::getWebUiPort()); spinWebUiPort->setValue(pref.getWebUiPort());
textWebUiUsername->setText(Preferences::getWebUiUsername()); textWebUiUsername->setText(pref.getWebUiUsername());
textWebUiPassword->setText(Preferences::getWebUiPassword()); textWebUiPassword->setText(pref.getWebUiPassword());
// End Web UI // End Web UI
// Random stuff // Random stuff
srand(time(0)); srand(time(0));
@ -889,7 +858,7 @@ float options_imp::getMaxRatio() const{
// Return Save Path // Return Save Path
QString options_imp::getSavePath() const{ QString options_imp::getSavePath() const{
if(textSavePath->text().trimmed().isEmpty()){ if(textSavePath->text().trimmed().isEmpty()){
QString save_path = Preferences::getSavePath(); QString save_path = Preferences().getSavePath();
#if defined(Q_WS_WIN) || defined(Q_OS_OS2) #if defined(Q_WS_WIN) || defined(Q_OS_OS2)
save_path = save_path.replace("/", "\\"); save_path = save_path.replace("/", "\\");
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@ -51,10 +51,11 @@ ProgramUpdater::ProgramUpdater(QObject *parent) :
QObject(parent) QObject(parent)
{ {
mp_manager = new QNetworkAccessManager(this); mp_manager = new QNetworkAccessManager(this);
Preferences pref;
// Proxy support // Proxy support
if(Preferences::isHTTPProxyEnabled()) { if(pref.isHTTPProxyEnabled()) {
QNetworkProxy proxy; QNetworkProxy proxy;
switch(Preferences::getHTTPProxyType()) { switch(pref.getHTTPProxyType()) {
case Proxy::SOCKS4: case Proxy::SOCKS4:
case Proxy::SOCKS5: case Proxy::SOCKS5:
case Proxy::SOCKS5_PW: case Proxy::SOCKS5_PW:
@ -63,12 +64,12 @@ ProgramUpdater::ProgramUpdater(QObject *parent) :
proxy.setType(QNetworkProxy::HttpProxy); proxy.setType(QNetworkProxy::HttpProxy);
break; break;
} }
proxy.setHostName(Preferences::getHTTPProxyIp()); proxy.setHostName(pref.getHTTPProxyIp());
proxy.setPort(Preferences::getHTTPProxyPort()); proxy.setPort(pref.getHTTPProxyPort());
// Proxy authentication // Proxy authentication
if(Preferences::isHTTPProxyAuthEnabled()) { if(pref.isHTTPProxyAuthEnabled()) {
proxy.setUser(Preferences::getHTTPProxyUsername()); proxy.setUser(pref.getHTTPProxyUsername());
proxy.setPassword(Preferences::getHTTPProxyPassword()); proxy.setPassword(pref.getHTTPProxyPassword());
} }
mp_manager->setProxy(proxy); mp_manager->setProxy(proxy);
} }

View File

@ -93,7 +93,7 @@ PeerListWidget::~PeerListWidget() {
} }
void PeerListWidget::updatePeerHostNameResolutionState() { void PeerListWidget::updatePeerHostNameResolutionState() {
if(Preferences::resolvePeerHostNames()) { if(Preferences().resolvePeerHostNames()) {
if(!resolver) { if(!resolver) {
resolver = new ReverseResolution(this); resolver = new ReverseResolution(this);
connect(resolver, SIGNAL(ip_resolved(QString,QString)), this, SLOT(handleResolved(QString,QString))); connect(resolver, SIGNAL(ip_resolved(QString,QString)), this, SLOT(handleResolved(QString,QString)));
@ -107,7 +107,7 @@ void PeerListWidget::updatePeerHostNameResolutionState() {
} }
void PeerListWidget::updatePeerCountryResolutionState() { void PeerListWidget::updatePeerCountryResolutionState() {
if(Preferences::resolvePeerCountries() != display_flags) { if(Preferences().resolvePeerCountries() != display_flags) {
display_flags = !display_flags; display_flags = !display_flags;
if(display_flags) { if(display_flags) {
const QTorrentHandle h = properties->getCurrentTorrent(); const QTorrentHandle h = properties->getCurrentTorrent();
@ -206,7 +206,7 @@ void PeerListWidget::limitUpRateSelectedPeers(QStringList peer_ips) {
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) return; if(!h.is_valid()) return;
bool ok=false; bool ok=false;
long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Upload rate limiting"), -1, Preferences::getGlobalUploadLimit()*1024.); long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Upload rate limiting"), -1, Preferences().getGlobalUploadLimit()*1024.);
if(!ok) return; if(!ok) return;
foreach(const QString &ip, peer_ips) { foreach(const QString &ip, peer_ips) {
libtorrent::asio::ip::tcp::endpoint ep = peerEndpoints.value(ip, libtorrent::asio::ip::tcp::endpoint()); libtorrent::asio::ip::tcp::endpoint ep = peerEndpoints.value(ip, libtorrent::asio::ip::tcp::endpoint());
@ -227,7 +227,7 @@ void PeerListWidget::limitDlRateSelectedPeers(QStringList peer_ips) {
QTorrentHandle h = properties->getCurrentTorrent(); QTorrentHandle h = properties->getCurrentTorrent();
if(!h.is_valid()) return; if(!h.is_valid()) return;
bool ok=false; bool ok=false;
long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Download rate limiting"), -1, Preferences::getGlobalDownloadLimit()*1024.); long limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Download rate limiting"), -1, Preferences().getGlobalDownloadLimit()*1024.);
if(!ok) return; if(!ok) return;
foreach(const QString &ip, peer_ips) { foreach(const QString &ip, peer_ips) {
libtorrent::asio::ip::tcp::endpoint ep = peerEndpoints.value(ip, libtorrent::asio::ip::tcp::endpoint()); libtorrent::asio::ip::tcp::endpoint ep = peerEndpoints.value(ip, libtorrent::asio::ip::tcp::endpoint());

View File

@ -15,7 +15,7 @@ private:
public: public:
BandwidthScheduler(QObject *parent): QTimer(parent), in_alternative_mode(false) { BandwidthScheduler(QObject *parent): QTimer(parent), in_alternative_mode(false) {
Q_ASSERT(Preferences::isSchedulerEnabled()); Q_ASSERT(Preferences().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
@ -24,10 +24,11 @@ public:
public slots: public slots:
void start() { void start() {
Q_ASSERT(Preferences::isSchedulerEnabled()); const Preferences pref;
Q_ASSERT(pref.isSchedulerEnabled());
QTime startAltSpeeds = Preferences::getSchedulerStartTime(); QTime startAltSpeeds = pref.getSchedulerStartTime();
QTime endAltSpeeds = Preferences::getSchedulerEndTime(); QTime endAltSpeeds = pref.getSchedulerEndTime();
if(startAltSpeeds == endAltSpeeds) { if(startAltSpeeds == endAltSpeeds) {
std::cerr << "Error: bandwidth scheduler have the same start time and end time." << std::endl; std::cerr << "Error: bandwidth scheduler have the same start time and end time." << std::endl;
std::cerr << "The bandwidth scheduler will be disabled" << std::endl; std::cerr << "The bandwidth scheduler will be disabled" << std::endl;
@ -56,19 +57,20 @@ public slots:
} }
void switchMode() { void switchMode() {
const Preferences pref;
// Get the day this mode was started (either today or yesterday) // Get the day this mode was started (either today or yesterday)
QDate current_date = QDateTime::currentDateTime().toLocalTime().date(); QDate current_date = QDateTime::currentDateTime().toLocalTime().date();
int day = current_date.dayOfWeek(); int day = current_date.dayOfWeek();
if(in_alternative_mode) { if(in_alternative_mode) {
// It is possible that starttime was yesterday // It is possible that starttime was yesterday
if(QTime::currentTime().secsTo(Preferences::getSchedulerStartTime()) > 0) { if(QTime::currentTime().secsTo(pref.getSchedulerStartTime()) > 0) {
current_date.addDays(-1); // Go to yesterday current_date.addDays(-1); // Go to yesterday
day = current_date.day(); day = current_date.day();
} }
} }
// Check if the day is in scheduler days // Check if the day is in scheduler days
// Notify BTSession only if necessary // Notify BTSession only if necessary
switch(Preferences::getSchedulerDays()) { switch(pref.getSchedulerDays()) {
case EVERY_DAY: case EVERY_DAY:
emit switchToAlternativeMode(!in_alternative_mode); emit switchToAlternativeMode(!in_alternative_mode);
break; break;
@ -82,7 +84,7 @@ public slots:
break; break;
default: default:
// Convert our enum index to Qt enum index // Convert our enum index to Qt enum index
int scheduler_day = ((int)Preferences::getSchedulerDays()) - 2; int scheduler_day = ((int)pref.getSchedulerDays()) - 2;
if(day == scheduler_day) if(day == scheduler_day)
emit switchToAlternativeMode(!in_alternative_mode); emit switchToAlternativeMode(!in_alternative_mode);
break; break;

View File

@ -85,6 +85,7 @@ QBtSession::QBtSession()
, geoipDBLoaded(false), resolve_countries(false) , geoipDBLoaded(false), resolve_countries(false)
#endif #endif
{ {
Preferences pref;
m_tracker = 0; m_tracker = 0;
// To avoid some exceptions // To avoid some exceptions
fs::path::default_name_check(fs::no_check); fs::path::default_name_check(fs::no_check);
@ -115,7 +116,7 @@ QBtSession::QBtSession()
#if LIBTORRENT_VERSION_MINOR > 14 #if LIBTORRENT_VERSION_MINOR > 14
s->add_extension(create_lt_trackers_plugin); s->add_extension(create_lt_trackers_plugin);
#endif #endif
if(Preferences::isPeXEnabled()) { if(pref.isPeXEnabled()) {
PeXEnabled = true; PeXEnabled = true;
s->add_extension(&create_ut_pex_plugin); s->add_extension(&create_ut_pex_plugin);
} else { } else {
@ -131,9 +132,9 @@ QBtSession::QBtSession()
downloader = new downloadThread(this); downloader = new downloadThread(this);
connect(downloader, SIGNAL(downloadFinished(QString, QString)), this, SLOT(processDownloadedFile(QString, QString))); connect(downloader, SIGNAL(downloadFinished(QString, QString)), this, SLOT(processDownloadedFile(QString, QString)));
connect(downloader, SIGNAL(downloadFailure(QString, QString)), this, SLOT(handleDownloadFailure(QString, QString))); connect(downloader, SIGNAL(downloadFailure(QString, QString)), this, SLOT(handleDownloadFailure(QString, QString)));
appendLabelToSavePath = Preferences::appendTorrentLabel(); appendLabelToSavePath = pref.appendTorrentLabel();
#if LIBTORRENT_VERSION_MINOR > 14 #if LIBTORRENT_VERSION_MINOR > 14
appendqBExtension = Preferences::useIncompleteFilesExtension(); appendqBExtension = pref.useIncompleteFilesExtension();
#endif #endif
connect(m_scanFolders, SIGNAL(torrentsAdded(QStringList&)), this, SLOT(addTorrentsFromScanFolder(QStringList&))); connect(m_scanFolders, SIGNAL(torrentsAdded(QStringList&)), this, SLOT(addTorrentsFromScanFolder(QStringList&)));
// Apply user settings to Bittorrent session // Apply user settings to Bittorrent session
@ -267,23 +268,24 @@ 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");
const Preferences pref;
// Downloads // Downloads
// * Save path // * Save path
defaultSavePath = Preferences::getSavePath(); defaultSavePath = pref.getSavePath();
if(Preferences::isTempPathEnabled()) { if(pref.isTempPathEnabled()) {
setDefaultTempPath(Preferences::getTempPath()); setDefaultTempPath(pref.getTempPath());
} else { } else {
setDefaultTempPath(QString::null); setDefaultTempPath(QString::null);
} }
setAppendLabelToSavePath(Preferences::appendTorrentLabel()); setAppendLabelToSavePath(pref.appendTorrentLabel());
#if LIBTORRENT_VERSION_MINOR > 14 #if LIBTORRENT_VERSION_MINOR > 14
setAppendqBExtension(Preferences::useIncompleteFilesExtension()); setAppendqBExtension(pref.useIncompleteFilesExtension());
#endif #endif
preAllocateAllFiles(Preferences::preAllocateAllFiles()); preAllocateAllFiles(pref.preAllocateAllFiles());
startTorrentsInPause(Preferences::addTorrentsInPause()); startTorrentsInPause(pref.addTorrentsInPause());
// * Scan dirs // * Scan dirs
const QStringList scan_dirs = Preferences::getScanDirs(); const QStringList scan_dirs = pref.getScanDirs();
QList<bool> downloadInDirList = Preferences::getDownloadInScanDirs(); QList<bool> downloadInDirList = pref.getDownloadInScanDirs();
while(scan_dirs.size() > downloadInDirList.size()) { while(scan_dirs.size() > downloadInDirList.size()) {
downloadInDirList << false; downloadInDirList << false;
} }
@ -293,29 +295,29 @@ void QBtSession::configureSession() {
++i; ++i;
} }
// * Export Dir // * Export Dir
const bool newTorrentExport = Preferences::isTorrentExportEnabled(); const bool newTorrentExport = pref.isTorrentExportEnabled();
if(torrentExport != newTorrentExport) { if(torrentExport != newTorrentExport) {
torrentExport = newTorrentExport; torrentExport = newTorrentExport;
if(torrentExport) { if(torrentExport) {
qDebug("Torrent export is enabled, exporting the current torrents"); qDebug("Torrent export is enabled, exporting the current torrents");
exportTorrentFiles(Preferences::getExportDir()); exportTorrentFiles(pref.getExportDir());
} }
} }
// Connection // Connection
// * Ports binding // * Ports binding
const unsigned short old_listenPort = getListenPort(); const unsigned short old_listenPort = getListenPort();
const unsigned short new_listenPort = Preferences::getSessionPort(); const unsigned short new_listenPort = pref.getSessionPort();
if(old_listenPort != new_listenPort) { if(old_listenPort != new_listenPort) {
setListeningPort(new_listenPort); setListeningPort(new_listenPort);
addConsoleMessage(tr("qBittorrent is bound to port: TCP/%1", "e.g: qBittorrent is bound to port: 6881").arg(QString::number(new_listenPort))); addConsoleMessage(tr("qBittorrent is bound to port: TCP/%1", "e.g: qBittorrent is bound to port: 6881").arg(QString::number(new_listenPort)));
} }
// * Global download limit // * Global download limit
const bool alternative_speeds = Preferences::isAltBandwidthEnabled(); const bool alternative_speeds = pref.isAltBandwidthEnabled();
int down_limit; int down_limit;
if(alternative_speeds) if(alternative_speeds)
down_limit = Preferences::getAltGlobalDownloadLimit(); down_limit = pref.getAltGlobalDownloadLimit();
else else
down_limit = Preferences::getGlobalDownloadLimit(); down_limit = pref.getGlobalDownloadLimit();
if(down_limit <= 0) { if(down_limit <= 0) {
// Download limit disabled // Download limit disabled
setDownloadRateLimit(-1); setDownloadRateLimit(-1);
@ -325,9 +327,9 @@ void QBtSession::configureSession() {
} }
int up_limit; int up_limit;
if(alternative_speeds) if(alternative_speeds)
up_limit = Preferences::getAltGlobalUploadLimit(); up_limit = pref.getAltGlobalUploadLimit();
else else
up_limit = Preferences::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
@ -336,7 +338,7 @@ void QBtSession::configureSession() {
// Enabled // Enabled
setUploadRateLimit(up_limit*1024); setUploadRateLimit(up_limit*1024);
} }
if(Preferences::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)));
@ -348,7 +350,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 = Preferences::resolvePeerCountries(); const bool new_resolv_countries = pref.resolvePeerCountries();
if(resolve_countries != new_resolv_countries) { if(resolve_countries != new_resolv_countries) {
qDebug("in country reoslution settings"); qDebug("in country reoslution settings");
resolve_countries = new_resolv_countries; resolve_countries = new_resolv_countries;
@ -368,7 +370,7 @@ void QBtSession::configureSession() {
} }
#endif #endif
// * UPnP // * UPnP
if(Preferences::isUPnPEnabled()) { if(pref.isUPnPEnabled()) {
enableUPnP(true); enableUPnP(true);
addConsoleMessage(tr("UPnP support [ON]"), QString::fromUtf8("blue")); addConsoleMessage(tr("UPnP support [ON]"), QString::fromUtf8("blue"));
} else { } else {
@ -376,7 +378,7 @@ void QBtSession::configureSession() {
addConsoleMessage(tr("UPnP support [OFF]"), QString::fromUtf8("blue")); addConsoleMessage(tr("UPnP support [OFF]"), QString::fromUtf8("blue"));
} }
// * NAT-PMP // * NAT-PMP
if(Preferences::isNATPMPEnabled()) { if(pref.isNATPMPEnabled()) {
enableNATPMP(true); enableNATPMP(true);
addConsoleMessage(tr("NAT-PMP support [ON]"), QString::fromUtf8("blue")); addConsoleMessage(tr("NAT-PMP support [ON]"), QString::fromUtf8("blue"));
} else { } else {
@ -404,13 +406,13 @@ void QBtSession::configureSession() {
#endif #endif
// To keep same behavior as in qBittorrent v1.2.0 // To keep same behavior as in qBittorrent v1.2.0
sessionSettings.rate_limit_ip_overhead = false; sessionSettings.rate_limit_ip_overhead = false;
sessionSettings.cache_size = Preferences::diskCacheSize()*64; sessionSettings.cache_size = pref.diskCacheSize()*64;
addConsoleMessage(tr("Using a disk cache size of %1 MiB").arg(Preferences::diskCacheSize())); addConsoleMessage(tr("Using a disk cache size of %1 MiB").arg(pref.diskCacheSize()));
// Queueing System // Queueing System
if(Preferences::isQueueingSystemEnabled()) { if(pref.isQueueingSystemEnabled()) {
sessionSettings.active_downloads = Preferences::getMaxActiveDownloads(); sessionSettings.active_downloads = pref.getMaxActiveDownloads();
sessionSettings.active_seeds = Preferences::getMaxActiveUploads(); sessionSettings.active_seeds = pref.getMaxActiveUploads();
sessionSettings.active_limit = Preferences::getMaxActiveTorrents(); sessionSettings.active_limit = pref.getMaxActiveTorrents();
sessionSettings.dont_count_slow_torrents = false; sessionSettings.dont_count_slow_torrents = false;
setQueueingEnabled(true); setQueueingEnabled(true);
} else { } else {
@ -420,30 +422,30 @@ void QBtSession::configureSession() {
setQueueingEnabled(false); setQueueingEnabled(false);
} }
// Outgoing ports // Outgoing ports
sessionSettings.outgoing_ports = std::make_pair(Preferences::outgoingPortsMin(), Preferences::outgoingPortsMax()); sessionSettings.outgoing_ports = std::make_pair(pref.outgoingPortsMin(), pref.outgoingPortsMax());
setSessionSettings(sessionSettings); setSessionSettings(sessionSettings);
// Ignore limits on LAN // Ignore limits on LAN
sessionSettings.ignore_limits_on_local_network = Preferences::ignoreLimitsOnLAN(); sessionSettings.ignore_limits_on_local_network = pref.ignoreLimitsOnLAN();
// Include overhead in transfer limits // Include overhead in transfer limits
sessionSettings.rate_limit_ip_overhead = Preferences::includeOverheadInLimits(); sessionSettings.rate_limit_ip_overhead = pref.includeOverheadInLimits();
// Bittorrent // Bittorrent
// * Max Half-open connections // * Max Half-open connections
s->set_max_half_open_connections(Preferences::getMaxHalfOpenConnections()); s->set_max_half_open_connections(pref.getMaxHalfOpenConnections());
// * Max connections limit // * Max connections limit
setMaxConnections(Preferences::getMaxConnecs()); setMaxConnections(pref.getMaxConnecs());
// * Max connections per torrent limit // * Max connections per torrent limit
setMaxConnectionsPerTorrent(Preferences::getMaxConnecsPerTorrent()); setMaxConnectionsPerTorrent(pref.getMaxConnecsPerTorrent());
// * Max uploads per torrent limit // * Max uploads per torrent limit
setMaxUploadsPerTorrent(Preferences::getMaxUploadsPerTorrent()); setMaxUploadsPerTorrent(pref.getMaxUploadsPerTorrent());
// * DHT // * DHT
if(Preferences::isDHTEnabled()) { if(pref.isDHTEnabled()) {
// Set DHT Port // Set DHT Port
if(enableDHT(true)) { if(enableDHT(true)) {
int dht_port; int dht_port;
if(Preferences::isDHTPortSameAsBT()) if(pref.isDHTPortSameAsBT())
dht_port = 0; dht_port = 0;
else else
dht_port = Preferences::getDHTPort(); dht_port = pref.getDHTPort();
setDHTPort(dht_port); setDHTPort(dht_port);
if(dht_port == 0) dht_port = new_listenPort; if(dht_port == 0) dht_port = new_listenPort;
addConsoleMessage(tr("DHT support [ON], port: UDP/%1").arg(dht_port), QString::fromUtf8("blue")); addConsoleMessage(tr("DHT support [ON], port: UDP/%1").arg(dht_port), QString::fromUtf8("blue"));
@ -460,11 +462,11 @@ void QBtSession::configureSession() {
} else { } else {
addConsoleMessage(tr("PeX support [OFF]"), QString::fromUtf8("red")); addConsoleMessage(tr("PeX support [OFF]"), QString::fromUtf8("red"));
} }
if(PeXEnabled != Preferences::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(Preferences::isLSDEnabled()) { if(pref.isLSDEnabled()) {
enableLSD(true); enableLSD(true);
addConsoleMessage(tr("Local Peer Discovery [ON]"), QString::fromUtf8("blue")); addConsoleMessage(tr("Local Peer Discovery [ON]"), QString::fromUtf8("blue"));
} else { } else {
@ -472,7 +474,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 = Preferences::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;
@ -495,40 +497,40 @@ void QBtSession::configureSession() {
} }
applyEncryptionSettings(encryptionSettings); applyEncryptionSettings(encryptionSettings);
// * Maximum ratio // * Maximum ratio
high_ratio_action = Preferences::getMaxRatioAction(); high_ratio_action = pref.getMaxRatioAction();
setMaxRatio(Preferences::getMaxRatio()); setMaxRatio(pref.getMaxRatio());
// Ip Filter // Ip Filter
FilterParserThread::processFilterList(s, Preferences::bannedIPs()); FilterParserThread::processFilterList(s, pref.bannedIPs());
if(Preferences::isFilteringEnabled()) { if(pref.isFilteringEnabled()) {
enableIPFilter(Preferences::getFilter()); enableIPFilter(pref.getFilter());
}else{ }else{
disableIPFilter(); disableIPFilter();
} }
// Update Web UI // Update Web UI
if (Preferences::isWebUiEnabled()) { if (pref.isWebUiEnabled()) {
const quint16 port = Preferences::getWebUiPort(); const quint16 port = pref.getWebUiPort();
const QString username = Preferences::getWebUiUsername(); const QString username = pref.getWebUiUsername();
const QString password = Preferences::getWebUiPassword(); const QString password = pref.getWebUiPassword();
initWebUi(username, password, port); initWebUi(username, password, port);
} else if(httpServer) { } else if(httpServer) {
delete httpServer; delete httpServer;
} }
// * Proxy settings // * Proxy settings
proxy_settings proxySettings; proxy_settings proxySettings;
if(Preferences::isPeerProxyEnabled()) { if(pref.isPeerProxyEnabled()) {
qDebug("Enabling P2P proxy"); qDebug("Enabling P2P proxy");
proxySettings.hostname = Preferences::getPeerProxyIp().toStdString(); proxySettings.hostname = pref.getPeerProxyIp().toStdString();
qDebug("hostname is %s", proxySettings.hostname.c_str()); qDebug("hostname is %s", proxySettings.hostname.c_str());
proxySettings.port = Preferences::getPeerProxyPort(); proxySettings.port = pref.getPeerProxyPort();
qDebug("port is %d", proxySettings.port); qDebug("port is %d", proxySettings.port);
if(Preferences::isPeerProxyAuthEnabled()) { if(pref.isPeerProxyAuthEnabled()) {
proxySettings.username = Preferences::getPeerProxyUsername().toStdString(); proxySettings.username = pref.getPeerProxyUsername().toStdString();
proxySettings.password = Preferences::getPeerProxyPassword().toStdString(); proxySettings.password = pref.getPeerProxyPassword().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(Preferences::getPeerProxyType()) { switch(pref.getPeerProxyType()) {
case Proxy::HTTP: case Proxy::HTTP:
qDebug("type: http"); qDebug("type: http");
proxySettings.type = proxy_settings::http; proxySettings.type = proxy_settings::http;
@ -553,38 +555,38 @@ void QBtSession::configureSession() {
setPeerProxySettings(proxySettings); setPeerProxySettings(proxySettings);
// HTTP Proxy // HTTP Proxy
proxy_settings http_proxySettings; proxy_settings http_proxySettings;
qDebug("HTTP Communications proxy type: %d", Preferences::getHTTPProxyType()); qDebug("HTTP Communications proxy type: %d", pref.getHTTPProxyType());
switch(Preferences::getHTTPProxyType()) { switch(pref.getHTTPProxyType()) {
case Proxy::HTTP_PW: case Proxy::HTTP_PW:
http_proxySettings.type = proxy_settings::http_pw; http_proxySettings.type = proxy_settings::http_pw;
http_proxySettings.username = Preferences::getHTTPProxyUsername().toStdString(); http_proxySettings.username = pref.getHTTPProxyUsername().toStdString();
http_proxySettings.password = Preferences::getHTTPProxyPassword().toStdString(); http_proxySettings.password = pref.getHTTPProxyPassword().toStdString();
http_proxySettings.hostname = Preferences::getHTTPProxyIp().toStdString(); http_proxySettings.hostname = pref.getHTTPProxyIp().toStdString();
http_proxySettings.port = Preferences::getHTTPProxyPort(); http_proxySettings.port = pref.getHTTPProxyPort();
break; break;
case Proxy::HTTP: case Proxy::HTTP:
http_proxySettings.type = proxy_settings::http; http_proxySettings.type = proxy_settings::http;
http_proxySettings.hostname = Preferences::getHTTPProxyIp().toStdString(); http_proxySettings.hostname = pref.getHTTPProxyIp().toStdString();
http_proxySettings.port = Preferences::getHTTPProxyPort(); http_proxySettings.port = pref.getHTTPProxyPort();
break; break;
case Proxy::SOCKS5: case Proxy::SOCKS5:
http_proxySettings.type = proxy_settings::socks5; http_proxySettings.type = proxy_settings::socks5;
http_proxySettings.hostname = Preferences::getHTTPProxyIp().toStdString(); http_proxySettings.hostname = pref.getHTTPProxyIp().toStdString();
http_proxySettings.port = Preferences::getHTTPProxyPort(); http_proxySettings.port = pref.getHTTPProxyPort();
break; break;
case Proxy::SOCKS5_PW: case Proxy::SOCKS5_PW:
http_proxySettings.type = proxy_settings::socks5_pw; http_proxySettings.type = proxy_settings::socks5_pw;
http_proxySettings.username = Preferences::getHTTPProxyUsername().toStdString(); http_proxySettings.username = pref.getHTTPProxyUsername().toStdString();
http_proxySettings.password = Preferences::getHTTPProxyPassword().toStdString(); http_proxySettings.password = pref.getHTTPProxyPassword().toStdString();
http_proxySettings.hostname = Preferences::getHTTPProxyIp().toStdString(); http_proxySettings.hostname = pref.getHTTPProxyIp().toStdString();
http_proxySettings.port = Preferences::getHTTPProxyPort(); http_proxySettings.port = pref.getHTTPProxyPort();
break; break;
default: default:
http_proxySettings.type = proxy_settings::none; http_proxySettings.type = proxy_settings::none;
} }
setHTTPProxySettings(http_proxySettings); setHTTPProxySettings(http_proxySettings);
// Tracker // Tracker
if(Preferences::isTrackerEnabled()) { if(pref.isTrackerEnabled()) {
if(!m_tracker) { if(!m_tracker) {
m_tracker = new QTracker(this); m_tracker = new QTracker(this);
} }
@ -623,20 +625,21 @@ bool QBtSession::initWebUi(QString username, QString password, int port) {
void QBtSession::useAlternativeSpeedsLimit(bool alternative) { void QBtSession::useAlternativeSpeedsLimit(bool alternative) {
// Save new state to remember it on startup // Save new state to remember it on startup
Preferences::setAltBandwidthEnabled(alternative); Preferences pref;
pref.setAltBandwidthEnabled(alternative);
// Apply settings to the bittorrent session // Apply settings to the bittorrent session
if(alternative) { if(alternative) {
s->set_download_rate_limit(Preferences::getAltGlobalDownloadLimit()*1024); s->set_download_rate_limit(pref.getAltGlobalDownloadLimit()*1024);
s->set_upload_rate_limit(Preferences::getAltGlobalUploadLimit()*1024); s->set_upload_rate_limit(pref.getAltGlobalUploadLimit()*1024);
} else { } else {
int down_limit = Preferences::getGlobalDownloadLimit(); int down_limit = pref.getGlobalDownloadLimit();
if(down_limit <= 0) { if(down_limit <= 0) {
down_limit = -1; down_limit = -1;
} else { } else {
down_limit *= 1024; down_limit *= 1024;
} }
s->set_download_rate_limit(down_limit); s->set_download_rate_limit(down_limit);
int up_limit = Preferences::getGlobalUploadLimit(); int up_limit = pref.getGlobalUploadLimit();
if(up_limit <= 0) { if(up_limit <= 0) {
up_limit = -1; up_limit = -1;
} else { } else {
@ -740,7 +743,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().banIP(ip);
} }
// Delete a torrent from the session, given its hash // Delete a torrent from the session, given its hash
@ -853,10 +856,11 @@ bool QBtSession::loadFastResumeData(QString hash, std::vector<char> &buf) {
} }
void QBtSession::loadTorrentSettings(QTorrentHandle h) { void QBtSession::loadTorrentSettings(QTorrentHandle h) {
Preferences pref;
// Connections limit per torrent // Connections limit per torrent
h.set_max_connections(Preferences::getMaxConnecsPerTorrent()); h.set_max_connections(pref.getMaxConnecsPerTorrent());
// Uploads limit per torrent // Uploads limit per torrent
h.set_max_uploads(Preferences::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);
@ -944,7 +948,7 @@ QTorrentHandle QBtSession::addMagnetUri(QString magnet_uri, bool resumed) {
if(!resumed) { if(!resumed) {
loadTorrentTempData(h, savePath, true); loadTorrentTempData(h, savePath, true);
} }
if(!fastResume && (!addInPause || (Preferences::useAdditionDialog()))) { if(!fastResume && (!addInPause || (Preferences().useAdditionDialog()))) {
// Start torrent because it was added in paused state // Start torrent because it was added in paused state
h.resume(); h.resume();
} }
@ -1130,7 +1134,7 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr
exportTorrentFile(h); exportTorrentFile(h);
} }
if(!fastResume && (!addInPause || (Preferences::useAdditionDialog() && !fromScanDir))) { if(!fastResume && (!addInPause || (Preferences().useAdditionDialog() && !fromScanDir))) {
// Start torrent because it was added in paused state // Start torrent because it was added in paused state
h.resume(); h.resume();
} }
@ -1159,7 +1163,7 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr
void QBtSession::exportTorrentFile(QTorrentHandle h) { void QBtSession::exportTorrentFile(QTorrentHandle h) {
Q_ASSERT(torrentExport); Q_ASSERT(torrentExport);
QString torrent_path = QDir(misc::BTBackupLocation()).absoluteFilePath(h.hash()+".torrent"); QString torrent_path = QDir(misc::BTBackupLocation()).absoluteFilePath(h.hash()+".torrent");
QDir exportPath(Preferences::getExportDir()); QDir exportPath(Preferences().getExportDir());
if(exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) { if(exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) {
QString new_torrent_path = exportPath.absoluteFilePath(h.name()+".torrent"); QString new_torrent_path = exportPath.absoluteFilePath(h.name()+".torrent");
if(QFile::exists(new_torrent_path) && misc::sameFiles(torrent_path, new_torrent_path)) { if(QFile::exists(new_torrent_path) && misc::sameFiles(torrent_path, new_torrent_path)) {
@ -1777,12 +1781,12 @@ void QBtSession::setAppendqBExtension(bool append) {
// session will listen to // session will listen to
void QBtSession::setListeningPort(int port) { void QBtSession::setListeningPort(int port) {
std::pair<int,int> ports(port, port); std::pair<int,int> ports(port, port);
const QString& iface_name = Preferences::getNetworkInterface(); const QString& iface_name = Preferences().getNetworkInterface();
if(iface_name.isEmpty()) { if(iface_name.isEmpty()) {
s->listen_on(ports); s->listen_on(ports);
return; return;
} }
QNetworkInterface network_iface = QNetworkInterface::interfaceFromName(iface_name); const QNetworkInterface network_iface = QNetworkInterface::interfaceFromName(iface_name);
if(!network_iface.isValid()) { if(!network_iface.isValid()) {
qDebug("Invalid network interface: %s", qPrintable(iface_name)); qDebug("Invalid network interface: %s", qPrintable(iface_name));
addConsoleMessage(tr("The network interface defined is invalid: %1").arg(iface_name), "red"); addConsoleMessage(tr("The network interface defined is invalid: %1").arg(iface_name), "red");
@ -1963,7 +1967,7 @@ void QBtSession::cleanUpAutoRunProcess(int) {
void QBtSession::autoRunExternalProgram(QTorrentHandle h, bool async) { void QBtSession::autoRunExternalProgram(QTorrentHandle h, bool async) {
if(!h.is_valid()) return; if(!h.is_valid()) return;
QString program = Preferences::getAutoRunProgram().trimmed(); QString program = Preferences().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;
@ -1990,7 +1994,7 @@ void QBtSession::sendNotificationEmail(QTorrentHandle h) {
content += tr("The torrent was downloaded in %1.", "The torrent was downloaded in 1 hour and 20 seconds").arg(misc::userFriendlyDuration(h.active_time())) + "\n\n\n"; content += tr("The torrent was downloaded in %1.", "The torrent was downloaded in 1 hour and 20 seconds").arg(misc::userFriendlyDuration(h.active_time())) + "\n\n\n";
content += tr("Thank you for using qBittorrent.") + "\n"; content += tr("Thank you for using qBittorrent.") + "\n";
// Send the notification email // Send the notification email
new Smtp("notification@qbittorrent.org", Preferences::getMailNotificationEmail(), tr("[qBittorrent] %1 has finished downloading").arg(h.name()), content); new Smtp("notification@qbittorrent.org", Preferences().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
@ -2048,26 +2052,27 @@ void QBtSession::readAlerts() {
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
if(Preferences::recheckTorrentsOnCompletion()) { Preferences pref;
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()));
bool will_shutdown = (Preferences::shutdownWhenDownloadsComplete() || Preferences::shutdownqBTWhenDownloadsComplete()) bool will_shutdown = (pref.shutdownWhenDownloadsComplete() || pref.shutdownqBTWhenDownloadsComplete())
&& !hasDownloadingTorrents(); && !hasDownloadingTorrents();
// AutoRun program // AutoRun program
if(Preferences::isAutoRunEnabled()) if(pref.isAutoRunEnabled())
autoRunExternalProgram(h, will_shutdown); autoRunExternalProgram(h, will_shutdown);
// Mail notification // Mail notification
if(Preferences::isMailNotificationEnabled()) if(pref.isMailNotificationEnabled())
sendNotificationEmail(h); sendNotificationEmail(h);
// Auto-Shutdown // Auto-Shutdown
if(will_shutdown) { if(will_shutdown) {
if(Preferences::shutdownWhenDownloadsComplete()) { if(pref.shutdownWhenDownloadsComplete()) {
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
Preferences::setShutdownWhenDownloadsComplete(false); pref.setShutdownWhenDownloadsComplete(false);
#if LIBTORRENT_VERSION_MINOR < 15 #if LIBTORRENT_VERSION_MINOR < 15
saveDHTEntry(); saveDHTEntry();
#endif #endif

View File

@ -390,7 +390,7 @@ void QTorrentHandle::resume() {
const QString torrent_hash = hash(); const QString torrent_hash = hash();
bool has_persistant_error = TorrentPersistentData::hasError(torrent_hash); bool has_persistant_error = TorrentPersistentData::hasError(torrent_hash);
TorrentPersistentData::setErrorState(torrent_hash, false); TorrentPersistentData::setErrorState(torrent_hash, false);
bool temp_path_enabled = Preferences::isTempPathEnabled(); bool temp_path_enabled = Preferences().isTempPathEnabled();
if(has_persistant_error && temp_path_enabled) { if(has_persistant_error && temp_path_enabled) {
// Torrent was supposed to be seeding, checking again in final destination // Torrent was supposed to be seeding, checking again in final destination
qDebug("Resuming a torrent with error..."); qDebug("Resuming a torrent with error...");
@ -427,8 +427,9 @@ void QTorrentHandle::prioritize_files(const std::vector<int> &v) {
// Reset seed status // Reset seed status
TorrentPersistentData::saveSeedStatus(*this); TorrentPersistentData::saveSeedStatus(*this);
// Move to temp folder if necessary // Move to temp folder if necessary
if(Preferences::isTempPathEnabled()) { const Preferences pref;
QString tmp_path = Preferences::getTempPath(); if(pref.isTempPathEnabled()) {
QString tmp_path = pref.getTempPath();
QString root_folder = TorrentPersistentData::getRootFolder(hash()); QString root_folder = TorrentPersistentData::getRootFolder(hash());
if(!root_folder.isEmpty()) if(!root_folder.isEmpty())
tmp_path = QDir(tmp_path).absoluteFilePath(root_folder); tmp_path = QDir(tmp_path).absoluteFilePath(root_folder);
@ -444,8 +445,9 @@ void QTorrentHandle::file_priority(int index, int priority) 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
if(Preferences::isTempPathEnabled()) { const Preferences pref;
QString tmp_path = Preferences::getTempPath(); if(pref.isTempPathEnabled()) {
QString tmp_path = pref.getTempPath();
QString root_folder = TorrentPersistentData::getRootFolder(hash()); QString root_folder = TorrentPersistentData::getRootFolder(hash());
if(!root_folder.isEmpty()) if(!root_folder.isEmpty())
tmp_path = QDir(tmp_path).absoluteFilePath(root_folder); tmp_path = QDir(tmp_path).absoluteFilePath(root_folder);

View File

@ -220,7 +220,7 @@ RssDownloadRule AutomatedRssDownloader::getCurrentRule() const
void AutomatedRssDownloader::initLabelCombobox() void AutomatedRssDownloader::initLabelCombobox()
{ {
// Load custom labels // Load custom labels
const QStringList customLabels = Preferences::getTorrentLabels(); const QStringList customLabels = Preferences().getTorrentLabels();
foreach(const QString& label, customLabels) { foreach(const QString& label, customLabels) {
ui->comboLabel->addItem(label); ui->comboLabel->addItem(label);
} }
@ -252,7 +252,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().addTorrentLabel(rule.label());
//rule.setRssFeeds(getSelectedFeeds()); //rule.setRssFeeds(getSelectedFeeds());
// Save it // Save it
m_ruleList->saveRule(rule); m_ruleList->saveRule(rule);

View File

@ -47,6 +47,7 @@
#include "rssfolder.h" #include "rssfolder.h"
#include "rssarticle.h" #include "rssarticle.h"
#include "rssfeed.h" #include "rssfeed.h"
#include "rsssettings.h"
#include "automatedrssdownloader.h" #include "automatedrssdownloader.h"
enum NewsCols { NEWS_ICON, NEWS_TITLE_COL, NEWS_URL_COL, NEWS_ID }; enum NewsCols { NEWS_ICON, NEWS_TITLE_COL, NEWS_URL_COL, NEWS_ID };
@ -117,9 +118,9 @@ 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;
QList<QByteArray> raw_cookies = CookiesDlg::askForCookies(this, Preferences::getHostNameCookies(feed_hostname), &ok); QList<QByteArray> raw_cookies = CookiesDlg::askForCookies(this, RssSettings::getHostNameCookies(feed_hostname), &ok);
if(ok) { if(ok) {
Preferences::setHostNameCookies(feed_hostname, raw_cookies); RssSettings::setHostNameCookies(feed_hostname, raw_cookies);
} }
} }
@ -642,7 +643,7 @@ RSSImp::~RSSImp(){
void RSSImp::on_settingsButton_clicked() { void RSSImp::on_settingsButton_clicked() {
RssSettingsDlg dlg(this); RssSettingsDlg dlg(this);
if(dlg.exec()) if(dlg.exec())
updateRefreshInterval(Preferences::getRefreshInterval()); updateRefreshInterval(RssSettings::getRSSRefreshInterval());
} }
void RSSImp::on_rssDownloaderBtn_clicked() void RSSImp::on_rssDownloaderBtn_clicked()

View File

@ -120,7 +120,7 @@ bool RssDownloadRule::operator==(const RssDownloadRule &other) {
void RssDownloadRule::setSavePath(const QString &save_path) void RssDownloadRule::setSavePath(const QString &save_path)
{ {
if(!save_path.isEmpty() && QDir(save_path) != QDir(Preferences::getSavePath())) if(!save_path.isEmpty() && QDir(save_path) != QDir(Preferences().getSavePath()))
m_savePath = save_path; m_savePath = save_path;
else else
m_savePath = QString(); m_savePath = QString();

View File

@ -95,6 +95,27 @@ public:
QIniSettings settings("qBittorrent", "qBittorrent"); QIniSettings settings("qBittorrent", "qBittorrent");
settings.setValue("Rss/streamAlias", rssAliases); settings.setValue("Rss/streamAlias", rssAliases);
} }
static QList<QByteArray> getHostNameCookies(const QString &host_name) {
QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss");
QMap<QString, QVariant> hosts_table = qBTRSS.value("hosts_cookies", QMap<QString, QVariant>()).toMap();
if(!hosts_table.contains(host_name)) return QList<QByteArray>();
QByteArray raw_cookies = hosts_table.value(host_name).toByteArray();
return raw_cookies.split(':');
}
static void setHostNameCookies(QString host_name, const QList<QByteArray> &cookies) {
QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss");
QMap<QString, QVariant> hosts_table = qBTRSS.value("hosts_cookies", QMap<QString, QVariant>()).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);
qBTRSS.setValue("hosts_cookies", hosts_table);
}
}; };
#endif // RSSSETTINGS_H #endif // RSSSETTINGS_H

View File

@ -28,7 +28,7 @@ Smtp::Smtp(const QString &from, const QString &to, const QString &subject, const
this->from = from; this->from = from;
rcpt = to; rcpt = to;
state = Init; state = Init;
socket->connectToHost(Preferences::getMailNotificationSMTP(), 25); socket->connectToHost(Preferences().getMailNotificationSMTP(), 25);
if(socket->waitForConnected ( 30000 )) { if(socket->waitForConnected ( 30000 )) {
qDebug("connected"); qDebug("connected");
} else { } else {

View File

@ -49,6 +49,7 @@ class StatusBar: public QObject {
public: public:
StatusBar(QStatusBar *bar): bar(bar) { StatusBar(QStatusBar *bar): bar(bar) {
Preferences pref;
connect(QBtSession::instance(), SIGNAL(alternativeSpeedsModeChanged(bool)), this, SLOT(updateAltSpeedsBtn(bool))); connect(QBtSession::instance(), SIGNAL(alternativeSpeedsModeChanged(bool)), this, SLOT(updateAltSpeedsBtn(bool)));
container = new QWidget(); container = new QWidget();
layout = new QGridLayout(container); layout = new QGridLayout(container);
@ -75,7 +76,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(Preferences::isAltBandwidthEnabled()); updateAltSpeedsBtn(pref.isAltBandwidthEnabled());
connect(altSpeedsBtn, SIGNAL(clicked()), this, SLOT(toggleAlternativeSpeeds())); connect(altSpeedsBtn, SIGNAL(clicked()), this, SLOT(toggleAlternativeSpeeds()));
@ -129,7 +130,7 @@ public:
bar->setContentsMargins(12, 0, 12, 0); bar->setContentsMargins(12, 0, 12, 0);
bar->setFixedHeight(dlSpeedLbl->fontMetrics().height()+9); bar->setFixedHeight(dlSpeedLbl->fontMetrics().height()+9);
// Is DHT enabled // Is DHT enabled
DHTLbl->setVisible(Preferences::isDHTEnabled()); DHTLbl->setVisible(pref.isDHTEnabled());
refreshTimer = new QTimer(bar); refreshTimer = new QTimer(bar);
connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refreshStatusBar())); connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refreshStatusBar()));
refreshTimer->start(1500); refreshTimer->start(1500);
@ -216,24 +217,25 @@ public slots:
} }
void toggleAlternativeSpeeds() { void toggleAlternativeSpeeds() {
QBtSession::instance()->useAlternativeSpeedsLimit(!Preferences::isAltBandwidthEnabled()); QBtSession::instance()->useAlternativeSpeedsLimit(!Preferences().isAltBandwidthEnabled());
} }
void capDownloadSpeed() { void capDownloadSpeed() {
bool ok = false; bool ok = false;
long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), QBtSession::instance()->getSession()->download_rate_limit()); long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), QBtSession::instance()->getSession()->download_rate_limit());
if(ok) { if(ok) {
bool alt = Preferences::isAltBandwidthEnabled(); Preferences pref;
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");
if(!alt) if(!alt)
QBtSession::instance()->getSession()->set_download_rate_limit(-1); QBtSession::instance()->getSession()->set_download_rate_limit(-1);
Preferences::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.);
if(!alt) if(!alt)
QBtSession::instance()->getSession()->set_download_rate_limit(new_limit); QBtSession::instance()->getSession()->set_download_rate_limit(new_limit);
Preferences::setGlobalDownloadLimit(new_limit/1024.); pref.setGlobalDownloadLimit(new_limit/1024.);
} }
} }
} }
@ -245,10 +247,10 @@ public slots:
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()->getSession()->set_upload_rate_limit(-1); QBtSession::instance()->getSession()->set_upload_rate_limit(-1);
Preferences::setGlobalUploadLimit(-1); Preferences().setGlobalUploadLimit(-1);
} else { } else {
qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.); qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.);
Preferences::setGlobalUploadLimit(new_limit/1024.); Preferences().setGlobalUploadLimit(new_limit/1024.);
QBtSession::instance()->getSession()->set_upload_rate_limit(new_limit); QBtSession::instance()->getSession()->set_upload_rate_limit(new_limit);
} }
} }

View File

@ -56,6 +56,7 @@
torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) : torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) :
QDialog(parent), old_label(""), hidden_height(0) { QDialog(parent), old_label(""), hidden_height(0) {
const Preferences pref;
setupUi(this); setupUi(this);
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
// Set Properties list model // Set Properties list model
@ -77,8 +78,8 @@ torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) :
// Remember columns width // Remember columns width
readSettings(); readSettings();
//torrentContentList->header()->setResizeMode(0, QHeaderView::Stretch); //torrentContentList->header()->setResizeMode(0, QHeaderView::Stretch);
defaultSavePath = Preferences::getSavePath(); defaultSavePath = pref.getSavePath();
appendLabelToSavePath = Preferences::appendTorrentLabel(); appendLabelToSavePath = pref.appendTorrentLabel();
QString display_path = defaultSavePath.replace("\\", "/"); QString display_path = defaultSavePath.replace("\\", "/");
if(!display_path.endsWith("/")) if(!display_path.endsWith("/"))
display_path += "/"; display_path += "/";
@ -88,7 +89,7 @@ torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) :
#endif #endif
savePathTxt->addItem(display_path); savePathTxt->addItem(display_path);
if(Preferences::addTorrentsInPause()) { if(pref.addTorrentsInPause()) {
addInPause->setChecked(true); addInPause->setChecked(true);
//addInPause->setEnabled(false); //addInPause->setEnabled(false);
} }

View File

@ -42,7 +42,7 @@ using namespace libtorrent;
QTracker::QTracker(QObject *parent) : QTracker::QTracker(QObject *parent) :
QTcpServer(parent) QTcpServer(parent)
{ {
Q_ASSERT(Preferences::isTrackerEnabled()); Q_ASSERT(Preferences().isTrackerEnabled());
connect(this, SIGNAL(newConnection()), this, SLOT(handlePeerConnection())); connect(this, SIGNAL(newConnection()), this, SLOT(handlePeerConnection()));
} }
@ -66,7 +66,7 @@ void QTracker::handlePeerConnection()
bool QTracker::start() bool QTracker::start()
{ {
const int listen_port = Preferences::getTrackerPort(); const int listen_port = Preferences().getTrackerPort();
// //
if(isListening()) { if(isListening()) {
if(serverPort() == listen_port) { if(serverPort() == listen_port) {

View File

@ -285,7 +285,7 @@ public:
void loadSettings() { void loadSettings() {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
statusFilters->setCurrentRow(settings.value("TransferListFilters/selectedFilterIndex", 0).toInt()); statusFilters->setCurrentRow(settings.value("TransferListFilters/selectedFilterIndex", 0).toInt());
const QStringList label_list = Preferences::getTorrentLabels(); const QStringList label_list = Preferences().getTorrentLabels();
foreach(const QString &label, label_list) { foreach(const QString &label, label_list) {
customLabels.insert(label, 0); customLabels.insert(label, 0);
qDebug("Creating label QListWidgetItem: %s", qPrintable(label)); qDebug("Creating label QListWidgetItem: %s", qPrintable(label));
@ -324,7 +324,7 @@ protected slots:
newLabel->setData(Qt::DecorationRole, QIcon(":/Icons/oxygen/folder.png")); newLabel->setData(Qt::DecorationRole, QIcon(":/Icons/oxygen/folder.png"));
labelFilters->addItem(newLabel); labelFilters->addItem(newLabel);
customLabels.insert(label, 0); customLabels.insert(label, 0);
Preferences::addTorrentLabel(label); Preferences().addTorrentLabel(label);
} }
void showLabelMenu(QPoint) { void showLabelMenu(QPoint) {
@ -391,7 +391,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().removeTorrentLabel(label);
} }
void applyLabelFilter(int row) { void applyLabelFilter(int row) {

View File

@ -180,9 +180,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().getActionOnDblClOnTorrentFn();
} else { } else {
action = Preferences::getActionOnDblClOnTorrentDl(); action = Preferences().getActionOnDblClOnTorrentDl();
} }
switch(action) { switch(action) {
@ -424,7 +424,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().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()));
@ -457,7 +457,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().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()));

View File

@ -125,9 +125,10 @@ QList<QVariantMap> EventManager::getPropFilesInfo(QString hash) const {
void EventManager::setGlobalPreferences(QVariantMap m) const { void EventManager::setGlobalPreferences(QVariantMap m) const {
// UI // UI
Preferences pref;
if(m.contains("locale")) { if(m.contains("locale")) {
QString locale = m["locale"].toString(); QString locale = m["locale"].toString();
if(Preferences::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));
@ -137,26 +138,26 @@ void EventManager::setGlobalPreferences(QVariantMap m) const {
qApp->installTranslator(translator); qApp->installTranslator(translator);
} }
Preferences::setLocale(locale); pref.setLocale(locale);
} }
// Downloads // Downloads
if(m.contains("save_path")) if(m.contains("save_path"))
Preferences::setSavePath(m["save_path"].toString()); pref.setSavePath(m["save_path"].toString());
if(m.contains("temp_path_enabled")) if(m.contains("temp_path_enabled"))
Preferences::setTempPathEnabled(m["temp_path_enabled"].toBool()); pref.setTempPathEnabled(m["temp_path_enabled"].toBool());
if(m.contains("temp_path")) if(m.contains("temp_path"))
Preferences::setTempPath(m["temp_path"].toString()); pref.setTempPath(m["temp_path"].toString());
if(m.contains("scan_dirs") && m.contains("download_in_scan_dirs")) { if(m.contains("scan_dirs") && m.contains("download_in_scan_dirs")) {
QVariantList download_at_path_tmp = m["download_in_scan_dirs"].toList(); QVariantList download_at_path_tmp = m["download_in_scan_dirs"].toList();
QList<bool> download_at_path; QList<bool> download_at_path;
foreach(QVariant var, download_at_path_tmp) { foreach(QVariant var, download_at_path_tmp) {
download_at_path << var.toBool(); download_at_path << var.toBool();
} }
QStringList old_folders = Preferences::getScanDirs(); QStringList old_folders = pref.getScanDirs();
QStringList new_folders = m["scan_dirs"].toStringList(); QStringList new_folders = m["scan_dirs"].toStringList();
if(download_at_path.size() == new_folders.size()) { if(download_at_path.size() == new_folders.size()) {
Preferences::setScanDirs(new_folders); pref.setScanDirs(new_folders);
Preferences::setDownloadInScanDirs(download_at_path); pref.setDownloadInScanDirs(download_at_path);
foreach(const QString &old_folder, old_folders) { foreach(const QString &old_folder, old_folders) {
// Update deleted folders // Update deleted folders
if(!new_folders.contains(old_folder)) { if(!new_folders.contains(old_folder)) {
@ -175,168 +176,169 @@ void EventManager::setGlobalPreferences(QVariantMap m) const {
} }
} }
if(m.contains("export_dir")) if(m.contains("export_dir"))
Preferences::setExportDir(m["export_dir"].toString()); pref.setExportDir(m["export_dir"].toString());
if(m.contains("mail_notification_enabled")) if(m.contains("mail_notification_enabled"))
Preferences::setMailNotificationEnabled(m["mail_notification_enabled"].toBool()); pref.setMailNotificationEnabled(m["mail_notification_enabled"].toBool());
if(m.contains("mail_notification_email")) if(m.contains("mail_notification_email"))
Preferences::setMailNotificationEmail(m["mail_notification_email"].toString()); pref.setMailNotificationEmail(m["mail_notification_email"].toString());
if(m.contains("mail_notification_smtp")) if(m.contains("mail_notification_smtp"))
Preferences::setMailNotificationSMTP(m["mail_notification_smtp"].toString()); pref.setMailNotificationSMTP(m["mail_notification_smtp"].toString());
if(m.contains("autorun_enabled")) if(m.contains("autorun_enabled"))
Preferences::setAutoRunEnabled(m["autorun_enabled"].toBool()); pref.setAutoRunEnabled(m["autorun_enabled"].toBool());
if(m.contains("autorun_program")) if(m.contains("autorun_program"))
Preferences::setAutoRunProgram(m["autorun_program"].toString()); pref.setAutoRunProgram(m["autorun_program"].toString());
if(m.contains("preallocate_all")) if(m.contains("preallocate_all"))
Preferences::preAllocateAllFiles(m["preallocate_all"].toBool()); pref.preAllocateAllFiles(m["preallocate_all"].toBool());
if(m.contains("queueing_enabled")) if(m.contains("queueing_enabled"))
Preferences::setQueueingSystemEnabled(m["queueing_enabled"].toBool()); pref.setQueueingSystemEnabled(m["queueing_enabled"].toBool());
if(m.contains("max_active_downloads")) if(m.contains("max_active_downloads"))
Preferences::setMaxActiveDownloads(m["max_active_downloads"].toInt()); pref.setMaxActiveDownloads(m["max_active_downloads"].toInt());
if(m.contains("max_active_torrents")) if(m.contains("max_active_torrents"))
Preferences::setMaxActiveTorrents(m["max_active_torrents"].toInt()); pref.setMaxActiveTorrents(m["max_active_torrents"].toInt());
if(m.contains("max_active_uploads")) if(m.contains("max_active_uploads"))
Preferences::setMaxActiveUploads(m["max_active_uploads"].toInt()); pref.setMaxActiveUploads(m["max_active_uploads"].toInt());
#if LIBTORRENT_VERSION_MINOR > 14 #if LIBTORRENT_VERSION_MINOR > 14
if(m.contains("incomplete_files_ext")) if(m.contains("incomplete_files_ext"))
Preferences::useIncompleteFilesExtension(m["incomplete_files_ext"].toBool()); pref.useIncompleteFilesExtension(m["incomplete_files_ext"].toBool());
#endif #endif
// Connection // Connection
if(m.contains("listen_port")) if(m.contains("listen_port"))
Preferences::setSessionPort(m["listen_port"].toInt()); pref.setSessionPort(m["listen_port"].toInt());
if(m.contains("upnp")) if(m.contains("upnp"))
Preferences::setUPnPEnabled(m["upnp"].toBool()); pref.setUPnPEnabled(m["upnp"].toBool());
if(m.contains("natpmp")) if(m.contains("natpmp"))
Preferences::setNATPMPEnabled(m["natpmp"].toBool()); pref.setNATPMPEnabled(m["natpmp"].toBool());
if(m.contains("dl_limit")) if(m.contains("dl_limit"))
Preferences::setGlobalDownloadLimit(m["dl_limit"].toInt()); pref.setGlobalDownloadLimit(m["dl_limit"].toInt());
if(m.contains("up_limit")) if(m.contains("up_limit"))
Preferences::setGlobalUploadLimit(m["up_limit"].toInt()); pref.setGlobalUploadLimit(m["up_limit"].toInt());
if(m.contains("max_connec")) if(m.contains("max_connec"))
Preferences::setMaxConnecs(m["max_connec"].toInt()); pref.setMaxConnecs(m["max_connec"].toInt());
if(m.contains("max_connec_per_torrent")) if(m.contains("max_connec_per_torrent"))
Preferences::setMaxConnecsPerTorrent(m["max_connec_per_torrent"].toInt()); pref.setMaxConnecsPerTorrent(m["max_connec_per_torrent"].toInt());
if(m.contains("max_uploads_per_torrent")) if(m.contains("max_uploads_per_torrent"))
Preferences::setMaxUploadsPerTorrent(m["max_uploads_per_torrent"].toInt()); pref.setMaxUploadsPerTorrent(m["max_uploads_per_torrent"].toInt());
// Bittorrent // Bittorrent
if(m.contains("dht")) if(m.contains("dht"))
Preferences::setDHTEnabled(m["dht"].toBool()); pref.setDHTEnabled(m["dht"].toBool());
if(m.contains("dhtSameAsBT")) if(m.contains("dhtSameAsBT"))
Preferences::setDHTPortSameAsBT(m["dhtSameAsBT"].toBool()); pref.setDHTPortSameAsBT(m["dhtSameAsBT"].toBool());
if(m.contains("dht_port")) if(m.contains("dht_port"))
Preferences::setDHTPort(m["dht_port"].toInt()); pref.setDHTPort(m["dht_port"].toInt());
if(m.contains("pex")) if(m.contains("pex"))
Preferences::setPeXEnabled(m["pex"].toBool()); pref.setPeXEnabled(m["pex"].toBool());
qDebug("Pex support: %d", (int)m["pex"].toBool()); qDebug("Pex support: %d", (int)m["pex"].toBool());
if(m.contains("lsd")) if(m.contains("lsd"))
Preferences::setLSDEnabled(m["lsd"].toBool()); pref.setLSDEnabled(m["lsd"].toBool());
if(m.contains("encryption")) if(m.contains("encryption"))
Preferences::setEncryptionSetting(m["encryption"].toInt()); pref.setEncryptionSetting(m["encryption"].toInt());
// Proxy // Proxy
if(m.contains("proxy_type")) if(m.contains("proxy_type"))
Preferences::setPeerProxyType(m["proxy_type"].toInt()); pref.setPeerProxyType(m["proxy_type"].toInt());
if(m.contains("proxy_ip")) if(m.contains("proxy_ip"))
Preferences::setPeerProxyIp(m["proxy_ip"].toString()); pref.setPeerProxyIp(m["proxy_ip"].toString());
if(m.contains("proxy_port")) if(m.contains("proxy_port"))
Preferences::setPeerProxyPort(m["proxy_port"].toUInt()); pref.setPeerProxyPort(m["proxy_port"].toUInt());
if(m.contains("proxy_auth_enabled")) if(m.contains("proxy_auth_enabled"))
Preferences::setPeerProxyAuthEnabled(m["proxy_auth_enabled"].toBool()); pref.setPeerProxyAuthEnabled(m["proxy_auth_enabled"].toBool());
if(m.contains("proxy_username")) if(m.contains("proxy_username"))
Preferences::setPeerProxyUsername(m["proxy_username"].toString()); pref.setPeerProxyUsername(m["proxy_username"].toString());
if(m.contains("proxy_password")) if(m.contains("proxy_password"))
Preferences::setPeerProxyPassword(m["proxy_password"].toString()); pref.setPeerProxyPassword(m["proxy_password"].toString());
if(m.contains("http_proxy_type")) if(m.contains("http_proxy_type"))
Preferences::setHTTPProxyType(m["http_proxy_type"].toInt()); pref.setHTTPProxyType(m["http_proxy_type"].toInt());
if(m.contains("http_proxy_ip")) if(m.contains("http_proxy_ip"))
Preferences::setHTTPProxyIp(m["http_proxy_ip"].toString()); pref.setHTTPProxyIp(m["http_proxy_ip"].toString());
if(m.contains("http_proxy_port")) if(m.contains("http_proxy_port"))
Preferences::setHTTPProxyPort(m["http_proxy_port"].toUInt()); pref.setHTTPProxyPort(m["http_proxy_port"].toUInt());
if(m.contains("http_proxy_auth_enabled")) if(m.contains("http_proxy_auth_enabled"))
Preferences::setHTTPProxyAuthEnabled(m["http_proxy_auth_enabled"].toBool()); pref.setHTTPProxyAuthEnabled(m["http_proxy_auth_enabled"].toBool());
if(m.contains("http_proxy_username")) if(m.contains("http_proxy_username"))
Preferences::setHTTPProxyUsername(m["http_proxy_username"].toString()); pref.setHTTPProxyUsername(m["http_proxy_username"].toString());
if(m.contains("http_proxy_password")) if(m.contains("http_proxy_password"))
Preferences::setHTTPProxyPassword(m["http_proxy_password"].toString()); pref.setHTTPProxyPassword(m["http_proxy_password"].toString());
// IP Filter // IP Filter
if(m.contains("ip_filter_enabled")) if(m.contains("ip_filter_enabled"))
Preferences::setFilteringEnabled(m["ip_filter_enabled"].toBool()); pref.setFilteringEnabled(m["ip_filter_enabled"].toBool());
if(m.contains("ip_filter_path")) if(m.contains("ip_filter_path"))
Preferences::setFilter(m["ip_filter_path"].toString()); pref.setFilter(m["ip_filter_path"].toString());
// Web UI // Web UI
if(m.contains("web_ui_port")) if(m.contains("web_ui_port"))
Preferences::setWebUiPort(m["web_ui_port"].toUInt()); pref.setWebUiPort(m["web_ui_port"].toUInt());
if(m.contains("web_ui_username")) if(m.contains("web_ui_username"))
Preferences::setWebUiUsername(m["web_ui_username"].toString()); pref.setWebUiUsername(m["web_ui_username"].toString());
if(m.contains("web_ui_password")) if(m.contains("web_ui_password"))
Preferences::setWebUiPassword(m["web_ui_password"].toString()); pref.setWebUiPassword(m["web_ui_password"].toString());
// Reload preferences // Reload preferences
QBtSession::instance()->configureSession(); QBtSession::instance()->configureSession();
} }
QVariantMap EventManager::getGlobalPreferences() const { QVariantMap EventManager::getGlobalPreferences() const {
const Preferences pref;
QVariantMap data; QVariantMap data;
// UI // UI
data["locale"] = Preferences::getLocale(); data["locale"] = pref.getLocale();
// Downloads // Downloads
data["save_path"] = Preferences::getSavePath(); data["save_path"] = pref.getSavePath();
data["temp_path_enabled"] = Preferences::isTempPathEnabled(); data["temp_path_enabled"] = pref.isTempPathEnabled();
data["temp_path"] = Preferences::getTempPath(); data["temp_path"] = pref.getTempPath();
data["scan_dirs"] = Preferences::getScanDirs(); data["scan_dirs"] = pref.getScanDirs();
QVariantList var_list; QVariantList var_list;
foreach(bool b, Preferences::getDownloadInScanDirs()) { foreach(bool b, pref.getDownloadInScanDirs()) {
var_list << b; var_list << b;
} }
data["download_in_scan_dirs"] = var_list; data["download_in_scan_dirs"] = var_list;
data["export_dir_enabled"] = Preferences::isTorrentExportEnabled(); data["export_dir_enabled"] = pref.isTorrentExportEnabled();
data["export_dir"] = Preferences::getExportDir(); data["export_dir"] = pref.getExportDir();
data["mail_notification_enabled"] = Preferences::isMailNotificationEnabled(); data["mail_notification_enabled"] = pref.isMailNotificationEnabled();
data["mail_notification_email"] = Preferences::getMailNotificationEmail(); data["mail_notification_email"] = pref.getMailNotificationEmail();
data["mail_notification_smtp"] = Preferences::getMailNotificationSMTP(); data["mail_notification_smtp"] = pref.getMailNotificationSMTP();
data["autorun_enabled"] = Preferences::isAutoRunEnabled(); data["autorun_enabled"] = pref.isAutoRunEnabled();
data["autorun_program"] = Preferences::getAutoRunProgram(); data["autorun_program"] = pref.getAutoRunProgram();
data["preallocate_all"] = Preferences::preAllocateAllFiles(); data["preallocate_all"] = pref.preAllocateAllFiles();
data["queueing_enabled"] = Preferences::isQueueingSystemEnabled(); data["queueing_enabled"] = pref.isQueueingSystemEnabled();
data["max_active_downloads"] = Preferences::getMaxActiveDownloads(); data["max_active_downloads"] = pref.getMaxActiveDownloads();
data["max_active_torrents"] = Preferences::getMaxActiveTorrents(); data["max_active_torrents"] = pref.getMaxActiveTorrents();
data["max_active_uploads"] = Preferences::getMaxActiveUploads(); data["max_active_uploads"] = pref.getMaxActiveUploads();
#if LIBTORRENT_VERSION_MINOR > 14 #if LIBTORRENT_VERSION_MINOR > 14
data["incomplete_files_ext"] = Preferences::useIncompleteFilesExtension(); data["incomplete_files_ext"] = pref.useIncompleteFilesExtension();
#endif #endif
// Connection // Connection
data["listen_port"] = Preferences::getSessionPort(); data["listen_port"] = pref.getSessionPort();
data["upnp"] = Preferences::isUPnPEnabled(); data["upnp"] = pref.isUPnPEnabled();
data["natpmp"] = Preferences::isNATPMPEnabled(); data["natpmp"] = pref.isNATPMPEnabled();
data["dl_limit"] = Preferences::getGlobalDownloadLimit(); data["dl_limit"] = pref.getGlobalDownloadLimit();
data["up_limit"] = Preferences::getGlobalUploadLimit(); data["up_limit"] = pref.getGlobalUploadLimit();
data["max_connec"] = Preferences::getMaxConnecs(); data["max_connec"] = pref.getMaxConnecs();
data["max_connec_per_torrent"] = Preferences::getMaxConnecsPerTorrent(); data["max_connec_per_torrent"] = pref.getMaxConnecsPerTorrent();
data["max_uploads_per_torrent"] = Preferences::getMaxUploadsPerTorrent(); data["max_uploads_per_torrent"] = pref.getMaxUploadsPerTorrent();
// Bittorrent // Bittorrent
data["dht"] = Preferences::isDHTEnabled(); data["dht"] = pref.isDHTEnabled();
data["dhtSameAsBT"] = Preferences::isDHTPortSameAsBT(); data["dhtSameAsBT"] = pref.isDHTPortSameAsBT();
data["dht_port"] = Preferences::getDHTPort(); data["dht_port"] = pref.getDHTPort();
data["pex"] = Preferences::isPeXEnabled(); data["pex"] = pref.isPeXEnabled();
data["lsd"] = Preferences::isLSDEnabled(); data["lsd"] = pref.isLSDEnabled();
data["encryption"] = Preferences::getEncryptionSetting(); data["encryption"] = pref.getEncryptionSetting();
// Proxy // Proxy
data["proxy_type"] = Preferences::getPeerProxyType(); data["proxy_type"] = pref.getPeerProxyType();
data["proxy_ip"] = Preferences::getPeerProxyIp(); data["proxy_ip"] = pref.getPeerProxyIp();
data["proxy_port"] = Preferences::getPeerProxyPort(); data["proxy_port"] = pref.getPeerProxyPort();
data["proxy_auth_enabled"] = Preferences::isPeerProxyAuthEnabled(); data["proxy_auth_enabled"] = pref.isPeerProxyAuthEnabled();
data["proxy_username"] = Preferences::getPeerProxyUsername(); data["proxy_username"] = pref.getPeerProxyUsername();
data["proxy_password"] = Preferences::getPeerProxyPassword(); data["proxy_password"] = pref.getPeerProxyPassword();
data["http_proxy_type"] = Preferences::getHTTPProxyType(); data["http_proxy_type"] = pref.getHTTPProxyType();
data["http_proxy_ip"] = Preferences::getHTTPProxyIp(); data["http_proxy_ip"] = pref.getHTTPProxyIp();
data["http_proxy_port"] = Preferences::getHTTPProxyPort(); data["http_proxy_port"] = pref.getHTTPProxyPort();
data["http_proxy_auth_enabled"] = Preferences::isHTTPProxyAuthEnabled(); data["http_proxy_auth_enabled"] = pref.isHTTPProxyAuthEnabled();
data["http_proxy_username"] = Preferences::getHTTPProxyUsername(); data["http_proxy_username"] = pref.getHTTPProxyUsername();
data["http_proxy_password"] = Preferences::getHTTPProxyPassword(); data["http_proxy_password"] = pref.getHTTPProxyPassword();
// IP Filter // IP Filter
data["ip_filter_enabled"] = Preferences::isFilteringEnabled(); data["ip_filter_enabled"] = pref.isFilteringEnabled();
data["ip_filter_path"] = Preferences::getFilter(); data["ip_filter_path"] = pref.getFilter();
// Web UI // Web UI
data["web_ui_port"] = Preferences::getWebUiPort(); data["web_ui_port"] = pref.getWebUiPort();
data["web_ui_username"] = Preferences::getWebUiUsername(); data["web_ui_username"] = pref.getWebUiUsername();
data["web_ui_password"] = Preferences::getWebUiPassword(); data["web_ui_password"] = pref.getWebUiPassword();
return data; return data;
} }

View File

@ -473,13 +473,13 @@ void HttpConnection::respondCommand(QString command)
qlonglong limit = parser.post("limit").toLongLong(); qlonglong limit = parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if(limit == 0) limit = -1;
QBtSession::instance()->getSession()->set_upload_rate_limit(limit); QBtSession::instance()->getSession()->set_upload_rate_limit(limit);
Preferences::setGlobalUploadLimit(limit/1024.); Preferences().setGlobalUploadLimit(limit/1024.);
} }
if(command == "setGlobalDlLimit") { if(command == "setGlobalDlLimit") {
qlonglong limit = parser.post("limit").toLongLong(); qlonglong limit = parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if(limit == 0) limit = -1;
QBtSession::instance()->getSession()->set_download_rate_limit(limit); QBtSession::instance()->getSession()->set_download_rate_limit(limit);
Preferences::setGlobalDownloadLimit(limit/1024.); Preferences().setGlobalDownloadLimit(limit/1024.);
} }
if(command == "pause") { if(command == "pause") {
emit pauseTorrent(parser.post("hash")); emit pauseTorrent(parser.post("hash"));

View File

@ -81,8 +81,9 @@ void HttpServer::resetNbFailedAttemptsForIp(QString ip) {
} }
HttpServer::HttpServer(int msec, QObject* parent) : QTcpServer(parent) { HttpServer::HttpServer(int msec, QObject* parent) : QTcpServer(parent) {
username = Preferences::getWebUiUsername().toLocal8Bit(); const Preferences pref;
password_ha1 = Preferences::getWebUiPassword().toLocal8Bit(); username = pref.getWebUiUsername().toLocal8Bit();
password_ha1 = pref.getWebUiPassword().toLocal8Bit();
connect(this, SIGNAL(newConnection()), this, SLOT(newHttpConnection())); connect(this, SIGNAL(newConnection()), this, SLOT(newHttpConnection()));
manager = new EventManager(this); manager = new EventManager(this);
//add torrents //add torrents