]> git.sur5r.net Git - minitube/blob - src/MainWindow.cpp
Keyboard shortcuts for the sortBar
[minitube] / src / MainWindow.cpp
1 #include "MainWindow.h"
2 #include "spacer.h"
3 #include "Constants.h"
4 #include "iconloader/qticonloader.h"
5 #include "global.h"
6
7 MainWindow::MainWindow() {
8     m_fullscreen = false;
9     mediaObject = 0;
10     audioOutput = 0;
11
12     // views mechanism
13     history = new QStack<QWidget*>();
14     views = new QStackedWidget(this);
15
16     // views
17     searchView = new SearchView(this);
18     connect(searchView, SIGNAL(search(QString)), this, SLOT(showMedia(QString)));
19     views->addWidget(searchView);
20     mediaView = new MediaView(this);
21     views->addWidget(mediaView);
22
23     // lazily initialized views
24     aboutView = 0;
25     settingsView = 0;
26
27     toolbarSearch = new SearchLineEdit(this);
28     toolbarSearch->setFont(qApp->font());
29     connect(toolbarSearch, SIGNAL(search(const QString&)), searchView, SLOT(watch(const QString&)));
30
31     // build ui
32     createActions();
33     createMenus();
34     createToolBars();
35     createStatusBar();
36
37     // remove that useless menu/toolbar context menu
38     this->setContextMenuPolicy(Qt::NoContextMenu);
39
40     // mediaView init stuff thats needs actions
41     mediaView->initialize();
42
43     // restore window position
44     readSettings();
45
46     // show the initial view
47     showWidget(searchView);
48
49     setCentralWidget(views);
50 }
51
52 MainWindow::~MainWindow() {
53     delete history;
54 }
55
56 void MainWindow::createActions() {
57
58     QMap<QString, QAction*> *actions = The::globalActions();
59
60     /*
61     settingsAct = new QAction(tr("&Preferences..."), this);
62     settingsAct->setStatusTip(tr(QString("Configure ").append(Constants::APP_NAME).toUtf8()));
63     // Mac integration
64     settingsAct->setMenuRole(QAction::PreferencesRole);
65     actions->insert("settings", settingsAct);
66     connect(settingsAct, SIGNAL(triggered()), this, SLOT(showSettings()));
67     */
68     
69     backAct = new QAction(QIcon(":/images/go-previous.png"), tr("&Back"), this);
70     backAct->setEnabled(false);
71     backAct->setShortcut(QKeySequence(Qt::ALT + Qt::Key_Left));
72     backAct->setStatusTip(tr("Go to the previous view"));
73     actions->insert("back", backAct);
74     connect(backAct, SIGNAL(triggered()), this, SLOT(goBack()));
75
76     stopAct = new QAction(QtIconLoader::icon("media-stop", QIcon(":/images/stop.png")), tr("&Stop"), this);
77     stopAct->setStatusTip(tr("Stop playback and go back to the search view"));
78     stopAct->setShortcut(QKeySequence(Qt::Key_Escape));
79     actions->insert("stop", stopAct);
80     connect(stopAct, SIGNAL(triggered()), this, SLOT(stop()));
81
82     skipAct = new QAction(QtIconLoader::icon("media-skip-forward", QIcon(":/images/skip.png")), tr("S&kip"), this);
83     skipAct->setStatusTip(tr("Skip to the next video"));
84     skipAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Right));
85     skipAct->setEnabled(false);
86     actions->insert("skip", skipAct);
87     connect(skipAct, SIGNAL(triggered()), mediaView, SLOT(skip()));
88
89     pauseAct = new QAction(QtIconLoader::icon("media-pause", QIcon(":/images/pause.png")), tr("&Pause"), this);
90     pauseAct->setStatusTip(tr("Pause playback"));
91     pauseAct->setShortcut(QKeySequence(Qt::Key_Space));
92     pauseAct->setEnabled(false);
93     actions->insert("pause", pauseAct);
94     connect(pauseAct, SIGNAL(triggered()), mediaView, SLOT(pause()));
95
96     fullscreenAct = new QAction(QtIconLoader::icon("view-fullscreen", QIcon(":/images/view-fullscreen.png")), tr("&Full Screen"), this);
97     fullscreenAct->setStatusTip(tr("Go full screen"));
98     fullscreenAct->setShortcut(QKeySequence(Qt::ALT + Qt::Key_Return));
99     fullscreenAct->setShortcutContext(Qt::ApplicationShortcut);
100     actions->insert("fullscreen", fullscreenAct);
101     connect(fullscreenAct, SIGNAL(triggered()), this, SLOT(fullscreen()));
102
103     compactViewAct = new QAction(tr("&Compact mode"), this);
104     compactViewAct->setStatusTip(tr("Hide the playlist and the toolbar"));
105     compactViewAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return));
106     compactViewAct->setCheckable(true);
107     compactViewAct->setChecked(false);
108     compactViewAct->setEnabled(false);
109     actions->insert("compactView", compactViewAct);
110     connect(compactViewAct, SIGNAL(toggled(bool)), this, SLOT(compactView(bool)));
111
112     // icon should be document-save but it is ugly
113     downloadAct = new QAction(QtIconLoader::icon("go-down", QIcon(":/images/go-down.png")), tr("&Download"), this);
114     downloadAct->setStatusTip(tr("Download this video"));
115     downloadAct->setShortcut(tr("Ctrl+S"));
116     downloadAct->setEnabled(false);
117     actions->insert("download", downloadAct);
118     connect(downloadAct, SIGNAL(triggered()), this, SLOT(download()));
119
120     webPageAct = new QAction(QtIconLoader::icon("internet-web-browser", QIcon(":/images/internet-web-browser.png")), tr("&YouTube"), this);
121     webPageAct->setStatusTip(tr("Open the YouTube video page"));
122     webPageAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Y));
123     webPageAct->setEnabled(false);
124     actions->insert("webpage", webPageAct);
125     connect(webPageAct, SIGNAL(triggered()), mediaView, SLOT(openWebPage()));
126
127     removeAct = new QAction(tr("&Remove"), this);
128     removeAct->setStatusTip(tr("Remove the selected videos from the playlist"));
129     QList<QKeySequence> shortcuts;
130     shortcuts << QKeySequence("Del") << QKeySequence("Backspace");
131     removeAct->setShortcuts(shortcuts);
132     removeAct->setEnabled(false);
133     actions->insert("remove", removeAct);
134     connect(removeAct, SIGNAL(triggered()), mediaView, SLOT(removeSelected()));
135
136     moveUpAct = new QAction(QtIconLoader::icon("go-up", QIcon(":/images/go-up.png")), tr("Move &Up"), this);
137     moveUpAct->setStatusTip(tr("Move up the selected videos in the playlist"));
138     moveUpAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Up));
139     moveUpAct->setEnabled(false);
140     actions->insert("moveUp", moveUpAct);
141     connect(moveUpAct, SIGNAL(triggered()), mediaView, SLOT(moveUpSelected()));
142
143     moveDownAct = new QAction(QtIconLoader::icon("go-down", QIcon(":/images/go-down.png")), tr("Move &Down"), this);
144     moveDownAct->setStatusTip(tr("Move down the selected videos in the playlist"));
145     moveDownAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Down));
146     moveDownAct->setEnabled(false);
147     actions->insert("moveDown", moveDownAct);
148     connect(moveDownAct, SIGNAL(triggered()), mediaView, SLOT(moveDownSelected()));
149
150     quitAct = new QAction(tr("&Quit"), this);
151     quitAct->setMenuRole(QAction::QuitRole);
152     quitAct->setShortcut(tr("Ctrl+Q"));
153     quitAct->setStatusTip(tr("Bye"));
154     actions->insert("quit", quitAct);
155     connect(quitAct, SIGNAL(triggered()), this, SLOT(quit()));
156
157     siteAct = new QAction(tr("&Website"), this);
158     siteAct->setShortcut(QKeySequence::HelpContents);
159     siteAct->setStatusTip(tr("%1 on the Web").arg(Constants::APP_NAME));
160     actions->insert("site", siteAct);
161     connect(siteAct, SIGNAL(triggered()), this, SLOT(visitSite()));
162
163     donateAct = new QAction(tr("&Donate via PayPal"), this);
164     donateAct->setStatusTip(tr("Please support the continued development of %1").arg(Constants::APP_NAME));
165     actions->insert("donate", donateAct);
166     connect(donateAct, SIGNAL(triggered()), this, SLOT(donate()));
167
168     aboutAct = new QAction(tr("&About"), this);
169     aboutAct->setMenuRole(QAction::AboutRole);
170     aboutAct->setStatusTip(tr("Info about %1").arg(Constants::APP_NAME));
171     actions->insert("about", aboutAct);
172     connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
173
174     // Invisible actions
175
176     searchFocusAct = new QAction(this);
177     searchFocusAct->setShortcut(QKeySequence::Find);
178     actions->insert("search", searchFocusAct);
179     connect(searchFocusAct, SIGNAL(triggered()), this, SLOT(searchFocus()));
180     addAction(searchFocusAct);
181
182     volumeUpAct = new QAction(this);
183     volumeUpAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Plus));
184     actions->insert("volume-up", volumeUpAct);
185     connect(volumeUpAct, SIGNAL(triggered()), this, SLOT(volumeUp()));
186     addAction(volumeUpAct);
187
188     volumeDownAct = new QAction(this);
189     volumeDownAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Minus));
190     actions->insert("volume-down", volumeDownAct);
191     connect(volumeDownAct, SIGNAL(triggered()), this, SLOT(volumeDown()));
192     addAction(volumeDownAct);
193
194     volumeMuteAct = new QAction(this);
195     volumeMuteAct->setShortcut(tr("Ctrl+M"));
196     actions->insert("volume-mute", volumeMuteAct);
197     connect(volumeMuteAct, SIGNAL(triggered()), this, SLOT(volumeMute()));
198     addAction(volumeMuteAct);
199
200     // common action properties
201     foreach (QAction *action, actions->values()) {
202
203         // add actions to the MainWindow so that they work
204         // when the menu is hidden
205         addAction(action);
206
207         // never autorepeat.
208         // unexperienced users tend to keep keys pressed for a "long" time
209         action->setAutoRepeat(false);
210         action->setToolTip(action->statusTip());
211
212         // make the actions work when video is fullscreen
213         action->setShortcutContext(Qt::ApplicationShortcut);
214
215 #ifdef Q_WS_MAC
216         // OSX does not use icons in menus
217         action->setIconVisibleInMenu(false);
218 #endif
219
220     }
221
222 }
223
224 void MainWindow::createMenus() {
225
226     QMap<QString, QMenu*> *menus = The::globalMenus();
227
228     fileMenu = menuBar()->addMenu(tr("&Application"));
229     // menus->insert("file", fileMenu);
230     /*
231     fileMenu->addAction(settingsAct);
232     fileMenu->addSeparator();
233     */
234     fileMenu->addAction(quitAct);
235
236     playlistMenu = menuBar()->addMenu(tr("&Playlist"));
237     menus->insert("playlist", playlistMenu);
238     playlistMenu->addAction(removeAct);
239     playlistMenu->addSeparator();
240     playlistMenu->addAction(moveUpAct);
241     playlistMenu->addAction(moveDownAct);
242
243     viewMenu = menuBar()->addMenu(tr("&Video"));
244     menus->insert("video", viewMenu);
245     // viewMenu->addAction(backAct);
246     viewMenu->addAction(stopAct);
247     viewMenu->addAction(pauseAct);
248     viewMenu->addAction(skipAct);
249     viewMenu->addSeparator();
250     viewMenu->addAction(webPageAct);
251     viewMenu->addSeparator();
252     viewMenu->addAction(downloadAct);
253     viewMenu->addAction(compactViewAct);
254     viewMenu->addAction(fullscreenAct);
255
256     helpMenu = menuBar()->addMenu(tr("&Help"));
257     helpMenu->addAction(siteAct);
258     helpMenu->addAction(donateAct);
259     helpMenu->addAction(aboutAct);
260 }
261
262 void MainWindow::createToolBars() {
263
264     setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
265
266     mainToolBar = new QToolBar(this);
267     mainToolBar->setFloatable(false);
268     mainToolBar->setMovable(false);
269
270     QFont smallerFont;
271     smallerFont.setPointSize(smallerFont.pointSize()*.85);
272     mainToolBar->setFont(smallerFont);
273
274     mainToolBar->setIconSize(QSize(32,32));
275     // mainToolBar->addAction(backAct);
276     mainToolBar->addAction(stopAct);
277     mainToolBar->addAction(pauseAct);
278     mainToolBar->addAction(skipAct);
279     mainToolBar->addAction(fullscreenAct);
280
281     seekSlider = new Phonon::SeekSlider(this);
282     seekSlider->setIconVisible(false);
283     Spacer *seekSliderSpacer = new Spacer(mainToolBar, seekSlider);
284     seekSliderSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
285     mainToolBar->addWidget(seekSliderSpacer);
286
287     volumeSlider = new Phonon::VolumeSlider(this);
288     // this makes the volume slider smaller
289     volumeSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
290     mainToolBar->addWidget(new Spacer(mainToolBar, volumeSlider));
291
292     mainToolBar->addWidget(new Spacer(mainToolBar, toolbarSearch));
293
294     addToolBar(mainToolBar);
295 }
296
297 void MainWindow::createStatusBar() {
298     currentTime = new QLabel(this);
299     statusBar()->addPermanentWidget(currentTime);
300
301     totalTime = new QLabel(this);
302     statusBar()->addPermanentWidget(totalTime);
303
304     // remove ugly borders on OSX
305     statusBar()->setStyleSheet("::item{border:0 solid}");
306
307     statusBar()->show();
308 }
309
310 void MainWindow::readSettings() {
311     QSettings settings;
312     restoreGeometry(settings.value("geometry").toByteArray());
313 }
314
315 void MainWindow::writeSettings() {
316     // do not save geometry when in full screen
317     if (m_fullscreen)
318         return;
319     QSettings settings;
320     settings.setValue("geometry", saveGeometry());
321 }
322
323 void MainWindow::goBack() {
324     if ( history->size() > 1 ) {
325         history->pop();
326         QWidget *widget = history->pop();
327         showWidget(widget);
328     }
329 }
330
331 void MainWindow::showWidget ( QWidget* widget ) {
332
333     setUpdatesEnabled(false);
334
335     // call hide method on the current view
336     View* oldView = dynamic_cast<View *> (views->currentWidget());
337     if (oldView != NULL) {
338         oldView->disappear();
339     }
340
341     // call show method on the new view
342     View* newView = dynamic_cast<View *> (widget);
343     if (newView != NULL) {
344         newView->appear();
345         QMap<QString,QVariant> metadata = newView->metadata();
346         QString windowTitle = metadata.value("title").toString();
347         if (windowTitle.length())
348             windowTitle += " - ";
349         setWindowTitle(windowTitle + Constants::APP_NAME);
350         statusBar()->showMessage((metadata.value("description").toString()));
351
352     }
353
354     // backAct->setEnabled(history->size() > 1);
355     // settingsAct->setEnabled(widget != settingsView);
356     stopAct->setEnabled(widget == mediaView);
357     fullscreenAct->setEnabled(widget == mediaView);
358     compactViewAct->setEnabled(widget == mediaView);
359     webPageAct->setEnabled(widget == mediaView);
360     aboutAct->setEnabled(widget != aboutView);
361     // this is not the best place to enable downloads, but the user is informed
362     // if there really is no video is playing
363     downloadAct->setEnabled(widget == mediaView);
364
365     // cool toolbar on the Mac
366     // setUnifiedTitleAndToolBarOnMac(widget == mediaView);
367
368     // toolbar only for the mediaView
369     mainToolBar->setVisible(widget == mediaView && !compactViewAct->isChecked());
370
371     history->push(widget);
372
373 #ifdef Q_WS_MAC
374     // crossfade only on OSX
375     // where we can be sure of video performance
376     fadeInWidget(views->currentWidget(), widget);
377 #endif
378
379     views->setCurrentWidget(widget);
380
381     setUpdatesEnabled(true);
382 }
383
384 void MainWindow::fadeInWidget(QWidget *oldWidget, QWidget *newWidget) {
385     if (faderWidget) faderWidget->close();
386     if (!oldWidget || !newWidget || oldWidget == mediaView || newWidget == mediaView) return;
387     QPixmap frozenView = QPixmap::grabWidget(oldWidget);
388     faderWidget = new FaderWidget(newWidget);
389     faderWidget->start(frozenView);
390 }
391
392 void MainWindow::about() {
393     if (!aboutView) {
394         aboutView = new AboutView(this);
395         views->addWidget(aboutView);
396     }
397     showWidget(aboutView);
398 }
399
400 void MainWindow::visitSite() {
401     QUrl url(Constants::WEBSITE);
402     statusBar()->showMessage(QString(tr("Opening %1").arg(url.toString())));
403     QDesktopServices::openUrl(url);
404 }
405
406 void MainWindow::donate() {
407     QUrl url(QString(Constants::WEBSITE) + "#donate");
408     statusBar()->showMessage(QString(tr("Opening %1").arg(url.toString())));
409     QDesktopServices::openUrl(url);
410 }
411
412 void MainWindow::quit() {
413     writeSettings();
414     qApp->quit();
415 }
416
417 void MainWindow::closeEvent(QCloseEvent *event) {
418     quit();
419     QWidget::closeEvent(event);
420 }
421
422 void MainWindow::showSettings() {
423     if (!settingsView) {
424         settingsView = new SettingsView(this);
425         views->addWidget(settingsView);
426     }
427     showWidget(settingsView);
428 }
429
430 void MainWindow::showSearch() {
431     showWidget(searchView);
432     currentTime->clear();
433     totalTime->clear();
434 }
435
436 void MainWindow::showMedia(QString query) {
437     initPhonon();
438     mediaView->setMediaObject(mediaObject);
439     SearchParams *searchParams = new SearchParams();
440     searchParams->setKeywords(query);
441     mediaView->search(searchParams);
442     showWidget(mediaView);
443 }
444
445 void MainWindow::stateChanged(Phonon::State newState, Phonon::State /* oldState */) {
446
447     // qDebug() << "Phonon state: " << newState;
448
449     switch (newState) {
450
451          case Phonon::ErrorState:
452         if (mediaObject->errorType() == Phonon::FatalError) {
453             statusBar()->showMessage(tr("Fatal error: %1").arg(mediaObject->errorString()));
454         } else {
455             statusBar()->showMessage(tr("Error: %1").arg(mediaObject->errorString()));
456         }
457         break;
458
459          case Phonon::PlayingState:
460         pauseAct->setEnabled(true);
461         pauseAct->setIcon(QtIconLoader::icon("media-pause", QIcon(":/images/pause.png")));
462         pauseAct->setText(tr("&Pause"));
463         pauseAct->setStatusTip(tr("Pause playback"));
464         skipAct->setEnabled(true);
465         break;
466
467          case Phonon::StoppedState:
468         pauseAct->setEnabled(false);
469         skipAct->setEnabled(false);
470         break;
471
472          case Phonon::PausedState:
473         skipAct->setEnabled(true);
474         pauseAct->setEnabled(true);
475         pauseAct->setIcon(QtIconLoader::icon("media-play", QIcon(":/images/play.png")));
476         pauseAct->setText(tr("&Play"));
477         pauseAct->setStatusTip(tr("Resume playback"));
478         break;
479
480          case Phonon::BufferingState:
481          case Phonon::LoadingState:
482         skipAct->setEnabled(true);
483         pauseAct->setEnabled(false);
484         currentTime->clear();
485         totalTime->clear();
486         break;
487
488          default:
489         ;
490     }
491 }
492
493 void MainWindow::stop() {
494     mediaView->stop();
495     showSearch();
496 }
497
498 void MainWindow::fullscreen() {
499
500     setUpdatesEnabled(false);
501
502     if (m_fullscreen) {
503         // use setShortucs instead of setShortcut
504         // the latter seems not to work
505         QList<QKeySequence> shortcuts;
506         shortcuts << QKeySequence(Qt::ALT + Qt::Key_Return);
507         fullscreenAct->setShortcuts(shortcuts);
508         fullscreenAct->setText(tr("&Full Screen"));
509         stopAct->setShortcut(QKeySequence(Qt::Key_Escape));
510         if (m_maximized) showMaximized();
511         else showNormal();
512     } else {
513         stopAct->setShortcut(QString(""));
514         QList<QKeySequence> shortcuts;
515         // for some reason it is important that ESC comes first
516         shortcuts << QKeySequence(Qt::Key_Escape) << QKeySequence(Qt::ALT + Qt::Key_Return);
517         fullscreenAct->setShortcuts(shortcuts);
518         fullscreenAct->setText(tr("Exit &Full Screen"));
519         m_maximized = isMaximized();
520
521         // save geometry now, if the user quits when in full screen
522         // geometry won't be saved
523         writeSettings();
524
525         showFullScreen();
526     }
527
528     // No compact view action when in full screen
529     compactViewAct->setVisible(m_fullscreen);
530     // Also no Youtube action since it opens a new window
531     webPageAct->setVisible(m_fullscreen);
532
533     // Hide anything but the video
534     mediaView->setPlaylistVisible(m_fullscreen);
535     mainToolBar->setVisible(m_fullscreen);
536     statusBar()->setVisible(m_fullscreen);
537     menuBar()->setVisible(m_fullscreen);
538
539     m_fullscreen = !m_fullscreen;
540
541     setUpdatesEnabled(true);
542 }
543
544 void MainWindow::compactView(bool enable) {
545
546     setUpdatesEnabled(false);
547
548     // setUnifiedTitleAndToolBarOnMac(!enable);
549     mediaView->setPlaylistVisible(!enable);
550     mainToolBar->setVisible(!enable);
551     statusBar()->setVisible(!enable);
552
553     // ensure focus does not end up to the search box
554     // as it would steal the Space shortcut
555     toolbarSearch->setEnabled(!enable);
556
557     if (enable) {
558         stopAct->setShortcut(QString(""));
559         QList<QKeySequence> shortcuts;
560         // for some reason it is important that ESC comes first
561         shortcuts << QKeySequence(Qt::CTRL + Qt::Key_Return) << QKeySequence(Qt::Key_Escape);
562         compactViewAct->setShortcuts(shortcuts);
563     } else {
564         compactViewAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return));
565         stopAct->setShortcut(QKeySequence(Qt::Key_Escape));
566     }
567
568     setUpdatesEnabled(true);
569 }
570
571 void MainWindow::searchFocus() {
572     QWidget *view = views->currentWidget();
573     if (view == mediaView) {
574         toolbarSearch->setFocus();
575     }
576 }
577
578 void MainWindow::initPhonon() {
579     // Phonon initialization
580     if (mediaObject) delete mediaObject;
581     if (audioOutput) delete audioOutput;
582     mediaObject = new Phonon::MediaObject(this);
583     mediaObject->setTickInterval(100);
584     connect(mediaObject, SIGNAL(stateChanged(Phonon::State, Phonon::State)),
585             this, SLOT(stateChanged(Phonon::State, Phonon::State)));
586     connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(tick(qint64)));
587     connect(mediaObject, SIGNAL(totalTimeChanged(qint64)), this, SLOT(totalTimeChanged(qint64)));
588     seekSlider->setMediaObject(mediaObject);
589     audioOutput = new Phonon::AudioOutput(Phonon::VideoCategory, this);
590     connect(audioOutput, SIGNAL(volumeChanged(qreal)), this, SLOT(volumeChanged(qreal)));
591     connect(audioOutput, SIGNAL(mutedChanged(bool)), this, SLOT(volumeMutedChanged(bool)));
592     volumeSlider->setAudioOutput(audioOutput);
593     Phonon::createPath(mediaObject, audioOutput);
594 }
595
596 void MainWindow::tick(qint64 time) {
597     if (time <= 0) {
598         totalTime->clear();
599         return;
600     }
601     QTime displayTime(0, (time / 60000) % 60, (time / 1000) % 60);
602     currentTime->setText(displayTime.toString("mm:ss"));
603     // qDebug() << "currentTime" << time << displayTime.toString("mm:ss");
604 }
605
606 void MainWindow::totalTimeChanged(qint64 time) {
607     if (time <= 0) {
608         totalTime->clear();
609         return;
610     }
611     QTime displayTime(0, (time / 60000) % 60, (time / 1000) % 60);
612     totalTime->setText(displayTime.toString("/ mm:ss"));
613     // qDebug() << "totalTime" << time << displayTime.toString("mm:ss");
614 }
615
616 void MainWindow::volumeUp() {
617     qreal newVolume = volumeSlider->audioOutput()->volume() + .1;
618     if (newVolume > volumeSlider->maximumVolume())
619         newVolume = volumeSlider->maximumVolume();
620     volumeSlider->audioOutput()->setVolume(newVolume);
621 }
622
623 void MainWindow::volumeDown() {
624     qreal newVolume = volumeSlider->audioOutput()->volume() - .1;
625     if (newVolume < 0)
626         newVolume = 0;
627     volumeSlider->audioOutput()->setVolume(newVolume);
628 }
629
630 void MainWindow::volumeMute() {
631     volumeSlider->audioOutput()->setMuted(!volumeSlider->audioOutput()->isMuted());
632 }
633
634 void MainWindow::volumeChanged(qreal newVolume) {
635     // automatically unmute when volume changes
636     if (volumeSlider->audioOutput()->isMuted())
637         volumeSlider->audioOutput()->setMuted(false);
638     statusBar()->showMessage(tr("Volume at %1%").arg(newVolume*100));
639 }
640
641 void MainWindow::volumeMutedChanged(bool muted) {
642     if (muted)
643         statusBar()->showMessage(tr("Volume is muted"));
644     else
645         statusBar()->showMessage(tr("Volume is unmuted"));
646 }
647
648 void MainWindow::abortDownload() {
649     QProgressDialog* dlg = dynamic_cast<QProgressDialog*>(this->sender());
650     QMap<QNetworkReply*, DownloadResource>::iterator cur;
651     QMap<QNetworkReply*, DownloadResource>::iterator end;
652     // locate the DownloadResource by its dialog address and trigger abortion
653     for(cur=m_downloads.begin(), end=m_downloads.end(); cur!=end; cur++){
654         if(cur.value().dialog == dlg) cur.key()->abort();
655     }
656 }
657
658 void MainWindow::download() {
659     if(mediaObject == NULL || mediaObject->currentSource().url().isEmpty()){
660         // complain unless video source apperas to be valid
661         QMessageBox::critical(this, tr("No Video playing"), tr("You must first play the video you intent to download !"));
662         return;
663     }
664     QString filename = QFileDialog::getSaveFileName(this,
665                                                     tr("Save video as..."),
666                                                     tr("minitube video.mp4"),
667                                                     "Video File(*.avi *.mp4)"
668                                                     );
669     if(!filename.isNull()) {
670         // open destination file and initialize download
671         DownloadResource res;
672         res.file = new QFile(filename);
673         if(res.file->open(QFile::WriteOnly) == true) {
674             res.dialog = new QProgressDialog(tr("Downloading: ") + res.file->fileName(),
675                                              tr("Abort Download"), 0, 100, this);
676             connect(res.dialog, SIGNAL(canceled()), this, SLOT(abortDownload()));
677             download(mediaObject->currentSource().url(), res);
678         }else{
679             QMessageBox::critical(this, tr("File creation failed"), res.file->errorString());
680             delete res.file;
681         }
682     }
683 }
684
685 void MainWindow::download(const QUrl& url, const DownloadResource& res) {
686     // create and store request and connect the reply signals
687     QNetworkReply *r = The::networkAccessManager()->get(QNetworkRequest(url));
688     m_downloads.insert(r, res);
689     connect(r, SIGNAL(finished()), this, SLOT(replyFinished()));
690     connect(r, SIGNAL(readyRead()), this, SLOT(replyReadyRead()));
691     connect(r, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(replyError(QNetworkReply::NetworkError)));
692     connect(r, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(replyDownloadProgress(qint64,qint64)));
693     connect(r, SIGNAL(metaDataChanged()), this, SLOT(replyMetaDataChanged()));
694 }
695
696 void MainWindow::replyReadyRead() {
697     QNetworkReply* r = dynamic_cast<QNetworkReply*>(this->sender());
698     m_downloads[r].file->write(r->readAll());
699 }
700
701 void MainWindow::replyDownloadProgress(qint64 bytesReceived, qint64 bytesTotal) {
702     QNetworkReply* r = dynamic_cast<QNetworkReply*>(this->sender());
703     if (bytesTotal > 0 && bytesReceived >0)
704         m_downloads[r].dialog->setValue( double(100.0/bytesTotal)*bytesReceived );  // pssst :-X
705 }
706
707 void MainWindow::replyError(QNetworkReply::NetworkError code) {
708     QNetworkReply* r = dynamic_cast<QNetworkReply*>(this->sender());
709     QMessageBox::critical(this, tr("Download failed"), r->errorString());
710 }
711
712 void MainWindow::replyFinished() {
713     QNetworkReply* r = dynamic_cast<QNetworkReply*>(this->sender());
714     m_downloads[r].dialog->close();
715     m_downloads[r].file->close();
716     delete m_downloads[r].file;
717     m_downloads.remove(r);
718 }
719
720 void MainWindow::replyMetaDataChanged() {
721     QNetworkReply* r = dynamic_cast<QNetworkReply*>(this->sender());
722     QUrl url = r->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
723     if(url.isValid()) {
724         // redirect - request new url, but keep the resources
725         qDebug() << "redirecting to: " << url.toString();
726         download(url, m_downloads[r]);
727         m_downloads.remove(r);
728     }
729 }