221ac603a28e2360c47c2ce924e7f43f9c5aa4cc
[qtrapids] / src / client / MainWindow.cpp
1 /***************************************************************************
2  *   Copyright (C) 2009 by Lassi Väätämöinen   *
3  *   lassi.vaatamoinen@ixonos.com   *
4  *                                                                         *
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.                                   *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21
22 #include <qtrapids/dbus.hpp>
23
24 #include <QDebug>
25 #include <QtGui/QMenuBar>
26 #include <QtGui/QToolBar>
27 #include <QAction>
28 #include <QFileDialog>
29 #include <QMessageBox>
30 //#include <QTreeWidgetItem>
31 #include <QApplication>
32 #include <QPluginLoader>
33
34 #include "DownloadView.h"
35 #include "SeedView.h"
36 #include "PreferencesDialog.h"
37 #include "ColumnSelectorDialog.h"
38
39 #include "MainWindow.h"
40
41 namespace qtrapids
42 {
43
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"));
51
52 const QString PLUGINS_DIR = "plugins";
53
54 // Consturctor
55 MainWindow::MainWindow() :
56                 QMainWindow(), // Superclass
57                 tabWidget_(NULL),
58                 dlView_(NULL),
59                 seedView_(NULL),
60                 searchWidget_(NULL),
61                 preferencesDialog_(NULL),
62                 settings_(QCoreApplication::organizationName()
63                           , QCoreApplication::applicationName()),
64                 pluginDirs_(),
65                 server_(QtRapidsServer::staticInterfaceName()
66                         , "/qtrapids", QDBusConnection::sessionBus())
67                 //      torrentHandles_(),
68 {
69         // MENUBAR
70         QMenuBar *menuBar = new QMenuBar();
71         QMenu *tempMenu = NULL;
72
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
79         tempMenu = menuBar->addMenu(tr("&View"));
80         QAction *columnsAction = tempMenu->addAction(tr("&Columns"));
81         
82         tempMenu = menuBar->addMenu(tr("&Settings"));
83         QAction *preferencesAction = tempMenu->addAction(tr("&Preferences"));
84
85         tempMenu = menuBar->addMenu(tr("&Help"));
86         QAction *aboutAction = tempMenu->addAction(tr("&About"));
87         QAction *aboutQtAction = tempMenu->addAction(tr("About &Qt"));
88
89         setMenuBar(menuBar);
90         connect(openAction, SIGNAL(triggered()), this, SLOT(on_openAction_clicked()));
91         connect(removeAction, SIGNAL(triggered()), this, SLOT(on_removeAction_clicked()));
92         connect(this, SIGNAL(itemSelected(bool)), removeAction, SLOT(setEnabled(bool)));
93         connect(quitAction, SIGNAL(triggered()), this, SLOT(on_quitAction_clicked()));
94         connect(columnsAction, SIGNAL(triggered()), this, SLOT(on_columnsAction_clicked()));
95         connect(preferencesAction, SIGNAL(triggered()), this, SLOT(on_preferencesAction_clicked()));
96         connect(aboutAction, SIGNAL(triggered()), this, SLOT(on_aboutAction_clicked()));
97         connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(on_aboutQtAction_clicked()));
98
99         // TABWIDGET (central widget)
100         tabWidget_ = new QTabWidget();
101         tabWidget_->setTabsClosable(true);
102
103         /// @todo Exception handling
104         dlView_ = new DownloadView(this);
105         seedView_ = new SeedView(this);
106         tabWidget_->addTab(dlView_, tr("Downloads"));
107         tabWidget_->addTab(seedView_, tr("Seeds"));
108         connect(dlView_, SIGNAL(itemSelectionChanged()), this,
109                 SLOT(on_downloadItemSelectionChanged()));
110
111         connect(seedView_, SIGNAL(itemSelectionChanged()), this,
112                 SLOT(on_seedItemSelectionChanged()));
113
114         // Tab widget as central widget.
115         setCentralWidget(tabWidget_);
116
117         // TOOLBAR
118         QToolBar *toolBar = new QToolBar();
119         toolBar->addAction(tr("Open"));
120         removeAction = toolBar->addAction(tr("Remove"));
121         removeAction->setEnabled(false);
122         addToolBar(Qt::TopToolBarArea, toolBar);
123
124         connect(this, SIGNAL(itemSelected(bool)), removeAction,
125                 SLOT(setEnabled(bool)));
126         connect(toolBar, SIGNAL(actionTriggered(QAction*)), this,
127                 SLOT(handleToolBarAction(QAction*)));
128         connect (tabWidget_, SIGNAL(tabCloseRequested(int)), this, SLOT(on_tabWidget_tabCloseRequested(int)));
129
130         connect(&server_, SIGNAL(alert(qtrapids::TorrentState, qtrapids::ParamsMap_t)), 
131                                         this, SLOT(on_alert(qtrapids::TorrentState, qtrapids::ParamsMap_t)));
132                                         
133 //      connect(&btSession_, SIGNAL(alert(std::auto_ptr<Alert>)),
134 //              this, SLOT(on_alert(std::auto_ptr<Alert>)));
135
136
137         LoadPlugins();
138
139 }
140
141
142 MainWindow::~MainWindow()
143 {
144         settings_.setValue("geometry", saveGeometry());
145 }
146
147 // ===================== Implements PluginInterface =========================
148 /// @todo add PluginInterface parameter to request plugin name 
149 bool MainWindow::setGui(QWidget* widget, PluginWidgetType type, qtrapids::PluginInterface* plugin)
150 {
151 #ifdef QTRAPIDS_DEBUG
152         qDebug() << "MainWindow::setGui():" << dlView_->currentItem();
153 #endif
154
155         if (plugin && plugin->identifier() == "SearchPlugin") {
156                 searchWidget_ = widget;
157         } else {
158                 return false;
159         }
160         
161         tabWidget_->addTab(widget, tr("Search"));
162         return true;
163 }
164
165 /// @todo Add PluginInterface parameter to check which plugin gives the widget, to handle appropriately
166 void MainWindow::addPluginWidget(QWidget* widget, PluginWidgetType type)
167 {
168 #ifdef QTRAPIDS_DEBUG
169         qDebug() << "MainWindow::addPluginWidget():" << dlView_->currentItem();
170 #endif
171
172         if (type == qtrapids::PluginHostInterface::TAB_PAGE) {
173                 int index = tabWidget_->addTab(widget, tr("Results"));
174                 tabWidget_->setCurrentIndex(index);
175                 //layout_->addWidget(widget);
176         }
177 }
178 void MainWindow::addToolbar(QWidget* widget, PluginWidgetType type)
179 {
180 }
181
182 void MainWindow::addToolItem(QWidget* widget, PluginWidgetType type)
183 {
184 }
185
186 void MainWindow::addMenu(QWidget* widget, PluginWidgetType type)
187 {
188 }
189
190 void MainWindow::addMenuItem(QWidget* widget, PluginWidgetType type)
191 {
192 }
193
194 bool MainWindow::eventRequest(QVariant param, PluginRequest req)
195 {
196         if (req == qtrapids::PluginHostInterface::OPEN_FILE) {
197                 QString sourceFile = param.toString();
198                 
199                 // Get the source files name from the full path:
200                 QFileInfo fInfo(sourceFile);
201                 QString targetFile = fInfo.fileName();
202                 targetFile = settings_.value("download/directory").toString() + "/" + targetFile;
203                 
204                 // Copy temoporary file to Downloads directory...
205                 if (!QFile::copy(sourceFile, targetFile)) {
206                         qDebug() << "File copying failed";
207                         return false;
208                 } else {
209                         // If copying was successful, remove the original temporary file.
210                         QFile::remove(sourceFile);
211                 }
212                 
213                 /// @todo Torrent bencoding validity should be checked before starting(?)
214                 // ...and start the torrent:
215                 on_torrentFileSelected(targetFile);
216         
217         } else if (req == qtrapids::PluginHostInterface::READ_BUFFER) {
218                 // Create torrent information from char* buffer and start.
219                 StartTorrentFromBufferData(param.toByteArray().constData(), param.toByteArray().size());
220         }
221         
222         return true;
223 }
224
225
226 //=========================== PRIVATE ================================
227
228 void MainWindow::LoadPlugins()
229 {
230         // Get plugin directories from 
231         QStringList pluginDirsTmp = settings_.value("plugins/path").toStringList();
232         QStringList nameFilters("*.so");
233         
234         /// @todo enable "application directory" for plugin search in development/debug mode only. In release version
235         /// search plugins directory under $HOME/.qtrapids or system library paths
236         pluginDirsTmp << qApp->applicationDirPath();
237         pluginDirsTmp.removeDuplicates();
238         
239         foreach (QString dir, pluginDirsTmp) {
240                 pluginDirs_.append(QDir(dir));
241         }
242         
243         foreach (QDir dir, pluginDirs_) {
244                 
245                 if (dir.cd(PLUGINS_DIR)) {
246                         
247                         foreach (QString fileName, dir.entryList(nameFilters, QDir::Files)) {
248                                 QPluginLoader pluginLoader(dir.absoluteFilePath(fileName));
249
250                                 // If plugin not loaded from another directory, then load
251                                 if (!pluginFileNames_.contains(fileName) && QLibrary::isLibrary(fileName)) {
252
253                                         if (pluginLoader.load()) {
254                                                 qDebug() << "Plugin loaded: "  << fileName;
255                                         } else {
256                                                 qWarning() << "Plugin load failed: " << pluginLoader.errorString();
257                                         }
258
259                                         QObject *baseInstance = pluginLoader.instance();
260                                         if (!baseInstance) {
261                                                 qDebug() << "Base instance = NULL.";
262                                         }
263
264                                         qtrapids::PluginInterface *plugin = qobject_cast<qtrapids::PluginInterface*>(baseInstance);
265
266                                         if (!plugin) {
267                                                 qDebug() << "Cast failed.";
268                                         } else {
269                                                 qtrapids::PluginInterface::Info info;
270                                                 info.directory = dir.path();
271                                                 qDebug() << dir.path();
272                                                 plugin->initialize(this, info);
273                                                 pluginFileNames_ += fileName;
274                                         }
275                                 } else {
276                                         qWarning() << "Plugin " 
277                                                 << fileName 
278                                                 << " already loaded from another directory, or not a valid library file";
279                                 }
280                         }
281                         
282                 } else {
283                         qWarning() << PLUGINS_DIR <<  "directory not accessible or does not exist in "  << dir.path();
284                 }
285         }
286 }
287
288
289 void MainWindow::RestoreSettings()
290 {
291         
292         // Restore previous main window geometry:
293         QVariant geometry(settings_.value("geometry"));
294         if (!geometry.isNull()) {
295                 qDebug() << "restoring geometry";
296                 restoreGeometry(geometry.toByteArray());
297         }
298         
299         // Restore DownloadView columns:
300         dlView_->restoreView();
301         
302         // Restore torrent session settings to server:
303         qtrapids::ParamsMap_t options;
304         options["net/downloadRate"] = settings_.value("net/downloadRate").toString();
305         options["net/uploadRate"] = settings_.value("net/uploadRate").toString();
306         server_.setOptions(options);
307 }
308
309
310 // Opens torrent information from buffer data and adds torrent to session 
311 void MainWindow::StartTorrentFromBufferData(char const* data, int size)
312 {
313
314 }
315
316 // =========================== PRIVATE SLOTS =================================
317 void MainWindow::on_openAction_clicked()
318 {
319         QFileDialog *dialog = new QFileDialog( this, "Open torrent file", QString(), tr("Torrent files (*.torrent)"));
320         dialog->setFileMode(QFileDialog::ExistingFile);
321         connect(dialog, SIGNAL(fileSelected(const QString&)), this, SLOT(on_torrentFileSelected(const QString&)));
322         dialog->show();
323
324 }
325
326 void MainWindow::on_removeAction_clicked()
327 {
328         QString hash = dlView_->prepareRemoveSelected();
329         try {
330                 server_.removeTorrent(hash);
331         } catch (...) {
332                 qDebug() << "Exception while removing torrent";
333         }
334 }
335
336
337 void MainWindow::on_quitAction_clicked()
338 {
339         close();
340 }
341
342
343 void MainWindow::on_columnsAction_clicked()
344 {       
345         ColumnSelectorDialog *dialog = new ColumnSelectorDialog(dlView_);
346         dialog->show();
347         dialog->exec();
348 //      dialog->raise();
349 //      dialog->activateWindow();
350         qDebug() << "dialog exit";
351
352         if (dialog->result() == QDialog::Accepted) {
353         qDebug() << "saved";
354                 dlView_->saveView();
355         }
356 }
357
358
359 void MainWindow::on_preferencesAction_clicked()
360 {
361         if (!preferencesDialog_) {
362                 preferencesDialog_ = new PreferencesDialog(this, 0, &server_);
363         }
364
365         preferencesDialog_->show();
366         preferencesDialog_->raise();
367         preferencesDialog_->activateWindow();
368 }
369
370
371 void MainWindow::on_aboutAction_clicked()
372 {
373         QMessageBox::about(this, tr("About QtRapids"), ABOUT_TEXT);
374 }
375
376
377 void MainWindow::on_aboutQtAction_clicked()
378 {
379         QMessageBox::aboutQt (this, tr("About Qt"));
380 }
381
382
383 void MainWindow::on_tabWidget_tabCloseRequested(int index)
384 {
385         
386         int searchWidgetIndex = tabWidget_->indexOf(searchWidget_);
387         
388         // Allow closing other tabs than the first two
389         // TODO The first two may well be closable, just add "show tabs" action for these in the menu
390         if (index != 0 && index != 1 && index != searchWidgetIndex) {
391                 QWidget *remove = tabWidget_->widget(index);
392                 tabWidget_->removeTab(index);
393                 delete remove;
394                 remove = NULL;
395         }
396 }
397
398
399 void MainWindow::on_downloadItemSelectionChanged()
400 {
401 #ifdef QTRAPIDS_DEBUG
402         qDebug() << "MainWindow::on_seedItemSelectionChanged():" << dlView_->currentItem();
403 #endif
404         if (dlView_->currentItem() != NULL) {
405                 emit(itemSelected(true));
406         } else {
407                 emit(itemSelected(false));
408         }
409 }
410
411
412 void MainWindow::on_seedItemSelectionChanged()
413 {
414 #ifdef QTRAPIDS_DEBUG
415         qDebug() << "MainWindow::on_seedItemSelectionChanged():" << seedView_->currentItem();
416 #endif
417         if (seedView_->currentItem() != NULL) {
418                 emit(itemSelected(true));
419         } else {
420                 emit(itemSelected(false));
421         }
422 }
423
424
425 void MainWindow::handleToolBarAction(QAction* action)
426 {
427         if (action->text() == "Open") {
428                 on_openAction_clicked();
429         } else if (action->text() == "Remove") {
430                 on_removeAction_clicked();
431         }
432 }
433
434
435 void MainWindow::on_torrentFileSelected(const QString& file)
436 {
437 #ifdef QTRAPIDS_DEBUG
438         qDebug() << " MainWindow::on_torrentFileSelected(): " << file;
439 #endif
440         // Torrent filename empty, do nothing.
441         if (file == "") {
442                 return;
443         }
444
445         // Otherwise add torrent
446         // For params, see: http://www.rasterbar.com/products/libtorrent/manual.html#add-torrent
447         // save_path is the only mandatory parameter, rest are optional.
448         //addParams.storage_mode = libtorrent::storage_mode_allocate;
449         try {
450                 server_.addTorrent(file, settings_.value("download/directory").toString()
451                                    , ParamsMap_t());
452         } catch (...) {
453                 qDebug() << "Exception adding torrent";
454         }
455 }
456
457
458 void MainWindow::on_alert(qtrapids::TorrentState info, qtrapids::ParamsMap_t other_info)
459 {
460 #ifdef QTRAPIDS_DEBUG
461         qDebug() << "got alert";
462 #endif
463         dlView_->updateItem(info, other_info);
464 }
465
466 } // namespace qtrapids