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 preferencesDialog_(NULL),
62 settings_(QCoreApplication::organizationName()
63 , QCoreApplication::applicationName()),
65 server_(QtRapidsServer::staticInterfaceName()
66 , "/qtrapids", QDBusConnection::sessionBus())
70 setWindowTitle("QtRapids");
73 QMenuBar *menuBar = new QMenuBar();
74 QMenu *tempMenu = NULL;
76 tempMenu = menuBar->addMenu(tr("&File"));
77 QAction *openAction = tempMenu->addAction(tr("&Open"));
78 QAction *removeAction = tempMenu->addAction(tr("&Remove"));
79 removeAction->setEnabled(false);
80 QAction *quitAction = tempMenu->addAction(tr("&Quit"));
81 QAction *stopDaemonAction = tempMenu->addAction(tr("Stop &daemon"));
84 tempMenu = menuBar->addMenu(tr("&View"));
85 QAction *columnsAction = tempMenu->addAction(tr("&Columns"));
87 tempMenu = menuBar->addMenu(tr("&Settings"));
88 QAction *preferencesAction = tempMenu->addAction(tr("&Preferences"));
90 tempMenu = menuBar->addMenu(tr("&Help"));
91 QAction *aboutAction = tempMenu->addAction(tr("&About"));
92 QAction *aboutQtAction = tempMenu->addAction(tr("About &Qt"));
95 connect(openAction, SIGNAL(triggered()), this, SLOT(on_openAction_clicked()));
96 connect(removeAction, SIGNAL(triggered()), this, SLOT(on_removeAction_clicked()));
97 connect(this, SIGNAL(itemSelected(bool)), removeAction, SLOT(setEnabled(bool)));
98 connect(quitAction, SIGNAL(triggered()), this, SLOT(on_quitAction_clicked()));
99 connect(stopDaemonAction, SIGNAL(triggered()), this, SLOT(on_stopDaemonAction_clicked()));
100 connect(columnsAction, SIGNAL(triggered()), this, SLOT(on_columnsAction_clicked()));
101 connect(preferencesAction, SIGNAL(triggered()), this, SLOT(on_preferencesAction_clicked()));
102 connect(aboutAction, SIGNAL(triggered()), this, SLOT(on_aboutAction_clicked()));
103 connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(on_aboutQtAction_clicked()));
105 // TABWIDGET (central widget)
106 tabWidget_ = new QTabWidget();
107 tabWidget_->setTabsClosable(true);
109 /// @todo Exception handling
110 dlView_ = new DownloadView(this);
111 seedView_ = new SeedView(this);
112 tabWidget_->addTab(dlView_, tr("Downloads"));
113 tabWidget_->addTab(seedView_, tr("Seeds"));
114 connect(dlView_, SIGNAL(itemSelectionChanged()), this,
115 SLOT(on_downloadItemSelectionChanged()));
117 connect(seedView_, SIGNAL(itemSelectionChanged()), this,
118 SLOT(on_seedItemSelectionChanged()));
120 // Tab widget as central widget.
121 setCentralWidget(tabWidget_);
124 QToolBar *toolBar = new QToolBar();
125 toolBar->addAction(tr("Open"));
126 removeAction = toolBar->addAction(tr("Remove"));
127 removeAction->setEnabled(false);
128 addToolBar(Qt::TopToolBarArea, toolBar);
130 connect(this, SIGNAL(itemSelected(bool)), removeAction,
131 SLOT(setEnabled(bool)));
132 connect(toolBar, SIGNAL(actionTriggered(QAction*)), this,
133 SLOT(handleToolBarAction(QAction*)));
134 connect (tabWidget_, SIGNAL(tabCloseRequested(int)), this, SLOT(on_tabWidget_tabCloseRequested(int)));
136 connect(&server_, SIGNAL(alert(qtrapids::TorrentState, qtrapids::ParamsMap_t)),
137 this, SLOT(on_alert(qtrapids::TorrentState, qtrapids::ParamsMap_t)));
139 // connect(&btSession_, SIGNAL(alert(std::auto_ptr<Alert>)),
140 // this, SLOT(on_alert(std::auto_ptr<Alert>)));
148 MainWindow::~MainWindow()
150 settings_.setValue("geometry", saveGeometry());
153 // ===================== Implements PluginInterface =========================
154 /// @todo add PluginInterface parameter to request plugin name
155 bool MainWindow::setGui(QWidget* widget, PluginWidgetType type, qtrapids::PluginInterface* plugin)
157 #ifdef QTRAPIDS_DEBUG
158 qDebug() << "MainWindow::setGui():" << dlView_->currentItem();
161 if (plugin && plugin->identifier() == "SearchPlugin") {
162 searchWidget_ = widget;
167 tabWidget_->addTab(widget, tr("Search"));
171 /// @todo Add PluginInterface parameter to check which plugin gives the widget, to handle appropriately
172 void MainWindow::addPluginWidget(QWidget* widget, PluginWidgetType type)
174 #ifdef QTRAPIDS_DEBUG
175 qDebug() << "MainWindow::addPluginWidget():" << dlView_->currentItem();
178 if (type == qtrapids::PluginHostInterface::TAB_PAGE) {
179 int index = tabWidget_->addTab(widget, tr("Results"));
180 tabWidget_->setCurrentIndex(index);
181 //layout_->addWidget(widget);
184 void MainWindow::addToolbar(QWidget* widget, PluginWidgetType type)
188 void MainWindow::addToolItem(QWidget* widget, PluginWidgetType type)
192 void MainWindow::addMenu(QWidget* widget, PluginWidgetType type)
196 void MainWindow::addMenuItem(QWidget* widget, PluginWidgetType type)
200 bool MainWindow::eventRequest(QVariant param, PluginRequest req)
202 if (req == qtrapids::PluginHostInterface::OPEN_FILE) {
203 QString sourceFile = param.toString();
205 // Get the source files name from the full path:
206 QFileInfo fInfo(sourceFile);
207 QString targetFile = fInfo.fileName();
208 targetFile = settings_.value("download/directory").toString() + "/" + targetFile;
210 // Copy temoporary file to Downloads directory...
211 if (!QFile::copy(sourceFile, targetFile)) {
212 qDebug() << "File copying failed";
215 // If copying was successful, remove the original temporary file.
216 QFile::remove(sourceFile);
219 /// @todo Torrent bencoding validity should be checked before starting(?)
220 // ...and start the torrent:
221 on_torrentFileSelected(targetFile);
223 } else if (req == qtrapids::PluginHostInterface::READ_BUFFER) {
224 // Create torrent information from char* buffer and start.
225 StartTorrentFromBufferData(param.toByteArray().constData(), param.toByteArray().size());
232 //=========================== PRIVATE ================================
234 void MainWindow::LoadPlugins()
236 // Get plugin directories from
237 QStringList pluginDirsTmp = settings_.value("plugins/path").toStringList();
238 QStringList nameFilters("*.so");
240 /// @todo enable "application directory" for plugin search in development/debug mode only. In release version
241 /// search plugins directory under $HOME/.qtrapids or system library paths
242 pluginDirsTmp << qApp->applicationDirPath();
243 pluginDirsTmp.removeDuplicates();
245 foreach (QString dir, pluginDirsTmp) {
246 pluginDirs_.append(QDir(dir));
249 foreach (QDir dir, pluginDirs_) {
251 if (dir.cd(PLUGINS_DIR)) {
253 foreach (QString fileName, dir.entryList(nameFilters, QDir::Files)) {
254 QPluginLoader pluginLoader(dir.absoluteFilePath(fileName));
256 // If plugin not loaded from another directory, then load
257 if (!pluginFileNames_.contains(fileName) && QLibrary::isLibrary(fileName)) {
259 if (pluginLoader.load()) {
260 qDebug() << "Plugin loaded: " << fileName;
262 qWarning() << "Plugin load failed: " << pluginLoader.errorString();
265 QObject *baseInstance = pluginLoader.instance();
267 qDebug() << "Base instance = NULL.";
270 qtrapids::PluginInterface *plugin = qobject_cast<qtrapids::PluginInterface*>(baseInstance);
273 qDebug() << "Cast failed.";
275 qtrapids::PluginInterface::Info info;
276 info.directory = dir.path();
277 qDebug() << dir.path();
278 plugin->initialize(this, info);
279 pluginFileNames_ += fileName;
282 qWarning() << "Plugin "
284 << " already loaded from another directory, or not a valid library file";
289 qWarning() << PLUGINS_DIR << "directory not accessible or does not exist in " << dir.path();
295 void MainWindow::RestoreSettings()
298 // Restore previous main window geometry:
299 QVariant geometry(settings_.value("geometry"));
300 if (!geometry.isNull()) {
301 qDebug() << "restoring geometry";
302 restoreGeometry(geometry.toByteArray());
305 // Restore DownloadView columns:
306 dlView_->restoreView();
308 // Restore torrent session settings to server:
309 qtrapids::ParamsMap_t options;
310 options["net/downloadRate"] = settings_.value("net/downloadRate").toString();
311 options["net/uploadRate"] = settings_.value("net/uploadRate").toString();
312 server_.setOptions(options);
316 // Opens torrent information from buffer data and adds torrent to session
317 void MainWindow::StartTorrentFromBufferData(char const* data, int size)
322 // =========================== PRIVATE SLOTS =================================
323 void MainWindow::on_openAction_clicked()
325 QFileDialog *dialog = new QFileDialog( this, "Open torrent file", QString(), tr("Torrent files (*.torrent)"));
326 dialog->setFileMode(QFileDialog::ExistingFile);
327 connect(dialog, SIGNAL(fileSelected(const QString&)), this, SLOT(on_torrentFileSelected(const QString&)));
332 void MainWindow::on_removeAction_clicked()
334 QString hash = dlView_->prepareRemoveSelected();
336 server_.removeTorrent(hash);
338 qDebug() << "Exception while removing torrent";
343 void MainWindow::on_quitAction_clicked()
349 void MainWindow::on_stopDaemonAction_clicked()
351 server_.terminateSession();
355 void MainWindow::on_columnsAction_clicked()
357 ColumnSelectorDialog *dialog = new ColumnSelectorDialog(dlView_);
361 // dialog->activateWindow();
362 qDebug() << "dialog exit";
364 if (dialog->result() == QDialog::Accepted) {
371 void MainWindow::on_preferencesAction_clicked()
373 if (!preferencesDialog_) {
374 preferencesDialog_ = new PreferencesDialog(this, 0, &server_);
377 preferencesDialog_->show();
378 preferencesDialog_->raise();
379 preferencesDialog_->activateWindow();
383 void MainWindow::on_aboutAction_clicked()
385 QMessageBox::about(this, tr("About QtRapids"), ABOUT_TEXT);
389 void MainWindow::on_aboutQtAction_clicked()
391 QMessageBox::aboutQt (this, tr("About Qt"));
395 void MainWindow::on_tabWidget_tabCloseRequested(int index)
398 int searchWidgetIndex = tabWidget_->indexOf(searchWidget_);
400 // Allow closing other tabs than the first two
401 // TODO The first two may well be closable, just add "show tabs" action for these in the menu
402 if (index != 0 && index != 1 && index != searchWidgetIndex) {
403 QWidget *remove = tabWidget_->widget(index);
404 tabWidget_->removeTab(index);
411 void MainWindow::on_downloadItemSelectionChanged()
413 #ifdef QTRAPIDS_DEBUG
414 qDebug() << "MainWindow::on_seedItemSelectionChanged():" << dlView_->currentItem();
416 if (dlView_->currentItem() != NULL) {
417 emit(itemSelected(true));
419 emit(itemSelected(false));
424 void MainWindow::on_seedItemSelectionChanged()
426 #ifdef QTRAPIDS_DEBUG
427 qDebug() << "MainWindow::on_seedItemSelectionChanged():" << seedView_->currentItem();
429 if (seedView_->currentItem() != NULL) {
430 emit(itemSelected(true));
432 emit(itemSelected(false));
437 void MainWindow::handleToolBarAction(QAction* action)
439 if (action->text() == "Open") {
440 on_openAction_clicked();
441 } else if (action->text() == "Remove") {
442 on_removeAction_clicked();
447 void MainWindow::on_torrentFileSelected(const QString& file)
449 #ifdef QTRAPIDS_DEBUG
450 qDebug() << " MainWindow::on_torrentFileSelected(): " << file;
452 // Torrent filename empty, do nothing.
457 // Otherwise add torrent
458 // For params, see: http://www.rasterbar.com/products/libtorrent/manual.html#add-torrent
459 // save_path is the only mandatory parameter, rest are optional.
460 //addParams.storage_mode = libtorrent::storage_mode_allocate;
462 server_.addTorrent(file, settings_.value("download/directory").toString()
465 qDebug() << "Exception adding torrent";
470 void MainWindow::on_alert(qtrapids::TorrentState info, qtrapids::ParamsMap_t other_info)
472 #ifdef QTRAPIDS_DEBUG
473 qDebug() << "got alert";
475 dlView_->updateItem(info, other_info);
478 } // namespace qtrapids