1 /***************************************************************************
2 * Copyright (C) 2009 by Lassi Väätämöinen *
3 * lassi.vaatamoinen@ixonos.com *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
22 #include <qtrapids/dbus.hpp>
25 #include <QtGui/QMenuBar>
26 #include <QtGui/QToolBar>
28 #include <QFileDialog>
29 #include <QMessageBox>
30 //#include <QTreeWidgetItem>
31 #include <QApplication>
32 #include <QPluginLoader>
34 #include "DownloadView.h"
36 #include "PreferencesDialog.h"
37 #include "ColumnSelectorDialog.h"
39 #include "MainWindow.h"
44 const QString ABOUT_TEXT
45 = QString(QObject::trUtf8("QtRapids, a simple BitTorrent client based on"
46 "\nQt and Libtorrent."
47 "\n\nURL: http://qtrapids.garage.maemo.org/"
48 "\n\nAuthors:\nLassi Väätämöinen, lassi.vaatamoinen@ixonos.com"
49 "\nDenis Zalevskiy, denis.zalewsky@gmail.com"
50 "\n\nIxonos Plc, Finland\n"));
52 const QString PLUGINS_DIR = "plugins";
55 MainWindow::MainWindow() :
56 QMainWindow(), // Superclass
61 startDaemonAction_(NULL),
62 stopDaemonAction_(NULL),
63 preferencesDialog_(NULL),
64 settings_(QCoreApplication::organizationName()
65 , QCoreApplication::applicationName()),
67 server_(QtRapidsServer::staticInterfaceName()
68 , "/qtrapids", QDBusConnection::sessionBus())
72 setWindowTitle("QtRapids");
75 QMenuBar *menuBar = new QMenuBar();
76 QMenu *tempMenu = NULL;
78 tempMenu = menuBar->addMenu(tr("&File"));
79 QAction *openAction = tempMenu->addAction(tr("&Open"));
80 QAction *removeAction = tempMenu->addAction(tr("&Remove"));
81 removeAction->setEnabled(false);
83 startDaemonAction_ = tempMenu->addAction(tr("S&tart daemon"));
84 stopDaemonAction_ = tempMenu->addAction(tr("Sto&p daemon"));
85 startDaemonAction_->setEnabled(false);
87 QAction *quitAction = tempMenu->addAction(tr("&Quit"));
89 tempMenu = menuBar->addMenu(tr("&View"));
90 QAction *columnsAction = tempMenu->addAction(tr("&Columns"));
92 tempMenu = menuBar->addMenu(tr("&Settings"));
93 QAction *preferencesAction = tempMenu->addAction(tr("&Preferences"));
95 tempMenu = menuBar->addMenu(tr("&Help"));
96 QAction *aboutAction = tempMenu->addAction(tr("&About"));
97 QAction *aboutQtAction = tempMenu->addAction(tr("About &Qt"));
100 connect(openAction, SIGNAL(triggered()), this, SLOT(on_openAction_clicked()));
101 connect(removeAction, SIGNAL(triggered()), this, SLOT(on_removeAction_clicked()));
102 connect(this, SIGNAL(itemSelected(bool)), removeAction, SLOT(setEnabled(bool)));
103 connect(quitAction, SIGNAL(triggered()), this, SLOT(on_quitAction_clicked()));
104 connect(startDaemonAction_, SIGNAL(triggered()), this, SLOT(on_startDaemonAction_clicked()));
105 connect(stopDaemonAction_, SIGNAL(triggered()), this, SLOT(on_stopDaemonAction_clicked()));
106 connect(columnsAction, SIGNAL(triggered()), this, SLOT(on_columnsAction_clicked()));
107 connect(preferencesAction, SIGNAL(triggered()), this, SLOT(on_preferencesAction_clicked()));
108 connect(aboutAction, SIGNAL(triggered()), this, SLOT(on_aboutAction_clicked()));
109 connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(on_aboutQtAction_clicked()));
111 // TABWIDGET (central widget)
112 tabWidget_ = new QTabWidget();
113 tabWidget_->setTabsClosable(true);
115 /// @todo Exception handling
116 dlView_ = new DownloadView(this);
117 seedView_ = new SeedView(this);
118 tabWidget_->addTab(dlView_, tr("Downloads"));
119 tabWidget_->addTab(seedView_, tr("Seeds"));
120 connect(dlView_, SIGNAL(itemSelectionChanged()), this,
121 SLOT(on_downloadItemSelectionChanged()));
123 connect(seedView_, SIGNAL(itemSelectionChanged()), this,
124 SLOT(on_seedItemSelectionChanged()));
126 // Tab widget as central widget.
127 setCentralWidget(tabWidget_);
130 QToolBar *toolBar = new QToolBar();
131 toolBar->addAction(tr("Open"));
132 removeAction = toolBar->addAction(tr("Remove"));
133 removeAction->setEnabled(false);
134 addToolBar(Qt::BottomToolBarArea, toolBar);
136 connect(this, SIGNAL(itemSelected(bool)), removeAction,
137 SLOT(setEnabled(bool)));
138 connect(toolBar, SIGNAL(actionTriggered(QAction*)), this,
139 SLOT(handleToolBarAction(QAction*)));
140 connect (tabWidget_, SIGNAL(tabCloseRequested(int)), this, SLOT(on_tabWidget_tabCloseRequested(int)));
142 connect(&server_, SIGNAL(alert(qtrapids::TorrentState, qtrapids::ParamsMap_t)),
143 this, SLOT(on_alert(qtrapids::TorrentState, qtrapids::ParamsMap_t)));
145 connect(&server_, SIGNAL(sessionTerminated()), this, SLOT(on_serverTerminated()));
147 // connect(&btSession_, SIGNAL(alert(std::auto_ptr<Alert>)),
148 // this, SLOT(on_alert(std::auto_ptr<Alert>)));
156 MainWindow::~MainWindow()
158 settings_.setValue("geometry", saveGeometry());
161 // ===================== Implements PluginInterface =========================
162 /// @todo add PluginInterface parameter to request plugin name
163 bool MainWindow::setGui(QWidget* widget, PluginWidgetType type, qtrapids::PluginInterface* plugin)
165 #ifdef QTRAPIDS_DEBUG
166 qDebug() << "MainWindow::setGui():" << dlView_->currentItem();
169 if (plugin && plugin->identifier() == "SearchPlugin") {
170 searchWidget_ = widget;
175 tabWidget_->addTab(widget, tr("Search"));
179 /// @todo Add PluginInterface parameter to check which plugin gives the widget, to handle appropriately
180 void MainWindow::addPluginWidget(QWidget* widget, PluginWidgetType type)
182 #ifdef QTRAPIDS_DEBUG
183 qDebug() << "MainWindow::addPluginWidget():" << dlView_->currentItem();
186 if (type == qtrapids::PluginHostInterface::TAB_PAGE) {
187 int index = tabWidget_->addTab(widget, tr("Results"));
188 tabWidget_->setCurrentIndex(index);
189 //layout_->addWidget(widget);
192 void MainWindow::addToolbar(QWidget* widget, PluginWidgetType type)
196 void MainWindow::addToolItem(QWidget* widget, PluginWidgetType type)
200 void MainWindow::addMenu(QWidget* widget, PluginWidgetType type)
204 void MainWindow::addMenuItem(QWidget* widget, PluginWidgetType type)
208 bool MainWindow::eventRequest(QVariant param, PluginRequest req)
210 if (req == qtrapids::PluginHostInterface::OPEN_FILE) {
211 QString sourceFile = param.toString();
213 // Get the source files name from the full path:
214 QFileInfo fInfo(sourceFile);
215 QString targetFile = fInfo.fileName();
216 targetFile = settings_.value("download/directory").toString() + "/" + targetFile;
218 // Copy temoporary file to Downloads directory...
219 if (!QFile::copy(sourceFile, targetFile)) {
220 qDebug() << "File copying failed";
223 // If copying was successful, remove the original temporary file.
224 QFile::remove(sourceFile);
227 /// @todo Torrent bencoding validity should be checked before starting(?)
228 // ...and start the torrent:
229 on_torrentFileSelected(targetFile);
231 } else if (req == qtrapids::PluginHostInterface::READ_BUFFER) {
232 // Create torrent information from char* buffer and start.
233 StartTorrentFromBufferData(param.toByteArray().constData(), param.toByteArray().size());
240 //=========================== PRIVATE ================================
242 void MainWindow::LoadPlugins()
244 // Get plugin directories from
245 QStringList pluginDirsTmp = settings_.value("plugins/path").toStringList();
246 QStringList nameFilters("*.so");
248 /// @todo enable "application directory" for plugin search in development/debug mode only. In release version
249 /// search plugins directory under $HOME/.qtrapids or system library paths
250 pluginDirsTmp << qApp->applicationDirPath();
251 pluginDirsTmp.removeDuplicates();
253 foreach (QString dir, pluginDirsTmp) {
254 pluginDirs_.append(QDir(dir));
257 foreach (QDir dir, pluginDirs_) {
259 if (dir.cd(PLUGINS_DIR)) {
261 foreach (QString fileName, dir.entryList(nameFilters, QDir::Files)) {
262 QPluginLoader pluginLoader(dir.absoluteFilePath(fileName));
264 // If plugin not loaded from another directory, then load
265 if (!pluginFileNames_.contains(fileName) && QLibrary::isLibrary(fileName)) {
267 if (pluginLoader.load()) {
268 qDebug() << "Plugin loaded: " << fileName;
270 qWarning() << "Plugin load failed: " << pluginLoader.errorString();
273 QObject *baseInstance = pluginLoader.instance();
275 qDebug() << "Base instance = NULL.";
278 qtrapids::PluginInterface *plugin = qobject_cast<qtrapids::PluginInterface*>(baseInstance);
281 qDebug() << "Cast failed.";
283 qtrapids::PluginInterface::Info info;
284 info.directory = dir.path();
285 qDebug() << dir.path();
286 plugin->initialize(this, info);
287 pluginFileNames_ += fileName;
290 qWarning() << "Plugin "
292 << " already loaded from another directory, or not a valid library file";
297 qWarning() << PLUGINS_DIR << "directory not accessible or does not exist in " << dir.path();
303 void MainWindow::RestoreSettings()
306 // Restore previous main window geometry:
307 QVariant geometry(settings_.value("geometry"));
308 if (!geometry.isNull()) {
309 qDebug() << "restoring geometry";
310 restoreGeometry(geometry.toByteArray());
313 // Restore DownloadView columns:
314 dlView_->restoreView();
316 // Restore torrent session settings to server:
317 qtrapids::ParamsMap_t options;
318 options["net/downloadRate"] = settings_.value("net/downloadRate").toString();
319 options["net/uploadRate"] = settings_.value("net/uploadRate").toString();
320 server_.setOptions(options);
324 // Opens torrent information from buffer data and adds torrent to session
325 void MainWindow::StartTorrentFromBufferData(char const* data, int size)
330 // =========================== PRIVATE SLOTS =================================
331 void MainWindow::on_openAction_clicked()
333 QString filename = QFileDialog::getOpenFileName( this, tr("Open torrent file"), QString(), tr("Torrent files (*.torrent)") );
334 on_torrentFileSelected(filename);
336 QFileDialog *dialog = new QFileDialog( this, "Open torrent file", QString(), tr("Torrent files (*.torrent)"));
337 dialog->setFileMode(QFileDialog::ExistingFile);
338 connect(dialog, SIGNAL(fileSelected(const QString&)), this, SLOT(on_torrentFileSelected(const QString&)));
343 void MainWindow::on_removeAction_clicked()
345 QString hash = dlView_->prepareRemoveSelected();
347 server_.removeTorrent(hash);
349 qDebug() << "Exception while removing torrent";
354 void MainWindow::on_quitAction_clicked()
360 void MainWindow::on_startDaemonAction_clicked()
363 /// @todo create signal that signals server startup and
364 /// enable controls in the handler slot
365 stopDaemonAction_->setEnabled(true);
366 startDaemonAction_->setEnabled(false);
370 void MainWindow::on_stopDaemonAction_clicked()
372 server_.terminateSession();
376 void MainWindow::on_serverTerminated()
378 stopDaemonAction_->setEnabled(false);
379 startDaemonAction_->setEnabled(true);
382 void MainWindow::on_columnsAction_clicked()
384 ColumnSelectorDialog *dialog = new ColumnSelectorDialog(dlView_);
388 // dialog->activateWindow();
389 qDebug() << "dialog exit";
391 if (dialog->result() == QDialog::Accepted) {
398 void MainWindow::on_preferencesAction_clicked()
400 if (!preferencesDialog_) {
401 preferencesDialog_ = new PreferencesDialog(this, 0, &server_);
404 preferencesDialog_->show();
405 preferencesDialog_->raise();
406 preferencesDialog_->activateWindow();
410 void MainWindow::on_aboutAction_clicked()
412 QMessageBox::about(this, tr("About QtRapids"), ABOUT_TEXT);
416 void MainWindow::on_aboutQtAction_clicked()
418 QMessageBox::aboutQt (this, tr("About Qt"));
422 void MainWindow::on_tabWidget_tabCloseRequested(int index)
425 int searchWidgetIndex = tabWidget_->indexOf(searchWidget_);
427 // Allow closing other tabs than the first two
428 // TODO The first two may well be closable, just add "show tabs" action for these in the menu
429 if (index != 0 && index != 1 && index != searchWidgetIndex) {
430 QWidget *remove = tabWidget_->widget(index);
431 tabWidget_->removeTab(index);
438 void MainWindow::on_downloadItemSelectionChanged()
440 #ifdef QTRAPIDS_DEBUG
441 qDebug() << "MainWindow::on_seedItemSelectionChanged():" << dlView_->currentItem();
443 if (dlView_->currentItem() != NULL) {
444 emit(itemSelected(true));
446 emit(itemSelected(false));
451 void MainWindow::on_seedItemSelectionChanged()
453 #ifdef QTRAPIDS_DEBUG
454 qDebug() << "MainWindow::on_seedItemSelectionChanged():" << seedView_->currentItem();
456 if (seedView_->currentItem() != NULL) {
457 emit(itemSelected(true));
459 emit(itemSelected(false));
464 void MainWindow::handleToolBarAction(QAction* action)
466 if (action->text() == "Open") {
467 on_openAction_clicked();
468 } else if (action->text() == "Remove") {
469 on_removeAction_clicked();
474 void MainWindow::on_torrentFileSelected(QString file)
476 #ifdef QTRAPIDS_DEBUG
477 qDebug() << " MainWindow::on_torrentFileSelected(): " << file;
479 // Torrent filename empty, do nothing.
484 // Otherwise add torrent
485 // For params, see: http://www.rasterbar.com/products/libtorrent/manual.html#add-torrent
486 // save_path is the only mandatory parameter, rest are optional.
487 //addParams.storage_mode = libtorrent::storage_mode_allocate;
489 server_.addTorrent(file, settings_.value("download/directory").toString()
492 qDebug() << "Exception adding torrent";
497 void MainWindow::on_alert(qtrapids::TorrentState info, qtrapids::ParamsMap_t other_info)
499 #ifdef QTRAPIDS_DEBUG
500 qDebug() << "got alert";
502 dlView_->updateItem(info, other_info);
505 } // namespace qtrapids