- SearchPlugin checks for Content-type -header, so now it is able to download
[qtrapids] / src / gui / 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 <QDebug>
23
24 #include <QMenuBar>
25 #include <QToolBar>
26 #include <QAction>
27 #include <QFileDialog>
28 #include <QMessageBox>
29 #include <QApplication>
30 #include <QPluginLoader>
31
32 #include "DownloadView.h"
33 #include "SeedView.h"
34 #include "PreferencesDialog.h"
35
36 #include "MainWindow.h"
37
38 const QString ABOUT_TEXT
39 = QString(QObject::trUtf8("QtRapids, a simple BitTorrent client based on"
40                           "\nQt and Libtorrent."
41                           "\n\nURL: http://qtrapids.garage.maemo.org/"
42                           "\n\nAuthors:\nLassi Väätämöinen, lassi.vaatamoinen@ixonos.com"
43                           "\nDenis Zalevskiy, denis.zalewsky@ixonos.com"
44                           "\n\nIxonos Plc, Finland\n"));
45
46 const QString PLUGINS_DIR = "plugins";
47
48 // Consturctor
49 MainWindow::MainWindow():
50                 QMainWindow(), // Superclass
51                 tabWidget_(NULL),
52                 dlView_(NULL),
53                 seedView_(NULL),
54                 preferencesDialog_(NULL),
55                 settings_(),
56                 pluginDirs_(),
57 //      torrentHandles_(),
58                 btSession_()
59 {
60         // MENUBAR
61         QMenuBar *menuBar = new QMenuBar();
62         QMenu *tempMenu = NULL;
63
64         tempMenu = menuBar->addMenu(tr("&File"));
65         QAction *openAction = tempMenu->addAction(tr("&Open"));
66         QAction *removeAction = tempMenu->addAction(tr("&Remove"));
67         removeAction->setEnabled(false);
68         QAction *quitAction = tempMenu->addAction(tr("&Quit"));
69
70         tempMenu = menuBar->addMenu(tr("&Settings"));
71         QAction *preferencesAction = tempMenu->addAction(tr("&Preferences"));
72
73         tempMenu = menuBar->addMenu(tr("&Help"));
74         QAction *aboutAction = tempMenu->addAction(tr("&About"));
75         QAction *aboutQtAction = tempMenu->addAction(tr("About &Qt"));
76
77         setMenuBar(menuBar);
78         connect(openAction, SIGNAL(triggered()), this, SLOT(on_openAction_clicked()));
79         connect(removeAction, SIGNAL(triggered()), this, SLOT(on_removeAction_clicked()));
80         connect(this, SIGNAL(itemSelected(bool)), removeAction, SLOT(setEnabled(bool)));
81         connect(quitAction, SIGNAL(triggered()), this, SLOT(on_quitAction_clicked()));
82         connect(preferencesAction, SIGNAL(triggered()), this, SLOT(on_preferencesAction_clicked()));
83         connect(aboutAction, SIGNAL(triggered()), this, SLOT(on_aboutAction_clicked()));
84         connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(on_aboutQtAction_clicked()));
85
86         // TABWIDGET (central widget)
87         tabWidget_ = new QTabWidget();
88         tabWidget_->setTabsClosable(true);
89
90         /// @todo Exception handling
91         dlView_ = new DownloadView(this);
92         seedView_ = new SeedView(this);
93         tabWidget_->addTab(dlView_, tr("Downloads"));
94         tabWidget_->addTab(seedView_, tr("Seeds"));
95         connect(dlView_, SIGNAL(itemSelectionChanged()), this,
96                 SLOT(on_downloadItemSelectionChanged()));
97         connect(seedView_, SIGNAL(itemSelectionChanged()), this,
98                 SLOT(on_seedItemSelectionChanged()));
99
100
101         // Tab widget as central widget.
102         setCentralWidget(tabWidget_);
103
104         // TOOLBAR
105         QToolBar *toolBar = new QToolBar();
106         toolBar->addAction(tr("Open"));
107         removeAction = toolBar->addAction(tr("Remove"));
108         removeAction->setEnabled(false);
109         addToolBar(Qt::TopToolBarArea, toolBar);
110
111         connect(this, SIGNAL(itemSelected(bool)), removeAction,
112                 SLOT(setEnabled(bool)));
113         connect(toolBar, SIGNAL(actionTriggered(QAction*)), this,
114                 SLOT(handleToolBarAction(QAction*)));
115
116         connect(&btSession_, SIGNAL(alert(std::auto_ptr<Alert>)),
117                 this, SLOT(on_alert(std::auto_ptr<Alert>)));
118
119         LoadPlugins();
120 }
121
122
123 MainWindow::~MainWindow()
124 {
125 }
126
127 // ===================== Implements PluginInterface =========================
128 bool MainWindow::setGui(QWidget* widget, PluginWidgetType type)
129 {
130 #ifdef QTRAPIDS_DEBUG
131         qDebug() << "MainWindow::setGui():" << dlView_->currentItem();
132 #endif
133         tabWidget_->addTab(widget, tr("Search"));
134         return true;
135 }
136
137 /// @todo Add PluginInterface parameter check which plugin gives the widget to handle appropriately
138 void MainWindow::addPluginWidget(QWidget* widget, PluginWidgetType type)
139 {
140 #ifdef QTRAPIDS_DEBUG
141         qDebug() << "MainWindow::addPluginWidget():" << dlView_->currentItem();
142 #endif
143
144         if (type == qtrapids::PluginHostInterface::TAB_PAGE) {
145                 int index = tabWidget_->addTab(widget, tr("Test"));
146                 tabWidget_->setCurrentIndex(index);
147                 //layout_->addWidget(widget);
148         }
149 }
150 void MainWindow::addToolbar(QWidget* widget, PluginWidgetType type)
151 {
152 }
153
154 void MainWindow::addToolItem(QWidget* widget, PluginWidgetType type)
155 {
156 }
157
158 void MainWindow::addMenu(QWidget* widget, PluginWidgetType type)
159 {
160 }
161
162 void MainWindow::addMenuItem(QWidget* widget, PluginWidgetType type)
163 {
164 }
165
166 bool MainWindow::eventRequest(QVariant param, PluginRequest req)
167 {
168         if (req == qtrapids::PluginHostInterface::OPEN_FILE) {
169                 QString sourceFile = param.toString();
170                 
171                 // Get the source files name from the full path:
172                 QFileInfo fInfo(sourceFile);
173                 QString targetFile = fInfo.fileName();
174                 targetFile = settings_.value("download/directory").toString() + "/" + targetFile;
175                 
176                 // Copy temoporary file to Downloads directory...
177                 if (!QFile::copy(sourceFile, targetFile)) {
178                         qDebug() << "File copying failed";
179                         return false;
180                 } else {
181                         // If copying was successful, remove the original temporary file.
182                         QFile::remove(sourceFile);
183                 }
184                 
185                 /// @todo Torrent bencoding validity should be checked before starting(?)
186                 // ...and start the torrent:
187                 on_torrentFileSelected(targetFile);
188         
189         } else if (req == qtrapids::PluginHostInterface::READ_BUFFER) {
190                 // Create torrent information from char* buffer and start.
191                 StartTorrentFromBufferData(param.toByteArray().constData(), param.toByteArray().size());
192         }
193         
194         return true;
195 }
196
197
198 //=========================== PRIVATE ================================
199
200 void MainWindow::LoadPlugins()
201 {
202         // Get plugin directories from 
203         QStringList pluginDirsTmp = settings_.value("plugins/path").toStringList();
204         QStringList nameFilters("*.so");
205         
206         /// @todo enable "application directory" for plugin search in development/debug mode only. In release version
207         /// search plugins directory under $HOME/.qtrapids or system library paths
208         pluginDirsTmp << qApp->applicationDirPath();
209         pluginDirsTmp.removeDuplicates();
210         
211         foreach (QString dir, pluginDirsTmp) {
212                 pluginDirs_.append(QDir(dir));
213         }
214         
215         foreach (QDir dir, pluginDirs_) {
216                 
217                 if (dir.cd(PLUGINS_DIR)) {
218                         
219                         foreach (QString fileName, dir.entryList(nameFilters, QDir::Files)) {
220                                 QPluginLoader pluginLoader(dir.absoluteFilePath(fileName));
221
222                                 // If plugin not loaded from another directory, then load
223                                 if (!pluginFileNames_.contains(fileName) && QLibrary::isLibrary(fileName)) {
224
225                                         if (pluginLoader.load()) {
226                                                 qDebug() << "Plugin loaded: "  << fileName;
227                                         } else {
228                                                 qWarning() << "Plugin load failed: " << pluginLoader.errorString();
229                                         }
230
231                                         QObject *baseInstance = pluginLoader.instance();
232                                         if (!baseInstance) {
233                                                 qDebug() << "Base instance = NULL.";
234                                         }
235
236                                         qtrapids::PluginInterface *plugin = qobject_cast<qtrapids::PluginInterface*>(baseInstance);
237
238                                         if (!plugin) {
239                                                 qDebug() << "Cast failed.";
240                                         } else {
241                                                 qtrapids::PluginInterface::Info info;
242                                                 info.directory = dir.path();
243                                                 qDebug() << dir.path();
244                                                 plugin->initialize(this, info);
245                                                 pluginFileNames_ += fileName;
246                                         }
247                                 } else {
248                                         qWarning() << "Plugin " 
249                                                 << fileName 
250                                                 << " already loaded from another directory, or not a valid library file";
251                                 }
252                         }
253                         
254                 } else {
255                         qWarning() << PLUGINS_DIR <<  "directory not accessible or does not exist in "  << dir.path();
256                 }
257         }
258 }
259
260
261
262 // Opens torrent information from buffer data and adds torrent to session 
263 void MainWindow::StartTorrentFromBufferData(char const* data, int size)
264 {
265         // For params, see: http://www.rasterbar.com/products/libtorrent/manual.html#add-torrent
266         /// @todo Should typedef libtorrent::torrent_info to something
267         AddTorrentParams addParams;
268         boost::intrusive_ptr<libtorrent::torrent_info> tiTmp =
269             new libtorrent::torrent_info(data, size);
270         addParams.ti = tiTmp;
271         // save_path is the only mandatory parameter, rest are optional.
272         addParams.save_path = boost::filesystem::path(settings_.value("download/directory").toString().toStdString());
273         //addParams.storage_mode = libtorrent::storage_mode_allocate;
274         qtrapids::QTorrentHandle handle = btSession_.addTorrent(addParams);
275         dlView_->newItem(handle);
276 //      torrentHandles_.push_back(handlePtr);
277 #ifdef QTRAPIDS_DEBUG
278         qDebug() << "Is valid: " << handle.isValid();
279 #endif
280 }
281
282 // =========================== SLOTS =================================
283 void MainWindow::on_openAction_clicked()
284 {
285         QFileDialog *dialog = new QFileDialog( this, "Open torrent file", QString(), tr("Torrent files (*.torrent)"));
286         dialog->setFileMode(QFileDialog::ExistingFile);
287         connect(dialog, SIGNAL(fileSelected(const QString&)), this, SLOT(on_torrentFileSelected(const QString&)));
288         dialog->show();
289 }
290
291 void MainWindow::on_removeAction_clicked()
292 {
293         qtrapids::QTorrentHandle handle = dlView_->removeSelected();
294         btSession_.removeTorrent(handle);
295 }
296
297 void MainWindow::on_quitAction_clicked()
298 {
299         close();
300 }
301
302 void MainWindow::on_preferencesAction_clicked()
303 {
304         if (!preferencesDialog_) {
305                 preferencesDialog_ = new PreferencesDialog(this);
306         }
307         preferencesDialog_->show();
308         preferencesDialog_->raise();
309         preferencesDialog_->activateWindow();
310 }
311
312 void MainWindow::on_aboutAction_clicked()
313 {
314         QMessageBox::about(this, tr("About QtRapids"), ABOUT_TEXT);
315 }
316
317
318 void MainWindow::on_aboutQtAction_clicked()
319 {
320         QMessageBox::aboutQt (this, tr("About Qt"));
321 }
322
323
324 void MainWindow::on_downloadItemSelectionChanged()
325 {
326 #ifdef QTRAPIDS_DEBUG
327         qDebug() << "MainWindow::on_seedItemSelectionChanged():" << dlView_->currentItem();
328 #endif
329         if (dlView_->currentItem() != NULL) {
330                 emit(itemSelected(true));
331         } else {
332                 emit(itemSelected(false));
333         }
334 }
335
336 void MainWindow::on_seedItemSelectionChanged()
337 {
338 #ifdef QTRAPIDS_DEBUG
339         qDebug() << "MainWindow::on_seedItemSelectionChanged():" << seedView_->currentItem();
340 #endif
341         if (seedView_->currentItem() != NULL) {
342                 emit(itemSelected(true));
343         } else {
344                 emit(itemSelected(false));
345         }
346 }
347
348 void MainWindow::handleToolBarAction(QAction* action)
349 {
350         if (action->text() == "Open") {
351                 on_openAction_clicked();
352         } else if (action->text() == "Remove") {
353                 on_removeAction_clicked();
354         }
355 }
356
357 void MainWindow::on_torrentFileSelected(const QString& file)
358 {
359 #ifdef QTRAPIDS_DEBUG
360         qDebug() << " MainWindow::on_torrentFileSelected(): " << file;
361 #endif
362         // Torrent filename empty, do nothing.
363         if (file == "") {
364                 return;
365         }
366
367         // Otherwise add torrent
368         // For params, see: http://www.rasterbar.com/products/libtorrent/manual.html#add-torrent
369         /// @todo Should typedef libtorrent::torrent_info to something
370         AddTorrentParams addParams;
371         boost::intrusive_ptr<libtorrent::torrent_info> tiTmp =
372             new libtorrent::torrent_info(boost::filesystem::path(file.toStdString()));
373         addParams.ti = tiTmp;
374         // save_path is the only mandatory parameter, rest are optional.
375         addParams.save_path = boost::filesystem::path(settings_.value("download/directory").toString().toStdString());
376         //addParams.storage_mode = libtorrent::storage_mode_allocate;
377         qtrapids::QTorrentHandle handle = btSession_.addTorrent(addParams);
378         dlView_->newItem(handle);
379 //      torrentHandles_.push_back(handlePtr);
380 #ifdef QTRAPIDS_DEBUG
381         qDebug() << "Is valid: " << handle.isValid();
382 #endif
383 }
384
385 void MainWindow::on_alert(std::auto_ptr<Alert> al)
386 {
387         if (al.get() != NULL) {
388 //              qDebug()
389 //                              << "MainWindow::on_torrentAlert(): "
390 //                              << QString::fromStdString(al->message());
391
392                 TorrentAlert *torrentAlert
393                 = dynamic_cast<TorrentAlert*> (al.get());
394
395                 if (torrentAlert) {
396                         qtrapids::QTorrentHandle torrentHandle = qtrapids::QTorrentHandle(torrentAlert->handle);
397                         dlView_->updateItem(qtrapids::QTorrentHandle(torrentAlert->handle));
398                 }
399
400         }
401 }
402
403 /*
404 bool MainWindow::IsNewTorrent(std::auto_ptr<qtrapids::QTorrentHandle> handlePtr)
405 {
406         for (unsigned i = 0; i < torrentHandles_.size(); ++i) {
407     if (torrentHandles_.at(i).get() == handlePtr.get()) {
408                         return false;
409                 } else {
410                         return true;
411                 }
412         }
413 }
414 */