- Fixed KineticScrolling due to Qt 4.6.1 changes.
[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         
70         setWindowTitle("QtRapids");
71         
72         // MENUBAR
73         QMenuBar *menuBar = new QMenuBar();
74         QMenu *tempMenu = NULL;
75
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"));
82         
83
84         tempMenu = menuBar->addMenu(tr("&View"));
85         QAction *columnsAction = tempMenu->addAction(tr("&Columns"));
86         
87         tempMenu = menuBar->addMenu(tr("&Settings"));
88         QAction *preferencesAction = tempMenu->addAction(tr("&Preferences"));
89
90         tempMenu = menuBar->addMenu(tr("&Help"));
91         QAction *aboutAction = tempMenu->addAction(tr("&About"));
92         QAction *aboutQtAction = tempMenu->addAction(tr("About &Qt"));
93
94         setMenuBar(menuBar);
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()));
104
105         // TABWIDGET (central widget)
106         tabWidget_ = new QTabWidget();
107         tabWidget_->setTabsClosable(true);
108
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()));
116
117         connect(seedView_, SIGNAL(itemSelectionChanged()), this,
118                 SLOT(on_seedItemSelectionChanged()));
119
120         // Tab widget as central widget.
121         setCentralWidget(tabWidget_);
122
123         // TOOLBAR
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);
129
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)));
135
136         connect(&server_, SIGNAL(alert(qtrapids::TorrentState, qtrapids::ParamsMap_t)), 
137                                         this, SLOT(on_alert(qtrapids::TorrentState, qtrapids::ParamsMap_t)));
138                                         
139 //      connect(&btSession_, SIGNAL(alert(std::auto_ptr<Alert>)),
140 //              this, SLOT(on_alert(std::auto_ptr<Alert>)));
141
142
143         LoadPlugins();
144
145 }
146
147
148 MainWindow::~MainWindow()
149 {
150         settings_.setValue("geometry", saveGeometry());
151 }
152
153 // ===================== Implements PluginInterface =========================
154 /// @todo add PluginInterface parameter to request plugin name 
155 bool MainWindow::setGui(QWidget* widget, PluginWidgetType type, qtrapids::PluginInterface* plugin)
156 {
157 #ifdef QTRAPIDS_DEBUG
158         qDebug() << "MainWindow::setGui():" << dlView_->currentItem();
159 #endif
160
161         if (plugin && plugin->identifier() == "SearchPlugin") {
162                 searchWidget_ = widget;
163         } else {
164                 return false;
165         }
166         
167         tabWidget_->addTab(widget, tr("Search"));
168         return true;
169 }
170
171 /// @todo Add PluginInterface parameter to check which plugin gives the widget, to handle appropriately
172 void MainWindow::addPluginWidget(QWidget* widget, PluginWidgetType type)
173 {
174 #ifdef QTRAPIDS_DEBUG
175         qDebug() << "MainWindow::addPluginWidget():" << dlView_->currentItem();
176 #endif
177
178         if (type == qtrapids::PluginHostInterface::TAB_PAGE) {
179                 int index = tabWidget_->addTab(widget, tr("Results"));
180                 tabWidget_->setCurrentIndex(index);
181                 //layout_->addWidget(widget);
182         }
183 }
184 void MainWindow::addToolbar(QWidget* widget, PluginWidgetType type)
185 {
186 }
187
188 void MainWindow::addToolItem(QWidget* widget, PluginWidgetType type)
189 {
190 }
191
192 void MainWindow::addMenu(QWidget* widget, PluginWidgetType type)
193 {
194 }
195
196 void MainWindow::addMenuItem(QWidget* widget, PluginWidgetType type)
197 {
198 }
199
200 bool MainWindow::eventRequest(QVariant param, PluginRequest req)
201 {
202         if (req == qtrapids::PluginHostInterface::OPEN_FILE) {
203                 QString sourceFile = param.toString();
204                 
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;
209                 
210                 // Copy temoporary file to Downloads directory...
211                 if (!QFile::copy(sourceFile, targetFile)) {
212                         qDebug() << "File copying failed";
213                         return false;
214                 } else {
215                         // If copying was successful, remove the original temporary file.
216                         QFile::remove(sourceFile);
217                 }
218                 
219                 /// @todo Torrent bencoding validity should be checked before starting(?)
220                 // ...and start the torrent:
221                 on_torrentFileSelected(targetFile);
222         
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());
226         }
227         
228         return true;
229 }
230
231
232 //=========================== PRIVATE ================================
233
234 void MainWindow::LoadPlugins()
235 {
236         // Get plugin directories from 
237         QStringList pluginDirsTmp = settings_.value("plugins/path").toStringList();
238         QStringList nameFilters("*.so");
239         
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();
244         
245         foreach (QString dir, pluginDirsTmp) {
246                 pluginDirs_.append(QDir(dir));
247         }
248         
249         foreach (QDir dir, pluginDirs_) {
250                 
251                 if (dir.cd(PLUGINS_DIR)) {
252                         
253                         foreach (QString fileName, dir.entryList(nameFilters, QDir::Files)) {
254                                 QPluginLoader pluginLoader(dir.absoluteFilePath(fileName));
255
256                                 // If plugin not loaded from another directory, then load
257                                 if (!pluginFileNames_.contains(fileName) && QLibrary::isLibrary(fileName)) {
258
259                                         if (pluginLoader.load()) {
260                                                 qDebug() << "Plugin loaded: "  << fileName;
261                                         } else {
262                                                 qWarning() << "Plugin load failed: " << pluginLoader.errorString();
263                                         }
264
265                                         QObject *baseInstance = pluginLoader.instance();
266                                         if (!baseInstance) {
267                                                 qDebug() << "Base instance = NULL.";
268                                         }
269
270                                         qtrapids::PluginInterface *plugin = qobject_cast<qtrapids::PluginInterface*>(baseInstance);
271
272                                         if (!plugin) {
273                                                 qDebug() << "Cast failed.";
274                                         } else {
275                                                 qtrapids::PluginInterface::Info info;
276                                                 info.directory = dir.path();
277                                                 qDebug() << dir.path();
278                                                 plugin->initialize(this, info);
279                                                 pluginFileNames_ += fileName;
280                                         }
281                                 } else {
282                                         qWarning() << "Plugin " 
283                                                 << fileName 
284                                                 << " already loaded from another directory, or not a valid library file";
285                                 }
286                         }
287                         
288                 } else {
289                         qWarning() << PLUGINS_DIR <<  "directory not accessible or does not exist in "  << dir.path();
290                 }
291         }
292 }
293
294
295 void MainWindow::RestoreSettings()
296 {
297         
298         // Restore previous main window geometry:
299         QVariant geometry(settings_.value("geometry"));
300         if (!geometry.isNull()) {
301                 qDebug() << "restoring geometry";
302                 restoreGeometry(geometry.toByteArray());
303         }
304         
305         // Restore DownloadView columns:
306         dlView_->restoreView();
307         
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);
313 }
314
315
316 // Opens torrent information from buffer data and adds torrent to session 
317 void MainWindow::StartTorrentFromBufferData(char const* data, int size)
318 {
319
320 }
321
322 // =========================== PRIVATE SLOTS =================================
323 void MainWindow::on_openAction_clicked()
324 {
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&)));
328         dialog->show();
329
330 }
331
332 void MainWindow::on_removeAction_clicked()
333 {
334         QString hash = dlView_->prepareRemoveSelected();
335         try {
336                 server_.removeTorrent(hash);
337         } catch (...) {
338                 qDebug() << "Exception while removing torrent";
339         }
340 }
341
342
343 void MainWindow::on_quitAction_clicked()
344 {
345         close();
346 }
347
348
349 void MainWindow::on_stopDaemonAction_clicked()
350 {
351         server_.terminateSession();
352 }
353
354
355 void MainWindow::on_columnsAction_clicked()
356 {       
357         ColumnSelectorDialog *dialog = new ColumnSelectorDialog(dlView_);
358         dialog->show();
359         dialog->exec();
360 //      dialog->raise();
361 //      dialog->activateWindow();
362         qDebug() << "dialog exit";
363
364         if (dialog->result() == QDialog::Accepted) {
365         qDebug() << "saved";
366                 dlView_->saveView();
367         }
368 }
369
370
371 void MainWindow::on_preferencesAction_clicked()
372 {
373         if (!preferencesDialog_) {
374                 preferencesDialog_ = new PreferencesDialog(this, 0, &server_);
375         }
376
377         preferencesDialog_->show();
378         preferencesDialog_->raise();
379         preferencesDialog_->activateWindow();
380 }
381
382
383 void MainWindow::on_aboutAction_clicked()
384 {
385         QMessageBox::about(this, tr("About QtRapids"), ABOUT_TEXT);
386 }
387
388
389 void MainWindow::on_aboutQtAction_clicked()
390 {
391         QMessageBox::aboutQt (this, tr("About Qt"));
392 }
393
394
395 void MainWindow::on_tabWidget_tabCloseRequested(int index)
396 {
397         
398         int searchWidgetIndex = tabWidget_->indexOf(searchWidget_);
399         
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);
405                 delete remove;
406                 remove = NULL;
407         }
408 }
409
410
411 void MainWindow::on_downloadItemSelectionChanged()
412 {
413 #ifdef QTRAPIDS_DEBUG
414         qDebug() << "MainWindow::on_seedItemSelectionChanged():" << dlView_->currentItem();
415 #endif
416         if (dlView_->currentItem() != NULL) {
417                 emit(itemSelected(true));
418         } else {
419                 emit(itemSelected(false));
420         }
421 }
422
423
424 void MainWindow::on_seedItemSelectionChanged()
425 {
426 #ifdef QTRAPIDS_DEBUG
427         qDebug() << "MainWindow::on_seedItemSelectionChanged():" << seedView_->currentItem();
428 #endif
429         if (seedView_->currentItem() != NULL) {
430                 emit(itemSelected(true));
431         } else {
432                 emit(itemSelected(false));
433         }
434 }
435
436
437 void MainWindow::handleToolBarAction(QAction* action)
438 {
439         if (action->text() == "Open") {
440                 on_openAction_clicked();
441         } else if (action->text() == "Remove") {
442                 on_removeAction_clicked();
443         }
444 }
445
446
447 void MainWindow::on_torrentFileSelected(const QString& file)
448 {
449 #ifdef QTRAPIDS_DEBUG
450         qDebug() << " MainWindow::on_torrentFileSelected(): " << file;
451 #endif
452         // Torrent filename empty, do nothing.
453         if (file == "") {
454                 return;
455         }
456
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;
461         try {
462                 server_.addTorrent(file, settings_.value("download/directory").toString()
463                                    , ParamsMap_t());
464         } catch (...) {
465                 qDebug() << "Exception adding torrent";
466         }
467 }
468
469
470 void MainWindow::on_alert(qtrapids::TorrentState info, qtrapids::ParamsMap_t other_info)
471 {
472 #ifdef QTRAPIDS_DEBUG
473         qDebug() << "got alert";
474 #endif
475         dlView_->updateItem(info, other_info);
476 }
477
478 } // namespace qtrapids