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 QMenuBar *menuBar = new QMenuBar();
71 QMenu *tempMenu = NULL;
73 tempMenu = menuBar->addMenu(tr("&File"));
74 QAction *openAction = tempMenu->addAction(tr("&Open"));
75 QAction *removeAction = tempMenu->addAction(tr("&Remove"));
76 removeAction->setEnabled(false);
77 QAction *quitAction = tempMenu->addAction(tr("&Quit"));
78 QAction *stopDaemonAction = tempMenu->addAction(tr("Stop &daemon"));
81 tempMenu = menuBar->addMenu(tr("&View"));
82 QAction *columnsAction = tempMenu->addAction(tr("&Columns"));
84 tempMenu = menuBar->addMenu(tr("&Settings"));
85 QAction *preferencesAction = tempMenu->addAction(tr("&Preferences"));
87 tempMenu = menuBar->addMenu(tr("&Help"));
88 QAction *aboutAction = tempMenu->addAction(tr("&About"));
89 QAction *aboutQtAction = tempMenu->addAction(tr("About &Qt"));
92 connect(openAction, SIGNAL(triggered()), this, SLOT(on_openAction_clicked()));
93 connect(removeAction, SIGNAL(triggered()), this, SLOT(on_removeAction_clicked()));
94 connect(this, SIGNAL(itemSelected(bool)), removeAction, SLOT(setEnabled(bool)));
95 connect(quitAction, SIGNAL(triggered()), this, SLOT(on_quitAction_clicked()));
96 connect(stopDaemonAction, SIGNAL(triggered()), this, SLOT(on_stopDaemonAction_clicked()));
97 connect(columnsAction, SIGNAL(triggered()), this, SLOT(on_columnsAction_clicked()));
98 connect(preferencesAction, SIGNAL(triggered()), this, SLOT(on_preferencesAction_clicked()));
99 connect(aboutAction, SIGNAL(triggered()), this, SLOT(on_aboutAction_clicked()));
100 connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(on_aboutQtAction_clicked()));
102 // TABWIDGET (central widget)
103 tabWidget_ = new QTabWidget();
104 tabWidget_->setTabsClosable(true);
106 /// @todo Exception handling
107 dlView_ = new DownloadView(this);
108 seedView_ = new SeedView(this);
109 tabWidget_->addTab(dlView_, tr("Downloads"));
110 tabWidget_->addTab(seedView_, tr("Seeds"));
111 connect(dlView_, SIGNAL(itemSelectionChanged()), this,
112 SLOT(on_downloadItemSelectionChanged()));
114 connect(seedView_, SIGNAL(itemSelectionChanged()), this,
115 SLOT(on_seedItemSelectionChanged()));
117 // Tab widget as central widget.
118 setCentralWidget(tabWidget_);
121 QToolBar *toolBar = new QToolBar();
122 toolBar->addAction(tr("Open"));
123 removeAction = toolBar->addAction(tr("Remove"));
124 removeAction->setEnabled(false);
125 addToolBar(Qt::TopToolBarArea, toolBar);
127 connect(this, SIGNAL(itemSelected(bool)), removeAction,
128 SLOT(setEnabled(bool)));
129 connect(toolBar, SIGNAL(actionTriggered(QAction*)), this,
130 SLOT(handleToolBarAction(QAction*)));
131 connect (tabWidget_, SIGNAL(tabCloseRequested(int)), this, SLOT(on_tabWidget_tabCloseRequested(int)));
133 connect(&server_, SIGNAL(alert(qtrapids::TorrentState, qtrapids::ParamsMap_t)),
134 this, SLOT(on_alert(qtrapids::TorrentState, qtrapids::ParamsMap_t)));
136 // connect(&btSession_, SIGNAL(alert(std::auto_ptr<Alert>)),
137 // this, SLOT(on_alert(std::auto_ptr<Alert>)));
145 MainWindow::~MainWindow()
147 settings_.setValue("geometry", saveGeometry());
150 // ===================== Implements PluginInterface =========================
151 /// @todo add PluginInterface parameter to request plugin name
152 bool MainWindow::setGui(QWidget* widget, PluginWidgetType type, qtrapids::PluginInterface* plugin)
154 #ifdef QTRAPIDS_DEBUG
155 qDebug() << "MainWindow::setGui():" << dlView_->currentItem();
158 if (plugin && plugin->identifier() == "SearchPlugin") {
159 searchWidget_ = widget;
164 tabWidget_->addTab(widget, tr("Search"));
168 /// @todo Add PluginInterface parameter to check which plugin gives the widget, to handle appropriately
169 void MainWindow::addPluginWidget(QWidget* widget, PluginWidgetType type)
171 #ifdef QTRAPIDS_DEBUG
172 qDebug() << "MainWindow::addPluginWidget():" << dlView_->currentItem();
175 if (type == qtrapids::PluginHostInterface::TAB_PAGE) {
176 int index = tabWidget_->addTab(widget, tr("Results"));
177 tabWidget_->setCurrentIndex(index);
178 //layout_->addWidget(widget);
181 void MainWindow::addToolbar(QWidget* widget, PluginWidgetType type)
185 void MainWindow::addToolItem(QWidget* widget, PluginWidgetType type)
189 void MainWindow::addMenu(QWidget* widget, PluginWidgetType type)
193 void MainWindow::addMenuItem(QWidget* widget, PluginWidgetType type)
197 bool MainWindow::eventRequest(QVariant param, PluginRequest req)
199 if (req == qtrapids::PluginHostInterface::OPEN_FILE) {
200 QString sourceFile = param.toString();
202 // Get the source files name from the full path:
203 QFileInfo fInfo(sourceFile);
204 QString targetFile = fInfo.fileName();
205 targetFile = settings_.value("download/directory").toString() + "/" + targetFile;
207 // Copy temoporary file to Downloads directory...
208 if (!QFile::copy(sourceFile, targetFile)) {
209 qDebug() << "File copying failed";
212 // If copying was successful, remove the original temporary file.
213 QFile::remove(sourceFile);
216 /// @todo Torrent bencoding validity should be checked before starting(?)
217 // ...and start the torrent:
218 on_torrentFileSelected(targetFile);
220 } else if (req == qtrapids::PluginHostInterface::READ_BUFFER) {
221 // Create torrent information from char* buffer and start.
222 StartTorrentFromBufferData(param.toByteArray().constData(), param.toByteArray().size());
229 //=========================== PRIVATE ================================
231 void MainWindow::LoadPlugins()
233 // Get plugin directories from
234 QStringList pluginDirsTmp = settings_.value("plugins/path").toStringList();
235 QStringList nameFilters("*.so");
237 /// @todo enable "application directory" for plugin search in development/debug mode only. In release version
238 /// search plugins directory under $HOME/.qtrapids or system library paths
239 pluginDirsTmp << qApp->applicationDirPath();
240 pluginDirsTmp.removeDuplicates();
242 foreach (QString dir, pluginDirsTmp) {
243 pluginDirs_.append(QDir(dir));
246 foreach (QDir dir, pluginDirs_) {
248 if (dir.cd(PLUGINS_DIR)) {
250 foreach (QString fileName, dir.entryList(nameFilters, QDir::Files)) {
251 QPluginLoader pluginLoader(dir.absoluteFilePath(fileName));
253 // If plugin not loaded from another directory, then load
254 if (!pluginFileNames_.contains(fileName) && QLibrary::isLibrary(fileName)) {
256 if (pluginLoader.load()) {
257 qDebug() << "Plugin loaded: " << fileName;
259 qWarning() << "Plugin load failed: " << pluginLoader.errorString();
262 QObject *baseInstance = pluginLoader.instance();
264 qDebug() << "Base instance = NULL.";
267 qtrapids::PluginInterface *plugin = qobject_cast<qtrapids::PluginInterface*>(baseInstance);
270 qDebug() << "Cast failed.";
272 qtrapids::PluginInterface::Info info;
273 info.directory = dir.path();
274 qDebug() << dir.path();
275 plugin->initialize(this, info);
276 pluginFileNames_ += fileName;
279 qWarning() << "Plugin "
281 << " already loaded from another directory, or not a valid library file";
286 qWarning() << PLUGINS_DIR << "directory not accessible or does not exist in " << dir.path();
292 void MainWindow::RestoreSettings()
295 // Restore previous main window geometry:
296 QVariant geometry(settings_.value("geometry"));
297 if (!geometry.isNull()) {
298 qDebug() << "restoring geometry";
299 restoreGeometry(geometry.toByteArray());
302 // Restore DownloadView columns:
303 dlView_->restoreView();
305 // Restore torrent session settings to server:
306 qtrapids::ParamsMap_t options;
307 options["net/downloadRate"] = settings_.value("net/downloadRate").toString();
308 options["net/uploadRate"] = settings_.value("net/uploadRate").toString();
309 server_.setOptions(options);
313 // Opens torrent information from buffer data and adds torrent to session
314 void MainWindow::StartTorrentFromBufferData(char const* data, int size)
319 // =========================== PRIVATE SLOTS =================================
320 void MainWindow::on_openAction_clicked()
322 QFileDialog *dialog = new QFileDialog( this, "Open torrent file", QString(), tr("Torrent files (*.torrent)"));
323 dialog->setFileMode(QFileDialog::ExistingFile);
324 connect(dialog, SIGNAL(fileSelected(const QString&)), this, SLOT(on_torrentFileSelected(const QString&)));
329 void MainWindow::on_removeAction_clicked()
331 QString hash = dlView_->prepareRemoveSelected();
333 server_.removeTorrent(hash);
335 qDebug() << "Exception while removing torrent";
340 void MainWindow::on_quitAction_clicked()
346 void MainWindow::on_stopDaemonAction_clicked()
348 server_.terminateSession();
352 void MainWindow::on_columnsAction_clicked()
354 ColumnSelectorDialog *dialog = new ColumnSelectorDialog(dlView_);
358 // dialog->activateWindow();
359 qDebug() << "dialog exit";
361 if (dialog->result() == QDialog::Accepted) {
368 void MainWindow::on_preferencesAction_clicked()
370 if (!preferencesDialog_) {
371 preferencesDialog_ = new PreferencesDialog(this, 0, &server_);
374 preferencesDialog_->show();
375 preferencesDialog_->raise();
376 preferencesDialog_->activateWindow();
380 void MainWindow::on_aboutAction_clicked()
382 QMessageBox::about(this, tr("About QtRapids"), ABOUT_TEXT);
386 void MainWindow::on_aboutQtAction_clicked()
388 QMessageBox::aboutQt (this, tr("About Qt"));
392 void MainWindow::on_tabWidget_tabCloseRequested(int index)
395 int searchWidgetIndex = tabWidget_->indexOf(searchWidget_);
397 // Allow closing other tabs than the first two
398 // TODO The first two may well be closable, just add "show tabs" action for these in the menu
399 if (index != 0 && index != 1 && index != searchWidgetIndex) {
400 QWidget *remove = tabWidget_->widget(index);
401 tabWidget_->removeTab(index);
408 void MainWindow::on_downloadItemSelectionChanged()
410 #ifdef QTRAPIDS_DEBUG
411 qDebug() << "MainWindow::on_seedItemSelectionChanged():" << dlView_->currentItem();
413 if (dlView_->currentItem() != NULL) {
414 emit(itemSelected(true));
416 emit(itemSelected(false));
421 void MainWindow::on_seedItemSelectionChanged()
423 #ifdef QTRAPIDS_DEBUG
424 qDebug() << "MainWindow::on_seedItemSelectionChanged():" << seedView_->currentItem();
426 if (seedView_->currentItem() != NULL) {
427 emit(itemSelected(true));
429 emit(itemSelected(false));
434 void MainWindow::handleToolBarAction(QAction* action)
436 if (action->text() == "Open") {
437 on_openAction_clicked();
438 } else if (action->text() == "Remove") {
439 on_removeAction_clicked();
444 void MainWindow::on_torrentFileSelected(const QString& file)
446 #ifdef QTRAPIDS_DEBUG
447 qDebug() << " MainWindow::on_torrentFileSelected(): " << file;
449 // Torrent filename empty, do nothing.
454 // Otherwise add torrent
455 // For params, see: http://www.rasterbar.com/products/libtorrent/manual.html#add-torrent
456 // save_path is the only mandatory parameter, rest are optional.
457 //addParams.storage_mode = libtorrent::storage_mode_allocate;
459 server_.addTorrent(file, settings_.value("download/directory").toString()
462 qDebug() << "Exception adding torrent";
467 void MainWindow::on_alert(qtrapids::TorrentState info, qtrapids::ParamsMap_t other_info)
469 #ifdef QTRAPIDS_DEBUG
470 qDebug() << "got alert";
472 dlView_->updateItem(info, other_info);
475 } // namespace qtrapids