Browse Source

Code clean up

adaptive-webui-19844
Christophe Dumez 14 years ago
parent
commit
126e2e7c75
  1. 10
      src/console_imp.h
  2. 4
      src/main.cpp
  3. 156
      src/mainwindow.cpp
  4. 6
      src/mainwindow.h
  5. 4
      src/properties/peerlistwidget.cpp
  6. 19
      src/properties/propertieswidget.cpp
  7. 9
      src/properties/propertieswidget.h
  8. 12
      src/properties/trackerlist.cpp
  9. 3
      src/qtlibtorrent/qbtsession.cpp
  10. 8
      src/rss/rssfeed.cpp
  11. 5
      src/rss/rssfeed.h
  12. 12
      src/rss/rssfolder.cpp
  13. 6
      src/rss/rssfolder.h
  14. 2
      src/rss/rssmanager.cpp
  15. 1
      src/rss/rssmanager.h
  16. 12
      src/searchengine/searchengine.cpp
  17. 53
      src/searchengine/searchengine.h
  18. 4
      src/src.pro
  19. 27
      src/statusbar.h
  20. 41
      src/torrentadditiondlg.cpp
  21. 34
      src/torrentadditiondlg.h
  22. 4
      src/torrentimportdlg.cpp
  23. 2
      src/torrentimportdlg.h
  24. 4
      src/transferlistwidget.cpp
  25. 6
      src/transferlistwidget.h
  26. 28
      src/webui/eventmanager.cpp
  27. 5
      src/webui/eventmanager.h
  28. 66
      src/webui/httpconnection.cpp
  29. 6
      src/webui/httpconnection.h
  30. 35
      src/webui/httpserver.cpp
  31. 4
      src/webui/httpserver.h

10
src/console_imp.h

