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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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