From d27c2db830de9a65d6a419479ee598cbf3697746 Mon Sep 17 00:00:00 2001 From: deztructor Date: Wed, 18 Nov 2009 09:36:34 +0000 Subject: [PATCH] Code formatting/indentation unified in trunk scripts/format_code.sh used for automatic indentation according to "ansi" indentation style git-svn-id: file:///svnroot/qtrapids/trunk@31 42ac0dd5-4c8c-4c71-bb3e-ecdfe252ffda --- src/client/DownloadView.cpp | 305 ++++++++++++++-------------- src/client/DownloadView.h | 155 +++++++------- src/client/MainWindow.cpp | 312 +++++++++++++++-------------- src/client/MainWindow.h | 117 +++++------ src/client/PreferencesDialog.cpp | 164 +++++++-------- src/client/PreferencesDialog.h | 34 ++-- src/client/SeedView.cpp | 36 ++-- src/client/SeedView.h | 119 +++++------ src/client/main.cpp | 74 +++---- src/engine/AlertWaiterThread.cpp | 49 ++--- src/engine/AlertWaiterThread.h | 32 +-- src/engine/QBittorrentSession.cpp | 45 +++-- src/engine/QBittorrentSession.h | 44 ++-- src/engine/QTorrentHandle.cpp | 112 ++++++----- src/engine/QTorrentHandle.h | 98 ++++----- src/gui/DownloadView.cpp | 299 +++++++++++++-------------- src/gui/DownloadView.h | 103 +++++----- src/gui/MainWindow.cpp | 291 ++++++++++++++------------- src/gui/MainWindow.h | 69 +++---- src/gui/PreferencesDialog.cpp | 164 +++++++-------- src/gui/PreferencesDialog.h | 34 ++-- src/gui/SeedView.cpp | 16 +- src/gui/SeedView.h | 99 ++++----- src/gui/main.cpp | 74 +++---- src/include/qtrapids/dbus.hpp | 180 +++++++++-------- src/include/qtrapids/error.hpp | 60 +++--- src/include/qtrapids/format.hpp | 59 +++--- src/include/qtrapids/info.hpp | 35 ++-- src/include/qtrapids/settings.hpp | 21 +- src/plugins/PluginInterface.h | 104 +++++----- src/plugins/searchplugin/SearchPlugin.cpp | 118 +++++------ src/plugins/searchplugin/SearchPlugin.h | 51 ++--- src/server/AlertWaiterThread.cpp | 64 +++--- src/server/AlertWaiterThread.hpp | 46 ++--- src/server/ServerDb.hpp | 175 ++++++++-------- src/server/TorrentHandle.cpp | 165 +++++++-------- src/server/TorrentHandle.hpp | 94 ++++----- src/server/TorrentSession.cpp | 229 +++++++++++---------- src/server/TorrentSession.hpp | 66 +++--- src/server/main.cpp | 8 +- 40 files changed, 2212 insertions(+), 2108 deletions(-) diff --git a/src/client/DownloadView.cpp b/src/client/DownloadView.cpp index 09b1e2e..d097234 100644 --- a/src/client/DownloadView.cpp +++ b/src/client/DownloadView.cpp @@ -28,183 +28,196 @@ namespace qtrapids { - DownloadView::DownloadView(QWidget* parent) : +DownloadView::DownloadView(QWidget* parent) : QTreeWidget(parent), items_() - { - setRootIsDecorated(false); // Hide branch lines, making one-level treeview (similar to list) - setHeaderItem(DownloadViewItem::getHeaderItem()); +{ + setRootIsDecorated(false); // Hide branch lines, making one-level treeview (similar to list) + setHeaderItem(DownloadViewItem::getHeaderItem()); - connect(this, SIGNAL(itemPressed(QTreeWidgetItem*, int)), - this, SLOT(on_itemClicked(QTreeWidgetItem*, int))); + connect(this, SIGNAL(itemPressed(QTreeWidgetItem*, int)), + this, SLOT(on_itemClicked(QTreeWidgetItem*, int))); - } +} - DownloadView::~DownloadView() - { - } +DownloadView::~DownloadView() +{ +} - void DownloadView::updateItem(TorrentState const& info, ParamsMap_t other_info) +void DownloadView::updateItem(TorrentState const& info, ParamsMap_t other_info) +{ + DownloadItems_t::iterator p = items_.find(info.hash); + switch (info.action) { - DownloadItems_t::iterator p = items_.find(info.hash); - switch (info.action) { - case TorrentState::action_add : - if (p == items_.end()) { - addItem_(info, other_info); - } else { - qWarning() << "item with similar info hash marked as added"; - updateItem_(p.value(), info, other_info); - } - break; - case TorrentState::action_update : - if (p != items_.end()) { - updateItem_(p.value(), info, other_info); - } else { - qWarning() << "item does not exist in list but information update arrived"; - } - break; - case TorrentState::action_remove : - if (p != items_.end()) { - removeItem_(p.value(), info); - } else { - qWarning() << "item removal request arrived but there is no such item"; - } - break; - default: - qWarning() << "unknown action requested: " << info.action; - break; + case TorrentState::action_add : + if (p == items_.end()) + { + addItem_(info, other_info); } - } - - void DownloadView::removeItem_(DownloadViewItem *item, TorrentState const& info) - { - QString hash = item->getHash(); - - int removed = items_.remove(hash); - if (!removed) - qDebug() << "Inconsistent download view state on item removal"; - - int index = indexOfTopLevelItem(item); - if (index >= 0) { - takeTopLevelItem(index); + else + { + qWarning() << "item with similar info hash marked as added"; + updateItem_(p.value(), info, other_info); + } + break; + case TorrentState::action_update : + if (p != items_.end()) + { + updateItem_(p.value(), info, other_info); + } + else + { + qWarning() << "item does not exist in list but information update arrived"; + } + break; + case TorrentState::action_remove : + if (p != items_.end()) + { + removeItem_(p.value(), info); + } + else + { + qWarning() << "item removal request arrived but there is no such item"; } + break; + default: + qWarning() << "unknown action requested: " << info.action; + break; } +} - void DownloadView::addItem_(TorrentState const& info, ParamsMap_t) - { - DownloadViewItem *item = new DownloadViewItem - ( info.hash, - QStringList() - << info.name - << formatSize(info.total_size) - << GetStatusString((TorrentStatus::Id)info.state) - << formatProgress(info.progress) - << QString::number(info.down_rate, 'f', 2) - << QString::number(info.up_rate, 'f', 2) - << QString::number(info.seeds) + "/" + QString::number(info.leeches) - << QString::number(info.ratio) - << "ETA" ); - - QBrush brushTmp(GetStatusColor((TorrentStatus::Id)info.state)); - item->setForeground(2, brushTmp); - - addTopLevelItem(item); - items_[info.hash] = item; - } +void DownloadView::removeItem_(DownloadViewItem *item, TorrentState const& info) +{ + QString hash = item->getHash(); + int removed = items_.remove(hash); + if (!removed) + qDebug() << "Inconsistent download view state on item removal"; - void DownloadView::updateItem_(DownloadViewItem *item - , TorrentState const& info, ParamsMap_t) + int index = indexOfTopLevelItem(item); + if (index >= 0) { - item->setData(2, Qt::DisplayRole, - QVariant(GetStatusString((TorrentStatus::Id)info.state))); - item->setData(3, Qt::DisplayRole, - QVariant(formatProgress(info.progress))); - item->setData(4, Qt::DisplayRole, - QVariant(QString::number(info.down_rate))); - item->setData(5, Qt::DisplayRole, - QVariant(QString::number(info.up_rate))); - item->setData(6, Qt::DisplayRole, - QString::number(info.seeds) + "/" + QString::number(info.leeches)); - - QBrush brushTmp(GetStatusColor((TorrentStatus::Id)info.state)); - item->setForeground(2, brushTmp); + takeTopLevelItem(index); } +} +void DownloadView::addItem_(TorrentState const& info, ParamsMap_t) +{ + DownloadViewItem *item = new DownloadViewItem + ( info.hash, + QStringList() + << info.name + << formatSize(info.total_size) + << GetStatusString((TorrentStatus::Id)info.state) + << formatProgress(info.progress) + << QString::number(info.down_rate, 'f', 2) + << QString::number(info.up_rate, 'f', 2) + << QString::number(info.seeds) + "/" + QString::number(info.leeches) + << QString::number(info.ratio) + << "ETA" ); + + QBrush brushTmp(GetStatusColor((TorrentStatus::Id)info.state)); + item->setForeground(2, brushTmp); + + addTopLevelItem(item); + items_[info.hash] = item; +} + + +void DownloadView::updateItem_(DownloadViewItem *item + , TorrentState const& info, ParamsMap_t) +{ + item->setData(2, Qt::DisplayRole, + QVariant(GetStatusString((TorrentStatus::Id)info.state))); + item->setData(3, Qt::DisplayRole, + QVariant(formatProgress(info.progress))); + item->setData(4, Qt::DisplayRole, + QVariant(QString::number(info.down_rate))); + item->setData(5, Qt::DisplayRole, + QVariant(QString::number(info.up_rate))); + item->setData(6, Qt::DisplayRole, + QString::number(info.seeds) + "/" + QString::number(info.leeches)); + + QBrush brushTmp(GetStatusColor((TorrentStatus::Id)info.state)); + item->setForeground(2, brushTmp); +} + + +QString DownloadView::prepareRemoveSelected() +{ + qDebug() << "DownloadView::removeSelected() " << topLevelItemCount() ; - QString DownloadView::prepareRemoveSelected() - { - qDebug() << "DownloadView::removeSelected() " << topLevelItemCount() ; + DownloadViewItem *item = dynamic_cast (currentItem()); + QString hash = item->getHash(); - DownloadViewItem *item = dynamic_cast (currentItem()); - QString hash = item->getHash(); + item->setDisabled(true); - item->setDisabled(true); + qDebug() << "DownloadView::removeSelected() " << topLevelItemCount() ; - qDebug() << "DownloadView::removeSelected() " << topLevelItemCount() ; + return hash; +} - return hash; - } +void DownloadView::on_itemClicked(QTreeWidgetItem * , int) +{ + /* + qDebug() << "DownloadView::on_itemClicked(()" << item << "," << column; + qDebug() << "current item" << currentItem(); - void DownloadView::on_itemClicked(QTreeWidgetItem * , int) - { - /* - qDebug() << "DownloadView::on_itemClicked(()" << item << "," << column; - qDebug() << "current item" << currentItem(); - - if (item == currentItem() && item->isSelected()) { - item->setSelected(false); - } - */ - } + if (item == currentItem() && item->isSelected()) { + item->setSelected(false); + } + */ +} - QString DownloadView::GetStatusString(TorrentStatus::Id status) +QString DownloadView::GetStatusString(TorrentStatus::Id status) +{ + switch (status) { - switch (status) { - case TorrentStatus::QUEUED_FOR_CHECKING : - return tr("Queued"); - case TorrentStatus::CHECKING_FILES : - return tr("Checking"); - case TorrentStatus::DOWNLOADING_METADATA : - return tr("DL meta"); - case TorrentStatus::DOWNLOADING : - return tr("Downloading"); - case TorrentStatus::FINISHED : - return tr("Finished"); - case TorrentStatus::SEEDING : - return tr("Seeding"); - case TorrentStatus::ALLOCATING : - return tr("Allocating"); - case TorrentStatus::CHECKING_RESUME_DATA : - return tr("Checking resume"); - default: - return tr("N/A"); - } + case TorrentStatus::QUEUED_FOR_CHECKING : + return tr("Queued"); + case TorrentStatus::CHECKING_FILES : + return tr("Checking"); + case TorrentStatus::DOWNLOADING_METADATA : + return tr("DL meta"); + case TorrentStatus::DOWNLOADING : + return tr("Downloading"); + case TorrentStatus::FINISHED : + return tr("Finished"); + case TorrentStatus::SEEDING : + return tr("Seeding"); + case TorrentStatus::ALLOCATING : + return tr("Allocating"); + case TorrentStatus::CHECKING_RESUME_DATA : + return tr("Checking resume"); + default: + return tr("N/A"); } +} + +QColor DownloadView::GetStatusColor(TorrentStatus::Id status) +{ + QColor green(40,205,40); + QColor yellow(255,174,0); - QColor DownloadView::GetStatusColor(TorrentStatus::Id status) + switch (status) { - QColor green(40,205,40); - QColor yellow(255,174,0); - - switch (status) { - case TorrentStatus::QUEUED_FOR_CHECKING : - case TorrentStatus::CHECKING_FILES : - case TorrentStatus::DOWNLOADING_METADATA : - case TorrentStatus::ALLOCATING : - case TorrentStatus::CHECKING_RESUME_DATA: - return yellow; - case TorrentStatus::DOWNLOADING : - case TorrentStatus::FINISHED : - case TorrentStatus::SEEDING : - return green; - default: - return QColor(); - } + case TorrentStatus::QUEUED_FOR_CHECKING : + case TorrentStatus::CHECKING_FILES : + case TorrentStatus::DOWNLOADING_METADATA : + case TorrentStatus::ALLOCATING : + case TorrentStatus::CHECKING_RESUME_DATA: + return yellow; + case TorrentStatus::DOWNLOADING : + case TorrentStatus::FINISHED : + case TorrentStatus::SEEDING : + return green; + default: + return QColor(); } +} } // namespace qtrapids diff --git a/src/client/DownloadView.h b/src/client/DownloadView.h index 5ddffe4..caf3daf 100644 --- a/src/client/DownloadView.h +++ b/src/client/DownloadView.h @@ -30,88 +30,89 @@ namespace qtrapids { - class DownloadViewItem; +class DownloadViewItem; - typedef QHash DownloadItems_t; +typedef QHash DownloadItems_t; - /** - @class DownloadView - @brief A view showing all downloaded torrents - @author Lassi Väätämöinen - */ - class DownloadView : public QTreeWidget - { - Q_OBJECT - - public: - DownloadView(QWidget* parent); - - ~DownloadView(); - - void updateItem(TorrentState const& info, ParamsMap_t other_info); - QString prepareRemoveSelected(); - - private slots: - void on_itemClicked(QTreeWidgetItem * item, int column); - private: - - void addItem_(TorrentState const& info, ParamsMap_t other_info); - void updateItem_(DownloadViewItem *item - , TorrentState const& info, ParamsMap_t other_info); - void removeItem_(DownloadViewItem *item, TorrentState const& info); - - // Maps torrent to downloadview item. - // Key: SHA1 info hash of torrent. Data: View item corresponding to torrent. - DownloadItems_t items_; - - // Private functions. - static QString GetStatusString(TorrentStatus::Id status); - static QColor GetStatusColor(TorrentStatus::Id status); - }; - - - /** - @class DownloadViewItem - @brief Represents one item row of DownloadView - */ - class DownloadViewItem : public QTreeWidgetItem { - - public: - DownloadViewItem(QTreeWidget* parent, int type) : +/** + @class DownloadView + @brief A view showing all downloaded torrents + @author Lassi Väätämöinen +*/ +class DownloadView : public QTreeWidget +{ + Q_OBJECT + +public: + DownloadView(QWidget* parent); + + ~DownloadView(); + + void updateItem(TorrentState const& info, ParamsMap_t other_info); + QString prepareRemoveSelected(); + +private slots: + void on_itemClicked(QTreeWidgetItem * item, int column); +private: + + void addItem_(TorrentState const& info, ParamsMap_t other_info); + void updateItem_(DownloadViewItem *item + , TorrentState const& info, ParamsMap_t other_info); + void removeItem_(DownloadViewItem *item, TorrentState const& info); + + // Maps torrent to downloadview item. + // Key: SHA1 info hash of torrent. Data: View item corresponding to torrent. + DownloadItems_t items_; + + // Private functions. + static QString GetStatusString(TorrentStatus::Id status); + static QColor GetStatusColor(TorrentStatus::Id status); +}; + + +/** + @class DownloadViewItem + @brief Represents one item row of DownloadView +*/ +class DownloadViewItem : public QTreeWidgetItem +{ + +public: + DownloadViewItem(QTreeWidget* parent, int type) : QTreeWidgetItem(parent, type = QTreeWidgetItem::UserType) {}; - - DownloadViewItem(QString hash, const QStringList& strings, - int type = QTreeWidgetItem::UserType) : + + DownloadViewItem(QString hash, const QStringList& strings, + int type = QTreeWidgetItem::UserType) : QTreeWidgetItem (strings, type = Type), hash_(hash) - {} - - - /// @return An item comprising of string list, suitable for QTableView - /// header. - static DownloadViewItem *getHeaderItem() - { - DownloadViewItem *item - = new DownloadViewItem("", QStringList() - << "Name" - << "Size" << "Status" - << "Progress" << "DL speed" - << "UL speed" << "Seeds/Leechers" - << "Ratio" << "ETA"); - - return item; - } - - /// @todo QTorrentHandle as one hidden column - - QString getHash() const - { - return hash_; - } - - private: - QString hash_; - }; + {} + + + /// @return An item comprising of string list, suitable for QTableView + /// header. + static DownloadViewItem *getHeaderItem() + { + DownloadViewItem *item + = new DownloadViewItem("", QStringList() + << "Name" + << "Size" << "Status" + << "Progress" << "DL speed" + << "UL speed" << "Seeds/Leechers" + << "Ratio" << "ETA"); + + return item; + } + + /// @todo QTorrentHandle as one hidden column + + QString getHash() const + { + return hash_; + } + +private: + QString hash_; +}; } // namespace qtrapids diff --git a/src/client/MainWindow.cpp b/src/client/MainWindow.cpp index 14b5372..e5e591f 100644 --- a/src/client/MainWindow.cpp +++ b/src/client/MainWindow.cpp @@ -38,17 +38,17 @@ namespace qtrapids { - const QString ABOUT_TEXT - = QString(QObject::trUtf8("QtRapids, a simple BitTorrent client based on" - "\nQt and Libtorrent." - "\n\nURL: http://qtrapids.garage.maemo.org/" - "\n\nAuthor(s):\nLassi Väätämöinen, lassi.vaatamoinen@ixonos.com" - "\nDenis Zalevskiy, denis.zalewsky@ixonos.com" - "\n\nIxonos Plc, Finland\n")); +const QString ABOUT_TEXT += QString(QObject::trUtf8("QtRapids, a simple BitTorrent client based on" + "\nQt and Libtorrent." + "\n\nURL: http://qtrapids.garage.maemo.org/" + "\n\nAuthor(s):\nLassi Väätämöinen, lassi.vaatamoinen@ixonos.com" + "\nDenis Zalevskiy, denis.zalewsky@ixonos.com" + "\n\nIxonos Plc, Finland\n")); - // Consturctor - MainWindow::MainWindow() : +// Consturctor +MainWindow::MainWindow() : QMainWindow(), // Superclass tabWidget_(NULL), dlView_(NULL), @@ -59,176 +59,194 @@ namespace qtrapids server_(QtRapidsServer::staticInterfaceName() , "/qtrapids", QDBusConnection::sessionBus()) // torrentHandles_(), +{ + // MENUBAR + QMenuBar *menuBar = new QMenuBar(); + QMenu *tempMenu = NULL; + + tempMenu = menuBar->addMenu(tr("&File")); + QAction *openAction = tempMenu->addAction(tr("&Open")); + QAction *removeAction = tempMenu->addAction(tr("&Remove")); + removeAction->setEnabled(false); + QAction *quitAction = tempMenu->addAction(tr("&Quit")); + + tempMenu = menuBar->addMenu(tr("&Settings")); + QAction *preferencesAction = tempMenu->addAction(tr("&Preferences")); + + tempMenu = menuBar->addMenu(tr("&Help")); + QAction *aboutAction = tempMenu->addAction(tr("&About")); + QAction *aboutQtAction = tempMenu->addAction(tr("About &Qt")); + + setMenuBar(menuBar); + connect(openAction, SIGNAL(triggered()), this, SLOT(on_openAction_clicked())); + connect(removeAction, SIGNAL(triggered()), this, SLOT(on_removeAction_clicked())); + connect(this, SIGNAL(itemSelected(bool)), removeAction, SLOT(setEnabled(bool))); + connect(quitAction, SIGNAL(triggered()), this, SLOT(on_quitAction_clicked())); + connect(preferencesAction, SIGNAL(triggered()), this, SLOT(on_preferencesAction_clicked())); + connect(aboutAction, SIGNAL(triggered()), this, SLOT(on_aboutAction_clicked())); + connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(on_aboutQtAction_clicked())); + + // TABWIDGET (central widget) + tabWidget_ = new QTabWidget(); + + /// @todo Exception handling + dlView_ = new DownloadView(this); + seedView_ = new SeedView(this); + tabWidget_->addTab(dlView_, tr("Downloads")); + tabWidget_->addTab(seedView_, tr("Seeds")); + connect(dlView_, SIGNAL(itemSelectionChanged()), this, + SLOT(on_downloadItemSelectionChanged())); + + connect(seedView_, SIGNAL(itemSelectionChanged()), this, + SLOT(on_seedItemSelectionChanged())); + + // Tab widget as central widget. + setCentralWidget(tabWidget_); + + // TOOLBAR + QToolBar *toolBar = new QToolBar(); + toolBar->addAction(tr("Open")); + removeAction = toolBar->addAction(tr("Remove")); + removeAction->setEnabled(false); + addToolBar(Qt::TopToolBarArea, toolBar); + + connect(this, SIGNAL(itemSelected(bool)), removeAction, + SLOT(setEnabled(bool))); + connect(toolBar, SIGNAL(actionTriggered(QAction*)), this, + SLOT(handleToolBarAction(QAction*))); + + QVariant geometry(settings_.value("geometry")); + if (!geometry.isNull()) { - // MENUBAR - QMenuBar *menuBar = new QMenuBar(); - QMenu *tempMenu = NULL; - - tempMenu = menuBar->addMenu(tr("&File")); - QAction *openAction = tempMenu->addAction(tr("&Open")); - QAction *removeAction = tempMenu->addAction(tr("&Remove")); - removeAction->setEnabled(false); - QAction *quitAction = tempMenu->addAction(tr("&Quit")); - - tempMenu = menuBar->addMenu(tr("&Settings")); - QAction *preferencesAction = tempMenu->addAction(tr("&Preferences")); - - tempMenu = menuBar->addMenu(tr("&Help")); - QAction *aboutAction = tempMenu->addAction(tr("&About")); - QAction *aboutQtAction = tempMenu->addAction(tr("About &Qt")); - - setMenuBar(menuBar); - connect(openAction, SIGNAL(triggered()), this, SLOT(on_openAction_clicked())); - connect(removeAction, SIGNAL(triggered()), this, SLOT(on_removeAction_clicked())); - connect(this, SIGNAL(itemSelected(bool)), removeAction, SLOT(setEnabled(bool))); - connect(quitAction, SIGNAL(triggered()), this, SLOT(on_quitAction_clicked())); - connect(preferencesAction, SIGNAL(triggered()), this, SLOT(on_preferencesAction_clicked())); - connect(aboutAction, SIGNAL(triggered()), this, SLOT(on_aboutAction_clicked())); - connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(on_aboutQtAction_clicked())); - - // TABWIDGET (central widget) - tabWidget_ = new QTabWidget(); - - /// @todo Exception handling - dlView_ = new DownloadView(this); - seedView_ = new SeedView(this); - tabWidget_->addTab(dlView_, tr("Downloads")); - tabWidget_->addTab(seedView_, tr("Seeds")); - connect(dlView_, SIGNAL(itemSelectionChanged()), this, - SLOT(on_downloadItemSelectionChanged())); - - connect(seedView_, SIGNAL(itemSelectionChanged()), this, - SLOT(on_seedItemSelectionChanged())); - - // Tab widget as central widget. - setCentralWidget(tabWidget_); - - // TOOLBAR - QToolBar *toolBar = new QToolBar(); - toolBar->addAction(tr("Open")); - removeAction = toolBar->addAction(tr("Remove")); - removeAction->setEnabled(false); - addToolBar(Qt::TopToolBarArea, toolBar); - - connect(this, SIGNAL(itemSelected(bool)), removeAction, - SLOT(setEnabled(bool))); - connect(toolBar, SIGNAL(actionTriggered(QAction*)), this, - SLOT(handleToolBarAction(QAction*))); - - QVariant geometry(settings_.value("geometry")); - if (!geometry.isNull()) { - qDebug() << "restoring geometry"; - restoreGeometry(geometry.toByteArray()); - } + qDebug() << "restoring geometry"; + restoreGeometry(geometry.toByteArray()); } +} - MainWindow::~MainWindow() - { - settings_.setValue("geometry", saveGeometry()); - } +MainWindow::~MainWindow() +{ + settings_.setValue("geometry", saveGeometry()); +} - // =========================== SLOTS ================================= - void MainWindow::on_openAction_clicked() - { - QFileDialog *dialog = new QFileDialog( this, "Open torrent file", QString(), tr("Torrent files (*.torrent)")); - dialog->setFileMode(QFileDialog::ExistingFile); - connect(dialog, SIGNAL(fileSelected(const QString&)), this, SLOT(on_torrentFileSelected(const QString&))); - dialog->show(); +// =========================== SLOTS ================================= +void MainWindow::on_openAction_clicked() +{ + QFileDialog *dialog = new QFileDialog( this, "Open torrent file", QString(), tr("Torrent files (*.torrent)")); + dialog->setFileMode(QFileDialog::ExistingFile); + connect(dialog, SIGNAL(fileSelected(const QString&)), this, SLOT(on_torrentFileSelected(const QString&))); + dialog->show(); - } +} - void MainWindow::on_removeAction_clicked() +void MainWindow::on_removeAction_clicked() +{ + QString hash = dlView_->prepareRemoveSelected(); + try { - QString hash = dlView_->prepareRemoveSelected(); - try { - server_.removeTorrent(hash); - } catch (...) { - qDebug() << "Exception removing torrent"; - } + server_.removeTorrent(hash); } - - void MainWindow::on_quitAction_clicked() + catch (...) { - close(); + qDebug() << "Exception removing torrent"; } +} + +void MainWindow::on_quitAction_clicked() +{ + close(); +} - void MainWindow::on_preferencesAction_clicked() +void MainWindow::on_preferencesAction_clicked() +{ + if (!preferencesDialog_) { - if (!preferencesDialog_) { - preferencesDialog_ = new PreferencesDialog(this); - } - preferencesDialog_->show(); - preferencesDialog_->raise(); - preferencesDialog_->activateWindow(); + preferencesDialog_ = new PreferencesDialog(this); } + preferencesDialog_->show(); + preferencesDialog_->raise(); + preferencesDialog_->activateWindow(); +} - void MainWindow::on_aboutAction_clicked() +void MainWindow::on_aboutAction_clicked() +{ + QMessageBox::about(this, tr("About QtRapids"), ABOUT_TEXT); +} + + +void MainWindow::on_aboutQtAction_clicked() +{ + QMessageBox::aboutQt (this, tr("About Qt")); +} + + +void MainWindow::on_downloadItemSelectionChanged() +{ + qDebug() << "MainWindow::on_seedItemSelectionChanged():" << dlView_->currentItem(); + if (dlView_->currentItem() != NULL) { - QMessageBox::about(this, tr("About QtRapids"), ABOUT_TEXT); + emit(itemSelected(true)); } - - - void MainWindow::on_aboutQtAction_clicked() + else { - QMessageBox::aboutQt (this, tr("About Qt")); + emit(itemSelected(false)); } +} - - void MainWindow::on_downloadItemSelectionChanged() +void MainWindow::on_seedItemSelectionChanged() +{ + qDebug() << "MainWindow::on_seedItemSelectionChanged():" << seedView_->currentItem(); + if (seedView_->currentItem() != NULL) + { + emit(itemSelected(true)); + } + else { - qDebug() << "MainWindow::on_seedItemSelectionChanged():" << dlView_->currentItem(); - if (dlView_->currentItem() != NULL) { - emit(itemSelected(true)); - } else { - emit(itemSelected(false)); - } + emit(itemSelected(false)); } +} - void MainWindow::on_seedItemSelectionChanged() +void MainWindow::handleToolBarAction(QAction* action) +{ + if (action->text() == "Open") { - qDebug() << "MainWindow::on_seedItemSelectionChanged():" << seedView_->currentItem(); - if (seedView_->currentItem() != NULL) { - emit(itemSelected(true)); - } else { - emit(itemSelected(false)); - } + on_openAction_clicked(); } - - void MainWindow::handleToolBarAction(QAction* action) + else if (action->text() == "Remove") { - if (action->text() == "Open") { - on_openAction_clicked(); - } else if (action->text() == "Remove") { - on_removeAction_clicked(); - } + on_removeAction_clicked(); } +} - void MainWindow::on_torrentFileSelected(const QString& file) +void MainWindow::on_torrentFileSelected(const QString& file) +{ + qDebug() << " MainWindow::on_torrentFileSelected(): " << file; + // Torrent filename empty, do nothing. + if (file == "") { - qDebug() << " MainWindow::on_torrentFileSelected(): " << file; - // Torrent filename empty, do nothing. - if (file == "") { - return; - } - - // Otherwise add torrent - // For params, see: http://www.rasterbar.com/products/libtorrent/manual.html#add-torrent - // save_path is the only mandatory parameter, rest are optional. - //addParams.storage_mode = libtorrent::storage_mode_allocate; - try { - server_.addTorrent(file, settings_.value("download/directory").toString() - , ParamsMap_t()); - } catch (...) { - qDebug() << "Exception adding torrent"; - } + return; } - - void MainWindow::alert(qtrapids::TorrentState info, qtrapids::ParamsMap_t other_info) + // Otherwise add torrent + // For params, see: http://www.rasterbar.com/products/libtorrent/manual.html#add-torrent + // save_path is the only mandatory parameter, rest are optional. + //addParams.storage_mode = libtorrent::storage_mode_allocate; + try + { + server_.addTorrent(file, settings_.value("download/directory").toString() + , ParamsMap_t()); + } + catch (...) { - std::cerr << "got alert" << std::endl; - dlView_->updateItem(info, other_info); + qDebug() << "Exception adding torrent"; } +} + + +void MainWindow::alert(qtrapids::TorrentState info, qtrapids::ParamsMap_t other_info) +{ + std::cerr << "got alert" << std::endl; + dlView_->updateItem(info, other_info); +} } // namespace qtrapids diff --git a/src/client/MainWindow.h b/src/client/MainWindow.h index 43e2bc4..0cef789 100644 --- a/src/client/MainWindow.h +++ b/src/client/MainWindow.h @@ -32,64 +32,65 @@ class PreferencesDialog; namespace qtrapids { - class SeedView; - - /** - @author Lassi Väätämöinen - */ - class MainWindow : public QMainWindow { - Q_OBJECT; - - public: - - MainWindow(); - ~MainWindow(); - - void connectToServer() - { - qDBusRegisterMetaType(); - qDBusRegisterMetaType(); - - connect(&server_ - , SIGNAL(alert(qtrapids::TorrentState - , qtrapids::ParamsMap_t)) - , this - , SLOT(alert(qtrapids::TorrentState - , qtrapids::ParamsMap_t))); - server_.getState(); - } - - signals: - void itemSelected(bool enabled); - - public slots: - private slots: - void on_openAction_clicked(); - void on_removeAction_clicked(); - void on_quitAction_clicked(); - void on_preferencesAction_clicked(); - void on_aboutAction_clicked(); - void on_aboutQtAction_clicked(); - void on_downloadItemSelectionChanged(); - void on_seedItemSelectionChanged(); - void handleToolBarAction(QAction* action); - void on_torrentFileSelected(const QString& file); - void alert(qtrapids::TorrentState, qtrapids::ParamsMap_t); - - private: - QTabWidget *tabWidget_; - DownloadView *dlView_; - SeedView *seedView_; - PreferencesDialog *preferencesDialog_; - QSettings settings_; - - //std::vector< std::auto_ptr const > torrentHandles_; - - QtRapidsServer server_; - - - //bool IsNewTorrent(std::auto_ptr handlePtr); - }; +class SeedView; + +/** + @author Lassi Väätämöinen +*/ +class MainWindow : public QMainWindow +{ + Q_OBJECT; + +public: + + MainWindow(); + ~MainWindow(); + + void connectToServer() + { + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + + connect(&server_ + , SIGNAL(alert(qtrapids::TorrentState + , qtrapids::ParamsMap_t)) + , this + , SLOT(alert(qtrapids::TorrentState + , qtrapids::ParamsMap_t))); + server_.getState(); + } + +signals: + void itemSelected(bool enabled); + +public slots: +private slots: + void on_openAction_clicked(); + void on_removeAction_clicked(); + void on_quitAction_clicked(); + void on_preferencesAction_clicked(); + void on_aboutAction_clicked(); + void on_aboutQtAction_clicked(); + void on_downloadItemSelectionChanged(); + void on_seedItemSelectionChanged(); + void handleToolBarAction(QAction* action); + void on_torrentFileSelected(const QString& file); + void alert(qtrapids::TorrentState, qtrapids::ParamsMap_t); + +private: + QTabWidget *tabWidget_; + DownloadView *dlView_; + SeedView *seedView_; + PreferencesDialog *preferencesDialog_; + QSettings settings_; + + //std::vector< std::auto_ptr const > torrentHandles_; + + QtRapidsServer server_; + + + //bool IsNewTorrent(std::auto_ptr handlePtr); +}; } // namespace qtrapids diff --git a/src/client/PreferencesDialog.cpp b/src/client/PreferencesDialog.cpp index 9ee381b..3742c41 100644 --- a/src/client/PreferencesDialog.cpp +++ b/src/client/PreferencesDialog.cpp @@ -28,44 +28,44 @@ #include "PreferencesDialog.h" -PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags f) : - QDialog(parent, f), // Superclass - dirLineEdit_(NULL), - dialogButtons_(NULL), - settings_() +PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags f) : + QDialog(parent, f), // Superclass + dirLineEdit_(NULL), + dialogButtons_(NULL), + settings_() { - setWindowTitle("Preferences"); - - QBoxLayout *verticalBox = new QBoxLayout(QBoxLayout::TopToBottom); - QBoxLayout *horizontalBox1 = new QBoxLayout(QBoxLayout::LeftToRight); - setLayout(verticalBox); - verticalBox->addLayout(horizontalBox1); - - QLabel *dirLabel = new QLabel(tr("Download directory: ")); - dirLineEdit_ = new QLineEdit(this); - QPushButton *browseDirButton = new QPushButton(tr("Browse..")); - - horizontalBox1->addWidget(dirLabel); - horizontalBox1->addWidget(dirLineEdit_); - horizontalBox1->addWidget(browseDirButton); - - connect(browseDirButton, SIGNAL(clicked()), - this, SLOT(on_browseDirButtonClicked())); - - - dialogButtons_ = new QDialogButtonBox(this); - dialogButtons_->setStandardButtons(QDialogButtonBox::Ok - | QDialogButtonBox::Apply - | QDialogButtonBox::Cancel); - - verticalBox->addWidget(dialogButtons_); - - connect(dialogButtons_, SIGNAL(clicked(QAbstractButton*)), - this, SLOT(on_buttonClicked(QAbstractButton*))); - - // Set saved preference values to fields. - ReadSettings(); - + setWindowTitle("Preferences"); + + QBoxLayout *verticalBox = new QBoxLayout(QBoxLayout::TopToBottom); + QBoxLayout *horizontalBox1 = new QBoxLayout(QBoxLayout::LeftToRight); + setLayout(verticalBox); + verticalBox->addLayout(horizontalBox1); + + QLabel *dirLabel = new QLabel(tr("Download directory: ")); + dirLineEdit_ = new QLineEdit(this); + QPushButton *browseDirButton = new QPushButton(tr("Browse..")); + + horizontalBox1->addWidget(dirLabel); + horizontalBox1->addWidget(dirLineEdit_); + horizontalBox1->addWidget(browseDirButton); + + connect(browseDirButton, SIGNAL(clicked()), + this, SLOT(on_browseDirButtonClicked())); + + + dialogButtons_ = new QDialogButtonBox(this); + dialogButtons_->setStandardButtons(QDialogButtonBox::Ok + | QDialogButtonBox::Apply + | QDialogButtonBox::Cancel); + + verticalBox->addWidget(dialogButtons_); + + connect(dialogButtons_, SIGNAL(clicked(QAbstractButton*)), + this, SLOT(on_buttonClicked(QAbstractButton*))); + + // Set saved preference values to fields. + ReadSettings(); + } @@ -76,68 +76,68 @@ PreferencesDialog::~PreferencesDialog() // ======================== SLOTS ======================== void PreferencesDialog::on_browseDirButtonClicked() { - QFileDialog *dialog - = new QFileDialog(this, "Download directory", - QString(), tr("Torrent files (*.torrent)")); - - dialog->setFileMode(QFileDialog::Directory); - dialog->setOption(QFileDialog::ShowDirsOnly, true); - - connect(dialog, SIGNAL(fileSelected(const QString&)), - this, SLOT(on_downloadDirectorySelected(const QString&))); - - dialog->show(); + QFileDialog *dialog + = new QFileDialog(this, "Download directory", + QString(), tr("Torrent files (*.torrent)")); + + dialog->setFileMode(QFileDialog::Directory); + dialog->setOption(QFileDialog::ShowDirsOnly, true); + + connect(dialog, SIGNAL(fileSelected(const QString&)), + this, SLOT(on_downloadDirectorySelected(const QString&))); + + dialog->show(); } void PreferencesDialog::on_buttonClicked(QAbstractButton* button) { - switch (dialogButtons_->buttonRole ( button ) ) - { - case QDialogButtonBox::AcceptRole : - qDebug() << "PreferencesDialog: OK"; - WriteSettings(); - close(); - break; - case QDialogButtonBox::ApplyRole : - qDebug() << "PreferencesDialog: APPLY"; - WriteSettings(); - break; - case QDialogButtonBox::RejectRole : - qDebug() << "PreferencesDialog: CANCEL"; - close(); - break; - default: - return; - } + switch (dialogButtons_->buttonRole ( button ) ) + { + case QDialogButtonBox::AcceptRole : + qDebug() << "PreferencesDialog: OK"; + WriteSettings(); + close(); + break; + case QDialogButtonBox::ApplyRole : + qDebug() << "PreferencesDialog: APPLY"; + WriteSettings(); + break; + case QDialogButtonBox::RejectRole : + qDebug() << "PreferencesDialog: CANCEL"; + close(); + break; + default: + return; + } } void PreferencesDialog::on_downloadDirectorySelected(const QString& directory) { - qDebug() << "PreferencesDialog::on_downloadDirectorySelected(): " << directory; - // Torrent filename empty, do nothing. - if (directory == "") - return; - - dirLineEdit_->insert(directory); - - /// @todo check that user has privileges to write to this directory. + qDebug() << "PreferencesDialog::on_downloadDirectorySelected(): " << directory; + // Torrent filename empty, do nothing. + if (directory == "") + return; + + dirLineEdit_->insert(directory); + + /// @todo check that user has privileges to write to this directory. } // ========================= Private functions ========================== void PreferencesDialog::WriteSettings() { - settings_.setValue("download/directory", dirLineEdit_->text()); - - // NOTE: We might need to call QSettigns::sync() here to instantly write settings. - // settings are written also by QSettings() destructor and by event loop at regular interval. + settings_.setValue("download/directory", dirLineEdit_->text()); + + // NOTE: We might need to call QSettigns::sync() here to instantly write settings. + // settings are written also by QSettings() destructor and by event loop at regular interval. } void PreferencesDialog::ReadSettings() { - dirLineEdit_->insert(settings_.value("download/directory").toString()); - - // NOTE: We might need to call QSettigns::sync() here to instantly write settings. - // settings are written also by QSettings() destructor and by event loop at regular interval. + dirLineEdit_->insert(settings_.value("download/directory").toString()); + + // NOTE: We might need to call QSettigns::sync() here to instantly write settings. + // settings are written also by QSettings() destructor and by event loop at regular interval. } diff --git a/src/client/PreferencesDialog.h b/src/client/PreferencesDialog.h index c368ea0..e6f685a 100644 --- a/src/client/PreferencesDialog.h +++ b/src/client/PreferencesDialog.h @@ -33,27 +33,27 @@ class QDialogButtonBox; */ class PreferencesDialog : public QDialog { - - Q_OBJECT - - public: + + Q_OBJECT + +public: PreferencesDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); ~PreferencesDialog(); - private slots: - void on_browseDirButtonClicked(); - void on_buttonClicked(QAbstractButton* button); - void on_downloadDirectorySelected(const QString& directory); - - private: - QLineEdit *dirLineEdit_; - QDialogButtonBox *dialogButtons_; - QSettings settings_; - - // Private functions: - void WriteSettings(); - void ReadSettings(); +private slots: + void on_browseDirButtonClicked(); + void on_buttonClicked(QAbstractButton* button); + void on_downloadDirectorySelected(const QString& directory); + +private: + QLineEdit *dirLineEdit_; + QDialogButtonBox *dialogButtons_; + QSettings settings_; + + // Private functions: + void WriteSettings(); + void ReadSettings(); }; #endif diff --git a/src/client/SeedView.cpp b/src/client/SeedView.cpp index 3d4d320..17c986b 100644 --- a/src/client/SeedView.cpp +++ b/src/client/SeedView.cpp @@ -24,24 +24,24 @@ namespace qtrapids { - SeedView::SeedView(QWidget* parent): +SeedView::SeedView(QWidget* parent): QTreeWidget(parent) - { - setRootIsDecorated(false); // Hide branch lines, making one-level treeview (similar to list) - setHeaderItem(SeedViewItem::getHeaderItem()); - - connect(this, SIGNAL(itemPressed(QTreeWidgetItem*, int)), - this, SLOT(on_itemPressed(QTreeWidgetItem*, int))); - } - - - SeedView::~SeedView() - { - } - - void SeedView::on_itemPressed(QTreeWidgetItem * item, int column) - { - qDebug() << "SeedView::on_itemPressed() " << item << "," << column; - } +{ + setRootIsDecorated(false); // Hide branch lines, making one-level treeview (similar to list) + setHeaderItem(SeedViewItem::getHeaderItem()); + + connect(this, SIGNAL(itemPressed(QTreeWidgetItem*, int)), + this, SLOT(on_itemPressed(QTreeWidgetItem*, int))); +} + + +SeedView::~SeedView() +{ +} + +void SeedView::on_itemPressed(QTreeWidgetItem * item, int column) +{ + qDebug() << "SeedView::on_itemPressed() " << item << "," << column; +} } // namespace qtrapids diff --git a/src/client/SeedView.h b/src/client/SeedView.h index 2eb8e15..7961138 100644 --- a/src/client/SeedView.h +++ b/src/client/SeedView.h @@ -25,67 +25,68 @@ namespace qtrapids { - class TorrentHandle; - class SeedViewItem; +class TorrentHandle; +class SeedViewItem; - /** - @author Lassi Väätämöinen - */ - class SeedView : public QTreeWidget +/** + @author Lassi Väätämöinen +*/ +class SeedView : public QTreeWidget +{ + Q_OBJECT +public: + SeedView(QWidget* parent); + + ~SeedView(); + +private slots: + void on_itemPressed(QTreeWidgetItem *item, int column); + +private: + + // Name + // Size + // Status + // UP speed + // Seeds/Leechers + // Connected peers + // total uploaded + // ratio +}; + +/** + @class DownloadViewItem + @brief Represents one item row of DownloadView +*/ +class SeedViewItem : public QTreeWidgetItem +{ + +public: + + SeedViewItem(QTreeWidget* parent, int type) : + QTreeWidgetItem(parent, type = QTreeWidgetItem::UserType) {}; + + SeedViewItem(const QStringList& strings, int type = QTreeWidgetItem::UserType ) : + QTreeWidgetItem (strings, type = Type) {}; + + + /// @return An item comprising of string list, suitable for QTableView + /// header. + static SeedViewItem *getHeaderItem() { - Q_OBJECT - public: - SeedView(QWidget* parent); - - ~SeedView(); - - private slots: - void on_itemPressed(QTreeWidgetItem *item, int column); - - private: - - // Name - // Size - // Status - // UP speed - // Seeds/Leechers - // Connected peers - // total uploaded - // ratio - }; - - /** - @class DownloadViewItem - @brief Represents one item row of DownloadView - */ - class SeedViewItem : public QTreeWidgetItem { - - public: - - SeedViewItem(QTreeWidget* parent, int type) : - QTreeWidgetItem(parent, type = QTreeWidgetItem::UserType) {}; - - SeedViewItem(const QStringList& strings, int type = QTreeWidgetItem::UserType ) : - QTreeWidgetItem (strings, type = Type) {}; - - - /// @return An item comprising of string list, suitable for QTableView - /// header. - static SeedViewItem *getHeaderItem() - { - SeedViewItem *item - = new SeedViewItem(QStringList() - << "Name" - << "Size" << "Status" - << "Progress" << "UL speed" << "Seeds/Leechers" - << "Conn. peers" - << "Ratio"); - - return item; - } - - /// @todo TorrentHandle as one hidden column - }; + SeedViewItem *item + = new SeedViewItem(QStringList() + << "Name" + << "Size" << "Status" + << "Progress" << "UL speed" << "Seeds/Leechers" + << "Conn. peers" + << "Ratio"); + + return item; + } + + /// @todo TorrentHandle as one hidden column +}; } // namespace qtrapids diff --git a/src/client/main.cpp b/src/client/main.cpp index 81b7b15..6968465 100644 --- a/src/client/main.cpp +++ b/src/client/main.cpp @@ -29,46 +29,46 @@ using qtrapids::MainWindow; int main(int argc, char *argv[]) { - - QCoreApplication::setOrganizationName("Ixonos"); - QCoreApplication::setOrganizationDomain("ixonos.com"); - QCoreApplication::setApplicationName("QtRapids"); - - // Q_INIT_RESOURCE(application); - QApplication app(argc, argv); - MainWindow mainWindow; + + QCoreApplication::setOrganizationName("Ixonos"); + QCoreApplication::setOrganizationDomain("ixonos.com"); + QCoreApplication::setApplicationName("QtRapids"); + + // Q_INIT_RESOURCE(application); + QApplication app(argc, argv); + MainWindow mainWindow; mainWindow.connectToServer(); // mainWindow->setGeometry(QApplication::desktop()->screenGeometry()); - mainWindow.show(); + mainWindow.show(); - /* - DownloadView* dlw = new DownloadView(NULL); + /* + DownloadView* dlw = new DownloadView(NULL); //qtrapids * mw = new qtrapids(); - dlw->show(); - DownloadViewItem* dlwItem = new DownloadViewItem(QStringList() << "Name" - << "Size" << "Status" - << "Progress" << "DL speed" - << "UL speed" << "Seeds/Leechers" - << "ratio"); - DownloadViewItem* dlwItem2 = new DownloadViewItem(QStringList() << "Name" - << "1000" << "Downloading" - << "23%" << "11" - << "0.1" << "0/2" - << "1.10"); - //dlwItem->insertChild(0, new DownloadViewItem(QStringList() << "Name")); - dlw->insertTopLevelItem(0,dlwItem); - dlw->insertTopLevelItem(1,dlwItem2); - - for (unsigned i = 0; i < 10; ++i) - { - DownloadViewItem *editItem = dynamic_cast - (dlw->itemAt(QPoint(0,0))); - editItem->setData ( 8, Qt::DisplayRole, QVariant("EDITED" + QString::number(i, 'g', 2))); - QTest::qSleep(2000); - } - */ - - - return app.exec(); + dlw->show(); + DownloadViewItem* dlwItem = new DownloadViewItem(QStringList() << "Name" + << "Size" << "Status" + << "Progress" << "DL speed" + << "UL speed" << "Seeds/Leechers" + << "ratio"); + DownloadViewItem* dlwItem2 = new DownloadViewItem(QStringList() << "Name" + << "1000" << "Downloading" + << "23%" << "11" + << "0.1" << "0/2" + << "1.10"); + //dlwItem->insertChild(0, new DownloadViewItem(QStringList() << "Name")); + dlw->insertTopLevelItem(0,dlwItem); + dlw->insertTopLevelItem(1,dlwItem2); + + for (unsigned i = 0; i < 10; ++i) + { + DownloadViewItem *editItem = dynamic_cast + (dlw->itemAt(QPoint(0,0))); + editItem->setData ( 8, Qt::DisplayRole, QVariant("EDITED" + QString::number(i, 'g', 2))); + QTest::qSleep(2000); + } + */ + + + return app.exec(); } diff --git a/src/engine/AlertWaiterThread.cpp b/src/engine/AlertWaiterThread.cpp index 4f18636..0274064 100644 --- a/src/engine/AlertWaiterThread.cpp +++ b/src/engine/AlertWaiterThread.cpp @@ -25,13 +25,13 @@ // Constants: // Timeout for waiting alerts -const libtorrent::time_duration ALERT_WAIT_TIMEOUT - = libtorrent::time_duration(libtorrent::seconds(15)); +const libtorrent::time_duration ALERT_WAIT_TIMEOUT += libtorrent::time_duration(libtorrent::seconds(15)); -AlertWaiterThread::AlertWaiterThread(TorrentSession *const session, QObject* parent) : - QThread(parent), - btSession_(session) +AlertWaiterThread::AlertWaiterThread(TorrentSession *const session, QObject* parent) : + QThread(parent), + btSession_(session) { } @@ -43,29 +43,32 @@ AlertWaiterThread::~AlertWaiterThread() void AlertWaiterThread::allAlerts(bool enable) { - // If all enabled, set all alert cateogries: - if (enable) { - btSession_->set_alert_mask(libtorrent::alert::all_categories); - } else { - // Otherwise set to default, which is only error notifications. - btSession_->set_alert_mask(libtorrent::alert::error_notification); - } + // If all enabled, set all alert cateogries: + if (enable) + { + btSession_->set_alert_mask(libtorrent::alert::all_categories); + } + else + { + // Otherwise set to default, which is only error notifications. + btSession_->set_alert_mask(libtorrent::alert::error_notification); + } } void AlertWaiterThread::run() { - Alert const *alertTemp = NULL; - while (true) - { + Alert const *alertTemp = NULL; + while (true) + { #ifdef QTRAPIDS_DEBUG - qDebug() << "AlertWaiter running"; + qDebug() << "AlertWaiter running"; #endif - // wait_for_alert() call blocks. Returns libtorrent alert. - // Returns NULL, if no alerts in timeout period. - alertTemp = btSession_->wait_for_alert(ALERT_WAIT_TIMEOUT); - emit alert(alertTemp); - // 2000 us = 2ms. Gives main thread time to handle alert signal. - usleep(2000); - } + // wait_for_alert() call blocks. Returns libtorrent alert. + // Returns NULL, if no alerts in timeout period. + alertTemp = btSession_->wait_for_alert(ALERT_WAIT_TIMEOUT); + emit alert(alertTemp); + // 2000 us = 2ms. Gives main thread time to handle alert signal. + usleep(2000); + } } diff --git a/src/engine/AlertWaiterThread.h b/src/engine/AlertWaiterThread.h index 7d14ef9..4ee3b87 100644 --- a/src/engine/AlertWaiterThread.h +++ b/src/engine/AlertWaiterThread.h @@ -29,25 +29,25 @@ */ class AlertWaiterThread : public QThread { - Q_OBJECT - - public: - AlertWaiterThread(TorrentSession *const session, QObject *parent = 0); + Q_OBJECT + +public: + AlertWaiterThread(TorrentSession *const session, QObject *parent = 0); virtual ~AlertWaiterThread(); - void allAlerts(bool enable = true); - - virtual void run(); // Overridden from QThread - - signals: - /// @TODO alert() uses direct connection, so th connected slot is executed by AlertWaiterThread - /// Hence, QMutex is needed in receiver slot/thread for thread-safety. - /// @NOTE Alternatively, we could use an event loop in the thread and use queued signal (is it heavier?) - void alert(Alert const *alert); - - private: - TorrentSession *const btSession_; + void allAlerts(bool enable = true); + + virtual void run(); // Overridden from QThread + +signals: + /// @TODO alert() uses direct connection, so th connected slot is executed by AlertWaiterThread + /// Hence, QMutex is needed in receiver slot/thread for thread-safety. + /// @NOTE Alternatively, we could use an event loop in the thread and use queued signal (is it heavier?) + void alert(Alert const *alert); + +private: + TorrentSession *const btSession_; }; diff --git a/src/engine/QBittorrentSession.cpp b/src/engine/QBittorrentSession.cpp index 2ab40ed..e474f7d 100644 --- a/src/engine/QBittorrentSession.cpp +++ b/src/engine/QBittorrentSession.cpp @@ -23,17 +23,18 @@ #include "AlertWaiterThread.h" #include "QBittorrentSession.h" -namespace qtrapids { - +namespace qtrapids +{ + QBittorrentSession::QBittorrentSession(QObject *parent): - QObject(parent), - btSession_(), - alertWaiter_(NULL) + QObject(parent), + btSession_(), + alertWaiter_(NULL) { - alertWaiter_ = new AlertWaiterThread(&btSession_, this); - alertWaiter_->allAlerts(); - connect(alertWaiter_, SIGNAL(alert(Alert const*)), this, SLOT(on_alert(Alert const*))); - alertWaiter_->start(); + alertWaiter_ = new AlertWaiterThread(&btSession_, this); + alertWaiter_->allAlerts(); + connect(alertWaiter_, SIGNAL(alert(Alert const*)), this, SLOT(on_alert(Alert const*))); + alertWaiter_->start(); } @@ -45,33 +46,33 @@ QBittorrentSession::~QBittorrentSession() qtrapids::QTorrentHandle QBittorrentSession::addTorrent(AddTorrentParams const& params) { - // Delegate to Libtorrent and return QTorrentHandle. - //std::auto_ptr handlePtr(new QTorrentHandle(btSession_.add_torrent(params))); - qtrapids::QTorrentHandle handle = qtrapids::QTorrentHandle(btSession_.add_torrent(params)); - return handle; + // Delegate to Libtorrent and return QTorrentHandle. + //std::auto_ptr handlePtr(new QTorrentHandle(btSession_.add_torrent(params))); + qtrapids::QTorrentHandle handle = qtrapids::QTorrentHandle(btSession_.add_torrent(params)); + return handle; } -void QBittorrentSession::removeTorrent(qtrapids::QTorrentHandle const& handle) +void QBittorrentSession::removeTorrent(qtrapids::QTorrentHandle const& handle) { - btSession_.remove_torrent(handle.getHandle()); + btSession_.remove_torrent(handle.getHandle()); } // ========================== SLOTS ============================== /// @TODO This function is called when AlertWaiterThread emits alert() /// If connection is direct, as it is now, we need to use QMutex here (if necessary?) -void QBittorrentSession::on_alert(Alert const *al) - //NOTE: al parameter not necessarily needed here, as we pop_alert() now! +void QBittorrentSession::on_alert(Alert const *al) +//NOTE: al parameter not necessarily needed here, as we pop_alert() now! { - + #ifdef QTRAPIDS_DEBUG - if (al) - qDebug() << "on_alert():" << QString::fromStdString(al->message()); + if (al) + qDebug() << "on_alert():" << QString::fromStdString(al->message()); #endif - std::auto_ptr alertPtr = btSession_.pop_alert(); - emit alert(alertPtr); + std::auto_ptr alertPtr = btSession_.pop_alert(); + emit alert(alertPtr); } } //namespace qtrapids diff --git a/src/engine/QBittorrentSession.h b/src/engine/QBittorrentSession.h index 7d2ea43..10f49e9 100644 --- a/src/engine/QBittorrentSession.h +++ b/src/engine/QBittorrentSession.h @@ -40,33 +40,35 @@ typedef libtorrent::torrent_alert TorrentAlert; typedef libtorrent::sha1_hash Sha1Hash; -namespace qtrapids { +namespace qtrapids +{ /** @author Lassi Väätämöinen */ -class QBittorrentSession : public QObject { - Q_OBJECT +class QBittorrentSession : public QObject +{ + Q_OBJECT // class BitTorrentSession; - - public: - QBittorrentSession(QObject *parent = 0); + +public: + QBittorrentSession(QObject *parent = 0); ~QBittorrentSession(); - - /// @brief Add torrent to session. - qtrapids::QTorrentHandle addTorrent(AddTorrentParams const& params); - void removeTorrent(qtrapids::QTorrentHandle const& handle); - - signals: - void alert(std::auto_ptr al); - - private slots: - void on_alert(Alert const *al); - - private: - TorrentSession btSession_; - AlertWaiterThread *alertWaiter_; - + + /// @brief Add torrent to session. + qtrapids::QTorrentHandle addTorrent(AddTorrentParams const& params); + void removeTorrent(qtrapids::QTorrentHandle const& handle); + +signals: + void alert(std::auto_ptr al); + +private slots: + void on_alert(Alert const *al); + +private: + TorrentSession btSession_; + AlertWaiterThread *alertWaiter_; + }; } //namespace qtrapids diff --git a/src/engine/QTorrentHandle.cpp b/src/engine/QTorrentHandle.cpp index b1f426a..093b1a3 100644 --- a/src/engine/QTorrentHandle.cpp +++ b/src/engine/QTorrentHandle.cpp @@ -21,11 +21,12 @@ #include "QTorrentHandle.h" -namespace qtrapids { +namespace qtrapids +{ + - -QTorrentHandle::QTorrentHandle(libtorrent::torrent_handle handle) : - torrentHandle_(handle) +QTorrentHandle::QTorrentHandle(libtorrent::torrent_handle handle) : + torrentHandle_(handle) { } @@ -37,126 +38,129 @@ QTorrentHandle::~QTorrentHandle() TorrentStatus QTorrentHandle::status() const { - return torrentHandle_.status(); + return torrentHandle_.status(); } TorrentInfo const& QTorrentHandle::getTorrentInfo() const { - return torrentHandle_.get_torrent_info(); + return torrentHandle_.get_torrent_info(); } bool QTorrentHandle::isValid() const { - return torrentHandle_.is_valid(); + return torrentHandle_.is_valid(); } QString QTorrentHandle::name() const { - return QString::fromStdString(torrentHandle_.name()); + return QString::fromStdString(torrentHandle_.name()); } size_t QTorrentHandle::getTotalSize() const { - TorrentInfo info = getTorrentInfo(); - return static_cast (info.total_size()); + TorrentInfo info = getTorrentInfo(); + return static_cast (info.total_size()); } QTorrentHandle::State QTorrentHandle::state() const { - TorrentStatus statusTmp = status(); - - switch (statusTmp.state) { - case TorrentStatus::queued_for_checking : - return QTorrentHandle::QUEUED_FOR_CHECKING; - case TorrentStatus::checking_files : - return QTorrentHandle::CHECKING_FILES; - case TorrentStatus::downloading_metadata : - return QTorrentHandle::DOWNLOADING_METADATA; - case TorrentStatus::downloading : - return QTorrentHandle::DOWNLOADING; - case TorrentStatus::finished : - return QTorrentHandle::FINISHED; - case TorrentStatus::seeding : - return QTorrentHandle::SEEDING; - case TorrentStatus::allocating : - return QTorrentHandle::ALLOCATING; - default: - return QTorrentHandle::UNSPECIFIED; - } - + TorrentStatus statusTmp = status(); + + switch (statusTmp.state) + { + case TorrentStatus::queued_for_checking : + return QTorrentHandle::QUEUED_FOR_CHECKING; + case TorrentStatus::checking_files : + return QTorrentHandle::CHECKING_FILES; + case TorrentStatus::downloading_metadata : + return QTorrentHandle::DOWNLOADING_METADATA; + case TorrentStatus::downloading : + return QTorrentHandle::DOWNLOADING; + case TorrentStatus::finished : + return QTorrentHandle::FINISHED; + case TorrentStatus::seeding : + return QTorrentHandle::SEEDING; + case TorrentStatus::allocating : + return QTorrentHandle::ALLOCATING; + default: + return QTorrentHandle::UNSPECIFIED; + } + } float QTorrentHandle::progress() const { - TorrentStatus statusTmp = status(); - return statusTmp.progress; + TorrentStatus statusTmp = status(); + return statusTmp.progress; } float QTorrentHandle::uploadRate() const { - TorrentStatus statusTmp = status(); - return statusTmp.upload_rate; + TorrentStatus statusTmp = status(); + return statusTmp.upload_rate; } float QTorrentHandle::downloadRate() const { - TorrentStatus statusTmp = status(); - return statusTmp.download_rate; + TorrentStatus statusTmp = status(); + return statusTmp.download_rate; } qint32 QTorrentHandle::numSeeds() const { - TorrentStatus statusTmp = status(); - return statusTmp.list_seeds; + TorrentStatus statusTmp = status(); + return statusTmp.list_seeds; } qint32 QTorrentHandle::numLeeches() const { - TorrentStatus statusTmp = status(); - return (statusTmp.list_peers - statusTmp.list_seeds); + TorrentStatus statusTmp = status(); + return (statusTmp.list_peers - statusTmp.list_seeds); } qint32 QTorrentHandle::ratio() const { - TorrentStatus statusTmp = status(); - size_t ratio; - if (statusTmp.total_payload_download == 0) { - ratio = 0; - } else { - ratio = static_cast (statusTmp.total_payload_upload / statusTmp.total_payload_download); - } - - return ratio; + TorrentStatus statusTmp = status(); + size_t ratio; + if (statusTmp.total_payload_download == 0) + { + ratio = 0; + } + else + { + ratio = static_cast (statusTmp.total_payload_upload / statusTmp.total_payload_download); + } + + return ratio; } TorrentHandle QTorrentHandle::getHandle() const { - return torrentHandle_; + return torrentHandle_; } bool QTorrentHandle::operator==(QTorrentHandle const& h) const { - return torrentHandle_ == h.torrentHandle_; + return torrentHandle_ == h.torrentHandle_; } bool QTorrentHandle::operator<(QTorrentHandle const& h) const { - return torrentHandle_ < h.torrentHandle_; + return torrentHandle_ < h.torrentHandle_; } } // namespace qtrapids - \ No newline at end of file diff --git a/src/engine/QTorrentHandle.h b/src/engine/QTorrentHandle.h index 855f0ca..e68a940 100644 --- a/src/engine/QTorrentHandle.h +++ b/src/engine/QTorrentHandle.h @@ -34,54 +34,56 @@ typedef libtorrent::torrent_handle TorrentHandle; @author Lassi Väätämöinen */ -namespace qtrapids { - - class QTorrentHandle - { - public: - - enum State { - QUEUED_FOR_CHECKING = TorrentStatus::queued_for_checking, - CHECKING_FILES, - DOWNLOADING_METADATA, - DOWNLOADING, - FINISHED, - SEEDING, - ALLOCATING, - UNSPECIFIED - }; - - QTorrentHandle(libtorrent::torrent_handle handle); - ~QTorrentHandle(); - - - - TorrentInfo const& getTorrentInfo() const; - - bool isValid() const; - - QString name() const; - size_t getTotalSize() const; - QTorrentHandle::State state() const; - float progress() const; - float uploadRate() const; - float downloadRate() const; - qint32 numSeeds() const; - qint32 numLeeches() const; - qint32 ratio() const; - - TorrentHandle getHandle() const; - - bool operator==(QTorrentHandle const& h) const; - bool operator<(QTorrentHandle const& h) const; - - private: - QTorrentHandle(); // Prevent default construct. - TorrentHandle torrentHandle_; - - TorrentStatus status() const; - - }; +namespace qtrapids +{ + +class QTorrentHandle +{ +public: + + enum State + { + QUEUED_FOR_CHECKING = TorrentStatus::queued_for_checking, + CHECKING_FILES, + DOWNLOADING_METADATA, + DOWNLOADING, + FINISHED, + SEEDING, + ALLOCATING, + UNSPECIFIED + }; + + QTorrentHandle(libtorrent::torrent_handle handle); + ~QTorrentHandle(); + + + + TorrentInfo const& getTorrentInfo() const; + + bool isValid() const; + + QString name() const; + size_t getTotalSize() const; + QTorrentHandle::State state() const; + float progress() const; + float uploadRate() const; + float downloadRate() const; + qint32 numSeeds() const; + qint32 numLeeches() const; + qint32 ratio() const; + + TorrentHandle getHandle() const; + + bool operator==(QTorrentHandle const& h) const; + bool operator<(QTorrentHandle const& h) const; + +private: + QTorrentHandle(); // Prevent default construct. + TorrentHandle torrentHandle_; + + TorrentStatus status() const; + +}; } // namespace qtrapids #endif diff --git a/src/gui/DownloadView.cpp b/src/gui/DownloadView.cpp index d6c9183..da9642b 100644 --- a/src/gui/DownloadView.cpp +++ b/src/gui/DownloadView.cpp @@ -25,19 +25,19 @@ DownloadView::DownloadView(QWidget* parent) : - QTreeWidget(parent), - items_(), - timer_(NULL) + QTreeWidget(parent), + items_(), + timer_(NULL) { - setRootIsDecorated(false); // Hide branch lines, making one-level treeview (similar to list) - setHeaderItem(DownloadViewItem::getHeaderItem()); + setRootIsDecorated(false); // Hide branch lines, making one-level treeview (similar to list) + setHeaderItem(DownloadViewItem::getHeaderItem()); - connect(this, SIGNAL(itemPressed(QTreeWidgetItem*, int)), - this, SLOT(on_itemClicked(QTreeWidgetItem*, int))); + connect(this, SIGNAL(itemPressed(QTreeWidgetItem*, int)), + this, SLOT(on_itemClicked(QTreeWidgetItem*, int))); - timer_ = new QTimer(this); - connect(timer_, SIGNAL(timeout()), this, SLOT(on_timeout())); - timer_->start(5000); + timer_ = new QTimer(this); + connect(timer_, SIGNAL(timeout()), this, SLOT(on_timeout())); + timer_->start(5000); } @@ -50,66 +50,68 @@ DownloadView::~DownloadView() void DownloadView::newItem(qtrapids::QTorrentHandle handle) { #ifdef QTRAPIDS_DEBUG - qDebug() << "DownloadView::newItem() " << items_.count(handle); + qDebug() << "DownloadView::newItem() " << items_.count(handle); #endif - DownloadViewItem *item = new DownloadViewItem(QStringList() - << handle.name() - << QString::number(handle.getTotalSize()) - << GetStatusString(handle.state()) - << QString::number(100*handle.progress() + '%') - << QString::number(handle.downloadRate(), 'f', 2) - << QString::number(handle.uploadRate(), 'f', 2) - << QString::number(handle.numSeeds()) + "/" - + QString::number(handle.numLeeches()) - << QString::number(handle.ratio()) - << "ETA" ); - - // Set text color for status: - QBrush brushTmp(GetStatusColor(handle.state())); - item->setForeground(2, brushTmp); - - addTopLevelItem(item); - items_[handle] = item; + DownloadViewItem *item = new DownloadViewItem(QStringList() + << handle.name() + << QString::number(handle.getTotalSize()) + << GetStatusString(handle.state()) + << QString::number(100*handle.progress() + '%') + << QString::number(handle.downloadRate(), 'f', 2) + << QString::number(handle.uploadRate(), 'f', 2) + << QString::number(handle.numSeeds()) + "/" + + QString::number(handle.numLeeches()) + << QString::number(handle.ratio()) + << "ETA" ); + + // Set text color for status: + QBrush brushTmp(GetStatusColor(handle.state())); + item->setForeground(2, brushTmp); + + addTopLevelItem(item); + items_[handle] = item; } void DownloadView::updateItem(qtrapids::QTorrentHandle handle) { - //qDebug() << "DownloadView::updateItem() " << items_.count(handle); - - static float lastProg = 0; - - // If there are items currently downloading, update: - if (items_.count(handle) > 0) { - - DownloadViewItem *item = items_[handle]; - - // Only the changing fields are being updated: - item->setData(2, Qt::DisplayRole, - QVariant(GetStatusString(handle.state()))); - item->setData(4, Qt::DisplayRole, - QVariant(QString::number(handle.downloadRate(), 'f', 2))); - item->setData(5, Qt::DisplayRole, - QVariant(QString::number(handle.uploadRate(), 'f', 2))); - item->setData(6, Qt::DisplayRole, - QString::number(handle.numSeeds()) + "/" - + QString::number(handle.numLeeches())); - - // Set progress if increment is 1 percent. - float prog = handle.progress(); - if ((prog-lastProg) >= 0.01 || prog >= 1.0) { - item->setData(3, Qt::DisplayRole, - QVariant(QString::number(100*prog) + '%')); - lastProg = prog; - } - - /// @TODO: ETA-counter adjusting,if ETA is to be implemented - - // Adjust color - QBrush brushTmp(GetStatusColor(handle.state())); - item->setForeground(2, brushTmp); - } + //qDebug() << "DownloadView::updateItem() " << items_.count(handle); + + static float lastProg = 0; + + // If there are items currently downloading, update: + if (items_.count(handle) > 0) + { + + DownloadViewItem *item = items_[handle]; + + // Only the changing fields are being updated: + item->setData(2, Qt::DisplayRole, + QVariant(GetStatusString(handle.state()))); + item->setData(4, Qt::DisplayRole, + QVariant(QString::number(handle.downloadRate(), 'f', 2))); + item->setData(5, Qt::DisplayRole, + QVariant(QString::number(handle.uploadRate(), 'f', 2))); + item->setData(6, Qt::DisplayRole, + QString::number(handle.numSeeds()) + "/" + + QString::number(handle.numLeeches())); + + // Set progress if increment is 1 percent. + float prog = handle.progress(); + if ((prog-lastProg) >= 0.01 || prog >= 1.0) + { + item->setData(3, Qt::DisplayRole, + QVariant(QString::number(100*prog) + '%')); + lastProg = prog; + } + + /// @TODO: ETA-counter adjusting,if ETA is to be implemented + + // Adjust color + QBrush brushTmp(GetStatusColor(handle.state())); + item->setForeground(2, brushTmp); + } } @@ -117,37 +119,40 @@ void DownloadView::updateItem(qtrapids::QTorrentHandle handle) qtrapids::QTorrentHandle DownloadView::removeSelected() { #ifdef QTRAPIDS_DEBUG - qDebug() << "DownloadView::removeSelected() " << topLevelItemCount() ; + qDebug() << "DownloadView::removeSelected() " << topLevelItemCount() ; #endif - DownloadViewItem *item = dynamic_cast (currentItem()); - - std::map::iterator listIter - = items_.begin(); - std::map::iterator listEnd - = items_.end(); - - while (listIter != listEnd) { - if (listIter->second == item) { - break; - } - ++listIter; - } - - qtrapids::QTorrentHandle handle = listIter->first; - items_.erase(listIter); - - - int index = indexOfTopLevelItem(currentItem()); - if (index >= 0) { - takeTopLevelItem(index); - } + DownloadViewItem *item = dynamic_cast (currentItem()); + + std::map::iterator listIter + = items_.begin(); + std::map::iterator listEnd + = items_.end(); + + while (listIter != listEnd) + { + if (listIter->second == item) + { + break; + } + ++listIter; + } + + qtrapids::QTorrentHandle handle = listIter->first; + items_.erase(listIter); + + + int index = indexOfTopLevelItem(currentItem()); + if (index >= 0) + { + takeTopLevelItem(index); + } #ifdef QTRAPIDS_DEBUG - qDebug() << "DownloadView::removeSelected() " << topLevelItemCount() ; + qDebug() << "DownloadView::removeSelected() " << topLevelItemCount() ; #endif - return handle; + return handle; } @@ -158,85 +163,89 @@ void DownloadView::removeItem(qtrapids::QTorrentHandle handle) void DownloadView::setRefreshInterval(int msec) { - timer_->setInterval(msec); + timer_->setInterval(msec); } void DownloadView::on_itemClicked(QTreeWidgetItem * item, int column) { - /* - qDebug() << "DownloadView::on_itemClicked(()" << item << "," << column; - qDebug() << "current item" << currentItem(); - - if (item == currentItem() && item->isSelected()) { - item->setSelected(false); - } - */ + /* + qDebug() << "DownloadView::on_itemClicked(()" << item << "," << column; + qDebug() << "current item" << currentItem(); + + if (item == currentItem() && item->isSelected()) { + item->setSelected(false); + } + */ } -void DownloadView::on_timeout() { +void DownloadView::on_timeout() +{ #ifdef QTRAPIDS_DEBUG - qDebug() << "DownloadView::on_timeout()"; + qDebug() << "DownloadView::on_timeout()"; #endif - UpdateView(); + UpdateView(); } QString DownloadView::GetStatusString(qtrapids::QTorrentHandle::State const& status) const { - switch (status) { - case qtrapids::QTorrentHandle::QUEUED_FOR_CHECKING : - return tr("Queued"); - case qtrapids::QTorrentHandle::CHECKING_FILES : - return tr("Checking"); - case qtrapids::QTorrentHandle::DOWNLOADING_METADATA : - return tr("DL meta"); - case qtrapids::QTorrentHandle::DOWNLOADING : - return tr("Downloading"); - case qtrapids::QTorrentHandle::FINISHED : - return tr("Finished"); - case qtrapids::QTorrentHandle::SEEDING : - return tr("Seeding"); - case qtrapids::QTorrentHandle::ALLOCATING : - return tr("Allocating"); - default: - return tr("N/A"); - } + switch (status) + { + case qtrapids::QTorrentHandle::QUEUED_FOR_CHECKING : + return tr("Queued"); + case qtrapids::QTorrentHandle::CHECKING_FILES : + return tr("Checking"); + case qtrapids::QTorrentHandle::DOWNLOADING_METADATA : + return tr("DL meta"); + case qtrapids::QTorrentHandle::DOWNLOADING : + return tr("Downloading"); + case qtrapids::QTorrentHandle::FINISHED : + return tr("Finished"); + case qtrapids::QTorrentHandle::SEEDING : + return tr("Seeding"); + case qtrapids::QTorrentHandle::ALLOCATING : + return tr("Allocating"); + default: + return tr("N/A"); + } } QColor DownloadView::GetStatusColor(qtrapids::QTorrentHandle::State const& status) const { - QColor green(40,205,40); - QColor yellow(255,174,0); - - switch (status) { - case qtrapids::QTorrentHandle::QUEUED_FOR_CHECKING : - case qtrapids::QTorrentHandle::CHECKING_FILES : - case qtrapids::QTorrentHandle::DOWNLOADING_METADATA : - case qtrapids::QTorrentHandle::ALLOCATING : - return yellow; - case qtrapids::QTorrentHandle::DOWNLOADING : - case qtrapids::QTorrentHandle::FINISHED : - case qtrapids::QTorrentHandle::SEEDING : - return green; - default: - return QColor(); - } + QColor green(40,205,40); + QColor yellow(255,174,0); + + switch (status) + { + case qtrapids::QTorrentHandle::QUEUED_FOR_CHECKING : + case qtrapids::QTorrentHandle::CHECKING_FILES : + case qtrapids::QTorrentHandle::DOWNLOADING_METADATA : + case qtrapids::QTorrentHandle::ALLOCATING : + return yellow; + case qtrapids::QTorrentHandle::DOWNLOADING : + case qtrapids::QTorrentHandle::FINISHED : + case qtrapids::QTorrentHandle::SEEDING : + return green; + default: + return QColor(); + } } void DownloadView::UpdateView() { - DownloadViewItem *item = dynamic_cast (currentItem()); - - std::map::iterator listIter - = items_.begin(); - std::map::iterator listEnd - = items_.end(); - - while (listIter != listEnd) { - updateItem(listIter->first); - ++listIter; - } + DownloadViewItem *item = dynamic_cast (currentItem()); + + std::map::iterator listIter + = items_.begin(); + std::map::iterator listEnd + = items_.end(); + + while (listIter != listEnd) + { + updateItem(listIter->first); + ++listIter; + } } diff --git a/src/gui/DownloadView.h b/src/gui/DownloadView.h index cb300ba..1ffc529 100644 --- a/src/gui/DownloadView.h +++ b/src/gui/DownloadView.h @@ -36,69 +36,70 @@ class QTimer; */ class DownloadView : public QTreeWidget { -Q_OBJECT - - public: + Q_OBJECT + +public: DownloadView(QWidget* parent); ~DownloadView(); - void newItem(qtrapids::QTorrentHandle handle); - void updateItem(qtrapids::QTorrentHandle handle); - qtrapids::QTorrentHandle removeSelected(); - void removeItem(qtrapids::QTorrentHandle handle); - void setRefreshInterval(int msec); - - private slots: - void on_itemClicked(QTreeWidgetItem * item, int column); - void on_timeout(); - - private: - // Maps torrent to downloadview item. - // Key: SHA1 info hash of torrent. Data: View item corresponding to torrent. - std::map items_; - QTimer *timer_; - - // Private functions. - QString GetStatusString(qtrapids::QTorrentHandle::State const& status) const; - QColor GetStatusColor(qtrapids::QTorrentHandle::State const& status) const; + void newItem(qtrapids::QTorrentHandle handle); + void updateItem(qtrapids::QTorrentHandle handle); + qtrapids::QTorrentHandle removeSelected(); + void removeItem(qtrapids::QTorrentHandle handle); + void setRefreshInterval(int msec); + +private slots: + void on_itemClicked(QTreeWidgetItem * item, int column); + void on_timeout(); + +private: + // Maps torrent to downloadview item. + // Key: SHA1 info hash of torrent. Data: View item corresponding to torrent. + std::map items_; + QTimer *timer_; + + // Private functions. + QString GetStatusString(qtrapids::QTorrentHandle::State const& status) const; + QColor GetStatusColor(qtrapids::QTorrentHandle::State const& status) const; void UpdateView(); - + }; /** - @class DownloadViewItem + @class DownloadViewItem @brief Represents one item row of DownloadView */ -class DownloadViewItem : public QTreeWidgetItem { - - public: - DownloadViewItem(QTreeWidget* parent, int type) : - QTreeWidgetItem(parent, type = QTreeWidgetItem::UserType) {}; - - DownloadViewItem(const QStringList& strings, - int type = QTreeWidgetItem::UserType) : - QTreeWidgetItem (strings, type = Type) {}; - - - /// @return An item comprising of string list, suitable for QTableView - /// header. - static DownloadViewItem *getHeaderItem() - { - DownloadViewItem *item - = new DownloadViewItem(QStringList() - << "Name" - << "Size" << "Status" - << "Progress" << "DL speed" - << "UL speed" << "Seeds/Leechers" - << "Ratio" << "ETA"); - - return item; - } - - /// @todo QTorrentHandle as one hidden column +class DownloadViewItem : public QTreeWidgetItem +{ + +public: + DownloadViewItem(QTreeWidget* parent, int type) : + QTreeWidgetItem(parent, type = QTreeWidgetItem::UserType) {}; + + DownloadViewItem(const QStringList& strings, + int type = QTreeWidgetItem::UserType) : + QTreeWidgetItem (strings, type = Type) {}; + + + /// @return An item comprising of string list, suitable for QTableView + /// header. + static DownloadViewItem *getHeaderItem() + { + DownloadViewItem *item + = new DownloadViewItem(QStringList() + << "Name" + << "Size" << "Status" + << "Progress" << "DL speed" + << "UL speed" << "Seeds/Leechers" + << "Ratio" << "ETA"); + + return item; + } + + /// @todo QTorrentHandle as one hidden column }; #endif diff --git a/src/gui/MainWindow.cpp b/src/gui/MainWindow.cpp index 4ccddd9..4d47618 100644 --- a/src/gui/MainWindow.cpp +++ b/src/gui/MainWindow.cpp @@ -33,83 +33,83 @@ #include "MainWindow.h" -const QString ABOUT_TEXT - = QString(QObject::trUtf8("QtRapids, a simple BitTorrent client based on" - "\nQt and Libtorrent." - "\n\nURL: http://qtrapids.garage.maemo.org/" - "\n\nAuthors:\nLassi Väätämöinen, lassi.vaatamoinen@ixonos.com" - "\nDenis Zalievsky, denis.zalewsky@ixonos.com" - "\n\nIxonos Plc, Finland\n")); +const QString ABOUT_TEXT += QString(QObject::trUtf8("QtRapids, a simple BitTorrent client based on" + "\nQt and Libtorrent." + "\n\nURL: http://qtrapids.garage.maemo.org/" + "\n\nAuthors:\nLassi Väätämöinen, lassi.vaatamoinen@ixonos.com" + "\nDenis Zalievsky, denis.zalewsky@ixonos.com" + "\n\nIxonos Plc, Finland\n")); // Consturctor MainWindow::MainWindow(): - QMainWindow(), // Superclass - tabWidget_(NULL), - dlView_(NULL), - seedView_(NULL), - preferencesDialog_(NULL), - settings_(), + QMainWindow(), // Superclass + tabWidget_(NULL), + dlView_(NULL), + seedView_(NULL), + preferencesDialog_(NULL), + settings_(), // torrentHandles_(), - btSession_() + btSession_() { - // MENUBAR - QMenuBar *menuBar = new QMenuBar(); - QMenu *tempMenu = NULL; - - tempMenu = menuBar->addMenu(tr("&File")); - QAction *openAction = tempMenu->addAction(tr("&Open")); - QAction *removeAction = tempMenu->addAction(tr("&Remove")); - removeAction->setEnabled(false); - QAction *quitAction = tempMenu->addAction(tr("&Quit")); - - tempMenu = menuBar->addMenu(tr("&Settings")); - QAction *preferencesAction = tempMenu->addAction(tr("&Preferences")); - - tempMenu = menuBar->addMenu(tr("&Help")); - QAction *aboutAction = tempMenu->addAction(tr("&About")); - QAction *aboutQtAction = tempMenu->addAction(tr("About &Qt")); - - setMenuBar(menuBar); - connect(openAction, SIGNAL(triggered()), this, SLOT(on_openAction_clicked())); - connect(removeAction, SIGNAL(triggered()), this, SLOT(on_removeAction_clicked())); - connect(this, SIGNAL(itemSelected(bool)), removeAction, SLOT(setEnabled(bool))); - connect(quitAction, SIGNAL(triggered()), this, SLOT(on_quitAction_clicked())); - connect(preferencesAction, SIGNAL(triggered()), this, SLOT(on_preferencesAction_clicked())); - connect(aboutAction, SIGNAL(triggered()), this, SLOT(on_aboutAction_clicked())); - connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(on_aboutQtAction_clicked())); - - // TABWIDGET (central widget) - tabWidget_ = new QTabWidget(); - - /// @todo Exception handling - dlView_ = new DownloadView(this); - seedView_ = new SeedView(this); - tabWidget_->addTab(dlView_, tr("Downloads")); - tabWidget_->addTab(seedView_, tr("Seeds")); - connect(dlView_, SIGNAL(itemSelectionChanged()), this, - SLOT(on_downloadItemSelectionChanged())); - connect(seedView_, SIGNAL(itemSelectionChanged()), this, - SLOT(on_seedItemSelectionChanged())); - - - // Tab widget as central widget. - setCentralWidget(tabWidget_); - - // TOOLBAR - QToolBar *toolBar = new QToolBar(); - toolBar->addAction(tr("Open")); - removeAction = toolBar->addAction(tr("Remove")); - removeAction->setEnabled(false); - addToolBar(Qt::TopToolBarArea, toolBar); - - connect(this, SIGNAL(itemSelected(bool)), removeAction, - SLOT(setEnabled(bool))); - connect(toolBar, SIGNAL(actionTriggered(QAction*)), this, - SLOT(handleToolBarAction(QAction*))); - - connect(&btSession_, SIGNAL(alert(std::auto_ptr)), - this, SLOT(on_alert(std::auto_ptr))); + // MENUBAR + QMenuBar *menuBar = new QMenuBar(); + QMenu *tempMenu = NULL; + + tempMenu = menuBar->addMenu(tr("&File")); + QAction *openAction = tempMenu->addAction(tr("&Open")); + QAction *removeAction = tempMenu->addAction(tr("&Remove")); + removeAction->setEnabled(false); + QAction *quitAction = tempMenu->addAction(tr("&Quit")); + + tempMenu = menuBar->addMenu(tr("&Settings")); + QAction *preferencesAction = tempMenu->addAction(tr("&Preferences")); + + tempMenu = menuBar->addMenu(tr("&Help")); + QAction *aboutAction = tempMenu->addAction(tr("&About")); + QAction *aboutQtAction = tempMenu->addAction(tr("About &Qt")); + + setMenuBar(menuBar); + connect(openAction, SIGNAL(triggered()), this, SLOT(on_openAction_clicked())); + connect(removeAction, SIGNAL(triggered()), this, SLOT(on_removeAction_clicked())); + connect(this, SIGNAL(itemSelected(bool)), removeAction, SLOT(setEnabled(bool))); + connect(quitAction, SIGNAL(triggered()), this, SLOT(on_quitAction_clicked())); + connect(preferencesAction, SIGNAL(triggered()), this, SLOT(on_preferencesAction_clicked())); + connect(aboutAction, SIGNAL(triggered()), this, SLOT(on_aboutAction_clicked())); + connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(on_aboutQtAction_clicked())); + + // TABWIDGET (central widget) + tabWidget_ = new QTabWidget(); + + /// @todo Exception handling + dlView_ = new DownloadView(this); + seedView_ = new SeedView(this); + tabWidget_->addTab(dlView_, tr("Downloads")); + tabWidget_->addTab(seedView_, tr("Seeds")); + connect(dlView_, SIGNAL(itemSelectionChanged()), this, + SLOT(on_downloadItemSelectionChanged())); + connect(seedView_, SIGNAL(itemSelectionChanged()), this, + SLOT(on_seedItemSelectionChanged())); + + + // Tab widget as central widget. + setCentralWidget(tabWidget_); + + // TOOLBAR + QToolBar *toolBar = new QToolBar(); + toolBar->addAction(tr("Open")); + removeAction = toolBar->addAction(tr("Remove")); + removeAction->setEnabled(false); + addToolBar(Qt::TopToolBarArea, toolBar); + + connect(this, SIGNAL(itemSelected(bool)), removeAction, + SLOT(setEnabled(bool))); + connect(toolBar, SIGNAL(actionTriggered(QAction*)), this, + SLOT(handleToolBarAction(QAction*))); + + connect(&btSession_, SIGNAL(alert(std::auto_ptr)), + this, SLOT(on_alert(std::auto_ptr))); } @@ -120,103 +120,114 @@ MainWindow::~MainWindow() // =========================== SLOTS ================================= void MainWindow::on_openAction_clicked() { - QFileDialog *dialog = new QFileDialog( this, "Open torrent file", QString(), tr("Torrent files (*.torrent)")); - dialog->setFileMode(QFileDialog::ExistingFile); - connect(dialog, SIGNAL(fileSelected(const QString&)), this, SLOT(on_torrentFileSelected(const QString&))); - dialog->show(); + QFileDialog *dialog = new QFileDialog( this, "Open torrent file", QString(), tr("Torrent files (*.torrent)")); + dialog->setFileMode(QFileDialog::ExistingFile); + connect(dialog, SIGNAL(fileSelected(const QString&)), this, SLOT(on_torrentFileSelected(const QString&))); + dialog->show(); } void MainWindow::on_removeAction_clicked() { - qtrapids::QTorrentHandle handle = dlView_->removeSelected(); - btSession_.removeTorrent(handle); + qtrapids::QTorrentHandle handle = dlView_->removeSelected(); + btSession_.removeTorrent(handle); } void MainWindow::on_quitAction_clicked() { - close(); + close(); } void MainWindow::on_preferencesAction_clicked() { - if (!preferencesDialog_) { - preferencesDialog_ = new PreferencesDialog(this); - } - preferencesDialog_->show(); - preferencesDialog_->raise(); - preferencesDialog_->activateWindow(); + if (!preferencesDialog_) + { + preferencesDialog_ = new PreferencesDialog(this); + } + preferencesDialog_->show(); + preferencesDialog_->raise(); + preferencesDialog_->activateWindow(); } void MainWindow::on_aboutAction_clicked() { - QMessageBox::about(this, tr("About QtRapids"), ABOUT_TEXT); + QMessageBox::about(this, tr("About QtRapids"), ABOUT_TEXT); } - - + + void MainWindow::on_aboutQtAction_clicked() { - QMessageBox::aboutQt (this, tr("About Qt")); + QMessageBox::aboutQt (this, tr("About Qt")); } void MainWindow::on_downloadItemSelectionChanged() { #ifdef QTRAPIDS_DEBUG - qDebug() << "MainWindow::on_seedItemSelectionChanged():" << dlView_->currentItem(); + qDebug() << "MainWindow::on_seedItemSelectionChanged():" << dlView_->currentItem(); #endif - if (dlView_->currentItem() != NULL) { - emit(itemSelected(true)); - } else { - emit(itemSelected(false)); - } + if (dlView_->currentItem() != NULL) + { + emit(itemSelected(true)); + } + else + { + emit(itemSelected(false)); + } } void MainWindow::on_seedItemSelectionChanged() { #ifdef QTRAPIDS_DEBUG - qDebug() << "MainWindow::on_seedItemSelectionChanged():" << seedView_->currentItem(); + qDebug() << "MainWindow::on_seedItemSelectionChanged():" << seedView_->currentItem(); #endif - if (seedView_->currentItem() != NULL) { - emit(itemSelected(true)); - } else { - emit(itemSelected(false)); - } + if (seedView_->currentItem() != NULL) + { + emit(itemSelected(true)); + } + else + { + emit(itemSelected(false)); + } } - + void MainWindow::handleToolBarAction(QAction* action) { - if (action->text() == "Open") { - on_openAction_clicked(); - } else if (action->text() == "Remove") { - on_removeAction_clicked(); - } + if (action->text() == "Open") + { + on_openAction_clicked(); + } + else if (action->text() == "Remove") + { + on_removeAction_clicked(); + } } void MainWindow::on_torrentFileSelected(const QString& file) { #ifdef QTRAPIDS_DEBUG - qDebug() << " MainWindow::on_torrentFileSelected(): " << file; + qDebug() << " MainWindow::on_torrentFileSelected(): " << file; #endif - // Torrent filename empty, do nothing. - if (file == "") { - return; - } - - // Otherwise add torrent - // For params, see: http://www.rasterbar.com/products/libtorrent/manual.html#add-torrent - AddTorrentParams addParams; - boost::intrusive_ptr tiTmp = - new libtorrent::torrent_info(boost::filesystem::path(file.toStdString())); - addParams.ti = tiTmp; - // save_path is the only mandatory parameter, rest are optional. - addParams.save_path = boost::filesystem::path(settings_.value("download/directory").toString().toStdString()); - //addParams.storage_mode = libtorrent::storage_mode_allocate; - qtrapids::QTorrentHandle handle = btSession_.addTorrent(addParams); - dlView_->newItem(handle); + // Torrent filename empty, do nothing. + if (file == "") + { + return; + } + + // Otherwise add torrent + // For params, see: http://www.rasterbar.com/products/libtorrent/manual.html#add-torrent + AddTorrentParams addParams; + boost::intrusive_ptr tiTmp = + new libtorrent::torrent_info(boost::filesystem::path(file.toStdString())); + addParams.ti = tiTmp; + // save_path is the only mandatory parameter, rest are optional. + addParams.save_path = boost::filesystem::path(settings_.value("download/directory").toString().toStdString()); + //addParams.storage_mode = libtorrent::storage_mode_allocate; + qtrapids::QTorrentHandle handle = btSession_.addTorrent(addParams); + dlView_->newItem(handle); // torrentHandles_.push_back(handlePtr); #ifdef QTRAPIDS_DEBUG - qDebug() << "Is valid: " << handle.isValid(); + qDebug() << "Is valid: " << handle.isValid(); #endif } @@ -224,24 +235,26 @@ void MainWindow::on_torrentFileSelected(const QString& file) void MainWindow::on_alert(std::auto_ptr al) { - - if (al.get() != NULL) { -// qDebug() -// << "MainWindow::on_torrentAlert(): " + + if (al.get() != NULL) + { +// qDebug() +// << "MainWindow::on_torrentAlert(): " // << QString::fromStdString(al->message()); - TorrentAlert *torrentAlert - = dynamic_cast (al.get()); + TorrentAlert *torrentAlert + = dynamic_cast (al.get()); + + if (torrentAlert) + { + qtrapids::QTorrentHandle torrentHandle = qtrapids::QTorrentHandle(torrentAlert->handle); + dlView_->updateItem(qtrapids::QTorrentHandle(torrentAlert->handle)); + } + + } + + - if (torrentAlert) { - qtrapids::QTorrentHandle torrentHandle = qtrapids::QTorrentHandle(torrentAlert->handle); - dlView_->updateItem(qtrapids::QTorrentHandle(torrentAlert->handle)); - } - - } - - - } /* diff --git a/src/gui/MainWindow.h b/src/gui/MainWindow.h index 3f546bb..f4d43b1 100644 --- a/src/gui/MainWindow.h +++ b/src/gui/MainWindow.h @@ -33,44 +33,45 @@ class PreferencesDialog; /** @author Lassi Väätämöinen */ -class MainWindow : public QMainWindow { - Q_OBJECT - - public: +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: MainWindow(); ~MainWindow(); - - signals: - void itemSelected(bool enabled); - - public slots: - private slots: - void on_openAction_clicked(); - void on_removeAction_clicked(); - void on_quitAction_clicked(); - void on_preferencesAction_clicked(); - void on_aboutAction_clicked(); - void on_aboutQtAction_clicked(); - void on_downloadItemSelectionChanged(); - void on_seedItemSelectionChanged(); - void handleToolBarAction(QAction* action); - void on_torrentFileSelected(const QString& file); - void on_alert(std::auto_ptr al); - - private: - QTabWidget *tabWidget_; - DownloadView *dlView_; - SeedView *seedView_; - PreferencesDialog *preferencesDialog_; - QSettings settings_; - - //std::vector< std::auto_ptr const > torrentHandles_; - - qtrapids::QBittorrentSession btSession_; - - //bool IsNewTorrent(std::auto_ptr handlePtr); +signals: + void itemSelected(bool enabled); + +public slots: +private slots: + void on_openAction_clicked(); + void on_removeAction_clicked(); + void on_quitAction_clicked(); + void on_preferencesAction_clicked(); + void on_aboutAction_clicked(); + void on_aboutQtAction_clicked(); + void on_downloadItemSelectionChanged(); + void on_seedItemSelectionChanged(); + void handleToolBarAction(QAction* action); + void on_torrentFileSelected(const QString& file); + void on_alert(std::auto_ptr al); + +private: + QTabWidget *tabWidget_; + DownloadView *dlView_; + SeedView *seedView_; + PreferencesDialog *preferencesDialog_; + QSettings settings_; + + //std::vector< std::auto_ptr const > torrentHandles_; + + qtrapids::QBittorrentSession btSession_; + + + //bool IsNewTorrent(std::auto_ptr handlePtr); }; #endif diff --git a/src/gui/PreferencesDialog.cpp b/src/gui/PreferencesDialog.cpp index 9ee381b..3742c41 100644 --- a/src/gui/PreferencesDialog.cpp +++ b/src/gui/PreferencesDialog.cpp @@ -28,44 +28,44 @@ #include "PreferencesDialog.h" -PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags f) : - QDialog(parent, f), // Superclass - dirLineEdit_(NULL), - dialogButtons_(NULL), - settings_() +PreferencesDialog::PreferencesDialog(QWidget* parent, Qt::WindowFlags f) : + QDialog(parent, f), // Superclass + dirLineEdit_(NULL), + dialogButtons_(NULL), + settings_() { - setWindowTitle("Preferences"); - - QBoxLayout *verticalBox = new QBoxLayout(QBoxLayout::TopToBottom); - QBoxLayout *horizontalBox1 = new QBoxLayout(QBoxLayout::LeftToRight); - setLayout(verticalBox); - verticalBox->addLayout(horizontalBox1); - - QLabel *dirLabel = new QLabel(tr("Download directory: ")); - dirLineEdit_ = new QLineEdit(this); - QPushButton *browseDirButton = new QPushButton(tr("Browse..")); - - horizontalBox1->addWidget(dirLabel); - horizontalBox1->addWidget(dirLineEdit_); - horizontalBox1->addWidget(browseDirButton); - - connect(browseDirButton, SIGNAL(clicked()), - this, SLOT(on_browseDirButtonClicked())); - - - dialogButtons_ = new QDialogButtonBox(this); - dialogButtons_->setStandardButtons(QDialogButtonBox::Ok - | QDialogButtonBox::Apply - | QDialogButtonBox::Cancel); - - verticalBox->addWidget(dialogButtons_); - - connect(dialogButtons_, SIGNAL(clicked(QAbstractButton*)), - this, SLOT(on_buttonClicked(QAbstractButton*))); - - // Set saved preference values to fields. - ReadSettings(); - + setWindowTitle("Preferences"); + + QBoxLayout *verticalBox = new QBoxLayout(QBoxLayout::TopToBottom); + QBoxLayout *horizontalBox1 = new QBoxLayout(QBoxLayout::LeftToRight); + setLayout(verticalBox); + verticalBox->addLayout(horizontalBox1); + + QLabel *dirLabel = new QLabel(tr("Download directory: ")); + dirLineEdit_ = new QLineEdit(this); + QPushButton *browseDirButton = new QPushButton(tr("Browse..")); + + horizontalBox1->addWidget(dirLabel); + horizontalBox1->addWidget(dirLineEdit_); + horizontalBox1->addWidget(browseDirButton); + + connect(browseDirButton, SIGNAL(clicked()), + this, SLOT(on_browseDirButtonClicked())); + + + dialogButtons_ = new QDialogButtonBox(this); + dialogButtons_->setStandardButtons(QDialogButtonBox::Ok + | QDialogButtonBox::Apply + | QDialogButtonBox::Cancel); + + verticalBox->addWidget(dialogButtons_); + + connect(dialogButtons_, SIGNAL(clicked(QAbstractButton*)), + this, SLOT(on_buttonClicked(QAbstractButton*))); + + // Set saved preference values to fields. + ReadSettings(); + } @@ -76,68 +76,68 @@ PreferencesDialog::~PreferencesDialog() // ======================== SLOTS ======================== void PreferencesDialog::on_browseDirButtonClicked() { - QFileDialog *dialog - = new QFileDialog(this, "Download directory", - QString(), tr("Torrent files (*.torrent)")); - - dialog->setFileMode(QFileDialog::Directory); - dialog->setOption(QFileDialog::ShowDirsOnly, true); - - connect(dialog, SIGNAL(fileSelected(const QString&)), - this, SLOT(on_downloadDirectorySelected(const QString&))); - - dialog->show(); + QFileDialog *dialog + = new QFileDialog(this, "Download directory", + QString(), tr("Torrent files (*.torrent)")); + + dialog->setFileMode(QFileDialog::Directory); + dialog->setOption(QFileDialog::ShowDirsOnly, true); + + connect(dialog, SIGNAL(fileSelected(const QString&)), + this, SLOT(on_downloadDirectorySelected(const QString&))); + + dialog->show(); } void PreferencesDialog::on_buttonClicked(QAbstractButton* button) { - switch (dialogButtons_->buttonRole ( button ) ) - { - case QDialogButtonBox::AcceptRole : - qDebug() << "PreferencesDialog: OK"; - WriteSettings(); - close(); - break; - case QDialogButtonBox::ApplyRole : - qDebug() << "PreferencesDialog: APPLY"; - WriteSettings(); - break; - case QDialogButtonBox::RejectRole : - qDebug() << "PreferencesDialog: CANCEL"; - close(); - break; - default: - return; - } + switch (dialogButtons_->buttonRole ( button ) ) + { + case QDialogButtonBox::AcceptRole : + qDebug() << "PreferencesDialog: OK"; + WriteSettings(); + close(); + break; + case QDialogButtonBox::ApplyRole : + qDebug() << "PreferencesDialog: APPLY"; + WriteSettings(); + break; + case QDialogButtonBox::RejectRole : + qDebug() << "PreferencesDialog: CANCEL"; + close(); + break; + default: + return; + } } void PreferencesDialog::on_downloadDirectorySelected(const QString& directory) { - qDebug() << "PreferencesDialog::on_downloadDirectorySelected(): " << directory; - // Torrent filename empty, do nothing. - if (directory == "") - return; - - dirLineEdit_->insert(directory); - - /// @todo check that user has privileges to write to this directory. + qDebug() << "PreferencesDialog::on_downloadDirectorySelected(): " << directory; + // Torrent filename empty, do nothing. + if (directory == "") + return; + + dirLineEdit_->insert(directory); + + /// @todo check that user has privileges to write to this directory. } // ========================= Private functions ========================== void PreferencesDialog::WriteSettings() { - settings_.setValue("download/directory", dirLineEdit_->text()); - - // NOTE: We might need to call QSettigns::sync() here to instantly write settings. - // settings are written also by QSettings() destructor and by event loop at regular interval. + settings_.setValue("download/directory", dirLineEdit_->text()); + + // NOTE: We might need to call QSettigns::sync() here to instantly write settings. + // settings are written also by QSettings() destructor and by event loop at regular interval. } void PreferencesDialog::ReadSettings() { - dirLineEdit_->insert(settings_.value("download/directory").toString()); - - // NOTE: We might need to call QSettigns::sync() here to instantly write settings. - // settings are written also by QSettings() destructor and by event loop at regular interval. + dirLineEdit_->insert(settings_.value("download/directory").toString()); + + // NOTE: We might need to call QSettigns::sync() here to instantly write settings. + // settings are written also by QSettings() destructor and by event loop at regular interval. } diff --git a/src/gui/PreferencesDialog.h b/src/gui/PreferencesDialog.h index c368ea0..e6f685a 100644 --- a/src/gui/PreferencesDialog.h +++ b/src/gui/PreferencesDialog.h @@ -33,27 +33,27 @@ class QDialogButtonBox; */ class PreferencesDialog : public QDialog { - - Q_OBJECT - - public: + + Q_OBJECT + +public: PreferencesDialog(QWidget* parent = 0, Qt::WindowFlags f = 0); ~PreferencesDialog(); - private slots: - void on_browseDirButtonClicked(); - void on_buttonClicked(QAbstractButton* button); - void on_downloadDirectorySelected(const QString& directory); - - private: - QLineEdit *dirLineEdit_; - QDialogButtonBox *dialogButtons_; - QSettings settings_; - - // Private functions: - void WriteSettings(); - void ReadSettings(); +private slots: + void on_browseDirButtonClicked(); + void on_buttonClicked(QAbstractButton* button); + void on_downloadDirectorySelected(const QString& directory); + +private: + QLineEdit *dirLineEdit_; + QDialogButtonBox *dialogButtons_; + QSettings settings_; + + // Private functions: + void WriteSettings(); + void ReadSettings(); }; #endif diff --git a/src/gui/SeedView.cpp b/src/gui/SeedView.cpp index 2765e14..d90daeb 100644 --- a/src/gui/SeedView.cpp +++ b/src/gui/SeedView.cpp @@ -21,14 +21,14 @@ #include "SeedView.h" SeedView::SeedView(QWidget* parent): - QTreeWidget(parent), - items_() + QTreeWidget(parent), + items_() { - setRootIsDecorated(false); // Hide branch lines, making one-level treeview (similar to list) - setHeaderItem(SeedViewItem::getHeaderItem()); - - connect(this, SIGNAL(itemPressed( QTreeWidgetItem*, int)), - this, SLOT(on_itemPressed(QTreeWidgetItem*, int))); + setRootIsDecorated(false); // Hide branch lines, making one-level treeview (similar to list) + setHeaderItem(SeedViewItem::getHeaderItem()); + + connect(this, SIGNAL(itemPressed( QTreeWidgetItem*, int)), + this, SLOT(on_itemPressed(QTreeWidgetItem*, int))); } @@ -38,6 +38,6 @@ SeedView::~SeedView() void SeedView::on_itemPressed(QTreeWidgetItem * item, int column) { - qDebug() << "SeedView::on_itemPressed() " << item << "," << column; + qDebug() << "SeedView::on_itemPressed() " << item << "," << column; } diff --git a/src/gui/SeedView.h b/src/gui/SeedView.h index 666a4c7..766fe19 100644 --- a/src/gui/SeedView.h +++ b/src/gui/SeedView.h @@ -31,64 +31,65 @@ class SeedViewItem; */ class SeedView : public QTreeWidget { -Q_OBJECT - public: + Q_OBJECT +public: SeedView(QWidget* parent); ~SeedView(); - - void newItem(qtrapids::QTorrentHandle const* handle); - void updateItem(qtrapids::QTorrentHandle const* handle); - - private slots: - void on_itemPressed(QTreeWidgetItem *item, int column); - - private: - // Maps torrent to SeedView item. - // Key: SHA1 info hash of torrent. Data: View item corresponding to torrent. - std::map items_; - - // Name - // Size - // Status - // UP speed - // Seeds/Leechers - // Connected peers - // total uploaded - // ratio + + void newItem(qtrapids::QTorrentHandle const* handle); + void updateItem(qtrapids::QTorrentHandle const* handle); + +private slots: + void on_itemPressed(QTreeWidgetItem *item, int column); + +private: + // Maps torrent to SeedView item. + // Key: SHA1 info hash of torrent. Data: View item corresponding to torrent. + std::map items_; + + // Name + // Size + // Status + // UP speed + // Seeds/Leechers + // Connected peers + // total uploaded + // ratio }; /** @class DownloadViewItem @brief Represents one item row of DownloadView */ -class SeedViewItem : public QTreeWidgetItem { - - public: - - SeedViewItem(QTreeWidget* parent, int type) : - QTreeWidgetItem(parent, type = QTreeWidgetItem::UserType) {}; - - SeedViewItem(const QStringList& strings, int type = QTreeWidgetItem::UserType ) : - QTreeWidgetItem (strings, type = Type) {}; - - - /// @return An item comprising of string list, suitable for QTableView - /// header. - static SeedViewItem *getHeaderItem() - { - SeedViewItem *item - = new SeedViewItem(QStringList() - << "Name" - << "Size" << "Status" - << "Progress" << "UL speed" << "Seeds/Leechers" - << "Conn. peers" - << "Ratio"); - - return item; - } - - /// @todo QTorrentHandle as one hidden column +class SeedViewItem : public QTreeWidgetItem +{ + +public: + + SeedViewItem(QTreeWidget* parent, int type) : + QTreeWidgetItem(parent, type = QTreeWidgetItem::UserType) {}; + + SeedViewItem(const QStringList& strings, int type = QTreeWidgetItem::UserType ) : + QTreeWidgetItem (strings, type = Type) {}; + + + /// @return An item comprising of string list, suitable for QTableView + /// header. + static SeedViewItem *getHeaderItem() + { + SeedViewItem *item + = new SeedViewItem(QStringList() + << "Name" + << "Size" << "Status" + << "Progress" << "UL speed" << "Seeds/Leechers" + << "Conn. peers" + << "Ratio"); + + return item; + } + + /// @todo QTorrentHandle as one hidden column }; #endif diff --git a/src/gui/main.cpp b/src/gui/main.cpp index 2538271..c6032bd 100644 --- a/src/gui/main.cpp +++ b/src/gui/main.cpp @@ -26,43 +26,43 @@ int main(int argc, char *argv[]) { - - QCoreApplication::setOrganizationName("Ixonos"); - QCoreApplication::setOrganizationDomain("ixonos.com"); - QCoreApplication::setApplicationName("QtRapids"); - - // Q_INIT_RESOURCE(application); - QApplication app(argc, argv); - MainWindow *mainWindow = new MainWindow(); - mainWindow->show(); - /* - DownloadView* dlw = new DownloadView(NULL); + QCoreApplication::setOrganizationName("Ixonos"); + QCoreApplication::setOrganizationDomain("ixonos.com"); + QCoreApplication::setApplicationName("QtRapids"); + + // Q_INIT_RESOURCE(application); + QApplication app(argc, argv); + MainWindow *mainWindow = new MainWindow(); + mainWindow->show(); + + /* + DownloadView* dlw = new DownloadView(NULL); //qtrapids * mw = new qtrapids(); - dlw->show(); - DownloadViewItem* dlwItem = new DownloadViewItem(QStringList() << "Name" - << "Size" << "Status" - << "Progress" << "DL speed" - << "UL speed" << "Seeds/Leechers" - << "ratio"); - DownloadViewItem* dlwItem2 = new DownloadViewItem(QStringList() << "Name" - << "1000" << "Downloading" - << "23%" << "11" - << "0.1" << "0/2" - << "1.10"); - //dlwItem->insertChild(0, new DownloadViewItem(QStringList() << "Name")); - dlw->insertTopLevelItem(0,dlwItem); - dlw->insertTopLevelItem(1,dlwItem2); - - for (unsigned i = 0; i < 10; ++i) - { - DownloadViewItem *editItem = dynamic_cast - (dlw->itemAt(QPoint(0,0))); - editItem->setData ( 8, Qt::DisplayRole, QVariant("EDITED" + QString::number(i, 'g', 2))); - QTest::qSleep(2000); - } - */ - - - return app.exec(); + dlw->show(); + DownloadViewItem* dlwItem = new DownloadViewItem(QStringList() << "Name" + << "Size" << "Status" + << "Progress" << "DL speed" + << "UL speed" << "Seeds/Leechers" + << "ratio"); + DownloadViewItem* dlwItem2 = new DownloadViewItem(QStringList() << "Name" + << "1000" << "Downloading" + << "23%" << "11" + << "0.1" << "0/2" + << "1.10"); + //dlwItem->insertChild(0, new DownloadViewItem(QStringList() << "Name")); + dlw->insertTopLevelItem(0,dlwItem); + dlw->insertTopLevelItem(1,dlwItem2); + + for (unsigned i = 0; i < 10; ++i) + { + DownloadViewItem *editItem = dynamic_cast + (dlw->itemAt(QPoint(0,0))); + editItem->setData ( 8, Qt::DisplayRole, QVariant("EDITED" + QString::number(i, 'g', 2))); + QTest::qSleep(2000); + } + */ + + + return app.exec(); } diff --git a/src/include/qtrapids/dbus.hpp b/src/include/qtrapids/dbus.hpp index 103c950..c7e91c4 100644 --- a/src/include/qtrapids/dbus.hpp +++ b/src/include/qtrapids/dbus.hpp @@ -11,17 +11,17 @@ namespace qtrapids { - struct TorrentState +struct TorrentState +{ + + enum torrent_action { + action_add, + action_remove, + action_update + }; - enum torrent_action - { - action_add, - action_remove, - action_update - }; - - TorrentState() + TorrentState() : hash("") , name("") , state(0) @@ -32,95 +32,97 @@ namespace qtrapids , leeches(0) , ratio(0) , total_size(0) - { } - - QString hash; - QString name; - torrent_action action; - uint state; - uint progress; - uint down_rate; - uint up_rate; - uint seeds; - uint leeches; - uint ratio; - qulonglong total_size; - }; - - typedef QHash ParamsMap_t; - typedef QHash const ParamsMapConst_t; - typedef QHash::iterator ParamsMapIterator_t; - typedef QHash::const_iterator ParamsMapConstIterator_t; - - static inline QDBusArgument& operator << (QDBusArgument& argument - , TorrentState const& state) - { - std::cout << "serialize" << std::endl; - argument.beginStructure(); - argument << state.hash << state.name << (uint)(state.action) << state.state << state.progress - << state.down_rate << state.up_rate << state.seeds - << state.leeches << state.ratio << state.total_size; - argument.endStructure(); - return argument; - } + { } + + QString hash; + QString name; + torrent_action action; + uint state; + uint progress; + uint down_rate; + uint up_rate; + uint seeds; + uint leeches; + uint ratio; + qulonglong total_size; +}; + +typedef QHash ParamsMap_t; +typedef QHash const ParamsMapConst_t; +typedef QHash::iterator ParamsMapIterator_t; +typedef QHash::const_iterator ParamsMapConstIterator_t; + +static inline QDBusArgument& operator << (QDBusArgument& argument + , TorrentState const& state) +{ + std::cout << "serialize" << std::endl; + argument.beginStructure(); + argument << state.hash << state.name << (uint)(state.action) << state.state << state.progress + << state.down_rate << state.up_rate << state.seeds + << state.leeches << state.ratio << state.total_size; + argument.endStructure(); + return argument; +} - static inline QDBusArgument const& operator >> (QDBusArgument const& argument - , TorrentState& state) - { - std::cout << "deserialize" << std::endl; - argument.beginStructure(); - uint action; - argument >> state.hash >> state.name >> action >> state.state >> state.progress - >> state.down_rate >> state.up_rate >> state.seeds - >> state.leeches >> state.ratio >> state.total_size; - state.action = (TorrentState::torrent_action)action; - argument.endStructure(); - return argument; - } +static inline QDBusArgument const& operator >> (QDBusArgument const& argument + , TorrentState& state) +{ + std::cout << "deserialize" << std::endl; + argument.beginStructure(); + uint action; + argument >> state.hash >> state.name >> action >> state.state >> state.progress + >> state.down_rate >> state.up_rate >> state.seeds + >> state.leeches >> state.ratio >> state.total_size; + state.action = (TorrentState::torrent_action)action; + argument.endStructure(); + return argument; +} - static inline QDBusArgument& operator << (QDBusArgument& argument - , ParamsMapConst_t& params) +static inline QDBusArgument& operator << (QDBusArgument& argument + , ParamsMapConst_t& params) +{ + ParamsMapConstIterator_t p; + std::cout << "serialize params" << std::endl; + argument.beginMap(); + for (p = params.constBegin(); p != params.constEnd(); ++p) { - ParamsMapConstIterator_t p; - std::cout << "serialize params" << std::endl; - argument.beginMap(); - for (p = params.constBegin(); p != params.constEnd(); ++p) { - argument.beginMapEntry(); - argument << p.key() << p.value(); - argument.endMapEntry(); - } - argument.endMap(); - return argument; + argument.beginMapEntry(); + argument << p.key() << p.value(); + argument.endMapEntry(); } + argument.endMap(); + return argument; +} - static inline QDBusArgument const& operator >> (QDBusArgument const& argument - , ParamsMap_t& params) +static inline QDBusArgument const& operator >> (QDBusArgument const& argument + , ParamsMap_t& params) +{ + ParamsMapConstIterator_t p; + QString key, value; + std::cout << "deserialize params" << std::endl; + argument.beginMap(); + for (p = params.constBegin(); p != params.constEnd(); ++p) { - ParamsMapConstIterator_t p; - QString key, value; - std::cout << "deserialize params" << std::endl; - argument.beginMap(); - for (p = params.constBegin(); p != params.constEnd(); ++p) { - argument.beginMapEntry(); - argument >> key >> value; - params[key] = value; - argument.endMapEntry(); - } - argument.endMap(); - return argument; + argument.beginMapEntry(); + argument >> key >> value; + params[key] = value; + argument.endMapEntry(); } + argument.endMap(); + return argument; +} - // class DBusConnector - // { - // public: - // DBusConnector() - // : connection_() - // { - // } - // private: - // QDBusConnection connection_; - // }; +// class DBusConnector +// { +// public: +// DBusConnector() +// : connection_() +// { +// } +// private: +// QDBusConnection connection_; +// }; } diff --git a/src/include/qtrapids/error.hpp b/src/include/qtrapids/error.hpp index 0bf83f5..f6e8946 100644 --- a/src/include/qtrapids/error.hpp +++ b/src/include/qtrapids/error.hpp @@ -6,46 +6,46 @@ namespace qtrapids { - class Error - { - public: +class Error +{ +public: - Error() + Error() : msg_("") - { } + { } - Error(char const *msg) + Error(char const *msg) : msg_(msg) - {} - - template - void append_to_msg(T val) - { - msg_ << val; - } - - private: - QString msg_; - - }; + {} template - Error& operator << (Error &self, T val) + void append_to_msg(T val) { - self.append_to_msg(val); - return self; + msg_ << val; } - class InvalidArgument : public Error - { - }; +private: + QString msg_; - template - InvalidArgument& operator << (InvalidArgument &self, T val) - { - self.append_to_msg(val); - return self; - } +}; + +template +Error& operator << (Error &self, T val) +{ + self.append_to_msg(val); + return self; +} + +class InvalidArgument : public Error +{ +}; + +template +InvalidArgument& operator << (InvalidArgument &self, T val) +{ + self.append_to_msg(val); + return self; +} } diff --git a/src/include/qtrapids/format.hpp b/src/include/qtrapids/format.hpp index 6bb49c8..8880348 100644 --- a/src/include/qtrapids/format.hpp +++ b/src/include/qtrapids/format.hpp @@ -9,41 +9,44 @@ namespace qtrapids { - - static inline QString formatProgress(uint progress) - { - return QString::number(progress / torrent_progress_percent); - } - namespace - { +static inline QString formatProgress(uint progress) +{ + return QString::number(progress / torrent_progress_percent); +} - static const qulonglong size_KB = 1024; - static const qulonglong size_MB = size_KB << 10; - static const qulonglong size_GB = size_MB << 10; +namespace +{ - static char const* size_names[] = { - "GB", - "MB", - "KB", - "B" - }; - } +static const qulonglong size_KB = 1024; +static const qulonglong size_MB = size_KB << 10; +static const qulonglong size_GB = size_MB << 10; - static inline QString formatSize(qulonglong size) +static char const* size_names[] = +{ + "GB", + "MB", + "KB", + "B" +}; +} + +static inline QString formatSize(qulonglong size) +{ + qulonglong unit = size_GB; + char const ** unit_name = &size_names[0]; + QString ret(""); + for (unit = size_GB; unit > 0; unit >>= 10, ++unit_name) { - qulonglong unit = size_GB; - char const ** unit_name = &size_names[0]; - QString ret(""); - for (unit = size_GB; unit > 0; unit >>= 10, ++unit_name) { - if (size & (~(unit - 1))) { - ret += (QString::number(size / unit) + *unit_name); - return ret; - } + if (size & (~(unit - 1))) + { + ret += (QString::number(size / unit) + *unit_name); + return ret; } - ret = QString::number(size) + "B"; - return ret; } + ret = QString::number(size) + "B"; + return ret; +} } // namespace qtrapids diff --git a/src/include/qtrapids/info.hpp b/src/include/qtrapids/info.hpp index f944677..221cc7a 100644 --- a/src/include/qtrapids/info.hpp +++ b/src/include/qtrapids/info.hpp @@ -9,27 +9,28 @@ namespace qtrapids { - static const uint32_t torrent_progress_max = 1000000; - static const uint32_t torrent_progress_percent = 10000; - //std::numeric_limits::max(); +static const uint32_t torrent_progress_max = 1000000; +static const uint32_t torrent_progress_percent = 10000; +//std::numeric_limits::max(); - typedef libtorrent::torrent_status TorrentStatus_t; - typedef libtorrent::torrent_status::state_t TorrentStatusIds_t; +typedef libtorrent::torrent_status TorrentStatus_t; +typedef libtorrent::torrent_status::state_t TorrentStatusIds_t; - struct TorrentStatus +struct TorrentStatus +{ + enum Id { - enum Id { - QUEUED_FOR_CHECKING = TorrentStatus_t::queued_for_checking, - CHECKING_FILES = TorrentStatus_t::checking_files, - DOWNLOADING_METADATA = TorrentStatus_t::downloading_metadata, - DOWNLOADING = TorrentStatus_t::downloading, - FINISHED = TorrentStatus_t::finished, - SEEDING = TorrentStatus_t::seeding, - ALLOCATING = TorrentStatus_t::allocating, - CHECKING_RESUME_DATA = TorrentStatus_t::checking_resume_data, - UNSPECIFIED - }; + QUEUED_FOR_CHECKING = TorrentStatus_t::queued_for_checking, + CHECKING_FILES = TorrentStatus_t::checking_files, + DOWNLOADING_METADATA = TorrentStatus_t::downloading_metadata, + DOWNLOADING = TorrentStatus_t::downloading, + FINISHED = TorrentStatus_t::finished, + SEEDING = TorrentStatus_t::seeding, + ALLOCATING = TorrentStatus_t::allocating, + CHECKING_RESUME_DATA = TorrentStatus_t::checking_resume_data, + UNSPECIFIED }; +}; } diff --git a/src/include/qtrapids/settings.hpp b/src/include/qtrapids/settings.hpp index d78625d..bc2ab96 100644 --- a/src/include/qtrapids/settings.hpp +++ b/src/include/qtrapids/settings.hpp @@ -4,17 +4,18 @@ namespace qtrapids { - static inline QVariant GetSettingsStoreDefault(QSettings &settings - , QString const& name - , QVariant const& default_value) +static inline QVariant GetSettingsStoreDefault(QSettings &settings + , QString const& name + , QVariant const& default_value) +{ + QVariant v(settings.value(name)); + if (!v.isNull()) { - QVariant v(settings.value(name)); - if (!v.isNull()) { - return v; - } - - settings.setValue(name, default_value); - return default_value; + return v; } + settings.setValue(name, default_value); + return default_value; +} + } diff --git a/src/plugins/PluginInterface.h b/src/plugins/PluginInterface.h index 5abf940..dc7a0f7 100644 --- a/src/plugins/PluginInterface.h +++ b/src/plugins/PluginInterface.h @@ -25,43 +25,45 @@ namespace qtrapids { - - /** @class PluginHostInterface - * @brief Defines interface for plugins to access the host application. - * A Host is an application that is extended by implementing Plugins, - * that implement the additional functionality - */ - class PluginHostInterface : public QObject { - public: - - /// @brief Sets the plugin GUI element to host application - /// @note It is up to the host application to decide how to manage - /// and show the actual widget. - virtual bool setGui(QWidget* widget) = 0; - - /// @brief Adds additional plugin wigdets to the host application. - /// This functio can be called by the plugin recursively, i.e. when GUI events occur - /// The host application must handle placing the additional widgets. - /// @todo Could we implement this using in a more manageable way, e.g. signal-slot? - virtual void addPluginWidget(QWidget* widget) = 0; - virtual void addToolbar() = 0; - virtual void addToolItem() = 0; - virtual void addMenu() = 0; - virtual void addMenuItem() = 0; - }; +/** @class PluginHostInterface + * @brief Defines interface for plugins to access the host application. + * A Host is an application that is extended by implementing Plugins, + * that implement the additional functionality +*/ +class PluginHostInterface : public QObject +{ +public: + + /// @brief Sets the plugin GUI element to host application + /// @note It is up to the host application to decide how to manage + /// and show the actual widget. + virtual bool setGui(QWidget* widget) = 0; + + /// @brief Adds additional plugin wigdets to the host application. + /// This functio can be called by the plugin recursively, i.e. when GUI events occur + /// The host application must handle placing the additional widgets. + /// @todo Could we implement this using in a more manageable way, e.g. signal-slot? + virtual void addPluginWidget(QWidget* widget) = 0; + virtual void addToolbar() = 0; + virtual void addToolItem() = 0; + virtual void addMenu() = 0; + virtual void addMenuItem() = 0; +}; - /** @class PluginInterface - * @brief Defines interface for a plugin instance. - * The host application uses PluginInterface interface for calling the plugins - * that extend the Host functionality - */ - class PluginInterface : public QObject { - public: - /// @brief Initializes the plugin instance. - virtual void initialize(PluginHostInterface* host) = 0; - virtual QWidget* getGui() = 0; - }; + +/** @class PluginInterface + * @brief Defines interface for a plugin instance. + * The host application uses PluginInterface interface for calling the plugins + * that extend the Host functionality +*/ +class PluginInterface : public QObject +{ +public: + /// @brief Initializes the plugin instance. + virtual void initialize(PluginHostInterface* host) = 0; + virtual QWidget* getGui() = 0; +}; } //namespace qtrapids @@ -71,59 +73,59 @@ Q_DECLARE_INTERFACE(qtrapids::PluginInterface, "com.ixonos.qtrapids.PluginInterface/1.0") Q_DECLARE_INTERFACE(qtrapids::PluginHostInterface, "com.ixonos.qtrapids.PluginHostInterface/1.0") - - + + //////////////// EXAMPLE PLUGIN DECLARATION ///////////////////////// // A simple plugin example using the PluginInterface // For more info, see Qt documentation: "How to Create Qt Plugins" // // namespace qtrapids // { -// +// // class MyPlugin : public PluginInterface { // Q_OBJECT // // NOTE: This macro tells Qt which interfaces the plugin implements (i.e. inherits): // Q_INTERFACES(qtrapids::PluginInterface) -// +// // public: // MyPlugin(); // virtual void initialize(PluginHostInterface* host); // virtual QWidget* getGui(); -// +// // // Additional plugin-specific signals and slots. -// signals: +// signals: // void searchResult(QWidget* resultwidget); -// -// private slots: +// +// private slots: // void on_button_clicked(); // void on_result(QWidget* resultWidget); -// +// // private: // }; -// +// // // MyPlugin::MyPlugin(): host_(NULL) {} -// +// // void SearchPlugin::initialize(AbstractPluginHost* host) // { // host_ = host; -// +// // if (host_ != NULL) { // QWidget *pluginWidget = new QWidget; // QVBoxLayout *vbox = new QVBoxLayout; // QPushButton *searchButton = new QPushButton("Search"); // vbox->addWidget(searchButton); // pluginWidget->setLayout(vbox); -// +// // connect(searchButton, SIGNAL(clicked()), this, SLOT(on_searchButton_clicked())); // //connect(this, SIGNAL(searchResult(QWidget*)), this, SLOT(on_searchResult(QWidget*))); -// -// // Call host interface function to set the plugin GUI. Host handles the setup +// +// // Call host interface function to set the plugin GUI. Host handles the setup // // to it's own policy // host_->setGui(pluginWidget); // } // } -// } // namespace qtrapids +// } // namespace qtrapids // //// NOTE: Remember to export the actual plugin to be visible for Qt: //// Q_EXPORT_PLUGIN2(myplugin, qtrapids::MyPlugin) diff --git a/src/plugins/searchplugin/SearchPlugin.cpp b/src/plugins/searchplugin/SearchPlugin.cpp index 656b5f9..f4ded6d 100644 --- a/src/plugins/searchplugin/SearchPlugin.cpp +++ b/src/plugins/searchplugin/SearchPlugin.cpp @@ -13,64 +13,66 @@ namespace qtrapids { - SearchPlugin::SearchPlugin() : - comboBox_(NULL), searchLine_(NULL), searchButton_(NULL), host_(NULL) - { - // TODO: Parse engine descriptions. - // -Add engines to model - // -Show model in comboBox - - } - - void SearchPlugin::initialize(PluginHostInterface* host) - { - host_ = host; - - if (host_ != NULL) { - - QWidget *pluginWidget = new QWidget; - QVBoxLayout *vbox = new QVBoxLayout; - QHBoxLayout *hbox = new QHBoxLayout; - comboBox_ = new QComboBox; - searchLine_ = new QLineEdit; - searchButton_ = new QPushButton("Search"); - - hbox->addWidget(searchLine_); - hbox->addWidget(searchButton_); - vbox->addWidget(comboBox_); - vbox->addLayout(hbox); - pluginWidget->setLayout(vbox); - - connect(searchButton_, SIGNAL(clicked()), this, SLOT(on_searchButton_clicked())); - //connect(this, SIGNAL(searchResult(QWidget*)), this, SLOT(on_searchResult(QWidget*))); - - host_->setGui(pluginWidget); - } - } - - QWidget* SearchPlugin::getGui() - { - return NULL; - } - - void SearchPlugin::on_searchButton_clicked() - { - QUrl searchUrl(QString("http://www.google.fi/search?q=" - + searchLine_->text())); - qDebug() << searchUrl; - QWebView *result = new QWebView; - result->load(searchUrl); - - on_searchResult((QWidget*)result); - } - - void SearchPlugin::on_searchResult(QWidget* resultWidget) - { - qDebug() << "on_searchResult()"; - if (host_) { - host_->addPluginWidget(resultWidget); - } - } +SearchPlugin::SearchPlugin() : + comboBox_(NULL), searchLine_(NULL), searchButton_(NULL), host_(NULL) +{ + // TODO: Parse engine descriptions. + // -Add engines to model + // -Show model in comboBox + +} + +void SearchPlugin::initialize(PluginHostInterface* host) +{ + host_ = host; + + if (host_ != NULL) + { + + QWidget *pluginWidget = new QWidget; + QVBoxLayout *vbox = new QVBoxLayout; + QHBoxLayout *hbox = new QHBoxLayout; + comboBox_ = new QComboBox; + searchLine_ = new QLineEdit; + searchButton_ = new QPushButton("Search"); + + hbox->addWidget(searchLine_); + hbox->addWidget(searchButton_); + vbox->addWidget(comboBox_); + vbox->addLayout(hbox); + pluginWidget->setLayout(vbox); + + connect(searchButton_, SIGNAL(clicked()), this, SLOT(on_searchButton_clicked())); + //connect(this, SIGNAL(searchResult(QWidget*)), this, SLOT(on_searchResult(QWidget*))); + + host_->setGui(pluginWidget); + } +} + +QWidget* SearchPlugin::getGui() +{ + return NULL; +} + +void SearchPlugin::on_searchButton_clicked() +{ + QUrl searchUrl(QString("http://www.google.fi/search?q=" + + searchLine_->text())); + qDebug() << searchUrl; + QWebView *result = new QWebView; + result->load(searchUrl); + + on_searchResult((QWidget*)result); +} + +void SearchPlugin::on_searchResult(QWidget* resultWidget) +{ + qDebug() << "on_searchResult()"; + if (host_) + { + host_->addPluginWidget(resultWidget); + } +} } // namespace qtrapids diff --git a/src/plugins/searchplugin/SearchPlugin.h b/src/plugins/searchplugin/SearchPlugin.h index 328131e..9024dee 100644 --- a/src/plugins/searchplugin/SearchPlugin.h +++ b/src/plugins/searchplugin/SearchPlugin.h @@ -14,30 +14,31 @@ class QLineEdit; namespace qtrapids { - class SearchPlugin : public PluginInterface { - Q_OBJECT - Q_INTERFACES(qtrapids::PluginInterface) - - public: - SearchPlugin(); - virtual void initialize(PluginHostInterface* host); - virtual QWidget* getGui(); - - signals: - void searchResult(QWidget* resultwidget); - - private slots: - void on_searchButton_clicked(); - void on_searchResult(QWidget* resultWidget); - - private: - QComboBox *comboBox_; - QLineEdit *searchLine_; - QPushButton *searchButton_; - PluginHostInterface* host_; - - }; - -} // namespace qtrapids +class SearchPlugin : public PluginInterface +{ + Q_OBJECT + Q_INTERFACES(qtrapids::PluginInterface) + +public: + SearchPlugin(); + virtual void initialize(PluginHostInterface* host); + virtual QWidget* getGui(); + +signals: + void searchResult(QWidget* resultwidget); + +private slots: + void on_searchButton_clicked(); + void on_searchResult(QWidget* resultWidget); + +private: + QComboBox *comboBox_; + QLineEdit *searchLine_; + QPushButton *searchButton_; + PluginHostInterface* host_; + +}; + +} // namespace qtrapids #endif \ No newline at end of file diff --git a/src/server/AlertWaiterThread.cpp b/src/server/AlertWaiterThread.cpp index f6029be..69ad8db 100644 --- a/src/server/AlertWaiterThread.cpp +++ b/src/server/AlertWaiterThread.cpp @@ -25,47 +25,51 @@ namespace qtrapids { - // Constants: - // Timeout for waiting alerts - const libtorrent::time_duration ALERT_WAIT_TIMEOUT - = libtorrent::time_duration(libtorrent::seconds(15)); +// Constants: +// Timeout for waiting alerts +const libtorrent::time_duration ALERT_WAIT_TIMEOUT += libtorrent::time_duration(libtorrent::seconds(15)); - AlertWaiterThread::AlertWaiterThread(session_t *session, QObject* parent) : - QThread(parent), - btSession_(session) - { - } +AlertWaiterThread::AlertWaiterThread(session_t *session, QObject* parent) : + QThread(parent), + btSession_(session) +{ +} - AlertWaiterThread::~AlertWaiterThread() - { - } +AlertWaiterThread::~AlertWaiterThread() +{ +} - void AlertWaiterThread::allAlerts(bool enable) +void AlertWaiterThread::allAlerts(bool enable) +{ + // If all enabled, set all alert cateogries: + if (enable) + { + btSession_->set_alert_mask(libtorrent::alert::all_categories); + } + else { - // If all enabled, set all alert cateogries: - if (enable) { - btSession_->set_alert_mask(libtorrent::alert::all_categories); - } else { - // Otherwise set to default, which is only error notifications. - btSession_->set_alert_mask(libtorrent::alert::error_notification); - } + // Otherwise set to default, which is only error notifications. + btSession_->set_alert_mask(libtorrent::alert::error_notification); } +} - void AlertWaiterThread::run() +void AlertWaiterThread::run() +{ + alert_t const *alertTemp = NULL; + while (true) { - alert_t const *alertTemp = NULL; - while (true) { - // wait_for_alert() call blocks. Returns libtorrent alert. - // Returns NULL, if no alerts in timeout period. - alertTemp = btSession_->wait_for_alert(ALERT_WAIT_TIMEOUT); - emit alert(); - // 2000 us = 2ms. Gives main thread time to handle alert signal. - usleep(2000); - } + // wait_for_alert() call blocks. Returns libtorrent alert. + // Returns NULL, if no alerts in timeout period. + alertTemp = btSession_->wait_for_alert(ALERT_WAIT_TIMEOUT); + emit alert(); + // 2000 us = 2ms. Gives main thread time to handle alert signal. + usleep(2000); } +} } diff --git a/src/server/AlertWaiterThread.hpp b/src/server/AlertWaiterThread.hpp index 9d35226..ef13a8c 100644 --- a/src/server/AlertWaiterThread.hpp +++ b/src/server/AlertWaiterThread.hpp @@ -26,29 +26,29 @@ namespace qtrapids { - /** - @author Lassi Väätämöinen - */ - class AlertWaiterThread : public QThread - { - Q_OBJECT - - public: - AlertWaiterThread(session_t *session, QObject *parent = 0); - - virtual ~AlertWaiterThread(); - - void allAlerts(bool enable = true); - - virtual void run(); // Overridden from QThread - - signals: - void alert(); - - private: - session_t *const btSession_; - - }; +/** + @author Lassi Väätämöinen +*/ +class AlertWaiterThread : public QThread +{ + Q_OBJECT + +public: + AlertWaiterThread(session_t *session, QObject *parent = 0); + + virtual ~AlertWaiterThread(); + + void allAlerts(bool enable = true); + + virtual void run(); // Overridden from QThread + +signals: + void alert(); + +private: + session_t *const btSession_; + +}; } // namespace qtrapids diff --git a/src/server/ServerDb.hpp b/src/server/ServerDb.hpp index 060bb96..fdda0a0 100644 --- a/src/server/ServerDb.hpp +++ b/src/server/ServerDb.hpp @@ -8,120 +8,125 @@ namespace qtrapids { - class ServerSettings - { +class ServerSettings +{ - public: - ServerSettings(QSettings *settings) +public: + ServerSettings(QSettings *settings) : settings_(settings) - { } + { } - ~ServerSettings() - { - - } + ~ServerSettings() + { - QString getDbEngine() const - { - return getParamAndStore("db_engine", getDefaultDbEngine()).toString(); - } + } - QString getDbName() const - { - QString default_db_path(QDir::home().filePath(appName() + ".sqlite")); - return getParamAndStore("db", default_db_path).toString(); - } + QString getDbEngine() const + { + return getParamAndStore("db_engine", getDefaultDbEngine()).toString(); + } - QString getTorrentsDir() const - { - QString default_dir(QDir::home().filePath(QString(".") + appName())); - return getParamAndStore("db", default_dir).toString(); - - } + QString getDbName() const + { + QString default_db_path(QDir::home().filePath(appName() + ".sqlite")); + return getParamAndStore("db", default_db_path).toString(); + } - private: + QString getTorrentsDir() const + { + QString default_dir(QDir::home().filePath(QString(".") + appName())); + return getParamAndStore("db", default_dir).toString(); - ServerSettings(ServerSettings const&); - ServerSettings& operator= (ServerSettings const&); + } - static inline QString appName() - { - return QCoreApplication::applicationName(); - } +private: + + ServerSettings(ServerSettings const&); + ServerSettings& operator= (ServerSettings const&); + + static inline QString appName() + { + return QCoreApplication::applicationName(); + } - static QString getDefaultDbEngine() + static QString getDefaultDbEngine() + { + // for (QStringListIterator p = QSqlDatabase::drivers(); p.hasNext();) { + // return p.next(); + // } + return "QSQLITE"; + } + + QVariant getParamAndStore(QString const& name, QVariant default_value) const + { + QVariant v(settings_->value(name)); + if (!v.isNull()) { - // for (QStringListIterator p = QSqlDatabase::drivers(); p.hasNext();) { - // return p.next(); - // } - return "QSQLITE"; + return v; } - QVariant getParamAndStore(QString const& name, QVariant default_value) const - { - QVariant v(settings_->value(name)); - if (!v.isNull()) { - return v; - } + settings_->setValue(name, default_value); + return default_value; + } - settings_->setValue(name, default_value); - return default_value; - } + mutable QSettings *settings_; +}; - mutable QSettings *settings_; - }; +class ServerDb +{ - class ServerDb +public: + ServerDb(ServerSettings *settings) + : db_(QSqlDatabase::addDatabase(settings->getDbEngine())) { + QString db_name(settings->getDbName()); + db_.setDatabaseName(db_name); - public: - ServerDb(ServerSettings *settings) - : db_(QSqlDatabase::addDatabase(settings->getDbEngine())) + if (!db_.open()) { - QString db_name(settings->getDbName()); - db_.setDatabaseName(db_name); - - if (!db_.open()) { - qDebug() << "cant open db"; - return; - } - qDebug() << "opened " << db_name; - - QSqlQuery q; - if (!q.exec("create table torrents (hash varchar primary key, path varchar, savepath varchar);\n")) { - qDebug() << "cant create table: " << q.lastError().text(); - } + qDebug() << "cant open db"; + return; } + qDebug() << "opened " << db_name; - ~ServerDb() + QSqlQuery q; + if (!q.exec("create table torrents (hash varchar primary key, path varchar, savepath varchar);\n")) { - db_.close(); + qDebug() << "cant create table: " << q.lastError().text(); } + } + + ~ServerDb() + { + db_.close(); + } - void addTorrent(const QString &hash, const QString &path, const QString &save_path) + void addTorrent(const QString &hash, const QString &path, const QString &save_path) + { + if (!db_.open()) + { + qDebug() << "cant open db"; + } + QSqlQuery query_add_; + query_add_.prepare("INSERT INTO torrents (hash, path, savepath) VALUES (?, ?, ?)"); + query_add_.bindValue(0, hash); + query_add_.bindValue(1, path); + query_add_.bindValue(2, save_path); + if (!query_add_.exec()) { - if (!db_.open()) { - qDebug() << "cant open db"; - } - QSqlQuery query_add_; - query_add_.prepare("INSERT INTO torrents (hash, path, savepath) VALUES (?, ?, ?)"); - query_add_.bindValue(0, hash); - query_add_.bindValue(1, path); - query_add_.bindValue(2, save_path); - if (!query_add_.exec()) { - qDebug() << "cant add torrent info into db: " - << query_add_.lastError().text(); - } - db_.close(); + qDebug() << "cant add torrent info into db: " + << query_add_.lastError().text(); } + db_.close(); + } - private: +private: - ServerDb(ServerDb const&); - ServerDb& operator= (ServerDb const&); + ServerDb(ServerDb const&); + ServerDb& operator= (ServerDb const&); - QSqlDatabase db_; - }; + QSqlDatabase db_; +}; } // namespace qtrapids diff --git a/src/server/TorrentHandle.cpp b/src/server/TorrentHandle.cpp index d4b5533..017d338 100644 --- a/src/server/TorrentHandle.cpp +++ b/src/server/TorrentHandle.cpp @@ -25,119 +25,122 @@ namespace qtrapids { - TorrentHandle::TorrentHandle(libtorrent::torrent_handle handle) : - torrentHandle_(handle) - { - } +TorrentHandle::TorrentHandle(libtorrent::torrent_handle handle) : + torrentHandle_(handle) +{ +} - TorrentHandle::~TorrentHandle() - { - } +TorrentHandle::~TorrentHandle() +{ +} - TorrentStatus_t TorrentHandle::status() const - { - return torrentHandle_.status(); - } +TorrentStatus_t TorrentHandle::status() const +{ + return torrentHandle_.status(); +} - torrent_info_cref TorrentHandle::getTorrentInfo() const - { - return torrentHandle_.get_torrent_info(); - } +torrent_info_cref TorrentHandle::getTorrentInfo() const +{ + return torrentHandle_.get_torrent_info(); +} - bool TorrentHandle::isValid() const - { - return torrentHandle_.is_valid(); - } +bool TorrentHandle::isValid() const +{ + return torrentHandle_.is_valid(); +} - QString TorrentHandle::name() const - { - return QString::fromStdString(torrentHandle_.name()); - } +QString TorrentHandle::name() const +{ + return QString::fromStdString(torrentHandle_.name()); +} - size_t TorrentHandle::getTotalSize() const - { - torrent_info_cref info = getTorrentInfo(); - return static_cast (info.total_size()); - } +size_t TorrentHandle::getTotalSize() const +{ + torrent_info_cref info = getTorrentInfo(); + return static_cast (info.total_size()); +} - TorrentStatus::Id TorrentHandle::state() const - { - TorrentStatus::Id s = (TorrentStatus::Id)(status().state); - return ( (s < TorrentStatus::UNSPECIFIED) - ? s : TorrentStatus::UNSPECIFIED ); - } +TorrentStatus::Id TorrentHandle::state() const +{ + TorrentStatus::Id s = (TorrentStatus::Id)(status().state); + return ( (s < TorrentStatus::UNSPECIFIED) + ? s : TorrentStatus::UNSPECIFIED ); +} - float TorrentHandle::progress() const - { - TorrentStatus_t statusTmp = status(); - return statusTmp.progress; - } +float TorrentHandle::progress() const +{ + TorrentStatus_t statusTmp = status(); + return statusTmp.progress; +} - float TorrentHandle::uploadRate() const - { - TorrentStatus_t statusTmp = status(); - return statusTmp.upload_rate; - } +float TorrentHandle::uploadRate() const +{ + TorrentStatus_t statusTmp = status(); + return statusTmp.upload_rate; +} - float TorrentHandle::downloadRate() const - { - TorrentStatus_t statusTmp = status(); - return statusTmp.download_rate; - } +float TorrentHandle::downloadRate() const +{ + TorrentStatus_t statusTmp = status(); + return statusTmp.download_rate; +} - qint32 TorrentHandle::numSeeds() const - { - TorrentStatus_t statusTmp = status(); - return statusTmp.list_seeds; - } +qint32 TorrentHandle::numSeeds() const +{ + TorrentStatus_t statusTmp = status(); + return statusTmp.list_seeds; +} - qint32 TorrentHandle::numLeeches() const - { - TorrentStatus_t statusTmp = status(); - return (statusTmp.list_peers - statusTmp.list_seeds); - } +qint32 TorrentHandle::numLeeches() const +{ + TorrentStatus_t statusTmp = status(); + return (statusTmp.list_peers - statusTmp.list_seeds); +} - qint32 TorrentHandle::ratio() const +qint32 TorrentHandle::ratio() const +{ + TorrentStatus_t statusTmp = status(); + size_t ratio; + if (statusTmp.total_payload_download == 0) { - TorrentStatus_t statusTmp = status(); - size_t ratio; - if (statusTmp.total_payload_download == 0) { - ratio = 0; - } else { - ratio = static_cast (statusTmp.total_payload_upload / statusTmp.total_payload_download); - } - - return ratio; + ratio = 0; } - - - torrent_handle_t TorrentHandle::getHandle() const + else { - return torrentHandle_; + ratio = static_cast (statusTmp.total_payload_upload / statusTmp.total_payload_download); } + return ratio; +} - bool TorrentHandle::operator==(TorrentHandle const& h) const - { - return torrentHandle_ == h.torrentHandle_; - } +torrent_handle_t TorrentHandle::getHandle() const +{ + return torrentHandle_; +} - bool TorrentHandle::operator<(TorrentHandle const& h) const - { - return torrentHandle_ < h.torrentHandle_; - } + +bool TorrentHandle::operator==(TorrentHandle const& h) const +{ + return torrentHandle_ == h.torrentHandle_; +} + + +bool TorrentHandle::operator<(TorrentHandle const& h) const +{ + return torrentHandle_ < h.torrentHandle_; +} } diff --git a/src/server/TorrentHandle.hpp b/src/server/TorrentHandle.hpp index c84c174..bf4423e 100644 --- a/src/server/TorrentHandle.hpp +++ b/src/server/TorrentHandle.hpp @@ -29,58 +29,58 @@ namespace qtrapids { - typedef libtorrent::torrent_info const& torrent_info_cref; - typedef libtorrent::torrent_handle torrent_handle_t; - typedef libtorrent::sha1_hash Sha1Hash; +typedef libtorrent::torrent_info const& torrent_info_cref; +typedef libtorrent::torrent_handle torrent_handle_t; +typedef libtorrent::sha1_hash Sha1Hash; - inline QString Hash2QStr(Sha1Hash const& hash) +inline QString Hash2QStr(Sha1Hash const& hash) +{ + return QString(hash.to_string().c_str()); +} + +/** + @author Lassi Väätämöinen +*/ +class TorrentHandle +{ +public: + + TorrentHandle(libtorrent::torrent_handle handle); + ~TorrentHandle(); + + + + torrent_info_cref getTorrentInfo() const; + + bool isValid() const; + + Sha1Hash hash() const { - return QString(hash.to_string().c_str()); + return torrentHandle_.info_hash(); } - /** - @author Lassi Väätämöinen - */ - class TorrentHandle - { - public: - - TorrentHandle(libtorrent::torrent_handle handle); - ~TorrentHandle(); - - - - torrent_info_cref getTorrentInfo() const; - - bool isValid() const; - - Sha1Hash hash() const - { - return torrentHandle_.info_hash(); - } - - QString name() const; - size_t getTotalSize() const; - TorrentStatus::Id state() const; - float progress() const; - float uploadRate() const; - float downloadRate() const; - qint32 numSeeds() const; - qint32 numLeeches() const; - qint32 ratio() const; - - torrent_handle_t getHandle() const; - bool operator==(TorrentHandle const& h) const; - bool operator<(TorrentHandle const& h) const; - - private: - TorrentHandle(); // Prevent default construct. - torrent_handle_t torrentHandle_; - - TorrentStatus_t status() const; - - }; + QString name() const; + size_t getTotalSize() const; + TorrentStatus::Id state() const; + float progress() const; + float uploadRate() const; + float downloadRate() const; + qint32 numSeeds() const; + qint32 numLeeches() const; + qint32 ratio() const; + + torrent_handle_t getHandle() const; + bool operator==(TorrentHandle const& h) const; + bool operator<(TorrentHandle const& h) const; + +private: + TorrentHandle(); // Prevent default construct. + torrent_handle_t torrentHandle_; + + TorrentStatus_t status() const; + +}; } diff --git a/src/server/TorrentSession.cpp b/src/server/TorrentSession.cpp index 531cd83..c2fb92b 100644 --- a/src/server/TorrentSession.cpp +++ b/src/server/TorrentSession.cpp @@ -8,118 +8,82 @@ namespace qtrapids - TorrentSession::TorrentSession(QObject *parent, QSettings *settings) +TorrentSession::TorrentSession(QObject *parent, QSettings *settings) : QObject(parent) , btSession_() - , alertWaiter_(new AlertWaiterThread(&btSession_, this)) - { - qDBusRegisterMetaType(); - qDBusRegisterMetaType(); - new QtRapidsServer(this); - - QDBusConnection dbus = QDBusConnection::sessionBus(); - dbus.registerObject("/qtrapids", this); - dbus.registerService("com.ixonos.qtrapids"); - - alertWaiter_->allAlerts(); - connect(alertWaiter_, SIGNAL(alert()), this, SLOT(on_alert())); - alertWaiter_->start(); + , alertWaiter_(new AlertWaiterThread(&btSession_, this)) +{ + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + new QtRapidsServer(this); + QDBusConnection dbus = QDBusConnection::sessionBus(); + dbus.registerObject("/qtrapids", this); + dbus.registerService("com.ixonos.qtrapids"); - } + alertWaiter_->allAlerts(); + connect(alertWaiter_, SIGNAL(alert()), this, SLOT(on_alert())); + alertWaiter_->start(); - void TorrentSession::on_alert() - //NOTE: al parameter not necessarily needed here, as we pop_alert() now! - { - //qDebug() << "QBittorrentSession:on_alert(" << al << ")"; - // if (al) - // qDebug() << "on_alert():" << QString::fromStdString(al->message()); +} - std::auto_ptr alertPtr = btSession_.pop_alert(); +void TorrentSession::on_alert() +//NOTE: al parameter not necessarily needed here, as we pop_alert() now! +{ - if (alertPtr.get() != NULL) { + //qDebug() << "QBittorrentSession:on_alert(" << al << ")"; + // if (al) + // qDebug() << "on_alert():" << QString::fromStdString(al->message()); - torrent_alert_t *ta = dynamic_cast (alertPtr.get()); + std::auto_ptr alertPtr = btSession_.pop_alert(); - qDebug() - << "QBittorrentSession::on_alert(): " - << QString::fromStdString(alertPtr->message()); + if (alertPtr.get() != NULL) + { + torrent_alert_t *ta = dynamic_cast (alertPtr.get()); - if (ta) { + qDebug() + << "QBittorrentSession::on_alert(): " + << QString::fromStdString(alertPtr->message()); - if (!ta->handle.is_valid()) { - qDebug() << "handle is invalid"; - return; - } - TorrentHandle handle(ta->handle); - TorrentState state; + if (ta) + { - state.hash = Hash2QStr(handle.hash()); - state.action = TorrentState::action_update; - state.state = handle.state(); - state.progress = handle.progress() * torrent_progress_max; - state.down_rate = handle.downloadRate(); - state.up_rate = handle.uploadRate(); - state.seeds = handle.numSeeds(); - state.leeches = handle.numLeeches(); - - ParamsMap_t params; - emit alert(state, params); + if (!ta->handle.is_valid()) + { + qDebug() << "handle is invalid"; + return; } - } - } - - void TorrentSession::getState() - { - torrents_t::const_iterator p; - for (p = torrents_.constBegin(); p != torrents_.constEnd(); ++p) { - TorrentHandlePtr handle = *p; + TorrentHandle handle(ta->handle); TorrentState state; - QString hash = Hash2QStr(handle->hash()); - - state.hash = hash; - state.name = handle->name(); - state.action = TorrentState::action_add; - state.state = handle->state(); - state.progress = handle->progress() * torrent_progress_max; - state.down_rate = handle->downloadRate(); - state.up_rate = handle->uploadRate(); - state.seeds = handle->numSeeds(); - state.leeches = handle->numLeeches(); - state.total_size = handle->getTotalSize(); - - emit alert(state, ParamsMap_t()); - } - } - void TorrentSession::addTorrent(const QString &path, const QString &save_path - , qtrapids::ParamsMap_t other_params) - { - add_torrent_params_t addParams; - QFile torrent_file(path); - if (!torrent_file.exists()) { - qWarning() << "Torrent file " << path << "doesn't exist"; - return; + state.hash = Hash2QStr(handle.hash()); + state.action = TorrentState::action_update; + state.state = handle.state(); + state.progress = handle.progress() * torrent_progress_max; + state.down_rate = handle.downloadRate(); + state.up_rate = handle.uploadRate(); + state.seeds = handle.numSeeds(); + state.leeches = handle.numLeeches(); + + ParamsMap_t params; + emit alert(state, params); } - qDebug() << "addTorrent: " << path << " save to " << save_path; - boost::intrusive_ptr tiTmp - = new libtorrent::torrent_info - (boost::filesystem::path(path.toStdString())); - addParams.ti = tiTmp; - - // save_path is the only mandatory parameter, rest are optional. - addParams.save_path = boost::filesystem::path(save_path.toStdString()); - //addParams.storage_mode = libtorrent::storage_mode_allocate; - - TorrentHandlePtr handle(new TorrentHandle(btSession_.add_torrent(addParams))); - QString hash = Hash2QStr(handle->hash()); + } +} +void TorrentSession::getState() +{ + torrents_t::const_iterator p; + for (p = torrents_.constBegin(); p != torrents_.constEnd(); ++p) + { + TorrentHandlePtr handle = *p; TorrentState state; + QString hash = Hash2QStr(handle->hash()); state.hash = hash; state.name = handle->name(); @@ -132,33 +96,78 @@ namespace qtrapids state.leeches = handle->numLeeches(); state.total_size = handle->getTotalSize(); - torrents_[hash] = handle; - emit alert(state, ParamsMap_t()); } +} - void TorrentSession::removeTorrent(const QString &hash) +void TorrentSession::addTorrent(const QString &path, const QString &save_path + , qtrapids::ParamsMap_t other_params) +{ + add_torrent_params_t addParams; + QFile torrent_file(path); + if (!torrent_file.exists()) { - torrents_t::iterator p = torrents_.find(hash); - - if (p == torrents_.end()) { - qDebug() << "Invalid request to remove torrent with hash " << hash; - return; - } - try { - btSession_.remove_torrent(p.value()->getHandle()); - } catch (torrent_exception_t e) { - qDebug() << // e.what() - "exception catched" - ; - } + qWarning() << "Torrent file " << path << "doesn't exist"; + return; + } - TorrentState state; - state.hash = hash; - state.action = TorrentState::action_remove; - emit alert(state, ParamsMap_t()); - torrents_.erase(p); + qDebug() << "addTorrent: " << path << " save to " << save_path; + boost::intrusive_ptr tiTmp + = new libtorrent::torrent_info + (boost::filesystem::path(path.toStdString())); + addParams.ti = tiTmp; + + // save_path is the only mandatory parameter, rest are optional. + addParams.save_path = boost::filesystem::path(save_path.toStdString()); + //addParams.storage_mode = libtorrent::storage_mode_allocate; + + TorrentHandlePtr handle(new TorrentHandle(btSession_.add_torrent(addParams))); + QString hash = Hash2QStr(handle->hash()); + + TorrentState state; + + state.hash = hash; + state.name = handle->name(); + state.action = TorrentState::action_add; + state.state = handle->state(); + state.progress = handle->progress() * torrent_progress_max; + state.down_rate = handle->downloadRate(); + state.up_rate = handle->uploadRate(); + state.seeds = handle->numSeeds(); + state.leeches = handle->numLeeches(); + state.total_size = handle->getTotalSize(); + + torrents_[hash] = handle; + + emit alert(state, ParamsMap_t()); +} + +void TorrentSession::removeTorrent(const QString &hash) +{ + torrents_t::iterator p = torrents_.find(hash); + + if (p == torrents_.end()) + { + qDebug() << "Invalid request to remove torrent with hash " << hash; + return; } + try + { + btSession_.remove_torrent(p.value()->getHandle()); + } + catch (torrent_exception_t e) + { + qDebug() << // e.what() + "exception catched" + ; + } + + TorrentState state; + state.hash = hash; + state.action = TorrentState::action_remove; + emit alert(state, ParamsMap_t()); + torrents_.erase(p); +} } // namespace qtrapids diff --git a/src/server/TorrentSession.hpp b/src/server/TorrentSession.hpp index 76b11f2..85a8c3f 100644 --- a/src/server/TorrentSession.hpp +++ b/src/server/TorrentSession.hpp @@ -21,52 +21,52 @@ class QSettings; namespace qtrapids { - typedef QWeakPointer settings_weak_ptr; +typedef QWeakPointer settings_weak_ptr; - class AlertWaiterThread; - typedef libtorrent::session session_t; - typedef libtorrent::session const* session_cptr; +class AlertWaiterThread; +typedef libtorrent::session session_t; +typedef libtorrent::session const* session_cptr; - typedef libtorrent::add_torrent_params add_torrent_params_t; - typedef libtorrent::alert alert_t; - // typedef libtorrent::alert const* alert_cptr; - typedef libtorrent::torrent_alert torrent_alert_t; - typedef libtorrent::libtorrent_exception torrent_exception_t; +typedef libtorrent::add_torrent_params add_torrent_params_t; +typedef libtorrent::alert alert_t; +// typedef libtorrent::alert const* alert_cptr; +typedef libtorrent::torrent_alert torrent_alert_t; +typedef libtorrent::libtorrent_exception torrent_exception_t; - typedef QSharedPointer TorrentHandlePtr; - typedef QHash torrents_t; +typedef QSharedPointer TorrentHandlePtr; +typedef QHash torrents_t; - class ServerDb; - class ServerSettings; +class ServerDb; +class ServerSettings; - class TorrentSession : public QObject - { +class TorrentSession : public QObject +{ - Q_OBJECT; - Q_CLASSINFO("D-Bus Interface", "com.ixonos.qtrapids"); + Q_OBJECT; + Q_CLASSINFO("D-Bus Interface", "com.ixonos.qtrapids"); - public: +public: - TorrentSession(QObject *parent, QSettings *); + TorrentSession(QObject *parent, QSettings *); - public slots: +public slots: - void getState(); - void addTorrent(const QString &path, const QString &save_path - , qtrapids::ParamsMap_t other_params); - void removeTorrent(const QString &hash); + void getState(); + void addTorrent(const QString &path, const QString &save_path + , qtrapids::ParamsMap_t other_params); + void removeTorrent(const QString &hash); - signals: - void alert(qtrapids::TorrentState info, qtrapids::ParamsMap_t other_info); +signals: + void alert(qtrapids::TorrentState info, qtrapids::ParamsMap_t other_info); - private slots: - void on_alert(); +private slots: + void on_alert(); - private: - session_t btSession_; - AlertWaiterThread *alertWaiter_; - torrents_t torrents_; - }; +private: + session_t btSession_; + AlertWaiterThread *alertWaiter_; + torrents_t torrents_; +}; } // namespace qtrapids diff --git a/src/server/main.cpp b/src/server/main.cpp index ef74cd3..9427202 100644 --- a/src/server/main.cpp +++ b/src/server/main.cpp @@ -7,13 +7,13 @@ using qtrapids::settings_weak_ptr; int main(int argc, char *argv[]) { - QCoreApplication::setOrganizationName("Ixonos"); - QCoreApplication::setOrganizationDomain("ixonos.com"); - QCoreApplication::setApplicationName("QtRapids"); + QCoreApplication::setOrganizationName("Ixonos"); + QCoreApplication::setOrganizationDomain("ixonos.com"); + QCoreApplication::setApplicationName("QtRapids"); QSettings settings(QCoreApplication::organizationName() , QCoreApplication::applicationName()); - QCoreApplication app(argc, argv); + QCoreApplication app(argc, argv); TorrentSession server(&app, &settings); return app.exec(); } -- 1.7.9.5