@ -39,17 +39,13 @@ using namespace libtorrent;
class consoleDlg : public QDialog, private Ui_ConsoleDlg{ class consoleDlg : public QDialog, private Ui_ConsoleDlg{
Q_OBJECT Q_OBJECT
private:
QBtSession *BTSession;
public: public:
consoleDlg(QWidget *parent, QBtSession* _BTSession) : QDialog(parent) { consoleDlg(QWidget *parent) : QDialog(parent) {
setupUi(this); setupUi(this);
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
setModal(true); setModal(true);
BTSession = _BTSession; textConsole->setHtml(QBtSession::instance()->getConsoleMessages().join("<br>"));
textConsole->setHtml(BTSession->getConsoleMessages().join("<br>")); textBannedPeers->setHtml(QBtSession::instance()->getPeerBanMessages().join("<br>"));
textBannedPeers->setHtml(BTSession->getPeerBanMessages().join("<br>"));
show(); show();
} }

4
src/main.cpp

@ -43,7 +43,7 @@
#include <QPushButton> #include <QPushButton>
#include <QTimer> #include <QTimer>
#include "sessionapplication.h" #include "sessionapplication.h"
#include "GUI.h" #include "mainwindow.h"
#include "ico.h" #include "ico.h"
#else #else
#include "qtsinglecoreapplication.h" #include "qtsinglecoreapplication.h"
@ -295,7 +295,7 @@ int main(int argc, char *argv[]){
// Remove first argument (program name) // Remove first argument (program name)
torrentCmdLine.removeFirst(); torrentCmdLine.removeFirst();
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
GUI window(0, torrentCmdLine); MainWindow window(0, torrentCmdLine);
QObject::connect(&app, SIGNAL(messageReceived(const QString&)), QObject::connect(&app, SIGNAL(messageReceived(const QString&)),
&window, SLOT(processParams(const QString&))); &window, SLOT(processParams(const QString&)));
app.setActivationWindow(&window); app.setActivationWindow(&window);

156
src/GUI.cpp → src/mainwindow.cpp

@ -44,7 +44,7 @@
#include <QShortcut> #include <QShortcut>
#include <QScrollBar> #include <QScrollBar>
#include "GUI.h" #include "mainwindow.h"
#include "transferlistwidget.h" #include "transferlistwidget.h"
#include "misc.h" #include "misc.h"
#include "torrentcreatordlg.h" #include "torrentcreatordlg.h"
@ -90,7 +90,7 @@ using namespace libtorrent;
*****************************************************/ *****************************************************/
// Constructor // Constructor
GUI::GUI(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent), force_exit(false) { MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent), force_exit(false) {
setupUi(this); setupUi(this);
ui_locked = Preferences::isUILocked(); ui_locked = Preferences::isUILocked();
setWindowTitle(tr("qBittorrent %1", "e.g: qBittorrent v0.x").arg(QString::fromUtf8(VERSION))); setWindowTitle(tr("qBittorrent %1", "e.g: qBittorrent v0.x").arg(QString::fromUtf8(VERSION)));
@ -153,7 +153,7 @@ GUI::GUI(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent), for
// Transfer List tab // Transfer List tab
transferList = new TransferListWidget(hSplitter, this, BTSession); transferList = new TransferListWidget(hSplitter, this, BTSession);
properties = new PropertiesWidget(hSplitter, this, transferList, BTSession); properties = new PropertiesWidget(hSplitter, this, transferList);
transferListFilters = new TransferListFiltersWidget(vSplitter, transferList); transferListFilters = new TransferListFiltersWidget(vSplitter, transferList);
hSplitter->addWidget(transferList); hSplitter->addWidget(transferList);
hSplitter->addWidget(properties); hSplitter->addWidget(properties);
@ -192,7 +192,7 @@ GUI::GUI(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent), for
setAcceptDrops(true); setAcceptDrops(true);
createKeyboardShortcuts(); createKeyboardShortcuts();
// Create status bar // Create status bar
status_bar = new StatusBar(QMainWindow::statusBar(), BTSession); status_bar = new StatusBar(QMainWindow::statusBar());
connect(status_bar->connectionStatusButton(), SIGNAL(clicked()), SLOT(showConnectionSettings())); connect(status_bar->connectionStatusButton(), SIGNAL(clicked()), SLOT(showConnectionSettings()));
connect(actionUse_alternative_speed_limits, SIGNAL(triggered()), status_bar, SLOT(toggleAlternativeSpeeds())); connect(actionUse_alternative_speed_limits, SIGNAL(triggered()), status_bar, SLOT(toggleAlternativeSpeeds()));
@ -259,7 +259,7 @@ GUI::GUI(QWidget *parent, QStringList torrentCmdLine) : QMainWindow(parent), for
#endif #endif
} }
void GUI::deleteBTSession() { void MainWindow::deleteBTSession() {
guiUpdater->stop(); guiUpdater->stop();
status_bar->stopTimer(); status_bar->stopTimer();
if(BTSession) { if(BTSession) {
@ -270,7 +270,7 @@ void GUI::deleteBTSession() {
} }
// Destructor // Destructor
GUI::~GUI() { MainWindow::~MainWindow() {
qDebug("GUI destruction"); qDebug("GUI destruction");
hide(); hide();
#ifdef Q_WS_MAC #ifdef Q_WS_MAC
@ -331,7 +331,7 @@ GUI::~GUI() {
qDebug("Exiting GUI destructor..."); qDebug("Exiting GUI destructor...");
} }
void GUI::defineUILockPassword() { void MainWindow::defineUILockPassword() {
QString old_pass_md5 = Preferences::getUILockPasswordMD5(); QString old_pass_md5 = Preferences::getUILockPasswordMD5();
if(old_pass_md5.isNull()) old_pass_md5 = ""; if(old_pass_md5.isNull()) old_pass_md5 = "";
bool ok = false; bool ok = false;
@ -344,7 +344,7 @@ void GUI::defineUILockPassword() {
} }
} }
void GUI::on_actionLock_qBittorrent_triggered() { void MainWindow::on_actionLock_qBittorrent_triggered() {
// Check if there is a password // Check if there is a password
if(Preferences::getUILockPasswordMD5().isEmpty()) { if(Preferences::getUILockPasswordMD5().isEmpty()) {
// Ask for a password // Ask for a password
@ -360,7 +360,7 @@ void GUI::on_actionLock_qBittorrent_triggered() {
hide(); hide();
} }
void GUI::displayRSSTab(bool enable) { void MainWindow::displayRSSTab(bool enable) {
if(enable) { if(enable) {
// RSS tab // RSS tab
if(!rssWidget) { if(!rssWidget) {
@ -378,11 +378,11 @@ void GUI::displayRSSTab(bool enable) {
} }
} }
void GUI::displaySearchTab(bool enable) { void MainWindow::displaySearchTab(bool enable) {
if(enable) { if(enable) {
// RSS tab // RSS tab
if(!searchEngine) { if(!searchEngine) {
searchEngine = new SearchEngine(this, BTSession); searchEngine = new SearchEngine(this);
tabs->insertTab(1, searchEngine, QIcon(QString::fromUtf8(":/Icons/oxygen/edit-find.png")), tr("Search")); tabs->insertTab(1, searchEngine, QIcon(QString::fromUtf8(":/Icons/oxygen/edit-find.png")), tr("Search"));
} }
tabs->showTabBar(true); tabs->showTabBar(true);
@ -395,26 +395,26 @@ void GUI::displaySearchTab(bool enable) {
} }
} }
void GUI::updateNbTorrents(unsigned int nb_downloading, unsigned int nb_seeding, unsigned int nb_active, unsigned int nb_inactive, unsigned int nb_paused) { void MainWindow::updateNbTorrents(unsigned int nb_downloading, unsigned int nb_seeding, unsigned int nb_active, unsigned int nb_inactive, unsigned int nb_paused) {
Q_UNUSED(nb_downloading); Q_UNUSED(nb_downloading);
Q_UNUSED(nb_seeding); Q_UNUSED(nb_seeding);
Q_UNUSED(nb_paused); Q_UNUSED(nb_paused);
tabs->setTabText(0, tr("Transfers (%1)").arg(QString::number(nb_inactive+nb_active))); tabs->setTabText(0, tr("Transfers (%1)").arg(QString::number(nb_inactive+nb_active)));
} }
void GUI::on_actionWebsite_triggered() const { void MainWindow::on_actionWebsite_triggered() const {
QDesktopServices::openUrl(QUrl(QString::fromUtf8("http://www.qbittorrent.org"))); QDesktopServices::openUrl(QUrl(QString::fromUtf8("http://www.qbittorrent.org")));
} }
void GUI::on_actionDocumentation_triggered() const { void MainWindow::on_actionDocumentation_triggered() const {
QDesktopServices::openUrl(QUrl(QString::fromUtf8("http://doc.qbittorrent.org"))); QDesktopServices::openUrl(QUrl(QString::fromUtf8("http://doc.qbittorrent.org")));
} }
void GUI::on_actionBugReport_triggered() const { void MainWindow::on_actionBugReport_triggered() const {
QDesktopServices::openUrl(QUrl(QString::fromUtf8("http://bugs.qbittorrent.org"))); QDesktopServices::openUrl(QUrl(QString::fromUtf8("http://bugs.qbittorrent.org")));
} }
void GUI::tab_changed(int new_tab) { void MainWindow::tab_changed(int new_tab) {
Q_UNUSED(new_tab); Q_UNUSED(new_tab);
// We cannot rely on the index new_tab // We cannot rely on the index new_tab
// because the tab order is undetermined now // because the tab order is undetermined now
@ -430,7 +430,7 @@ void GUI::tab_changed(int new_tab) {
} }
} }
void GUI::writeSettings() { void MainWindow::writeSettings() {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
settings.beginGroup(QString::fromUtf8("MainWindow")); settings.beginGroup(QString::fromUtf8("MainWindow"));
settings.setValue("geometry", saveGeometry()); settings.setValue("geometry", saveGeometry());
@ -443,18 +443,18 @@ void GUI::writeSettings() {
} }
// called when a torrent has finished // called when a torrent has finished
void GUI::finishedTorrent(QTorrentHandle& h) const { void MainWindow::finishedTorrent(QTorrentHandle& h) const {
if(!TorrentPersistentData::isSeed(h.hash())) if(!TorrentPersistentData::isSeed(h.hash()))
showNotificationBaloon(tr("Download completion"), tr("%1 has finished downloading.", "e.g: xxx.avi has finished downloading.").arg(h.name())); showNotificationBaloon(tr("Download completion"), tr("%1 has finished downloading.", "e.g: xxx.avi has finished downloading.").arg(h.name()));
} }
// Notification when disk is full // Notification when disk is full
void GUI::fullDiskError(QTorrentHandle& h, QString msg) const { void MainWindow::fullDiskError(QTorrentHandle& h, QString msg) const {
if(!h.is_valid()) return; if(!h.is_valid()) return;
showNotificationBaloon(tr("I/O Error", "i.e: Input/Output Error"), tr("An I/O error occured for torrent %1.\n Reason: %2", "e.g: An error occured for torrent xxx.avi.\n Reason: disk is full.").arg(h.name()).arg(msg)); showNotificationBaloon(tr("I/O Error", "i.e: Input/Output Error"), tr("An I/O error occured for torrent %1.\n Reason: %2", "e.g: An error occured for torrent xxx.avi.\n Reason: disk is full.").arg(h.name()).arg(msg));
} }
void GUI::createKeyboardShortcuts() { void MainWindow::createKeyboardShortcuts() {
actionCreate_torrent->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+N"))); actionCreate_torrent->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+N")));
actionOpen->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+O"))); actionOpen->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+O")));
actionExit->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+Q"))); actionExit->setShortcut(QKeySequence(QString::fromUtf8("Ctrl+Q")));
@ -478,23 +478,23 @@ void GUI::createKeyboardShortcuts() {
} }
// Keyboard shortcuts slots // Keyboard shortcuts slots
void GUI::displayTransferTab() const { void MainWindow::displayTransferTab() const {
tabs->setCurrentWidget(transferList); tabs->setCurrentWidget(transferList);
} }
void GUI::displaySearchTab() const { void MainWindow::displaySearchTab() const {
if(searchEngine) if(searchEngine)
tabs->setCurrentWidget(searchEngine); tabs->setCurrentWidget(searchEngine);
} }
void GUI::displayRSSTab() const { void MainWindow::displayRSSTab() const {
if(rssWidget) if(rssWidget)
tabs->setCurrentWidget(rssWidget); tabs->setCurrentWidget(rssWidget);
} }
// End of keyboard shortcuts slots // End of keyboard shortcuts slots
void GUI::readSettings() { void MainWindow::readSettings() {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
settings.beginGroup(QString::fromUtf8("MainWindow")); settings.beginGroup(QString::fromUtf8("MainWindow"));
restoreGeometry(settings.value("geometry").toByteArray()); restoreGeometry(settings.value("geometry").toByteArray());
@ -513,7 +513,7 @@ void GUI::readSettings() {
settings.endGroup(); settings.endGroup();
} }
void GUI::balloonClicked() { void MainWindow::balloonClicked() {
if(isHidden()) { if(isHidden()) {
show(); show();
if(isMinimized()) { if(isMinimized()) {
@ -524,7 +524,7 @@ void GUI::balloonClicked() {
} }
} }
void GUI::askRecursiveTorrentDownloadConfirmation(QTorrentHandle &h) { void MainWindow::askRecursiveTorrentDownloadConfirmation(QTorrentHandle &h) {
if(Preferences::recursiveDownloadDisabled()) return; if(Preferences::recursiveDownloadDisabled()) return;
QMessageBox confirmBox(QMessageBox::Question, tr("Recursive download confirmation"), tr("The torrent %1 contains torrent files, do you want to proceed with their download?").arg(h.name())); QMessageBox confirmBox(QMessageBox::Question, tr("Recursive download confirmation"), tr("The torrent %1 contains torrent files, do you want to proceed with their download?").arg(h.name()));
QPushButton *yes = confirmBox.addButton(tr("Yes"), QMessageBox::YesRole); QPushButton *yes = confirmBox.addButton(tr("Yes"), QMessageBox::YesRole);
@ -541,12 +541,12 @@ void GUI::askRecursiveTorrentDownloadConfirmation(QTorrentHandle &h) {
} }
} }
void GUI::handleDownloadFromUrlFailure(QString url, QString reason) const{ void MainWindow::handleDownloadFromUrlFailure(QString url, QString reason) const{
// Display a message box // Display a message box
showNotificationBaloon(tr("Url download error"), tr("Couldn't download file at url: %1, reason: %2.").arg(url).arg(reason)); showNotificationBaloon(tr("Url download error"), tr("Couldn't download file at url: %1, reason: %2.").arg(url).arg(reason));
} }
void GUI::on_actionSet_global_upload_limit_triggered() { void MainWindow::on_actionSet_global_upload_limit_triggered() {
qDebug("actionSet_global_upload_limit_triggered"); qDebug("actionSet_global_upload_limit_triggered");
bool ok; bool ok;
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), BTSession->getSession()->upload_rate_limit()); const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), BTSession->getSession()->upload_rate_limit());
@ -560,15 +560,15 @@ void GUI::on_actionSet_global_upload_limit_triggered() {
} }
} }
void GUI::on_actionShow_console_triggered() { void MainWindow::on_actionShow_console_triggered() {
if(!console) { if(!console) {
console = new consoleDlg(this, BTSession); console = new consoleDlg(this);
} else { } else {
console->setFocus(); console->setFocus();
} }
} }
void GUI::on_actionSet_global_download_limit_triggered() { void MainWindow::on_actionSet_global_download_limit_triggered() {
qDebug("actionSet_global_download_limit_triggered"); qDebug("actionSet_global_download_limit_triggered");
bool ok; bool ok;
const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), BTSession->getSession()->download_rate_limit()); const long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), BTSession->getSession()->download_rate_limit());
@ -584,12 +584,12 @@ void GUI::on_actionSet_global_download_limit_triggered() {
// Necessary if we want to close the window // Necessary if we want to close the window
// in one time if "close to systray" is enabled // in one time if "close to systray" is enabled
void GUI::on_actionExit_triggered() { void MainWindow::on_actionExit_triggered() {
force_exit = true; force_exit = true;
close(); close();
} }
QWidget* GUI::getCurrentTabWidget() const { QWidget* MainWindow::getCurrentTabWidget() const {
if(isMinimized() || !isVisible()) if(isMinimized() || !isVisible())
return 0; return 0;
if(tabs->currentIndex() == 0) if(tabs->currentIndex() == 0)
@ -597,11 +597,11 @@ QWidget* GUI::getCurrentTabWidget() const {
return tabs->currentWidget(); return tabs->currentWidget();
} }
void GUI::setTabText(int index, QString text) const { void MainWindow::setTabText(int index, QString text) const {
tabs->setTabText(index, text); tabs->setTabText(index, text);
} }
bool GUI::unlockUI() { bool MainWindow::unlockUI() {
bool ok = false; bool ok = false;
QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok); QString clear_password = QInputDialog::getText(this, tr("UI lock password"), tr("Please type the UI lock password:"), QLineEdit::Password, "", &ok);
if(!ok) return false; if(!ok) return false;
@ -619,7 +619,7 @@ bool GUI::unlockUI() {
return false; return false;
} }
void GUI::notifyOfUpdate(QString) { void MainWindow::notifyOfUpdate(QString) {
// Show restart message // Show restart message
status_bar->showRestartRequired(); status_bar->showRestartRequired();
// Delete the executable watcher // Delete the executable watcher
@ -628,7 +628,7 @@ void GUI::notifyOfUpdate(QString) {
} }
// Toggle Main window visibility // Toggle Main window visibility
void GUI::toggleVisibility(QSystemTrayIcon::ActivationReason e) { void MainWindow::toggleVisibility(QSystemTrayIcon::ActivationReason e) {
if(e == QSystemTrayIcon::Trigger || e == QSystemTrayIcon::DoubleClick) { if(e == QSystemTrayIcon::Trigger || e == QSystemTrayIcon::DoubleClick) {
if(isHidden()) { if(isHidden()) {
if(ui_locked) { if(ui_locked) {
@ -653,7 +653,7 @@ void GUI::toggleVisibility(QSystemTrayIcon::ActivationReason e) {
} }
// Display About Dialog // Display About Dialog
void GUI::on_actionAbout_triggered() { void MainWindow::on_actionAbout_triggered() {
//About dialog //About dialog
if(aboutDlg) { if(aboutDlg) {
aboutDlg->setFocus(); aboutDlg->setFocus();
@ -662,7 +662,7 @@ void GUI::on_actionAbout_triggered() {
} }
} }
void GUI::showEvent(QShowEvent *e) { void MainWindow::showEvent(QShowEvent *e) {
qDebug("** Show Event **"); qDebug("** Show Event **");
if(getCurrentTabWidget() == transferList) { if(getCurrentTabWidget() == transferList) {
qDebug("-> Refreshing transfer list"); qDebug("-> Refreshing transfer list");
@ -673,7 +673,7 @@ void GUI::showEvent(QShowEvent *e) {
} }
// Called when we close the program // Called when we close the program
void GUI::closeEvent(QCloseEvent *e) { void MainWindow::closeEvent(QCloseEvent *e) {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
const bool goToSystrayOnExit = settings.value(QString::fromUtf8("Preferences/General/CloseToTray"), false).toBool(); const bool goToSystrayOnExit = settings.value(QString::fromUtf8("Preferences/General/CloseToTray"), false).toBool();
if(!force_exit && systrayIcon && goToSystrayOnExit && !this->isHidden()) { if(!force_exit && systrayIcon && goToSystrayOnExit && !this->isHidden()) {
@ -718,7 +718,7 @@ void GUI::closeEvent(QCloseEvent *e) {
} }
// Display window to create a torrent // Display window to create a torrent
void GUI::on_actionCreate_torrent_triggered() { void MainWindow::on_actionCreate_torrent_triggered() {
if(createTorrentDlg) { if(createTorrentDlg) {
createTorrentDlg->setFocus(); createTorrentDlg->setFocus();
} else { } else {
@ -727,7 +727,7 @@ void GUI::on_actionCreate_torrent_triggered() {
} }
} }
bool GUI::event(QEvent * e) { bool MainWindow::event(QEvent * e) {
switch(e->type()) { switch(e->type()) {
case QEvent::WindowStateChange: { case QEvent::WindowStateChange: {
qDebug("Window change event"); qDebug("Window change event");
@ -774,7 +774,7 @@ bool GUI::event(QEvent * e) {
} }
// Action executed when a file is dropped // Action executed when a file is dropped
void GUI::dropEvent(QDropEvent *event) { void MainWindow::dropEvent(QDropEvent *event) {
event->acceptProposedAction(); event->acceptProposedAction();
QStringList files; QStringList files;
if(event->mimeData()->hasUrls()) { if(event->mimeData()->hasUrls()) {
@ -811,7 +811,7 @@ void GUI::dropEvent(QDropEvent *event) {
continue; continue;
} }
if(useTorrentAdditionDialog) { if(useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this, BTSession); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoad(file); dialog->showLoad(file);
}else{ }else{
BTSession->addTorrent(file); BTSession->addTorrent(file);
@ -820,7 +820,7 @@ void GUI::dropEvent(QDropEvent *event) {
} }
// Decode if we accept drag 'n drop or not // Decode if we accept drag 'n drop or not
void GUI::dragEnterEvent(QDragEnterEvent *event) { void MainWindow::dragEnterEvent(QDragEnterEvent *event) {
foreach(const QString &mime, event->mimeData()->formats()){ foreach(const QString &mime, event->mimeData()->formats()){
qDebug("mimeData: %s", mime.toLocal8Bit().data()); qDebug("mimeData: %s", mime.toLocal8Bit().data());
} }
@ -837,7 +837,7 @@ void GUI::dragEnterEvent(QDragEnterEvent *event) {
// Display a dialog to allow user to add // Display a dialog to allow user to add
// torrents to download list // torrents to download list
void GUI::on_actionOpen_triggered() { void MainWindow::on_actionOpen_triggered() {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
// Open File Open Dialog // Open File Open Dialog
// Note: it is possible to select more than one file // Note: it is possible to select more than one file
@ -849,7 +849,7 @@ void GUI::on_actionOpen_triggered() {
const uint listSize = pathsList.size(); const uint listSize = pathsList.size();
for(uint i=0; i<listSize; ++i) { for(uint i=0; i<listSize; ++i) {
if(useTorrentAdditionDialog) { if(useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this, BTSession); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoad(pathsList.at(i)); dialog->showLoad(pathsList.at(i));
}else{ }else{
BTSession->addTorrent(pathsList.at(i)); BTSession->addTorrent(pathsList.at(i));
@ -866,11 +866,11 @@ void GUI::on_actionOpen_triggered() {
// This function parse the parameters and call // This function parse the parameters and call
// the right addTorrent function, considering // the right addTorrent function, considering
// the parameter type. // the parameter type.
void GUI::processParams(const QString& params_str) { void MainWindow::processParams(const QString& params_str) {
processParams(params_str.split("|", QString::SkipEmptyParts)); processParams(params_str.split("|", QString::SkipEmptyParts));
} }
void GUI::processParams(const QStringList& params) { void MainWindow::processParams(const QStringList& params) {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool(); const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool();
foreach(QString param, params) { foreach(QString param, params) {
@ -884,14 +884,14 @@ void GUI::processParams(const QStringList& params) {
} }
if(param.startsWith("magnet:", Qt::CaseInsensitive)) { if(param.startsWith("magnet:", Qt::CaseInsensitive)) {
if(useTorrentAdditionDialog) { if(useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this, BTSession); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoadMagnetURI(param); dialog->showLoadMagnetURI(param);
} else { } else {
BTSession->addMagnetUri(param); BTSession->addMagnetUri(param);
} }
} else { } else {
if(useTorrentAdditionDialog) { if(useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this, BTSession); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoad(param); dialog->showLoad(param);
}else{ }else{
BTSession->addTorrent(param); BTSession->addTorrent(param);
@ -901,27 +901,27 @@ void GUI::processParams(const QStringList& params) {
} }
} }
void GUI::addTorrent(QString path) { void MainWindow::addTorrent(QString path) {
BTSession->addTorrent(path); BTSession->addTorrent(path);
} }
void GUI::processDownloadedFiles(QString path, QString url) { void MainWindow::processDownloadedFiles(QString path, QString url) {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool(); const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool();
if(useTorrentAdditionDialog) { if(useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this, BTSession); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoad(path, url); dialog->showLoad(path, url);
}else{ }else{
BTSession->addTorrent(path, false, url); BTSession->addTorrent(path, false, url);
} }
} }
void GUI::optionsSaved() { void MainWindow::optionsSaved() {
loadPreferences(); loadPreferences();
} }
// Load program preferences // Load program preferences
void GUI::loadPreferences(bool configure_session) { void MainWindow::loadPreferences(bool configure_session) {
BTSession->addConsoleMessage(tr("Options were saved successfully.")); BTSession->addConsoleMessage(tr("Options were saved successfully."));
const bool newSystrayIntegration = Preferences::systrayIntegration(); const bool newSystrayIntegration = Preferences::systrayIntegration();
actionLock_qBittorrent->setEnabled(newSystrayIntegration); actionLock_qBittorrent->setEnabled(newSystrayIntegration);
@ -992,7 +992,7 @@ void GUI::loadPreferences(bool configure_session) {
qDebug("GUI settings loaded"); qDebug("GUI settings loaded");
} }
void GUI::addUnauthenticatedTracker(const QPair<QTorrentHandle,QString> &tracker) { void MainWindow::addUnauthenticatedTracker(const QPair<QTorrentHandle,QString> &tracker) {
// Trackers whose authentication was cancelled // Trackers whose authentication was cancelled
if(unauthenticated_trackers.indexOf(tracker) < 0) { if(unauthenticated_trackers.indexOf(tracker) < 0) {
unauthenticated_trackers << tracker; unauthenticated_trackers << tracker;
@ -1000,7 +1000,7 @@ void GUI::addUnauthenticatedTracker(const QPair<QTorrentHandle,QString> &tracker
} }
// Called when a tracker requires authentication // Called when a tracker requires authentication
void GUI::trackerAuthenticationRequired(QTorrentHandle& h) { void MainWindow::trackerAuthenticationRequired(QTorrentHandle& h) {
if(unauthenticated_trackers.indexOf(QPair<QTorrentHandle,QString>(h, h.current_tracker())) < 0) { if(unauthenticated_trackers.indexOf(QPair<QTorrentHandle,QString>(h, h.current_tracker())) < 0) {
// Tracker login // Tracker login
new trackerLogin(this, h); new trackerLogin(this, h);
@ -1008,7 +1008,7 @@ void GUI::trackerAuthenticationRequired(QTorrentHandle& h) {
} }
// Check connection status and display right icon // Check connection status and display right icon
void GUI::updateGUI() { void MainWindow::updateGUI() {
// update global informations // update global informations
if(systrayIcon) { if(systrayIcon) {
#if defined(Q_WS_X11) || defined(Q_WS_MAC) #if defined(Q_WS_X11) || defined(Q_WS_MAC)
@ -1034,7 +1034,7 @@ void GUI::updateGUI() {
} }
} }
void GUI::showNotificationBaloon(QString title, QString msg) const { void MainWindow::showNotificationBaloon(QString title, QString msg) const {
if(!Preferences::useProgramNotification()) return; if(!Preferences::useProgramNotification()) return;
#ifdef WITH_LIBNOTIFY #ifdef WITH_LIBNOTIFY
if (notify_init ("summary-body")) { if (notify_init ("summary-body")) {
@ -1063,7 +1063,7 @@ void GUI::showNotificationBaloon(QString title, QString msg) const {
* * * *
*****************************************************/ *****************************************************/
void GUI::downloadFromURLList(const QStringList& url_list) { void MainWindow::downloadFromURLList(const QStringList& url_list) {
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool(); const bool useTorrentAdditionDialog = settings.value(QString::fromUtf8("Preferences/Downloads/AdditionDialog"), true).toBool();
foreach(QString url, url_list) { foreach(QString url, url_list) {
@ -1073,7 +1073,7 @@ void GUI::downloadFromURLList(const QStringList& url_list) {
} }
if(url.startsWith("magnet:", Qt::CaseInsensitive)) { if(url.startsWith("magnet:", Qt::CaseInsensitive)) {
if(useTorrentAdditionDialog) { if(useTorrentAdditionDialog) {
torrentAdditionDialog *dialog = new torrentAdditionDialog(this, BTSession); torrentAdditionDialog *dialog = new torrentAdditionDialog(this);
dialog->showLoadMagnetURI(url); dialog->showLoadMagnetURI(url);
} else { } else {
BTSession->addMagnetUri(url); BTSession->addMagnetUri(url);
@ -1090,7 +1090,7 @@ void GUI::downloadFromURLList(const QStringList& url_list) {
* * * *
*****************************************************/ *****************************************************/
void GUI::createSystrayDelayed() { void MainWindow::createSystrayDelayed() {
static int timeout = 20; static int timeout = 20;
if(QSystemTrayIcon::isSystemTrayAvailable()) { if(QSystemTrayIcon::isSystemTrayAvailable()) {
// Ok, systray integration is now supported // Ok, systray integration is now supported
@ -1113,11 +1113,11 @@ void GUI::createSystrayDelayed() {
} }
} }
void GUI::updateAltSpeedsBtn(bool alternative) { void MainWindow::updateAltSpeedsBtn(bool alternative) {
actionUse_alternative_speed_limits->setChecked(alternative); actionUse_alternative_speed_limits->setChecked(alternative);
} }
QMenu* GUI::getTrayIconMenu() { QMenu* MainWindow::getTrayIconMenu() {
if(myTrayIconMenu) if(myTrayIconMenu)
return myTrayIconMenu; return myTrayIconMenu;
// Tray icon Menu // Tray icon Menu
@ -1140,7 +1140,7 @@ QMenu* GUI::getTrayIconMenu() {
return myTrayIconMenu; return myTrayIconMenu;
} }
void GUI::createTrayIcon() { void MainWindow::createTrayIcon() {
// Tray icon // Tray icon
#ifdef Q_WS_WIN #ifdef Q_WS_WIN
systrayIcon = new QSystemTrayIcon(QIcon(QString::fromUtf8(":/Icons/skin/qbittorrent16.png")), this); systrayIcon = new QSystemTrayIcon(QIcon(QString::fromUtf8(":/Icons/skin/qbittorrent16.png")), this);
@ -1156,7 +1156,7 @@ void GUI::createTrayIcon() {
} }
// Display Program Options // Display Program Options
void GUI::on_actionOptions_triggered() { void MainWindow::on_actionOptions_triggered() {
if(options) { if(options) {
// Get focus // Get focus
options->setFocus(); options->setFocus();
@ -1166,23 +1166,23 @@ void GUI::on_actionOptions_triggered() {
} }
} }
void GUI::on_actionTop_tool_bar_triggered() { void MainWindow::on_actionTop_tool_bar_triggered() {
bool is_visible = static_cast<QAction*>(sender())->isChecked(); bool is_visible = static_cast<QAction*>(sender())->isChecked();
toolBar->setVisible(is_visible); toolBar->setVisible(is_visible);
Preferences::setToolbarDisplayed(is_visible); Preferences::setToolbarDisplayed(is_visible);
} }
void GUI::on_actionShutdown_when_downloads_complete_triggered() { void MainWindow::on_actionShutdown_when_downloads_complete_triggered() {
bool is_checked = static_cast<QAction*>(sender())->isChecked(); bool is_checked = static_cast<QAction*>(sender())->isChecked();
Preferences::setShutdownWhenDownloadsComplete(is_checked); Preferences::setShutdownWhenDownloadsComplete(is_checked);
} }
void GUI::on_actionShutdown_qBittorrent_when_downloads_complete_triggered() { void MainWindow::on_actionShutdown_qBittorrent_when_downloads_complete_triggered() {
bool is_checked = static_cast<QAction*>(sender())->isChecked(); bool is_checked = static_cast<QAction*>(sender())->isChecked();
Preferences::setShutdownqBTWhenDownloadsComplete(is_checked); Preferences::setShutdownqBTWhenDownloadsComplete(is_checked);
} }
void GUI::on_actionSpeed_in_title_bar_triggered() { void MainWindow::on_actionSpeed_in_title_bar_triggered() {
displaySpeedInTitle = static_cast<QAction*>(sender())->isChecked(); displaySpeedInTitle = static_cast<QAction*>(sender())->isChecked();
Preferences::showSpeedInTitleBar(displaySpeedInTitle); Preferences::showSpeedInTitleBar(displaySpeedInTitle);
if(displaySpeedInTitle) if(displaySpeedInTitle)
@ -1191,19 +1191,19 @@ void GUI::on_actionSpeed_in_title_bar_triggered() {
setWindowTitle(tr("qBittorrent %1", "e.g: qBittorrent v0.x").arg(QString::fromUtf8(VERSION))); setWindowTitle(tr("qBittorrent %1", "e.g: qBittorrent v0.x").arg(QString::fromUtf8(VERSION)));
} }
void GUI::on_actionRSS_Reader_triggered() { void MainWindow::on_actionRSS_Reader_triggered() {
RssSettings::setRSSEnabled(actionRSS_Reader->isChecked()); RssSettings::setRSSEnabled(actionRSS_Reader->isChecked());
displayRSSTab(actionRSS_Reader->isChecked()); displayRSSTab(actionRSS_Reader->isChecked());
} }
void GUI::on_actionSearch_engine_triggered() { void MainWindow::on_actionSearch_engine_triggered() {
Preferences::setSearchEnabled(actionSearch_engine->isChecked()); Preferences::setSearchEnabled(actionSearch_engine->isChecked());
displaySearchTab(actionSearch_engine->isChecked()); displaySearchTab(actionSearch_engine->isChecked());
} }
void GUI::on_action_Import_Torrent_triggered() void MainWindow::on_action_Import_Torrent_triggered()
{ {
TorrentImportDlg::importTorrent(BTSession); TorrentImportDlg::importTorrent();
} }
/***************************************************** /*****************************************************
@ -1214,7 +1214,7 @@ void GUI::on_action_Import_Torrent_triggered()
// Display an input dialog to prompt user for // Display an input dialog to prompt user for
// an url // an url
void GUI::on_actionDownload_from_URL_triggered() { void MainWindow::on_actionDownload_from_URL_triggered() {
if(!downloadFromURLDialog) { if(!downloadFromURLDialog) {
downloadFromURLDialog = new downloadFromURL(this); downloadFromURLDialog = new downloadFromURL(this);
connect(downloadFromURLDialog, SIGNAL(urlsReadyToBeDownloaded(const QStringList&)), this, SLOT(downloadFromURLList(const QStringList&))); connect(downloadFromURLDialog, SIGNAL(urlsReadyToBeDownloaded(const QStringList&)), this, SLOT(downloadFromURLList(const QStringList&)));
@ -1248,12 +1248,12 @@ void GUI::handleUpdateInstalled(QString error_msg)
#endif #endif
void GUI::on_actionDonate_money_triggered() void MainWindow::on_actionDonate_money_triggered()
{ {
QDesktopServices::openUrl(QUrl("http://sourceforge.net/donate/index.php?group_id=163414")); QDesktopServices::openUrl(QUrl("http://sourceforge.net/donate/index.php?group_id=163414"));
} }
void GUI::showConnectionSettings() void MainWindow::showConnectionSettings()
{ {
on_actionOptions_triggered(); on_actionOptions_triggered();
options->showConnectionTab(); options->showConnectionTab();

6
src/GUI.h → src/mainwindow.h

@ -60,13 +60,13 @@ class HidableTabWidget;
class LineEdit; class LineEdit;
class QFileSystemWatcher; class QFileSystemWatcher;
class GUI : public QMainWindow, private Ui::MainWindow{ class MainWindow : public QMainWindow, private Ui::MainWindow{
Q_OBJECT Q_OBJECT
public: public:
// Construct / Destruct // Construct / Destruct
GUI(QWidget *parent=0, QStringList torrentCmdLine=QStringList()); MainWindow(QWidget *parent=0, QStringList torrentCmdLine=QStringList());
~GUI(); ~MainWindow();
// Methods // Methods
QWidget* getCurrentTabWidget() const; QWidget* getCurrentTabWidget() const;
TransferListWidget* getTransferList() const { return transferList; } TransferListWidget* getTransferList() const { return transferList; }

4
src/properties/peerlistwidget.cpp

@ -195,8 +195,8 @@ void PeerListWidget::banSelectedPeers(QStringList peer_ips) {
if(ret) return; if(ret) return;
foreach(const QString &ip, peer_ips) { foreach(const QString &ip, peer_ips) {
qDebug("Banning peer %s...", ip.toLocal8Bit().data()); qDebug("Banning peer %s...", ip.toLocal8Bit().data());
properties->getBTSession()->addConsoleMessage(tr("Manually banning peer %1...").arg(ip)); QBtSession::instance()->addConsoleMessage(tr("Manually banning peer %1...").arg(ip));
properties->getBTSession()->banIP(ip); QBtSession::instance()->banIP(ip);
} }
// Refresh list // Refresh list
loadPeers(properties->getCurrentTorrent()); loadPeers(properties->getCurrentTorrent());

19
src/properties/propertieswidget.cpp

@ -49,14 +49,15 @@
#include "torrentfilesmodel.h" #include "torrentfilesmodel.h"
#include "peerlistwidget.h" #include "peerlistwidget.h"
#include "trackerlist.h" #include "trackerlist.h"
#include "GUI.h" #include "mainwindow.h"
#include "downloadedpiecesbar.h" #include "downloadedpiecesbar.h"
#include "pieceavailabilitybar.h" #include "pieceavailabilitybar.h"
#include "qinisettings.h" #include "qinisettings.h"
#include "proptabbar.h" #include "proptabbar.h"
PropertiesWidget::PropertiesWidget(QWidget *parent, GUI* main_window, TransferListWidget *transferList, QBtSession* BTSession): PropertiesWidget::PropertiesWidget(QWidget *parent, MainWindow* main_window, TransferListWidget *transferList):
QWidget(parent), transferList(transferList), main_window(main_window), BTSession(BTSession) { QWidget(parent), transferList(transferList), main_window(main_window) {
setupUi(this); setupUi(this);
state = VISIBLE; state = VISIBLE;
setEnabled(false); setEnabled(false);
@ -79,8 +80,8 @@ PropertiesWidget::PropertiesWidget(QWidget *parent, GUI* main_window, TransferLi
connect(transferList, SIGNAL(currentTorrentChanged(QTorrentHandle&)), this, SLOT(loadTorrentInfos(QTorrentHandle &))); connect(transferList, SIGNAL(currentTorrentChanged(QTorrentHandle&)), this, SLOT(loadTorrentInfos(QTorrentHandle &)));
connect(PropDelegate, SIGNAL(filteredFilesChanged()), this, SLOT(filteredFilesChanged())); connect(PropDelegate, SIGNAL(filteredFilesChanged()), this, SLOT(filteredFilesChanged()));
connect(stackedProperties, SIGNAL(currentChanged(int)), this, SLOT(loadDynamicData())); connect(stackedProperties, SIGNAL(currentChanged(int)), this, SLOT(loadDynamicData()));
connect(BTSession, SIGNAL(savePathChanged(QTorrentHandle&)), this, SLOT(updateSavePath(QTorrentHandle&))); connect(QBtSession::instance(), SIGNAL(savePathChanged(QTorrentHandle&)), this, SLOT(updateSavePath(QTorrentHandle&)));
connect(BTSession, SIGNAL(metadataReceived(QTorrentHandle&)), this, SLOT(updateTorrentInfos(QTorrentHandle&))); connect(QBtSession::instance(), SIGNAL(metadataReceived(QTorrentHandle&)), this, SLOT(updateTorrentInfos(QTorrentHandle&)));
// Downloaded pieces progress bar // Downloaded pieces progress bar
downloaded_pieces = new DownloadedPiecesBar(this); downloaded_pieces = new DownloadedPiecesBar(this);
@ -196,10 +197,6 @@ QTorrentHandle PropertiesWidget::getCurrentTorrent() const {
return h; return h;
} }
QBtSession* PropertiesWidget::getBTSession() const {
return BTSession;
}
void PropertiesWidget::updateSavePath(QTorrentHandle& _h) { void PropertiesWidget::updateSavePath(QTorrentHandle& _h) {
if(h.is_valid() && h == _h) { if(h.is_valid() && h == _h) {
QString p; QString p;
@ -341,7 +338,7 @@ void PropertiesWidget::loadDynamicData() {
// Update next announce time // Update next announce time
reannounce_lbl->setText(h.next_announce()); reannounce_lbl->setText(h.next_announce());
// Update ratio info // Update ratio info
const double ratio = BTSession->getRealRatio(h.hash()); const double ratio = QBtSession::instance()->getRealRatio(h.hash());
if(ratio > 100.) if(ratio > 100.)
shareRatio->setText(QString::fromUtf8("")); shareRatio->setText(QString::fromUtf8(""));
else else
@ -720,7 +717,7 @@ void PropertiesWidget::renameSelectedFile() {
} }
QDir savePath(misc::expandPath(save_path_dir)); QDir savePath(misc::expandPath(save_path_dir));
// Actually move storage // Actually move storage
if(!BTSession->useTemporaryFolder() || h.is_seed()) { if(!QBtSession::instance()->useTemporaryFolder() || h.is_seed()) {
if(!savePath.exists()) savePath.mkpath(savePath.absolutePath()); if(!savePath.exists()) savePath.mkpath(savePath.absolutePath());
h.move_storage(savePath.absolutePath()); h.move_storage(savePath.absolutePath());
} }

9
src/properties/propertieswidget.h

@ -38,14 +38,13 @@
class TransferListWidget; class TransferListWidget;
class QTimer; class QTimer;
class QBtSession;
class TorrentFilesModel; class TorrentFilesModel;
class PropListDelegate; class PropListDelegate;
class QAction; class QAction;
class torrent_file; class torrent_file;
class PeerListWidget; class PeerListWidget;
class TrackerList; class TrackerList;
class GUI; class MainWindow;
class DownloadedPiecesBar; class DownloadedPiecesBar;
class PieceAvailabilityBar; class PieceAvailabilityBar;
class PropTabBar; class PropTabBar;
@ -58,10 +57,9 @@ public:
enum SlideState {REDUCED, VISIBLE}; enum SlideState {REDUCED, VISIBLE};
public: public:
PropertiesWidget(QWidget *parent, GUI* main_window, TransferListWidget *transferList, QBtSession* BTSession); PropertiesWidget(QWidget *parent, MainWindow* main_window, TransferListWidget *transferList);
~PropertiesWidget(); ~PropertiesWidget();
QTorrentHandle getCurrentTorrent() const; QTorrentHandle getCurrentTorrent() const;
QBtSession* getBTSession() const;
TrackerList* getTrackerList() const { return trackerList; } TrackerList* getTrackerList() const { return trackerList; }
PeerListWidget* getPeerList() const { return peersList; } PeerListWidget* getPeerList() const { return peersList; }
QTreeView* getFilesList() const { return filesList; } QTreeView* getFilesList() const { return filesList; }
@ -97,10 +95,9 @@ public slots:
private: private:
TransferListWidget *transferList; TransferListWidget *transferList;
GUI *main_window; MainWindow *main_window;
QTorrentHandle h; QTorrentHandle h;
QTimer *refreshTimer; QTimer *refreshTimer;
QBtSession* BTSession;
SlideState state; SlideState state;
TorrentFilesModel *PropListModel; TorrentFilesModel *PropListModel;
PropListDelegate *PropDelegate; PropListDelegate *PropDelegate;

12
src/properties/trackerlist.cpp

@ -200,7 +200,7 @@ void TrackerList::loadStickyItems(const QTorrentHandle &h) {
++nb_pex; ++nb_pex;
} }
// load DHT information // load DHT information
if(properties->getBTSession()->isDHTEnabled() && h.has_metadata() && !h.priv()) { if(QBtSession::instance()->isDHTEnabled() && h.has_metadata() && !h.priv()) {
dht_item->setText(COL_STATUS, tr("Working")); dht_item->setText(COL_STATUS, tr("Working"));
} else { } else {
dht_item->setText(COL_STATUS, tr("Disabled")); dht_item->setText(COL_STATUS, tr("Disabled"));
@ -210,13 +210,13 @@ void TrackerList::loadStickyItems(const QTorrentHandle &h) {
dht_item->setText(COL_MSG, tr("This torrent is private")); dht_item->setText(COL_MSG, tr("This torrent is private"));
} }
// Load PeX Information // Load PeX Information
if(properties->getBTSession()->isPexEnabled()) if(QBtSession::instance()->isPexEnabled())
pex_item->setText(COL_STATUS, tr("Working")); pex_item->setText(COL_STATUS, tr("Working"));
else else
pex_item->setText(COL_STATUS, tr("Disabled")); pex_item->setText(COL_STATUS, tr("Disabled"));
pex_item->setText(COL_PEERS, QString::number(nb_pex)); pex_item->setText(COL_PEERS, QString::number(nb_pex));
// Load LSD Information // Load LSD Information
if(properties->getBTSession()->isLSDEnabled()) if(QBtSession::instance()->isLSDEnabled())
lsd_item->setText(COL_STATUS, tr("Working")); lsd_item->setText(COL_STATUS, tr("Working"));
else else
lsd_item->setText(COL_STATUS, tr("Disabled")); lsd_item->setText(COL_STATUS, tr("Disabled"));
@ -229,7 +229,7 @@ void TrackerList::loadTrackers() {
if(!h.is_valid()) return; if(!h.is_valid()) return;
loadStickyItems(h); loadStickyItems(h);
// Load actual trackers information // Load actual trackers information
QHash<QString, TrackerInfos> trackers_data = properties->getBTSession()->getTrackersInfo(h.hash()); QHash<QString, TrackerInfos> trackers_data = QBtSession::instance()->getTrackersInfo(h.hash());
QStringList old_trackers_urls = tracker_items.keys(); QStringList old_trackers_urls = tracker_items.keys();
const std::vector<announce_entry> trackers = h.trackers(); const std::vector<announce_entry> trackers = h.trackers();
for(std::vector<announce_entry>::const_iterator it = trackers.begin(); it != trackers.end(); it++) { for(std::vector<announce_entry>::const_iterator it = trackers.begin(); it != trackers.end(); it++) {
@ -300,8 +300,6 @@ void TrackerList::askForTrackers(){
h.force_reannounce(); h.force_reannounce();
// Reload tracker list // Reload tracker list
loadTrackers(); loadTrackers();
// XXX: I don't think this is necessary now
//BTSession->saveTrackerFile(h.hash());
} }
} }
@ -336,8 +334,6 @@ void TrackerList::deleteSelectedTrackers(){
h.force_reannounce(); h.force_reannounce();
// Reload Trackers // Reload Trackers
loadTrackers(); loadTrackers();
//XXX: I don't think this is necessary
//BTSession->saveTrackerFile(h.hash());
} }
void TrackerList::showTrackerListMenu(QPoint) { void TrackerList::showTrackerListMenu(QPoint) {

3
src/qtlibtorrent/qbtsession.cpp

@ -607,7 +607,7 @@ bool QBtSession::initWebUi(QString username, QString password, int port) {
httpServer->close(); httpServer->close();
} }
} else { } else {
httpServer = new HttpServer(this, 3000, this); httpServer = new HttpServer(3000, this);
} }
httpServer->setAuthorization(username, password); httpServer->setAuthorization(username, password);
bool success = true; bool success = true;
@ -2253,6 +2253,7 @@ void QBtSession::readAlerts() {
QTorrentHandle h(p->handle); QTorrentHandle h(p->handle);
if(!h.has_error()) if(!h.has_error())
h.save_resume_data(); h.save_resume_data();
emit pausedTorrent(h);
} }
} }
else if (tracker_error_alert* p = dynamic_cast<tracker_error_alert*>(a.get())) { else if (tracker_error_alert* p = dynamic_cast<tracker_error_alert*>(a.get())) {

8
src/rss/rssfeed.cpp

@ -37,7 +37,7 @@
#include "misc.h" #include "misc.h"
#include "rssdownloadrulelist.h" #include "rssdownloadrulelist.h"
RssFeed::RssFeed(RssFolder* parent, RssManager *rssmanager, QBtSession *BTSession, QString _url): parent(parent), rssmanager(rssmanager), BTSession(BTSession), alias(""), iconPath(":/Icons/rss16.png"), refreshed(false), downloadFailure(false), currently_loading(false) { RssFeed::RssFeed(RssFolder* parent, QString _url): parent(parent), alias(""), iconPath(":/Icons/rss16.png"), refreshed(false), downloadFailure(false), currently_loading(false) {
qDebug("RSSStream constructed"); qDebug("RSSStream constructed");
QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss"); QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss");
url = QUrl(_url).toString(); url = QUrl(_url).toString();
@ -186,7 +186,7 @@ void RssFeed::markAllAsRead() {
foreach(RssArticle *item, this->values()){ foreach(RssArticle *item, this->values()){
item->setRead(); item->setRead();
} }
rssmanager->forwardFeedInfosChanged(url, getName(), 0); RssManager::instance()->forwardFeedInfosChanged(url, getName(), 0);
} }
unsigned int RssFeed::getNbUnRead() const{ unsigned int RssFeed::getNbUnRead() const{
@ -302,8 +302,8 @@ short RssFeed::readDoc(QIODevice* device) {
const RssDownloadRule matching_rule = RssDownloadRuleList::instance()->findMatchingRule(url, item->getTitle()); const RssDownloadRule matching_rule = RssDownloadRuleList::instance()->findMatchingRule(url, item->getTitle());
if(matching_rule.isValid()) { if(matching_rule.isValid()) {
// Download the torrent // Download the torrent
BTSession->addConsoleMessage(tr("Automatically downloading %1 torrent from %2 RSS feed...").arg(item->getTitle()).arg(getName())); QBtSession::instance()->addConsoleMessage(tr("Automatically downloading %1 torrent from %2 RSS feed...").arg(item->getTitle()).arg(getName()));
BTSession->downloadUrlAndSkipDialog(torrent_url, matching_rule.savePath(), matching_rule.label()); QBtSession::instance()->downloadUrlAndSkipDialog(torrent_url, matching_rule.savePath(), matching_rule.label());
// Item was downloaded, consider it as Read // Item was downloaded, consider it as Read
item->setRead(); item->setRead();
} }

5
src/rss/rssfeed.h

@ -36,15 +36,12 @@
#include "rssfile.h" #include "rssfile.h"
class RssManager; class RssManager;
class QBtSession;
class RssFeed: public RssFile, public QHash<QString, RssArticle*> { class RssFeed: public RssFile, public QHash<QString, RssArticle*> {
Q_OBJECT Q_OBJECT
private: private:
RssFolder *parent; RssFolder *parent;
RssManager *rssmanager;
QBtSession *BTSession;
QString title; QString title;
QString link; QString link;
QString description; QString description;
@ -63,7 +60,7 @@ public slots:
void setDownloadFailed(); void setDownloadFailed();
public: public:
RssFeed(RssFolder* parent, RssManager *rssmanager, QBtSession *BTSession, QString _url); RssFeed(RssFolder* parent, QString _url);
~RssFeed(); ~RssFeed();
RssFolder* getParent() const { return parent; } RssFolder* getParent() const { return parent; }
void setParent(RssFolder* _parent) { parent = _parent; } void setParent(RssFolder* _parent) { parent = _parent; }

12
src/rss/rssfolder.cpp

@ -35,7 +35,7 @@
#include "rssmanager.h" #include "rssmanager.h"
#include "rssfeed.h" #include "rssfeed.h"
RssFolder::RssFolder(RssFolder *parent, RssManager *rssmanager, QBtSession *BTSession, QString name): parent(parent), rssmanager(rssmanager), BTSession(BTSession), name(name) { RssFolder::RssFolder(RssFolder *parent, QString name): parent(parent), name(name) {
downloader = new downloadThread(this); downloader = new downloadThread(this);
connect(downloader, SIGNAL(downloadFinished(QString, QString)), this, SLOT(processFinishedDownload(QString, QString))); connect(downloader, SIGNAL(downloadFinished(QString, QString)), this, SLOT(processFinishedDownload(QString, QString)));
connect(downloader, SIGNAL(downloadFailure(QString, QString)), this, SLOT(handleDownloadFailure(QString, QString))); connect(downloader, SIGNAL(downloadFailure(QString, QString)), this, SLOT(handleDownloadFailure(QString, QString)));
@ -95,7 +95,7 @@ void RssFolder::removeFile(QString ID) {
RssFolder* RssFolder::addFolder(QString name) { RssFolder* RssFolder::addFolder(QString name) {
RssFolder *subfolder; RssFolder *subfolder;
if(!this->contains(name)) { if(!this->contains(name)) {
subfolder = new RssFolder(this, rssmanager, BTSession, name); subfolder = new RssFolder(this, name);
(*this)[name] = subfolder; (*this)[name] = subfolder;
} else { } else {
subfolder = (RssFolder*)this->value(name); subfolder = (RssFolder*)this->value(name);
@ -104,7 +104,7 @@ RssFolder* RssFolder::addFolder(QString name) {
} }
RssFeed* RssFolder::addStream(QString url) { RssFeed* RssFolder::addStream(QString url) {
RssFeed* stream = new RssFeed(this, rssmanager, BTSession, url); RssFeed* stream = new RssFeed(this, url);
Q_ASSERT(!this->contains(stream->getUrl())); Q_ASSERT(!this->contains(stream->getUrl()));
(*this)[stream->getUrl()] = stream; (*this)[stream->getUrl()] = stream;
refreshStream(stream->getUrl()); refreshStream(stream->getUrl());
@ -181,7 +181,7 @@ void RssFolder::processFinishedDownload(QString url, QString path) {
foreach(stream, res){ foreach(stream, res){
stream->setIconPath(path); stream->setIconPath(path);
if(!stream->isLoading()) if(!stream->isLoading())
rssmanager->forwardFeedIconChanged(stream->getUrl(), stream->getIconPath()); RssManager::instance()->forwardFeedIconChanged(stream->getUrl(), stream->getIconPath());
} }
}else{ }else{
qDebug("Unsupported icon format at %s", (const char*)url.toLocal8Bit()); qDebug("Unsupported icon format at %s", (const char*)url.toLocal8Bit());
@ -202,7 +202,7 @@ void RssFolder::processFinishedDownload(QString url, QString path) {
if(!stream->getTitle().isEmpty()) if(!stream->getTitle().isEmpty())
stream->rename(stream->getTitle()); stream->rename(stream->getTitle());
} }
rssmanager->forwardFeedInfosChanged(url, stream->getName(), stream->getNbUnRead()); RssManager::instance()->forwardFeedInfosChanged(url, stream->getName(), stream->getNbUnRead());
} }
void RssFolder::handleDownloadFailure(QString url, QString reason) { void RssFolder::handleDownloadFailure(QString url, QString reason) {
@ -219,7 +219,7 @@ void RssFolder::handleDownloadFailure(QString url, QString reason) {
stream->setLoading(false); stream->setLoading(false);
qDebug("Could not download Rss at %s, reason: %s", (const char*)url.toLocal8Bit(), (const char*)reason.toLocal8Bit()); qDebug("Could not download Rss at %s, reason: %s", (const char*)url.toLocal8Bit(), (const char*)reason.toLocal8Bit());
stream->setDownloadFailed(); stream->setDownloadFailed();
rssmanager->forwardFeedInfosChanged(url, stream->getName(), stream->getNbUnRead()); RssManager::instance()->forwardFeedInfosChanged(url, stream->getName(), stream->getNbUnRead());
} }
QList<RssFeed*> RssFolder::findFeedsWithIcon(QString icon_url) const { QList<RssFeed*> RssFolder::findFeedsWithIcon(QString icon_url) const {

6
src/rss/rssfolder.h

@ -36,16 +36,14 @@
#include "rssfile.h" #include "rssfile.h"
class RssArticle; class RssArticle;
class QBtSession;
class downloadThread; class downloadThread;
class RssManager;
class RssFeed; class RssFeed;
class RssFolder: public RssFile, public QHash<QString, RssFile*> { class RssFolder: public RssFile, public QHash<QString, RssFile*> {
Q_OBJECT Q_OBJECT
public: public:
RssFolder(RssFolder *parent, RssManager *rssmanager, QBtSession *BTSession, QString name); RssFolder(RssFolder *parent = 0, QString name = QString());
~RssFolder(); ~RssFolder();
RssFolder* getParent() const { return parent; } RssFolder* getParent() const { return parent; }
void setParent(RssFolder* _parent) { parent = _parent; } void setParent(RssFolder* _parent) { parent = _parent; }
@ -79,9 +77,7 @@ public slots:
private: private:
RssFolder *parent; RssFolder *parent;
RssManager *rssmanager;
downloadThread *downloader; downloadThread *downloader;
QBtSession *BTSession;
QString name; QString name;
}; };

2
src/rss/rssmanager.cpp

@ -37,7 +37,7 @@
RssManager* RssManager::m_instance = 0; RssManager* RssManager::m_instance = 0;
RssManager::RssManager(): RssFolder(0, this, QBtSession::instance(), QString::null) { RssManager::RssManager(): RssFolder() {
loadStreamList(); loadStreamList();
connect(&newsRefresher, SIGNAL(timeout()), this, SLOT(refreshAll())); connect(&newsRefresher, SIGNAL(timeout()), this, SLOT(refreshAll()));
refreshInterval = RssSettings::getRSSRefreshInterval(); refreshInterval = RssSettings::getRSSRefreshInterval();

1
src/rss/rssmanager.h

@ -63,7 +63,6 @@ signals:
private: private:
QTimer newsRefresher; QTimer newsRefresher;
unsigned int refreshInterval; unsigned int refreshInterval;
QBtSession *BTSession;
}; };

12
src/searchengine/searchengine.cpp

@ -54,12 +54,12 @@
#include "preferences.h" #include "preferences.h"
#include "searchlistdelegate.h" #include "searchlistdelegate.h"
#include "qinisettings.h" #include "qinisettings.h"
#include "GUI.h" #include "mainwindow.h"
#define SEARCHHISTORY_MAXSIZE 50 #define SEARCHHISTORY_MAXSIZE 50
/*SEARCH ENGINE START*/ /*SEARCH ENGINE START*/
SearchEngine::SearchEngine(GUI *parent, QBtSession *BTSession) : QWidget(parent), BTSession(BTSession), parent(parent) { SearchEngine::SearchEngine(MainWindow *parent) : QWidget(parent), mp_mainWindow(parent) {
setupUi(this); setupUi(this);
// new qCompleter to the search pattern // new qCompleter to the search pattern
startSearchHistory(); startSearchHistory();
@ -410,7 +410,7 @@ void SearchEngine::downloadTorrent(QString engine_url, QString torrent_url) {
if(torrent_url.startsWith("magnet:")) { if(torrent_url.startsWith("magnet:")) {
QStringList urls; QStringList urls;
urls << torrent_url; urls << torrent_url;
parent->downloadFromURLList(urls); mp_mainWindow->downloadFromURLList(urls);
} else { } else {
QProcess *downloadProcess = new QProcess(this); QProcess *downloadProcess = new QProcess(this);
downloadProcess->setEnvironment(QProcess::systemEnvironment()); downloadProcess->setEnvironment(QProcess::systemEnvironment());
@ -459,7 +459,7 @@ void SearchEngine::downloadFinished(int exitcode, QProcess::ExitStatus) {
if(parts.size() == 2) { if(parts.size() == 2) {
QString path = parts[0]; QString path = parts[0];
QString url = parts[1]; QString url = parts[1];
BTSession->processDownloadedFile(url, path); QBtSession::instance()->processDownloadedFile(url, path);
} }
} }
qDebug("Deleting downloadProcess"); qDebug("Deleting downloadProcess");
@ -564,8 +564,8 @@ void SearchEngine::searchFinished(int exitcode,QProcess::ExitStatus){
} }
QIniSettings settings("qBittorrent", "qBittorrent"); QIniSettings settings("qBittorrent", "qBittorrent");
bool useNotificationBalloons = settings.value("Preferences/General/NotificationBaloons", true).toBool(); bool useNotificationBalloons = settings.value("Preferences/General/NotificationBaloons", true).toBool();
if(useNotificationBalloons && parent->getCurrentTabWidget() != this) { if(useNotificationBalloons && mp_mainWindow->getCurrentTabWidget() != this) {
parent->showNotificationBaloon(tr("Search Engine"), tr("Search has finished")); mp_mainWindow->showNotificationBaloon(tr("Search Engine"), tr("Search has finished"));
} }
if(exitcode){ if(exitcode){
#ifdef Q_WS_WIN #ifdef Q_WS_WIN

53
src/searchengine/searchengine.h

@ -41,41 +41,17 @@
#include "searchtab.h" #include "searchtab.h"
#include "supportedengines.h" #include "supportedengines.h"
class QBtSession;
class downloadThread; class downloadThread;
class QTimer; class QTimer;
class SearchEngine; class SearchEngine;
class GUI; class MainWindow;
class SearchEngine : public QWidget, public Ui::search_engine{ class SearchEngine : public QWidget, public Ui::search_engine{
Q_OBJECT Q_OBJECT
Q_DISABLE_COPY(SearchEngine)
private:
// Search related
QProcess *searchProcess;
QList<QProcess*> downloaders;
bool search_stopped;
bool no_search_results;
QByteArray search_result_line_truncated;
unsigned long nb_search_results;
QPointer<QCompleter> searchCompleter;
QStringListModel searchHistory;
QBtSession *BTSession;
SupportedEngines *supported_engines;
QTimer *searchTimeout;
QPointer<SearchTab> currentSearchTab;
#if QT_VERSION < 0x040500
QPushButton *closeTab_button;
#endif
QList<QPointer<SearchTab> > all_tab; // To store all tabs
const SearchCategories full_cat_names;
GUI *parent;
#ifdef Q_WS_WIN
bool has_python;
#endif
public: public:
SearchEngine(GUI *parent, QBtSession *BTSession); SearchEngine(MainWindow *mp_mainWindow);
~SearchEngine(); ~SearchEngine();
QString selectedCategory() const; QString selectedCategory() const;
@ -136,6 +112,29 @@ protected slots:
void pythonDownloadSuccess(QString url, QString file_path); void pythonDownloadSuccess(QString url, QString file_path);
void pythonDownloadFailure(QString url, QString error); void pythonDownloadFailure(QString url, QString error);
#endif #endif
private:
// Search related
QProcess *searchProcess;
QList<QProcess*> downloaders;
bool search_stopped;
bool no_search_results;
QByteArray search_result_line_truncated;
unsigned long nb_search_results;
QPointer<QCompleter> searchCompleter;
QStringListModel searchHistory;
SupportedEngines *supported_engines;
QTimer *searchTimeout;
QPointer<SearchTab> currentSearchTab;
#if QT_VERSION < 0x040500
QPushButton *closeTab_button;
#endif
QList<QPointer<SearchTab> > all_tab; // To store all tabs
const SearchCategories full_cat_names;
MainWindow *mp_mainWindow;
#ifdef Q_WS_WIN
bool has_python;
#endif
}; };
#endif #endif

4
src/src.pro

@ -286,7 +286,7 @@ HEADERS += misc.h \
contains(DEFINES, DISABLE_GUI) { contains(DEFINES, DISABLE_GUI) {
HEADERS += headlessloader.h HEADERS += headlessloader.h
} else { } else {
HEADERS += GUI.h \ HEADERS += mainwindow.h\
transferlistwidget.h \ transferlistwidget.h \
transferlistdelegate.h \ transferlistdelegate.h \
transferlistfilterswidget.h \ transferlistfilterswidget.h \
@ -376,7 +376,7 @@ SOURCES += main.cpp \
smtp.cpp smtp.cpp
!contains(DEFINES, DISABLE_GUI) { !contains(DEFINES, DISABLE_GUI) {
SOURCES += GUI.cpp \ SOURCES += mainwindow.cpp \
options_imp.cpp \ options_imp.cpp \
ico.cpp \ ico.cpp \
transferlistwidget.cpp \ transferlistwidget.cpp \

27
src/statusbar.h

@ -48,8 +48,8 @@ class StatusBar: public QObject {
Q_OBJECT Q_OBJECT
public: public:
StatusBar(QStatusBar *bar, QBtSession *BTSession): bar(bar), BTSession(BTSession) { StatusBar(QStatusBar *bar): bar(bar) {
connect(BTSession, SIGNAL(alternativeSpeedsModeChanged(bool)), this, SLOT(updateAltSpeedsBtn(bool))); connect(QBtSession::instance(), SIGNAL(alternativeSpeedsModeChanged(bool)), this, SLOT(updateAltSpeedsBtn(bool)));
container = new QWidget(); container = new QWidget();
layout = new QGridLayout(container); layout = new QGridLayout(container);
layout->setVerticalSpacing(0); layout->setVerticalSpacing(0);
@ -167,7 +167,7 @@ public slots:
bar->insertWidget(1, restartLbl); bar->insertWidget(1, restartLbl);
QFontMetrics fm(restartLbl->font()); QFontMetrics fm(restartLbl->font());
restartLbl->setText(fm.elidedText(restart_text, Qt::ElideRight, restartLbl->width())); restartLbl->setText(fm.elidedText(restart_text, Qt::ElideRight, restartLbl->width()));
BTSession->addConsoleMessage(tr("qBittorrent was just updated and needs to be restarted for the changes to be effective."), "red"); QBtSession::instance()->addConsoleMessage(tr("qBittorrent was just updated and needs to be restarted for the changes to be effective."), "red");
} }
void stopTimer() { void stopTimer() {
@ -176,8 +176,8 @@ public slots:
void refreshStatusBar() { void refreshStatusBar() {
// Update connection status // Update connection status
const session_status sessionStatus = BTSession->getSessionStatus(); const session_status sessionStatus = QBtSession::instance()->getSessionStatus();
if(!BTSession->getSession()->is_listening()) { if(!QBtSession::instance()->getSession()->is_listening()) {
connecStatusLblIcon->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/disconnected.png"))); connecStatusLblIcon->setIcon(QIcon(QString::fromUtf8(":/Icons/skin/disconnected.png")));
connecStatusLblIcon->setToolTip(QString::fromUtf8("<b>")+tr("Connection Status:")+QString::fromUtf8("</b><br>")+tr("Offline. This usually means that qBittorrent failed to listen on the selected port for incoming connections.")); connecStatusLblIcon->setToolTip(QString::fromUtf8("<b>")+tr("Connection Status:")+QString::fromUtf8("</b><br>")+tr("Offline. This usually means that qBittorrent failed to listen on the selected port for incoming connections."));
} else { } else {
@ -191,7 +191,7 @@ public slots:
} }
} }
// Update Number of DHT nodes // Update Number of DHT nodes
if(BTSession->isDHTEnabled()) { if(QBtSession::instance()->isDHTEnabled()) {
DHTLbl->setVisible(true); DHTLbl->setVisible(true);
//statusSep1->setVisible(true); //statusSep1->setVisible(true);
DHTLbl->setText(tr("DHT: %1 nodes").arg(QString::number(sessionStatus.dht_nodes))); DHTLbl->setText(tr("DHT: %1 nodes").arg(QString::number(sessionStatus.dht_nodes)));
@ -216,23 +216,23 @@ public slots:
} }
void toggleAlternativeSpeeds() { void toggleAlternativeSpeeds() {
BTSession->useAlternativeSpeedsLimit(!Preferences::isAltBandwidthEnabled()); QBtSession::instance()->useAlternativeSpeedsLimit(!Preferences::isAltBandwidthEnabled());
} }
void capDownloadSpeed() { void capDownloadSpeed() {
bool ok = false; bool ok = false;
long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), BTSession->getSession()->download_rate_limit()); long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Download Speed Limit"), QBtSession::instance()->getSession()->download_rate_limit());
if(ok) { if(ok) {
bool alt = Preferences::isAltBandwidthEnabled(); bool alt = Preferences::isAltBandwidthEnabled();
if(new_limit <= 0) { if(new_limit <= 0) {
qDebug("Setting global download rate limit to Unlimited"); qDebug("Setting global download rate limit to Unlimited");
if(!alt) if(!alt)
BTSession->getSession()->set_download_rate_limit(-1); QBtSession::instance()->getSession()->set_download_rate_limit(-1);
Preferences::setGlobalDownloadLimit(-1); Preferences::setGlobalDownloadLimit(-1);
} else { } else {
qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.); qDebug("Setting global download rate limit to %.1fKb/s", new_limit/1024.);
if(!alt) if(!alt)
BTSession->getSession()->set_download_rate_limit(new_limit); QBtSession::instance()->getSession()->set_download_rate_limit(new_limit);
Preferences::setGlobalDownloadLimit(new_limit/1024.); Preferences::setGlobalDownloadLimit(new_limit/1024.);
} }
} }
@ -240,16 +240,16 @@ public slots:
void capUploadSpeed() { void capUploadSpeed() {
bool ok = false; bool ok = false;
long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), BTSession->getSession()->upload_rate_limit()); long new_limit = SpeedLimitDialog::askSpeedLimit(&ok, tr("Global Upload Speed Limit"), QBtSession::instance()->getSession()->upload_rate_limit());
if(ok) { if(ok) {
if(new_limit <= 0) { if(new_limit <= 0) {
qDebug("Setting global upload rate limit to Unlimited"); qDebug("Setting global upload rate limit to Unlimited");
BTSession->getSession()->set_upload_rate_limit(-1); QBtSession::instance()->getSession()->set_upload_rate_limit(-1);
Preferences::setGlobalUploadLimit(-1); Preferences::setGlobalUploadLimit(-1);
} else { } else {
qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.); qDebug("Setting global upload rate limit to %.1fKb/s", new_limit/1024.);
Preferences::setGlobalUploadLimit(new_limit/1024.); Preferences::setGlobalUploadLimit(new_limit/1024.);
BTSession->getSession()->set_upload_rate_limit(new_limit); QBtSession::instance()->getSession()->set_upload_rate_limit(new_limit);
} }
} }
} }
@ -268,7 +268,6 @@ private:
QTimer *refreshTimer; QTimer *refreshTimer;
QWidget *container; QWidget *container;
QGridLayout *layout; QGridLayout *layout;
QBtSession *BTSession;
}; };

41
src/torrentadditiondlg.cpp

@ -28,14 +28,36 @@
* Contact : chris@qbittorrent.org * Contact : chris@qbittorrent.org
*/ */
#include <QDir>
#include <QFileDialog>
#include <QFile>
#include <fstream>
#include <QMessageBox>
#include <QMenu>
#include <QHeaderView>
#include <QApplication>
#include <QDesktopWidget>
#include <QInputDialog>
#include <libtorrent/version.hpp>
#include <libtorrent/session.hpp>
#include <libtorrent/bencode.hpp>
#include "qbtsession.h"
#include "torrentfilesmodel.h"
#include "preferences.h"
#include "transferlistwidget.h"
#include "qinisettings.h"
#include "misc.h"
#include "proplistdelegate.h"
#include "torrentpersistentdata.h"
#include "torrentadditiondlg.h" #include "torrentadditiondlg.h"
torrentAdditionDialog::torrentAdditionDialog(GUI *parent, QBtSession* _BTSession) : torrentAdditionDialog::torrentAdditionDialog(QWidget *parent) :
QDialog((QWidget*)parent), old_label(""), hidden_height(0) { QDialog(parent), old_label(""), hidden_height(0) {
setupUi(this); setupUi(this);
setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DeleteOnClose);
connect(this, SIGNAL(torrentPaused(QTorrentHandle&)), parent->getTransferList(), SLOT(pauseTorrent(QTorrentHandle&)));
BTSession = _BTSession;
// Set Properties list model // Set Properties list model
PropListModel = new TorrentFilesModel(); PropListModel = new TorrentFilesModel();
connect(PropListModel, SIGNAL(filteredFilesChanged()), SLOT(updateDiskSpaceLabels())); connect(PropListModel, SIGNAL(filteredFilesChanged()), SLOT(updateDiskSpaceLabels()));
@ -178,7 +200,7 @@ void torrentAdditionDialog::showLoadMagnetURI(QString magnet_uri) {
// Get torrent hash // Get torrent hash
hash = misc::magnetUriToHash(magnet_uri); hash = misc::magnetUriToHash(magnet_uri);
if(hash.isEmpty()) { if(hash.isEmpty()) {
BTSession->addConsoleMessage(tr("Unable to decode magnet link:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red")); QBtSession::instance()->addConsoleMessage(tr("Unable to decode magnet link:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red"));
return; return;
} }
// Set torrent name // Set torrent name
@ -213,10 +235,10 @@ void torrentAdditionDialog::showLoad(QString filePath, QString from_url) {
} catch(std::exception&) { } catch(std::exception&) {
qDebug("Caught error loading torrent"); qDebug("Caught error loading torrent");
if(!from_url.isNull()){ if(!from_url.isNull()){
BTSession->addConsoleMessage(tr("Unable to decode torrent file:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red")); QBtSession::instance()->addConsoleMessage(tr("Unable to decode torrent file:")+QString::fromUtf8(" '")+from_url+QString::fromUtf8("'"), QString::fromUtf8("red"));
misc::safeRemove(filePath); misc::safeRemove(filePath);
}else{ }else{
BTSession->addConsoleMessage(tr("Unable to decode torrent file:")+QString::fromUtf8(" '")+filePath+QString::fromUtf8("'"), QString::fromUtf8("red")); QBtSession::instance()->addConsoleMessage(tr("Unable to decode torrent file:")+QString::fromUtf8(" '")+filePath+QString::fromUtf8("'"), QString::fromUtf8("red"));
} }
close(); close();
return; return;
@ -622,12 +644,11 @@ void torrentAdditionDialog::renameSelectedFile() {
// Add to download list // Add to download list
QTorrentHandle h; QTorrentHandle h;
if(is_magnet) if(is_magnet)
h = BTSession->addMagnetUri(from_url, false); h = QBtSession::instance()->addMagnetUri(from_url, false);
else else
h = BTSession->addTorrent(filePath, false, from_url); h = QBtSession::instance()->addTorrent(filePath, false, from_url);
if(addInPause->isChecked() && h.is_valid()) { if(addInPause->isChecked() && h.is_valid()) {
h.pause(); h.pause();
emit torrentPaused(h);
} }
// Close the dialog // Close the dialog
qDebug("Closing torrent addition dialog..."); qDebug("Closing torrent addition dialog...");

34
src/torrentadditiondlg.h

@ -31,38 +31,22 @@
#ifndef TORRENTADDITION_H #ifndef TORRENTADDITION_H
#define TORRENTADDITION_H #define TORRENTADDITION_H
#include <QDir> #include <QStringList>
#include <QFileDialog>
#include <QFile>
#include <fstream>
#include <QMessageBox>
#include <QMenu>
#include <QHeaderView>
#include <QApplication>
#include <QDesktopWidget>
#include <QInputDialog>
#include <libtorrent/version.hpp>
#include <libtorrent/session.hpp>
#include <libtorrent/bencode.hpp>
#include "qbtsession.h"
#include "misc.h"
#include "proplistdelegate.h"
#include "ui_torrentadditiondlg.h" #include "ui_torrentadditiondlg.h"
#include "torrentpersistentdata.h"
#include "torrentfilesmodel.h" #include <libtorrent/torrent_info.hpp>
#include "preferences.h"
#include "GUI.h"
#include "transferlistwidget.h"
#include "qinisettings.h"
using namespace libtorrent; using namespace libtorrent;
class TorrentFilesModel;
class PropListDelegate;
class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{ class torrentAdditionDialog : public QDialog, private Ui_addTorrentDialog{
Q_OBJECT Q_OBJECT
public: public:
torrentAdditionDialog(GUI *parent, QBtSession* _BTSession); torrentAdditionDialog(QWidget *parent);
~torrentAdditionDialog(); ~torrentAdditionDialog();
void readSettings(); void readSettings();
void saveSettings(); void saveSettings();
@ -89,11 +73,7 @@ public slots:
void updateSavePathCurrentText(); void updateSavePathCurrentText();
void resetComboLabelIndex(QString text); void resetComboLabelIndex(QString text);
signals:
void torrentPaused(QTorrentHandle &h);
private: private:
QBtSession *BTSession;
QString fileName; QString fileName;
QString hash; QString hash;
QString filePath; QString filePath;

4
src/torrentimportdlg.cpp

@ -179,7 +179,7 @@ QString TorrentImportDlg::getContentPath() const
return m_contentPath; return m_contentPath;
} }
void TorrentImportDlg::importTorrent(QBtSession *BTSession) void TorrentImportDlg::importTorrent()
{ {
TorrentImportDlg dlg; TorrentImportDlg dlg;
if(dlg.exec()) { if(dlg.exec()) {
@ -195,7 +195,7 @@ void TorrentImportDlg::importTorrent(QBtSession *BTSession)
TorrentTempData::setSeedingMode(hash, dlg.skipFileChecking()); TorrentTempData::setSeedingMode(hash, dlg.skipFileChecking());
#endif #endif
qDebug("Adding the torrent to the session..."); qDebug("Adding the torrent to the session...");
BTSession->addTorrent(torrent_path); QBtSession::instance()->addTorrent(torrent_path);
// Remember the last opened folder // Remember the last opened folder
QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent"));
settings.setValue(QString::fromUtf8("MainWindowLastDir"), torrent_path); settings.setValue(QString::fromUtf8("MainWindowLastDir"), torrent_path);

2
src/torrentimportdlg.h

@ -49,7 +49,7 @@ class TorrentImportDlg : public QDialog
public: public:
explicit TorrentImportDlg(QWidget *parent = 0); explicit TorrentImportDlg(QWidget *parent = 0);
~TorrentImportDlg(); ~TorrentImportDlg();
static void importTorrent(QBtSession *BTSession); static void importTorrent();
QString getTorrentPath() const; QString getTorrentPath() const;
QString getContentPath() const; QString getContentPath() const;
bool fileRenamed() const; bool fileRenamed() const;

4
src/transferlistwidget.cpp

@ -35,7 +35,7 @@
#include "previewselect.h" #include "previewselect.h"
#include "speedlimitdlg.h" #include "speedlimitdlg.h"
#include "options_imp.h" #include "options_imp.h"
#include "GUI.h" #include "mainwindow.h"
#include "preferences.h" #include "preferences.h"
#include "deletionconfirmationdlg.h" #include "deletionconfirmationdlg.h"
#include "propertieswidget.h" #include "propertieswidget.h"
@ -55,7 +55,7 @@
#include "qinisettings.h" #include "qinisettings.h"
TransferListWidget::TransferListWidget(QWidget *parent, GUI *main_window, QBtSession *_BTSession): TransferListWidget::TransferListWidget(QWidget *parent, MainWindow *main_window, QBtSession *_BTSession):
QTreeView(parent), BTSession(_BTSession), main_window(main_window) { QTreeView(parent), BTSession(_BTSession), main_window(main_window) {
QIniSettings settings("qBittorrent", "qBittorrent"); QIniSettings settings("qBittorrent", "qBittorrent");
// Create and apply delegate // Create and apply delegate

6
src/transferlistwidget.h

@ -40,7 +40,7 @@ class QSortFilterProxyModel;
class QBtSession; class QBtSession;
class QTimer; class QTimer;
class TransferListDelegate; class TransferListDelegate;
class GUI; class MainWindow;
enum TorrentFilter {FILTER_ALL, FILTER_DOWNLOADING, FILTER_COMPLETED, FILTER_PAUSED, FILTER_ACTIVE, FILTER_INACTIVE}; enum TorrentFilter {FILTER_ALL, FILTER_DOWNLOADING, FILTER_COMPLETED, FILTER_PAUSED, FILTER_ACTIVE, FILTER_INACTIVE};
@ -48,7 +48,7 @@ class TransferListWidget: public QTreeView {
Q_OBJECT Q_OBJECT
public: public:
TransferListWidget(QWidget *parent, GUI *main_window, QBtSession* BTSession); TransferListWidget(QWidget *parent, MainWindow *main_window, QBtSession* BTSession);
~TransferListWidget(); ~TransferListWidget();
int getNbTorrents() const; int getNbTorrents() const;
QStandardItemModel* getSourceModel() const; QStandardItemModel* getSourceModel() const;
@ -137,7 +137,7 @@ private:
QSortFilterProxyModel *labelFilterModel; QSortFilterProxyModel *labelFilterModel;
QBtSession* BTSession; QBtSession* BTSession;
QTimer *refreshTimer; QTimer *refreshTimer;
GUI *main_window; MainWindow *main_window;
}; };
#endif // TRANSFERLISTWIDGET_H #endif // TRANSFERLISTWIDGET_H

28
src/webui/eventmanager.cpp

@ -40,8 +40,8 @@
#include <QDebug> #include <QDebug>
#include <QTranslator> #include <QTranslator>
EventManager::EventManager(QObject *parent, QBtSession *BTSession) EventManager::EventManager(QObject *parent)
: QObject(parent), BTSession(BTSession) : QObject(parent)
{ {
} }
@ -51,9 +51,9 @@ QList<QVariantMap> EventManager::getEventList() const {
QList<QVariantMap> EventManager::getPropTrackersInfo(QString hash) const { QList<QVariantMap> EventManager::getPropTrackersInfo(QString hash) const {
QList<QVariantMap> trackersInfo; QList<QVariantMap> trackersInfo;
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if(h.is_valid()) {
QHash<QString, TrackerInfos> trackers_data = BTSession->getTrackersInfo(hash); QHash<QString, TrackerInfos> trackers_data = QBtSession::instance()->getTrackersInfo(hash);
std::vector<announce_entry> vect_trackers = h.trackers(); std::vector<announce_entry> vect_trackers = h.trackers();
std::vector<announce_entry>::iterator it; std::vector<announce_entry>::iterator it;
for(it = vect_trackers.begin(); it != vect_trackers.end(); it++) { for(it = vect_trackers.begin(); it != vect_trackers.end(); it++) {
@ -96,7 +96,7 @@ QList<QVariantMap> EventManager::getPropTrackersInfo(QString hash) const {
QList<QVariantMap> EventManager::getPropFilesInfo(QString hash) const { QList<QVariantMap> EventManager::getPropFilesInfo(QString hash) const {
QList<QVariantMap> files; QList<QVariantMap> files;
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(!h.is_valid() || !h.has_metadata()) return files; if(!h.is_valid() || !h.has_metadata()) return files;
std::vector<int> priorities = h.file_priorities(); std::vector<int> priorities = h.file_priorities();
std::vector<size_type> fp; std::vector<size_type> fp;
@ -160,7 +160,7 @@ void EventManager::setGlobalPreferences(QVariantMap m) const {
foreach(const QString &old_folder, old_folders) { foreach(const QString &old_folder, old_folders) {
// Update deleted folders // Update deleted folders
if(!new_folders.contains(old_folder)) { if(!new_folders.contains(old_folder)) {
BTSession->getScanFoldersModel()->removePath(old_folder); QBtSession::instance()->getScanFoldersModel()->removePath(old_folder);
} }
} }
int i = 0; int i = 0;
@ -168,7 +168,7 @@ void EventManager::setGlobalPreferences(QVariantMap m) const {
qDebug("New watched folder: %s", qPrintable(new_folder)); qDebug("New watched folder: %s", qPrintable(new_folder));
// Update new folders // Update new folders
if(!old_folders.contains(new_folder)) { if(!old_folders.contains(new_folder)) {
BTSession->getScanFoldersModel()->addPath(new_folder, download_at_path.at(i)); QBtSession::instance()->getScanFoldersModel()->addPath(new_folder, download_at_path.at(i));
} }
++i; ++i;
} }
@ -269,7 +269,7 @@ void EventManager::setGlobalPreferences(QVariantMap m) const {
if(m.contains("web_ui_password")) if(m.contains("web_ui_password"))
Preferences::setWebUiPassword(m["web_ui_password"].toString()); Preferences::setWebUiPassword(m["web_ui_password"].toString());
// Reload preferences // Reload preferences
BTSession->configureSession(); QBtSession::instance()->configureSession();
} }
QVariantMap EventManager::getGlobalPreferences() const { QVariantMap EventManager::getGlobalPreferences() const {
@ -342,7 +342,7 @@ QVariantMap EventManager::getGlobalPreferences() const {
QVariantMap EventManager::getPropGeneralInfo(QString hash) const { QVariantMap EventManager::getPropGeneralInfo(QString hash) const {
QVariantMap data; QVariantMap data;
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid() && h.has_metadata()) { if(h.is_valid() && h.has_metadata()) {
// Save path // Save path
QString p = TorrentPersistentData::getSavePath(hash); QString p = TorrentPersistentData::getSavePath(hash);
@ -370,7 +370,7 @@ QVariantMap EventManager::getPropGeneralInfo(QString hash) const {
data["time_elapsed"] = elapsed_txt; data["time_elapsed"] = elapsed_txt;
data["nb_connections"] = QVariant(QString::number(h.num_connections())+" ("+tr("%1 max", "e.g. 10 max").arg(QString::number(h.connections_limit()))+")"); data["nb_connections"] = QVariant(QString::number(h.num_connections())+" ("+tr("%1 max", "e.g. 10 max").arg(QString::number(h.connections_limit()))+")");
// Update ratio info // Update ratio info
double ratio = BTSession->getRealRatio(h.hash()); double ratio = QBtSession::instance()->getRealRatio(h.hash());
if(ratio > 100.) if(ratio > 100.)
data["share_ratio"] = QString::fromUtf8(""); data["share_ratio"] = QString::fromUtf8("");
else else
@ -404,7 +404,7 @@ void EventManager::modifiedTorrent(QTorrentHandle h)
event["state"] = QVariant("pausedDL"); event["state"] = QVariant("pausedDL");
} }
} else { } else {
if(BTSession->isQueueingEnabled() && h.is_queued()) { if(QBtSession::instance()->isQueueingEnabled() && h.is_queued()) {
if(h.is_seed()) if(h.is_seed())
event["state"] = QVariant("queuedUP"); event["state"] = QVariant("queuedUP");
else else
@ -436,7 +436,7 @@ void EventManager::modifiedTorrent(QTorrentHandle h)
event["state"] = QVariant("downloading"); event["state"] = QVariant("downloading");
else else
event["state"] = QVariant("stalledDL"); event["state"] = QVariant("stalledDL");
event["eta"] = misc::userFriendlyDuration(BTSession->getETA(hash)); event["eta"] = misc::userFriendlyDuration(QBtSession::instance()->getETA(hash));
break; break;
default: default:
qDebug("No status, should not happen!!! status is %d", h.state()); qDebug("No status, should not happen!!! status is %d", h.state());
@ -448,7 +448,7 @@ void EventManager::modifiedTorrent(QTorrentHandle h)
event["size"] = QVariant(misc::friendlyUnit(h.actual_size())); event["size"] = QVariant(misc::friendlyUnit(h.actual_size()));
event["progress"] = QVariant((double)h.progress()); event["progress"] = QVariant((double)h.progress());
event["dlspeed"] = QVariant(tr("%1/s", "e.g. 120 KiB/s").arg(misc::friendlyUnit(h.download_payload_rate()))); event["dlspeed"] = QVariant(tr("%1/s", "e.g. 120 KiB/s").arg(misc::friendlyUnit(h.download_payload_rate())));
if(BTSession->isQueueingEnabled()) { if(QBtSession::instance()->isQueueingEnabled()) {
if(h.queue_position() >= 0) if(h.queue_position() >= 0)
event["priority"] = QVariant(QString::number(h.queue_position())); event["priority"] = QVariant(QString::number(h.queue_position()));
else else
@ -466,7 +466,7 @@ void EventManager::modifiedTorrent(QTorrentHandle h)
leechs += " ("+QString::number(h.num_incomplete())+")"; leechs += " ("+QString::number(h.num_incomplete())+")";
event["num_leechs"] = QVariant(leechs); event["num_leechs"] = QVariant(leechs);
event["seed"] = QVariant(h.is_seed()); event["seed"] = QVariant(h.is_seed());
double ratio = BTSession->getRealRatio(hash); double ratio = QBtSession::instance()->getRealRatio(hash);
if(ratio > 100.) if(ratio > 100.)
event["ratio"] = QString::fromUtf8(""); event["ratio"] = QString::fromUtf8("");
else else

5
src/webui/eventmanager.h

@ -36,8 +36,6 @@
#include <QHash> #include <QHash>
#include <QVariant> #include <QVariant>
class QBtSession;
class EventManager : public QObject class EventManager : public QObject
{ {
Q_OBJECT Q_OBJECT
@ -45,13 +43,12 @@ class EventManager : public QObject
private: private:
QHash<QString, QVariantMap> event_list; QHash<QString, QVariantMap> event_list;
QBtSession* BTSession;
protected: protected:
void update(QVariantMap event); void update(QVariantMap event);
public: public:
EventManager(QObject *parent, QBtSession* BTSession); EventManager(QObject *parent);
QList<QVariantMap> getEventList() const; QList<QVariantMap> getEventList() const;
QVariantMap getPropGeneralInfo(QString hash) const; QVariantMap getPropGeneralInfo(QString hash) const;
QList<QVariantMap> getPropTrackersInfo(QString hash) const; QList<QVariantMap> getPropTrackersInfo(QString hash) const;

66
src/webui/httpconnection.cpp

@ -46,8 +46,8 @@
#include <QRegExp> #include <QRegExp>
#include <QTemporaryFile> #include <QTemporaryFile>
HttpConnection::HttpConnection(QTcpSocket *socket, QBtSession *BTSession, HttpServer *parent) HttpConnection::HttpConnection(QTcpSocket *socket, HttpServer *parent)
: QObject(parent), socket(socket), parent(parent), BTSession(BTSession) : QObject(parent), socket(socket), httpserver(parent)
{ {
socket->setParent(this); socket->setParent(this);
connect(socket, SIGNAL(readyRead()), this, SLOT(read())); connect(socket, SIGNAL(readyRead()), this, SLOT(read()));
@ -134,7 +134,7 @@ QString HttpConnection::translateDocument(QString data) {
void HttpConnection::respond() { void HttpConnection::respond() {
//qDebug("Respond called"); //qDebug("Respond called");
const QString peer_ip = socket->peerAddress().toString(); const QString peer_ip = socket->peerAddress().toString();
const int nb_fail = parent->NbFailedAttemptsForIp(peer_ip); const int nb_fail = httpserver->NbFailedAttemptsForIp(peer_ip);
if(nb_fail >= MAX_AUTH_FAILED_ATTEMPTS) { if(nb_fail >= MAX_AUTH_FAILED_ATTEMPTS) {
generator.setStatusLine(403, "Forbidden"); generator.setStatusLine(403, "Forbidden");
generator.setMessage(tr("Your IP address has been banned after too many failed authentication attempts.")); generator.setMessage(tr("Your IP address has been banned after too many failed authentication attempts."));
@ -146,23 +146,23 @@ void HttpConnection::respond() {
// Return unauthorized header // Return unauthorized header
qDebug("Auth is Empty..."); qDebug("Auth is Empty...");
generator.setStatusLine(401, "Unauthorized"); generator.setStatusLine(401, "Unauthorized");
generator.setValue("WWW-Authenticate", "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+parent->generateNonce()+"\", opaque=\""+parent->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\""); generator.setValue("WWW-Authenticate", "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+httpserver->generateNonce()+"\", opaque=\""+httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\"");
write(); write();
return; return;
} }
//qDebug("Auth: %s", qPrintable(auth.split(" ").first())); //qDebug("Auth: %s", qPrintable(auth.split(" ").first()));
if (QString::compare(auth.split(" ").first(), "Digest", Qt::CaseInsensitive) != 0 || !parent->isAuthorized(auth.toLocal8Bit(), parser.method())) { if (QString::compare(auth.split(" ").first(), "Digest", Qt::CaseInsensitive) != 0 || !httpserver->isAuthorized(auth.toLocal8Bit(), parser.method())) {
// Update failed attempt counter // Update failed attempt counter
parent->increaseNbFailedAttemptsForIp(peer_ip); httpserver->increaseNbFailedAttemptsForIp(peer_ip);
qDebug("client IP: %s (%d failed attempts)", qPrintable(peer_ip), nb_fail+1); qDebug("client IP: %s (%d failed attempts)", qPrintable(peer_ip), nb_fail+1);
// Return unauthorized header // Return unauthorized header
generator.setStatusLine(401, "Unauthorized"); generator.setStatusLine(401, "Unauthorized");
generator.setValue("WWW-Authenticate", "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+parent->generateNonce()+"\", opaque=\""+parent->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\""); generator.setValue("WWW-Authenticate", "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+httpserver->generateNonce()+"\", opaque=\""+httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\"");
write(); write();
return; return;
} }
// Client successfully authenticated, reset number of failed attempts // Client successfully authenticated, reset number of failed attempts
parent->resetNbFailedAttemptsForIp(peer_ip); httpserver->resetNbFailedAttemptsForIp(peer_ip);
QString url = parser.url(); QString url = parser.url();
// Favicon // Favicon
if(url.endsWith("favicon.ico")) { if(url.endsWith("favicon.ico")) {
@ -271,7 +271,7 @@ void HttpConnection::respondNotFound()
void HttpConnection::respondJson() void HttpConnection::respondJson()
{ {
EventManager* manager = parent->eventManager(); EventManager* manager = httpserver->eventManager();
QString string = json::toJson(manager->getEventList()); QString string = json::toJson(manager->getEventList());
generator.setStatusLine(200, "OK"); generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("js"); generator.setContentTypeByExt("js");
@ -280,7 +280,7 @@ void HttpConnection::respondJson()
} }
void HttpConnection::respondGenPropertiesJson(QString hash) { void HttpConnection::respondGenPropertiesJson(QString hash) {
EventManager* manager = parent->eventManager(); EventManager* manager = httpserver->eventManager();
QString string = json::toJson(manager->getPropGeneralInfo(hash)); QString string = json::toJson(manager->getPropGeneralInfo(hash));
generator.setStatusLine(200, "OK"); generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("js"); generator.setContentTypeByExt("js");
@ -289,7 +289,7 @@ void HttpConnection::respondGenPropertiesJson(QString hash) {
} }
void HttpConnection::respondTrackersPropertiesJson(QString hash) { void HttpConnection::respondTrackersPropertiesJson(QString hash) {
EventManager* manager = parent->eventManager(); EventManager* manager = httpserver->eventManager();
QString string = json::toJson(manager->getPropTrackersInfo(hash)); QString string = json::toJson(manager->getPropTrackersInfo(hash));
generator.setStatusLine(200, "OK"); generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("js"); generator.setContentTypeByExt("js");
@ -298,7 +298,7 @@ void HttpConnection::respondTrackersPropertiesJson(QString hash) {
} }
void HttpConnection::respondFilesPropertiesJson(QString hash) { void HttpConnection::respondFilesPropertiesJson(QString hash) {
EventManager* manager = parent->eventManager(); EventManager* manager = httpserver->eventManager();
QString string = json::toJson(manager->getPropFilesInfo(hash)); QString string = json::toJson(manager->getPropFilesInfo(hash));
generator.setStatusLine(200, "OK"); generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("js"); generator.setContentTypeByExt("js");
@ -307,7 +307,7 @@ void HttpConnection::respondFilesPropertiesJson(QString hash) {
} }
void HttpConnection::respondPreferencesJson() { void HttpConnection::respondPreferencesJson() {
EventManager* manager = parent->eventManager(); EventManager* manager = httpserver->eventManager();
QString string = json::toJson(manager->getGlobalPreferences()); QString string = json::toJson(manager->getGlobalPreferences());
generator.setStatusLine(200, "OK"); generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("js"); generator.setContentTypeByExt("js");
@ -317,7 +317,7 @@ void HttpConnection::respondPreferencesJson() {
void HttpConnection::respondGlobalTransferInfoJson() { void HttpConnection::respondGlobalTransferInfoJson() {
QVariantMap info; QVariantMap info;
session_status sessionStatus = BTSession->getSessionStatus(); session_status sessionStatus = QBtSession::instance()->getSessionStatus();
info["DlInfos"] = tr("D: %1/s - T: %2", "Download speed: x KiB/s - Transferred: x MiB").arg(misc::friendlyUnit(sessionStatus.payload_download_rate)).arg(misc::friendlyUnit(sessionStatus.total_payload_download)); info["DlInfos"] = tr("D: %1/s - T: %2", "Download speed: x KiB/s - Transferred: x MiB").arg(misc::friendlyUnit(sessionStatus.payload_download_rate)).arg(misc::friendlyUnit(sessionStatus.total_payload_download));
info["UpInfos"] = tr("U: %1/s - T: %2", "Upload speed: x KiB/s - Transferred: x MiB").arg(misc::friendlyUnit(sessionStatus.payload_upload_rate)).arg(misc::friendlyUnit(sessionStatus.total_payload_upload)); info["UpInfos"] = tr("U: %1/s - T: %2", "Upload speed: x KiB/s - Transferred: x MiB").arg(misc::friendlyUnit(sessionStatus.payload_upload_rate)).arg(misc::friendlyUnit(sessionStatus.total_payload_upload));
QString string = json::toJson(info); QString string = json::toJson(info);
@ -353,7 +353,7 @@ void HttpConnection::respondCommand(QString command)
if(command == "addTrackers") { if(command == "addTrackers") {
QString hash = parser.post("hash"); QString hash = parser.post("hash");
if(!hash.isEmpty()) { if(!hash.isEmpty()) {
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid() && h.has_metadata()) { if(h.is_valid() && h.has_metadata()) {
QString urls = parser.post("urls"); QString urls = parser.post("urls");
QStringList list = urls.split('\n'); QStringList list = urls.split('\n');
@ -407,14 +407,14 @@ void HttpConnection::respondCommand(QString command)
} }
if(command == "setPreferences") { if(command == "setPreferences") {
QString json_str = parser.post("json"); QString json_str = parser.post("json");
EventManager* manager = parent->eventManager(); EventManager* manager = httpserver->eventManager();
manager->setGlobalPreferences(json::fromJson(json_str)); manager->setGlobalPreferences(json::fromJson(json_str));
} }
if(command == "setFilePrio") { if(command == "setFilePrio") {
QString hash = parser.post("hash"); QString hash = parser.post("hash");
int file_id = parser.post("id").toInt(); int file_id = parser.post("id").toInt();
int priority = parser.post("priority").toInt(); int priority = parser.post("priority").toInt();
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid() && h.has_metadata()) { if(h.is_valid() && h.has_metadata()) {
h.file_priority(file_id, priority); h.file_priority(file_id, priority);
} }
@ -422,18 +422,18 @@ void HttpConnection::respondCommand(QString command)
if(command == "getGlobalUpLimit") { if(command == "getGlobalUpLimit") {
generator.setStatusLine(200, "OK"); generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("html"); generator.setContentTypeByExt("html");
generator.setMessage(QString::number(BTSession->getSession()->upload_rate_limit())); generator.setMessage(QString::number(QBtSession::instance()->getSession()->upload_rate_limit()));
write(); write();
} }
if(command == "getGlobalDlLimit") { if(command == "getGlobalDlLimit") {
generator.setStatusLine(200, "OK"); generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("html"); generator.setContentTypeByExt("html");
generator.setMessage(QString::number(BTSession->getSession()->download_rate_limit())); generator.setMessage(QString::number(QBtSession::instance()->getSession()->download_rate_limit()));
write(); write();
} }
if(command == "getTorrentUpLimit") { if(command == "getTorrentUpLimit") {
QString hash = parser.post("hash"); QString hash = parser.post("hash");
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if(h.is_valid()) {
generator.setStatusLine(200, "OK"); generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("html"); generator.setContentTypeByExt("html");
@ -443,7 +443,7 @@ void HttpConnection::respondCommand(QString command)
} }
if(command == "getTorrentDlLimit") { if(command == "getTorrentDlLimit") {
QString hash = parser.post("hash"); QString hash = parser.post("hash");
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if(h.is_valid()) {
generator.setStatusLine(200, "OK"); generator.setStatusLine(200, "OK");
generator.setContentTypeByExt("html"); generator.setContentTypeByExt("html");
@ -455,7 +455,7 @@ void HttpConnection::respondCommand(QString command)
QString hash = parser.post("hash"); QString hash = parser.post("hash");
qlonglong limit = parser.post("limit").toLongLong(); qlonglong limit = parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if(limit == 0) limit = -1;
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if(h.is_valid()) {
h.set_upload_limit(limit); h.set_upload_limit(limit);
} }
@ -464,7 +464,7 @@ void HttpConnection::respondCommand(QString command)
QString hash = parser.post("hash"); QString hash = parser.post("hash");
qlonglong limit = parser.post("limit").toLongLong(); qlonglong limit = parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if(limit == 0) limit = -1;
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()) { if(h.is_valid()) {
h.set_download_limit(limit); h.set_download_limit(limit);
} }
@ -472,13 +472,13 @@ void HttpConnection::respondCommand(QString command)
if(command == "setGlobalUpLimit") { if(command == "setGlobalUpLimit") {
qlonglong limit = parser.post("limit").toLongLong(); qlonglong limit = parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if(limit == 0) limit = -1;
BTSession->getSession()->set_upload_rate_limit(limit); QBtSession::instance()->getSession()->set_upload_rate_limit(limit);
Preferences::setGlobalUploadLimit(limit/1024.); Preferences::setGlobalUploadLimit(limit/1024.);
} }
if(command == "setGlobalDlLimit") { if(command == "setGlobalDlLimit") {
qlonglong limit = parser.post("limit").toLongLong(); qlonglong limit = parser.post("limit").toLongLong();
if(limit == 0) limit = -1; if(limit == 0) limit = -1;
BTSession->getSession()->set_download_rate_limit(limit); QBtSession::instance()->getSession()->set_download_rate_limit(limit);
Preferences::setGlobalDownloadLimit(limit/1024.); Preferences::setGlobalDownloadLimit(limit/1024.);
} }
if(command == "pause") { if(command == "pause") {
@ -494,22 +494,22 @@ void HttpConnection::respondCommand(QString command)
return; return;
} }
if(command == "increasePrio") { if(command == "increasePrio") {
QTorrentHandle h = BTSession->getTorrentHandle(parser.post("hash")); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(parser.post("hash"));
if(h.is_valid()) h.queue_position_up(); if(h.is_valid()) h.queue_position_up();
return; return;
} }
if(command == "decreasePrio") { if(command == "decreasePrio") {
QTorrentHandle h = BTSession->getTorrentHandle(parser.post("hash")); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(parser.post("hash"));
if(h.is_valid()) h.queue_position_down(); if(h.is_valid()) h.queue_position_down();
return; return;
} }
if(command == "topPrio") { if(command == "topPrio") {
QTorrentHandle h = BTSession->getTorrentHandle(parser.post("hash")); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(parser.post("hash"));
if(h.is_valid()) h.queue_position_top(); if(h.is_valid()) h.queue_position_top();
return; return;
} }
if(command == "bottomPrio") { if(command == "bottomPrio") {
QTorrentHandle h = BTSession->getTorrentHandle(parser.post("hash")); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(parser.post("hash"));
if(h.is_valid()) h.queue_position_bottom(); if(h.is_valid()) h.queue_position_bottom();
return; return;
} }
@ -524,18 +524,18 @@ void HttpConnection::respondCommand(QString command)
} }
void HttpConnection::recheckTorrent(QString hash) { void HttpConnection::recheckTorrent(QString hash) {
QTorrentHandle h = BTSession->getTorrentHandle(hash); QTorrentHandle h = QBtSession::instance()->getTorrentHandle(hash);
if(h.is_valid()){ if(h.is_valid()){
BTSession->recheckTorrent(h.hash()); QBtSession::instance()->recheckTorrent(h.hash());
} }
} }
void HttpConnection::recheckAllTorrents() { void HttpConnection::recheckAllTorrents() {
std::vector<torrent_handle> torrents = BTSession->getTorrents(); std::vector<torrent_handle> torrents = QBtSession::instance()->getTorrents();
std::vector<torrent_handle>::iterator torrentIT; std::vector<torrent_handle>::iterator torrentIT;
for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) {
QTorrentHandle h = QTorrentHandle(*torrentIT); QTorrentHandle h = QTorrentHandle(*torrentIT);
if(h.is_valid()) if(h.is_valid())
BTSession->recheckTorrent(h.hash()); QBtSession::instance()->recheckTorrent(h.hash());
} }
} }

6
src/webui/httpconnection.h

@ -38,7 +38,6 @@
class QTcpSocket; class QTcpSocket;
class HttpServer; class HttpServer;
class QBtSession;
class HttpConnection : public QObject class HttpConnection : public QObject
{ {
@ -47,8 +46,7 @@ class HttpConnection : public QObject
private: private:
QTcpSocket *socket; QTcpSocket *socket;
HttpServer *parent; HttpServer *httpserver;
QBtSession *BTSession;
protected: protected:
HttpRequestParser parser; HttpRequestParser parser;
@ -71,7 +69,7 @@ protected slots:
void recheckAllTorrents(); void recheckAllTorrents();
public: public:
HttpConnection(QTcpSocket *socket, QBtSession* BTSession, HttpServer *parent); HttpConnection(QTcpSocket *socket, HttpServer *httpserver);
~HttpConnection(); ~HttpConnection();
QString translateDocument(QString data); QString translateDocument(QString data);

35
src/webui/httpserver.cpp

@ -80,23 +80,22 @@ void HttpServer::resetNbFailedAttemptsForIp(QString ip) {
client_failed_attempts.remove(ip); client_failed_attempts.remove(ip);
} }
HttpServer::HttpServer(QBtSession *_BTSession, int msec, QObject* parent) : QTcpServer(parent) { HttpServer::HttpServer(int msec, QObject* parent) : QTcpServer(parent) {
username = Preferences::getWebUiUsername().toLocal8Bit(); username = Preferences::getWebUiUsername().toLocal8Bit();
password_ha1 = Preferences::getWebUiPassword().toLocal8Bit(); password_ha1 = Preferences::getWebUiPassword().toLocal8Bit();
connect(this, SIGNAL(newConnection()), this, SLOT(newHttpConnection())); connect(this, SIGNAL(newConnection()), this, SLOT(newHttpConnection()));
BTSession = _BTSession; manager = new EventManager(this);
manager = new EventManager(this, BTSession);
//add torrents //add torrents
std::vector<torrent_handle> torrents = BTSession->getTorrents(); std::vector<torrent_handle> torrents = QBtSession::instance()->getTorrents();
std::vector<torrent_handle>::iterator torrentIT; std::vector<torrent_handle>::iterator torrentIT;
for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) {
QTorrentHandle h = QTorrentHandle(*torrentIT); QTorrentHandle h = QTorrentHandle(*torrentIT);
if(h.is_valid()) if(h.is_valid())
manager->addedTorrent(h); manager->addedTorrent(h);
} }
//connect BTSession to manager //connect QBtSession::instance() to manager
connect(BTSession, SIGNAL(addedTorrent(QTorrentHandle&)), manager, SLOT(addedTorrent(QTorrentHandle&))); connect(QBtSession::instance(), SIGNAL(addedTorrent(QTorrentHandle&)), manager, SLOT(addedTorrent(QTorrentHandle&)));
connect(BTSession, SIGNAL(deletedTorrent(QString)), manager, SLOT(deletedTorrent(QString))); connect(QBtSession::instance(), SIGNAL(deletedTorrent(QString)), manager, SLOT(deletedTorrent(QString)));
//set timer //set timer
timer = new QTimer(this); timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(onTimer())); connect(timer, SIGNAL(timeout()), this, SLOT(onTimer()));
@ -138,21 +137,21 @@ void HttpServer::newHttpConnection()
QTcpSocket *socket; QTcpSocket *socket;
while((socket = nextPendingConnection())) while((socket = nextPendingConnection()))
{ {
HttpConnection *connection = new HttpConnection(socket, BTSession, this); HttpConnection *connection = new HttpConnection(socket, this);
//connect connection to BTSession //connect connection to QBtSession::instance()
connect(connection, SIGNAL(UrlReadyToBeDownloaded(QString)), BTSession, SLOT(downloadUrlAndSkipDialog(QString))); connect(connection, SIGNAL(UrlReadyToBeDownloaded(QString)), QBtSession::instance(), SLOT(downloadUrlAndSkipDialog(QString)));
connect(connection, SIGNAL(MagnetReadyToBeDownloaded(QString)), BTSession, SLOT(addMagnetSkipAddDlg(QString))); connect(connection, SIGNAL(MagnetReadyToBeDownloaded(QString)), QBtSession::instance(), SLOT(addMagnetSkipAddDlg(QString)));
connect(connection, SIGNAL(torrentReadyToBeDownloaded(QString, bool, QString, bool)), BTSession, SLOT(addTorrent(QString, bool, QString, bool))); connect(connection, SIGNAL(torrentReadyToBeDownloaded(QString, bool, QString, bool)), QBtSession::instance(), SLOT(addTorrent(QString, bool, QString, bool)));
connect(connection, SIGNAL(deleteTorrent(QString, bool)), BTSession, SLOT(deleteTorrent(QString, bool))); connect(connection, SIGNAL(deleteTorrent(QString, bool)), QBtSession::instance(), SLOT(deleteTorrent(QString, bool)));
connect(connection, SIGNAL(pauseTorrent(QString)), BTSession, SLOT(pauseTorrent(QString))); connect(connection, SIGNAL(pauseTorrent(QString)), QBtSession::instance(), SLOT(pauseTorrent(QString)));
connect(connection, SIGNAL(resumeTorrent(QString)), BTSession, SLOT(resumeTorrent(QString))); connect(connection, SIGNAL(resumeTorrent(QString)), QBtSession::instance(), SLOT(resumeTorrent(QString)));
connect(connection, SIGNAL(pauseAllTorrents()), BTSession, SLOT(pauseAllTorrents())); connect(connection, SIGNAL(pauseAllTorrents()), QBtSession::instance(), SLOT(pauseAllTorrents()));
connect(connection, SIGNAL(resumeAllTorrents()), BTSession, SLOT(resumeAllTorrents())); connect(connection, SIGNAL(resumeAllTorrents()), QBtSession::instance(), SLOT(resumeAllTorrents()));
} }
} }
void HttpServer::onTimer() { void HttpServer::onTimer() {
std::vector<torrent_handle> torrents = BTSession->getTorrents(); std::vector<torrent_handle> torrents = QBtSession::instance()->getTorrents();
std::vector<torrent_handle>::iterator torrentIT; std::vector<torrent_handle>::iterator torrentIT;
for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) { for(torrentIT = torrents.begin(); torrentIT != torrents.end(); torrentIT++) {
QTorrentHandle h = QTorrentHandle(*torrentIT); QTorrentHandle h = QTorrentHandle(*torrentIT);

4
src/webui/httpserver.h

@ -38,7 +38,6 @@
#include <QHash> #include <QHash>
#include "preferences.h" #include "preferences.h"
class QBtSession;
class QTimer; class QTimer;
class EventManager; class EventManager;
@ -49,7 +48,7 @@ class HttpServer : public QTcpServer {
Q_DISABLE_COPY(HttpServer) Q_DISABLE_COPY(HttpServer)
public: public:
HttpServer(QBtSession *BTSession, int msec, QObject* parent = 0); HttpServer(int msec, QObject* parent = 0);
~HttpServer(); ~HttpServer();
void setAuthorization(QString username, QString password_ha1); void setAuthorization(QString username, QString password_ha1);
bool isAuthorized(QByteArray auth, QString method) const; bool isAuthorized(QByteArray auth, QString method) const;
@ -67,7 +66,6 @@ private slots:
private: private:
QByteArray username; QByteArray username;
QByteArray password_ha1; QByteArray password_ha1;
QBtSession *BTSession;
EventManager *manager; EventManager *manager;
QTimer *timer; QTimer *timer;
QHash<QString, int> client_failed_attempts; QHash<QString, int> client_failed_attempts;

Loading…
Cancel
Save