9a6770ca96c3406c91f93ee73f955c6e18b74dc1
[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                 // ...and start the torrent:
186                 on_torrentFileSelected(targetFile);
187         }
188         
189         return true;
190 }
191
192
193 //=========================== PRIVATE ================================
194
195 void MainWindow::LoadPlugins()
196 {
197         // Get plugin directories from 
198         QStringList pluginDirsTmp = settings_.value("plugins/path").toStringList();
199         QStringList nameFilters("*.so");
200         
201         /// @todo enable "application directory" for plugin search in development/debug mode only. In release version
202         /// search plugins directory under $HOME/.qtrapids or system library paths
203         pluginDirsTmp << qApp->applicationDirPath();
204         pluginDirsTmp.removeDuplicates();
205         
206         foreach (QString dir, pluginDirsTmp) {
207                 pluginDirs_.append(QDir(dir));
208         }
209         
210         foreach (QDir dir, pluginDirs_) {
211                 
212                 if (dir.cd(PLUGINS_DIR)) {
213                         
214                         foreach (QString fileName, dir.entryList(nameFilters, QDir::Files)) {
215                                 QPluginLoader pluginLoader(dir.absoluteFilePath(fileName));
216
217                                 // If plugin not loaded from another directory, then load
218                                 if (!pluginFileNames_.contains(fileName) && QLibrary::isLibrary(fileName)) {
219
220                                         if (pluginLoader.load()) {
221                                                 qDebug() << "Plugin loaded: "  << fileName;
222                                         } else {
223                                                 qWarning() << "Plugin load failed: " << pluginLoader.errorString();
224                                         }
225
226                                         QObject *baseInstance = pluginLoader.instance();
227                                         if (!baseInstance) {
228                                                 qDebug() << "Base instance = NULL.";
229                                         }
230
231                                         qtrapids::PluginInterface *plugin = qobject_cast<qtrapids::PluginInterface*>(baseInstance);
232
233                                         if (!plugin) {
234                                                 qDebug() << "Cast failed.";
235                                         } else {
236                                                 qtrapids::PluginInterface::Info info;
237                                                 info.directory = dir.path();
238                                                 qDebug() << dir.path();
239                                                 plugin->initialize(this, info);
240                                                 pluginFileNames_ += fileName;
241                                         }
242                                 } else {
243                                         qWarning() << "Plugin " 
244                                                 << fileName 
245                                                 << " already loaded from another directory, or not a valid library file";
246                                 }
247                         }
248                         
249                 } else {
250                         qWarning() << PLUGINS_DIR <<  "directory not accessible or does not exist in "  << dir.path();
251                 }
252         }
253 }
254
255 // =========================== SLOTS =================================
256 void MainWindow::on_openAction_clicked()
257 {
258         QFileDialog *dialog = new QFileDialog( this, "Open torrent file", QString(), tr("Torrent files (*.torrent)"));
259         dialog->setFileMode(QFileDialog::ExistingFile);
260         connect(dialog, SIGNAL(fileSelected(const QString&)), this, SLOT(on_torrentFileSelected(const QString&)));
261         dialog->show();
262 }
263
264 void MainWindow::on_removeAction_clicked()
265 {
266         qtrapids::QTorrentHandle handle = dlView_->removeSelected();
267         btSession_.removeTorrent(handle);
268 }
269
270 void MainWindow::on_quitAction_clicked()
271 {
272         close();
273 }
274
275 void MainWindow::on_preferencesAction_clicked()
276 {
277         if (!preferencesDialog_) {
278                 preferencesDialog_ = new PreferencesDialog(this);
279         }
280         preferencesDialog_->show();
281         preferencesDialog_->raise();
282         preferencesDialog_->activateWindow();
283 }
284
285 void MainWindow::on_aboutAction_clicked()
286 {
287         QMessageBox::about(this, tr("About QtRapids"), ABOUT_TEXT);
288 }
289
290
291 void MainWindow::on_aboutQtAction_clicked()
292 {
293         QMessageBox::aboutQt (this, tr("About Qt"));
294 }
295
296
297 void MainWindow::on_downloadItemSelectionChanged()
298 {
299 #ifdef QTRAPIDS_DEBUG
300         qDebug() << "MainWindow::on_seedItemSelectionChanged():" << dlView_->currentItem();
301 #endif
302         if (dlView_->currentItem() != NULL) {
303                 emit(itemSelected(true));
304         } else {
305                 emit(itemSelected(false));
306         }
307 }
308
309 void MainWindow::on_seedItemSelectionChanged()
310 {
311 #ifdef QTRAPIDS_DEBUG
312         qDebug() << "MainWindow::on_seedItemSelectionChanged():" << seedView_->currentItem();
313 #endif
314         if (seedView_->currentItem() != NULL) {
315                 emit(itemSelected(true));
316         } else {
317                 emit(itemSelected(false));
318         }
319 }
320
321 void MainWindow::handleToolBarAction(QAction* action)
322 {
323         if (action->text() == "Open") {
324                 on_openAction_clicked();
325         } else if (action->text() == "Remove") {
326                 on_removeAction_clicked();
327         }
328 }
329
330 void MainWindow::on_torrentFileSelected(const QString& file)
331 {
332 #ifdef QTRAPIDS_DEBUG
333         qDebug() << " MainWindow::on_torrentFileSelected(): " << file;
334 #endif
335         // Torrent filename empty, do nothing.
336         if (file == "") {
337                 return;
338         }
339
340         // Otherwise add torrent
341         // For params, see: http://www.rasterbar.com/products/libtorrent/manual.html#add-torrent
342         AddTorrentParams addParams;
343         boost::intrusive_ptr<libtorrent::torrent_info> tiTmp =
344             new libtorrent::torrent_info(boost::filesystem::path(file.toStdString()));
345         addParams.ti = tiTmp;
346         // save_path is the only mandatory parameter, rest are optional.
347         addParams.save_path = boost::filesystem::path(settings_.value("download/directory").toString().toStdString());
348         //addParams.storage_mode = libtorrent::storage_mode_allocate;
349         qtrapids::QTorrentHandle handle = btSession_.addTorrent(addParams);
350         dlView_->newItem(handle);
351 //      torrentHandles_.push_back(handlePtr);
352 #ifdef QTRAPIDS_DEBUG
353         qDebug() << "Is valid: " << handle.isValid();
354 #endif
355 }
356
357
358 void MainWindow::on_alert(std::auto_ptr<Alert> al)
359 {
360         if (al.get() != NULL) {
361 //              qDebug()
362 //                              << "MainWindow::on_torrentAlert(): "
363 //                              << QString::fromStdString(al->message());
364
365                 TorrentAlert *torrentAlert
366                 = dynamic_cast<TorrentAlert*> (al.get());
367
368                 if (torrentAlert) {
369                         qtrapids::QTorrentHandle torrentHandle = qtrapids::QTorrentHandle(torrentAlert->handle);
370                         dlView_->updateItem(qtrapids::QTorrentHandle(torrentAlert->handle));
371                 }
372
373         }
374 }
375
376 /*
377 bool MainWindow::IsNewTorrent(std::auto_ptr<qtrapids::QTorrentHandle> handlePtr)
378 {
379         for (unsigned i = 0; i < torrentHandles_.size(); ++i) {
380     if (torrentHandles_.at(i).get() == handlePtr.get()) {
381                         return false;
382                 } else {
383                         return true;
384                 }
385         }
386 }
387 */