]> git.sur5r.net Git - minitube/blob - src/MainWindow.cpp
Support YouTube author display names
[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 #include "videodefinition.h"
7 #include "fontutils.h"
8 #include "globalshortcuts.h"
9 #ifdef Q_WS_X11
10 #include "gnomeglobalshortcutbackend.h"
11 #endif
12 #ifdef Q_WS_MAC
13 #include "mac_startup.h"
14 #include "macfullscreen.h"
15 #include "macsupport.h"
16 #include "macutils.h"
17 #endif
18 #include "downloadmanager.h"
19 #include "youtubesuggest.h"
20 #include "updatechecker.h"
21 #include "temporary.h"
22 #ifdef APP_MAC
23 #include "searchlineedit_mac.h"
24 #else
25 #include "searchlineedit.h"
26 #endif
27 #include <iostream>
28 #ifndef Q_WS_X11
29 #include "extra.h"
30 #include "updatedialog.h"
31 #endif
32 #ifdef APP_ACTIVATION
33 #include "activation.h"
34 #include "activationview.h"
35 #include "activationdialog.h"
36 #endif
37
38 static MainWindow *singleton = 0;
39
40 MainWindow* MainWindow::instance() {
41     if (!singleton) singleton = new MainWindow();
42     return singleton;
43 }
44
45 MainWindow::MainWindow() :
46         updateChecker(0),
47         aboutView(0),
48         downloadView(0),
49         mediaObject(0),
50         audioOutput(0),
51         m_fullscreen(false) {
52
53     singleton = this;
54
55     // views mechanism
56     history = new QStack<QWidget*>();
57     views = new QStackedWidget(this);
58
59     // views
60     searchView = new SearchView(this);
61     connect(searchView, SIGNAL(search(SearchParams*)), this, SLOT(showMedia(SearchParams*)));
62     views->addWidget(searchView);
63
64     mediaView = new MediaView(this);
65     mediaView->setEnabled(false);
66     views->addWidget(mediaView);
67
68     // build ui
69     createActions();
70     createMenus();
71     createToolBars();
72     createStatusBar();
73
74     initPhonon();
75     mediaView->setSlider(seekSlider);
76     mediaView->setMediaObject(mediaObject);
77
78     // remove that useless menu/toolbar context menu
79     this->setContextMenuPolicy(Qt::NoContextMenu);
80
81     // mediaView init stuff thats needs actions
82     mediaView->initialize();
83
84     // event filter to block ugly toolbar tooltips
85     qApp->installEventFilter(this);
86
87     setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
88
89     // restore window position
90     readSettings();
91
92     // fix stacked widget minimum size
93     for (int i = 0; i < views->count(); i++) {
94         QWidget* view = views->widget(i);
95         if (view) view->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
96     }
97     setMinimumWidth(0);
98
99     // show the initial view
100     showSearch(false);
101
102 #ifdef APP_ACTIVATION
103     if (!Activation::instance().isActivated())
104         showActivationView(false);
105 #endif
106
107     setCentralWidget(views);
108
109     // Global shortcuts
110     GlobalShortcuts &shortcuts = GlobalShortcuts::instance();
111 #ifdef Q_WS_X11
112     if (GnomeGlobalShortcutBackend::IsGsdAvailable())
113         shortcuts.setBackend(new GnomeGlobalShortcutBackend(&shortcuts));
114 #endif
115 #ifdef Q_WS_MAC
116     mac::MacSetup();
117 #endif
118     connect(&shortcuts, SIGNAL(PlayPause()), pauseAct, SLOT(trigger()));
119     connect(&shortcuts, SIGNAL(Stop()), this, SLOT(stop()));
120     connect(&shortcuts, SIGNAL(Next()), skipAct, SLOT(trigger()));
121     connect(&shortcuts, SIGNAL(Previous()), skipBackwardAct, SLOT(trigger()));
122     // connect(&shortcuts, SIGNAL(StopAfter()), The::globalActions()->value("stopafterthis"), SLOT(toggle()));
123
124     connect(DownloadManager::instance(), SIGNAL(statusMessageChanged(QString)),
125             SLOT(updateDownloadMessage(QString)));
126     connect(DownloadManager::instance(), SIGNAL(finished()),
127             SLOT(downloadsFinished()));
128
129     setAcceptDrops(true);
130
131     mouseTimer = new QTimer(this);
132     mouseTimer->setInterval(5000);
133     mouseTimer->setSingleShot(true);
134     connect(mouseTimer, SIGNAL(timeout()), SLOT(hideMouse()));
135
136     QTimer::singleShot(0, this, SLOT(checkForUpdate()));
137
138 }
139
140 MainWindow::~MainWindow() {
141     delete history;
142 }
143
144 void MainWindow::changeEvent(QEvent* event) {
145 #ifdef APP_MAC
146     if (event->type() == QEvent::WindowStateChange) {
147         The::globalActions()->value("minimize")->setEnabled(!isMinimized());
148     }
149 #endif
150     QMainWindow::changeEvent(event);
151 }
152
153 bool MainWindow::eventFilter(QObject *obj, QEvent *event) {
154
155     if (m_fullscreen && event->type() == QEvent::MouseMove) {
156
157         QMouseEvent *mouseEvent = static_cast<QMouseEvent*> (event);
158         const int x = mouseEvent->pos().x();
159         const QString className = QString(obj->metaObject()->className());
160         const bool isHoveringVideo = (className == "QGLWidget") || (className == "VideoAreaWidget");
161
162         // qDebug() << obj << mouseEvent->pos() << isHoveringVideo << mediaView->isPlaylistVisible();
163
164         if (mediaView->isPlaylistVisible()) {
165             if (isHoveringVideo && x > 5) mediaView->setPlaylistVisible(false);
166         } else {
167             if (isHoveringVideo && x >= 0 && x < 5) mediaView->setPlaylistVisible(true);
168         }
169
170 #ifndef APP_MAC
171         const int y = mouseEvent->pos().y();
172         if (mainToolBar->isVisible()) {
173             if (isHoveringVideo && y > 5) mainToolBar->setVisible(false);
174         } else {
175             if (isHoveringVideo && y >= 0 && y < 5) mainToolBar->setVisible(true);
176         }
177 #endif
178
179         // show the normal cursor
180         unsetCursor();
181         // then hide it again after a few seconds
182         mouseTimer->start();
183
184     }
185
186     if (event->type() == QEvent::ToolTip) {
187         // kill tooltips
188         return true;
189     }
190     // standard event processing
191     return QMainWindow::eventFilter(obj, event);
192 }
193
194 void MainWindow::createActions() {
195
196     QMap<QString, QAction*> *actions = The::globalActions();
197
198     stopAct = new QAction(QtIconLoader::icon("media-playback-stop"), tr("&Stop"), this);
199     stopAct->setStatusTip(tr("Stop playback and go back to the search view"));
200     stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Escape) << QKeySequence(Qt::Key_MediaStop));
201     stopAct->setEnabled(false);
202     actions->insert("stop", stopAct);
203     connect(stopAct, SIGNAL(triggered()), this, SLOT(stop()));
204
205     skipBackwardAct = new QAction(
206                 QtIconLoader::icon("media-skip-backward"),
207                 tr("P&revious"), this);
208     skipBackwardAct->setStatusTip(tr("Go back to the previous track"));
209     skipBackwardAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Left));
210 #if QT_VERSION >= 0x040600
211     skipBackwardAct->setPriority(QAction::LowPriority);
212 #endif
213     skipBackwardAct->setEnabled(false);
214     actions->insert("previous", skipBackwardAct);
215     connect(skipBackwardAct, SIGNAL(triggered()), mediaView, SLOT(skipBackward()));
216
217     skipAct = new QAction(QtIconLoader::icon("media-skip-forward"), tr("S&kip"), this);
218     skipAct->setStatusTip(tr("Skip to the next video"));
219     skipAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_Right) << QKeySequence(Qt::Key_MediaNext));
220     skipAct->setEnabled(false);
221     actions->insert("skip", skipAct);
222     connect(skipAct, SIGNAL(triggered()), mediaView, SLOT(skip()));
223
224     pauseAct = new QAction(QtIconLoader::icon("media-playback-pause"), tr("&Pause"), this);
225     pauseAct->setStatusTip(tr("Pause playback"));
226     pauseAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Space) << QKeySequence(Qt::Key_MediaPlay));
227     pauseAct->setEnabled(false);
228     actions->insert("pause", pauseAct);
229     connect(pauseAct, SIGNAL(triggered()), mediaView, SLOT(pause()));
230
231     fullscreenAct = new QAction(QtIconLoader::icon("view-fullscreen"), tr("&Full Screen"), this);
232     fullscreenAct->setStatusTip(tr("Go full screen"));
233     QList<QKeySequence> fsShortcuts;
234 #ifdef APP_MAC
235     fsShortcuts << QKeySequence(Qt::CTRL + Qt::META + Qt::Key_F);
236 #else
237     fsShortcuts << QKeySequence(Qt::Key_F11) << QKeySequence(Qt::ALT + Qt::Key_Return);
238 #endif
239     fullscreenAct->setShortcuts(fsShortcuts);
240     fullscreenAct->setShortcutContext(Qt::ApplicationShortcut);
241 #if QT_VERSION >= 0x040600
242     fullscreenAct->setPriority(QAction::LowPriority);
243 #endif
244     actions->insert("fullscreen", fullscreenAct);
245     connect(fullscreenAct, SIGNAL(triggered()), this, SLOT(fullscreen()));
246
247     compactViewAct = new QAction(tr("&Compact Mode"), this);
248     compactViewAct->setStatusTip(tr("Hide the playlist and the toolbar"));
249 #ifdef APP_MAC
250     compactViewAct->setShortcut(QKeySequence(Qt::CTRL + Qt::META + Qt::Key_C));
251 #else
252     compactViewAct->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C));
253 #endif
254     compactViewAct->setCheckable(true);
255     compactViewAct->setChecked(false);
256     compactViewAct->setEnabled(false);
257     actions->insert("compactView", compactViewAct);
258     connect(compactViewAct, SIGNAL(toggled(bool)), this, SLOT(compactView(bool)));
259
260     webPageAct = new QAction(tr("Open the &YouTube Page"), this);
261     webPageAct->setStatusTip(tr("Go to the YouTube video page and pause playback"));
262     webPageAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Y));
263     webPageAct->setEnabled(false);
264     actions->insert("webpage", webPageAct);
265     connect(webPageAct, SIGNAL(triggered()), mediaView, SLOT(openWebPage()));
266
267     copyPageAct = new QAction(tr("Copy the YouTube &Link"), this);
268     copyPageAct->setStatusTip(tr("Copy the current video YouTube link to the clipboard"));
269     copyPageAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
270     copyPageAct->setEnabled(false);
271     actions->insert("pagelink", copyPageAct);
272     connect(copyPageAct, SIGNAL(triggered()), mediaView, SLOT(copyWebPage()));
273
274     copyLinkAct = new QAction(tr("Copy the Video Stream &URL"), this);
275     copyLinkAct->setStatusTip(tr("Copy the current video stream URL to the clipboard"));
276     copyLinkAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_U));
277     copyLinkAct->setEnabled(false);
278     actions->insert("videolink", copyLinkAct);
279     connect(copyLinkAct, SIGNAL(triggered()), mediaView, SLOT(copyVideoLink()));
280
281     findVideoPartsAct = new QAction(tr("Find Video &Parts"), this);
282     findVideoPartsAct->setStatusTip(tr("Find other video parts hopefully in the right order"));
283     findVideoPartsAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_P));
284     findVideoPartsAct->setEnabled(false);
285     connect(findVideoPartsAct, SIGNAL(triggered()), mediaView, SLOT(findVideoParts()));
286     actions->insert("findVideoParts", findVideoPartsAct);
287
288     removeAct = new QAction(tr("&Remove"), this);
289     removeAct->setStatusTip(tr("Remove the selected videos from the playlist"));
290     removeAct->setShortcuts(QList<QKeySequence>() << QKeySequence("Del") << QKeySequence("Backspace"));
291     removeAct->setEnabled(false);
292     actions->insert("remove", removeAct);
293     connect(removeAct, SIGNAL(triggered()), mediaView, SLOT(removeSelected()));
294
295     moveUpAct = new QAction(tr("Move &Up"), this);
296     moveUpAct->setStatusTip(tr("Move up the selected videos in the playlist"));
297     moveUpAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Up));
298     moveUpAct->setEnabled(false);
299     actions->insert("moveUp", moveUpAct);
300     connect(moveUpAct, SIGNAL(triggered()), mediaView, SLOT(moveUpSelected()));
301
302     moveDownAct = new QAction(tr("Move &Down"), this);
303     moveDownAct->setStatusTip(tr("Move down the selected videos in the playlist"));
304     moveDownAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Down));
305     moveDownAct->setEnabled(false);
306     actions->insert("moveDown", moveDownAct);
307     connect(moveDownAct, SIGNAL(triggered()), mediaView, SLOT(moveDownSelected()));
308
309     clearAct = new QAction(tr("&Clear Recent Searches"), this);
310     clearAct->setMenuRole(QAction::ApplicationSpecificRole);
311     clearAct->setShortcuts(QList<QKeySequence>()
312                            << QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Delete)
313                            << QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Backspace));
314     clearAct->setStatusTip(tr("Clear the search history. Cannot be undone."));
315     clearAct->setEnabled(true);
316     actions->insert("clearRecentKeywords", clearAct);
317     connect(clearAct, SIGNAL(triggered()), SLOT(clearRecentKeywords()));
318
319     quitAct = new QAction(tr("&Quit"), this);
320     quitAct->setMenuRole(QAction::QuitRole);
321     quitAct->setShortcut(QKeySequence(QKeySequence::Quit));
322     quitAct->setStatusTip(tr("Bye"));
323     actions->insert("quit", quitAct);
324     connect(quitAct, SIGNAL(triggered()), SLOT(quit()));
325
326     siteAct = new QAction(tr("&Website"), this);
327     siteAct->setShortcut(QKeySequence::HelpContents);
328     siteAct->setStatusTip(tr("%1 on the Web").arg(Constants::NAME));
329     actions->insert("site", siteAct);
330     connect(siteAct, SIGNAL(triggered()), this, SLOT(visitSite()));
331
332 #if !defined(APP_MAC) && !defined(APP_WIN)
333     donateAct = new QAction(tr("Make a &Donation"), this);
334     donateAct->setStatusTip(tr("Please support the continued development of %1").arg(Constants::NAME));
335     actions->insert("donate", donateAct);
336     connect(donateAct, SIGNAL(triggered()), this, SLOT(donate()));
337 #endif
338
339     aboutAct = new QAction(tr("&About"), this);
340     aboutAct->setMenuRole(QAction::AboutRole);
341     aboutAct->setStatusTip(tr("Info about %1").arg(Constants::NAME));
342     actions->insert("about", aboutAct);
343     connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
344
345     // Invisible actions
346
347     searchFocusAct = new QAction(this);
348     searchFocusAct->setShortcut(QKeySequence::Find);
349     searchFocusAct->setStatusTip(tr("Search"));
350     actions->insert("search", searchFocusAct);
351     connect(searchFocusAct, SIGNAL(triggered()), this, SLOT(searchFocus()));
352     addAction(searchFocusAct);
353
354     volumeUpAct = new QAction(this);
355     volumeUpAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_Plus));
356     actions->insert("volume-up", volumeUpAct);
357     connect(volumeUpAct, SIGNAL(triggered()), this, SLOT(volumeUp()));
358     addAction(volumeUpAct);
359
360     volumeDownAct = new QAction(this);
361     volumeDownAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_Minus));
362     actions->insert("volume-down", volumeDownAct);
363     connect(volumeDownAct, SIGNAL(triggered()), this, SLOT(volumeDown()));
364     addAction(volumeDownAct);
365
366     volumeMuteAct = new QAction(this);
367     volumeMuteAct->setIcon(QtIconLoader::icon("audio-volume-high"));
368     volumeMuteAct->setStatusTip(tr("Mute volume"));
369     volumeMuteAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_E));
370     actions->insert("volume-mute", volumeMuteAct);
371     connect(volumeMuteAct, SIGNAL(triggered()), SLOT(volumeMute()));
372     addAction(volumeMuteAct);
373
374     QAction *definitionAct = new QAction(this);
375     definitionAct->setIcon(QtIconLoader::icon("video-display"));
376     definitionAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_D));
377     /*
378     QMenu *definitionMenu = new QMenu(this);
379     foreach (QString definition, VideoDefinition::getDefinitionNames()) {
380         definitionMenu->addAction(definition);
381     }
382     definitionAct->setMenu(definitionMenu);
383     */
384     actions->insert("definition", definitionAct);
385     connect(definitionAct, SIGNAL(triggered()), SLOT(toggleDefinitionMode()));
386     addAction(definitionAct);
387
388     QAction *action;
389
390     action = new QAction(QtIconLoader::icon("media-playback-start"), tr("&Manually Start Playing"), this);
391     action->setStatusTip(tr("Manually start playing videos"));
392     action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_B));
393     action->setCheckable(true);
394     connect(action, SIGNAL(toggled(bool)), SLOT(setManualPlay(bool)));
395     actions->insert("manualplay", action);
396
397     action = new QAction(tr("&Downloads"), this);
398     action->setStatusTip(tr("Show details about video downloads"));
399     action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_J));
400     action->setCheckable(true);
401     action->setIcon(QtIconLoader::icon("go-down"));
402     action->setVisible(false);
403     connect(action, SIGNAL(toggled(bool)), SLOT(toggleDownloads(bool)));
404     actions->insert("downloads", action);
405
406     action = new QAction(tr("&Download"), this);
407     action->setStatusTip(tr("Download the current video"));
408 #ifndef APP_NO_DOWNLOADS
409     action->setShortcut(QKeySequence::Save);
410 #endif
411     action->setIcon(QtIconLoader::icon("go-down"));
412     action->setEnabled(false);
413 #if QT_VERSION >= 0x040600
414     action->setPriority(QAction::LowPriority);
415 #endif
416     connect(action, SIGNAL(triggered()), mediaView, SLOT(downloadVideo()));
417     actions->insert("download", action);
418
419     /*
420     action = new QAction(tr("&Snapshot"), this);
421     action->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_S));
422     actions->insert("snapshot", action);
423     connect(action, SIGNAL(triggered()), mediaView, SLOT(snapshot()));
424     */
425
426     QString shareTip = tr("Share the current video using %1");
427
428     action = new QAction("&Twitter", this);
429     action->setStatusTip(shareTip.arg("Twitter"));
430     actions->insert("twitter", action);
431     connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaTwitter()));
432
433     action = new QAction("&Facebook", this);
434     action->setStatusTip(shareTip.arg("Facebook"));
435     actions->insert("facebook", action);
436     connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaFacebook()));
437
438     action = new QAction("&Buffer", this);
439     action->setStatusTip(shareTip.arg("Buffer"));
440     actions->insert("buffer", action);
441     connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaBuffer()));
442
443     action = new QAction(tr("&Email"), this);
444     action->setStatusTip(shareTip.arg(tr("Email")));
445     actions->insert("email", action);
446     connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaEmail()));
447
448     action = new QAction(tr("&Close"), this);
449     action->setShortcut(QKeySequence(QKeySequence::Close));
450     actions->insert("close", action);
451     connect(action, SIGNAL(triggered()), SLOT(close()));
452
453     action = new QAction(Constants::NAME, this);
454     action->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_1));
455     actions->insert("restore", action);
456     connect(action, SIGNAL(triggered()), SLOT(restore()));
457
458     action = new QAction(QtIconLoader::icon("go-top"), tr("&Float on Top"), this);
459     action->setCheckable(true);
460     actions->insert("ontop", action);
461     connect(action, SIGNAL(toggled(bool)), SLOT(floatOnTop(bool)));
462
463     action = new QAction(QtIconLoader::icon("media-playback-stop"), tr("&Stop After This Video"), this);
464     action->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Escape));
465     action->setCheckable(true);
466     action->setEnabled(false);
467     actions->insert("stopafterthis", action);
468     connect(action, SIGNAL(toggled(bool)), SLOT(showStopAfterThisInStatusBar(bool)));
469
470     action = new QAction(tr("&Report an Issue..."), this);
471     actions->insert("report-issue", action);
472     connect(action, SIGNAL(triggered()), SLOT(reportIssue()));
473
474     action = new QAction(tr("&Refine Search..."), this);
475     action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R));
476     action->setCheckable(true);
477     actions->insert("refine-search", action);
478
479 #ifdef APP_ACTIVATION
480     Extra::createActivationAction(tr("Buy %1...").arg(Constants::NAME));
481 #endif
482
483     // common action properties
484     foreach (QAction *action, actions->values()) {
485
486         // add actions to the MainWindow so that they work
487         // when the menu is hidden
488         addAction(action);
489
490         // never autorepeat.
491         // unexperienced users tend to keep keys pressed for a "long" time
492         action->setAutoRepeat(false);
493
494         // set to something more meaningful then the toolbar text
495         if (!action->statusTip().isEmpty())
496             action->setToolTip(action->statusTip());
497
498         // show keyboard shortcuts in the status bar
499         if (!action->shortcut().isEmpty())
500             action->setStatusTip(action->statusTip() + " (" + action->shortcut().toString(QKeySequence::NativeText) + ")");
501     }
502
503 }
504
505 void MainWindow::createMenus() {
506
507     QMap<QString, QMenu*> *menus = The::globalMenus();
508
509     fileMenu = menuBar()->addMenu(tr("&Application"));
510 #ifdef APP_ACTIVATION
511     QAction *buyAction = The::globalActions()->value("buy");
512     if (buyAction) fileMenu->addAction(buyAction);
513 #ifndef APP_MAC
514     fileMenu->addSeparator();
515 #endif
516 #endif
517     fileMenu->addAction(clearAct);
518 #ifndef APP_MAC
519     fileMenu->addSeparator();
520 #endif
521     fileMenu->addAction(quitAct);
522
523     QMenu* playbackMenu = menuBar()->addMenu(tr("&Playback"));
524     menus->insert("playback", playbackMenu);
525     playbackMenu->addAction(pauseAct);
526     playbackMenu->addAction(stopAct);
527     playbackMenu->addAction(The::globalActions()->value("stopafterthis"));
528     playbackMenu->addSeparator();
529     playbackMenu->addAction(skipAct);
530     playbackMenu->addAction(skipBackwardAct);
531     playbackMenu->addSeparator();
532     playbackMenu->addAction(The::globalActions()->value("manualplay"));
533 #ifdef APP_MAC
534     MacSupport::dockMenu(playbackMenu);
535 #endif
536
537     playlistMenu = menuBar()->addMenu(tr("&Playlist"));
538     menus->insert("playlist", playlistMenu);
539     playlistMenu->addAction(removeAct);
540     playlistMenu->addSeparator();
541     playlistMenu->addAction(moveUpAct);
542     playlistMenu->addAction(moveDownAct);
543     playlistMenu->addSeparator();
544     playlistMenu->addAction(The::globalActions()->value("refine-search"));
545
546     QMenu* videoMenu = menuBar()->addMenu(tr("&Video"));
547     menus->insert("video", videoMenu);
548     videoMenu->addAction(findVideoPartsAct);
549     videoMenu->addSeparator();
550     videoMenu->addAction(webPageAct);
551     videoMenu->addSeparator();
552 #ifndef APP_NO_DOWNLOADS
553     videoMenu->addAction(The::globalActions()->value("download"));
554     // videoMenu->addAction(copyLinkAct);
555 #endif
556     // videoMenu->addAction(The::globalActions()->value("snapshot"));
557
558     QMenu* viewMenu = menuBar()->addMenu(tr("&View"));
559     menus->insert("view", viewMenu);
560     viewMenu->addAction(fullscreenAct);
561     viewMenu->addAction(compactViewAct);
562     viewMenu->addSeparator();
563     viewMenu->addAction(The::globalActions()->value("ontop"));
564
565     QMenu* shareMenu = menuBar()->addMenu(tr("&Share"));
566     menus->insert("share", shareMenu);
567     shareMenu->addAction(copyPageAct);
568     shareMenu->addSeparator();
569     shareMenu->addAction(The::globalActions()->value("twitter"));
570     shareMenu->addAction(The::globalActions()->value("facebook"));
571     shareMenu->addAction(The::globalActions()->value("buffer"));
572     shareMenu->addSeparator();
573     shareMenu->addAction(The::globalActions()->value("email"));
574
575 #ifdef APP_MAC
576     MacSupport::windowMenu(this);
577 #endif
578
579     helpMenu = menuBar()->addMenu(tr("&Help"));
580     helpMenu->addAction(siteAct);
581 #if !defined(APP_MAC) && !defined(APP_WIN)
582     helpMenu->addAction(donateAct);
583 #endif
584     helpMenu->addAction(The::globalActions()->value("report-issue"));
585     helpMenu->addAction(aboutAct);
586 }
587
588 void MainWindow::createToolBars() {
589
590     setUnifiedTitleAndToolBarOnMac(true);
591
592     mainToolBar = new QToolBar(this);
593 #if QT_VERSION < 0x040600 | defined(APP_MAC)
594     mainToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
595 #else
596     mainToolBar->setToolButtonStyle(Qt::ToolButtonFollowStyle);
597 #endif
598     mainToolBar->setFloatable(false);
599     mainToolBar->setMovable(false);
600
601 #if defined(APP_MAC) | defined(APP_WIN)
602     mainToolBar->setIconSize(QSize(32, 32));
603 #endif
604
605     mainToolBar->addAction(stopAct);
606     mainToolBar->addAction(pauseAct);
607     mainToolBar->addAction(skipAct);
608
609     bool addFullScreenAct = true;
610 #ifdef Q_WS_MAC
611     addFullScreenAct = !mac::CanGoFullScreen(winId());
612 #endif
613     if (addFullScreenAct) mainToolBar->addAction(fullscreenAct);
614
615 #ifndef APP_NO_DOWNLOADS
616     mainToolBar->addAction(The::globalActions()->value("download"));
617 #endif
618
619     mainToolBar->addWidget(new Spacer());
620
621     QFont smallerFont = FontUtils::small();
622     currentTime = new QLabel(mainToolBar);
623     currentTime->setFont(smallerFont);
624     mainToolBar->addWidget(currentTime);
625
626     mainToolBar->addWidget(new Spacer());
627
628     seekSlider = new Phonon::SeekSlider(this);
629     seekSlider->setIconVisible(false);
630     seekSlider->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
631     mainToolBar->addWidget(seekSlider);
632
633 /*
634     mainToolBar->addWidget(new Spacer());
635     slider = new QSlider(this);
636     slider->setOrientation(Qt::Horizontal);
637     slider->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
638     mainToolBar->addWidget(slider);
639 */
640
641     mainToolBar->addWidget(new Spacer());
642
643     totalTime = new QLabel(mainToolBar);
644     totalTime->setFont(smallerFont);
645     mainToolBar->addWidget(totalTime);
646
647     mainToolBar->addWidget(new Spacer());
648
649     mainToolBar->addAction(volumeMuteAct);
650
651     volumeSlider = new Phonon::VolumeSlider(this);
652     volumeSlider->setMuteVisible(false);
653     // qDebug() << volumeSlider->children();
654     // status tip for the volume slider
655     QSlider* volumeQSlider = volumeSlider->findChild<QSlider*>();
656     if (volumeQSlider)
657         volumeQSlider->setStatusTip(tr("Press %1 to raise the volume, %2 to lower it").arg(
658                 volumeUpAct->shortcut().toString(QKeySequence::NativeText), volumeDownAct->shortcut().toString(QKeySequence::NativeText)));
659     // this makes the volume slider smaller
660     volumeSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
661     mainToolBar->addWidget(volumeSlider);
662
663     mainToolBar->addWidget(new Spacer());
664
665 #ifdef APP_MAC
666     SearchWrapper* searchWrapper = new SearchWrapper(this);
667     toolbarSearch = searchWrapper->getSearchLineEdit();
668 #else
669     toolbarSearch = new SearchLineEdit(this);
670 #endif
671     toolbarSearch->setMinimumWidth(toolbarSearch->fontInfo().pixelSize()*15);
672     toolbarSearch->setSuggester(new YouTubeSuggest(this));
673     connect(toolbarSearch, SIGNAL(search(const QString&)), this, SLOT(startToolbarSearch(const QString&)));
674     connect(toolbarSearch, SIGNAL(suggestionAccepted(const QString&)), SLOT(startToolbarSearch(const QString&)));
675     toolbarSearch->setStatusTip(searchFocusAct->statusTip());
676 #ifdef APP_MAC
677     mainToolBar->addWidget(searchWrapper);
678 #else
679     mainToolBar->addWidget(toolbarSearch);
680     Spacer* spacer = new Spacer();
681     // spacer->setWidth(4);
682     mainToolBar->addWidget(spacer);
683 #endif
684
685     addToolBar(mainToolBar);
686 }
687
688 void MainWindow::createStatusBar() {
689     QToolBar* toolBar = new QToolBar(this);
690     statusToolBar = toolBar;
691     toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
692     toolBar->setIconSize(QSize(16, 16));
693     toolBar->addAction(The::globalActions()->value("downloads"));
694     toolBar->addAction(The::globalActions()->value("definition"));
695     statusBar()->addPermanentWidget(toolBar);
696     statusBar()->show();
697 }
698
699 void MainWindow::showStopAfterThisInStatusBar(bool show) {
700     QAction* action = The::globalActions()->value("stopafterthis");
701     showActionInStatusBar(action, show);
702 }
703
704 void MainWindow::showActionInStatusBar(QAction* action, bool show) {
705     if (show) {
706         statusToolBar->insertAction(statusToolBar->actions().first(), action);
707     } else {
708         statusToolBar->removeAction(action);
709     }
710 }
711
712 void MainWindow::readSettings() {
713     QSettings settings;
714     if (settings.contains("geometry")) {
715         restoreGeometry(settings.value("geometry").toByteArray());
716 #ifdef APP_MAC
717     MacSupport::fixGeometry(this);
718 #endif
719     } else {
720         setGeometry(100, 100, 1000, 500);
721     }
722     setDefinitionMode(settings.value("definition", VideoDefinition::getDefinitionNames().first()).toString());
723     audioOutput->setVolume(settings.value("volume", 1).toDouble());
724     audioOutput->setMuted(settings.value("volumeMute").toBool());
725     The::globalActions()->value("manualplay")->setChecked(settings.value("manualplay", false).toBool());
726 }
727
728 void MainWindow::writeSettings() {
729     QSettings settings;
730
731     settings.setValue("geometry", saveGeometry());
732     mediaView->saveSplitterState();
733
734     settings.setValue("volume", audioOutput->volume());
735     settings.setValue("volumeMute", audioOutput->isMuted());
736     settings.setValue("manualplay", The::globalActions()->value("manualplay")->isChecked());
737 }
738
739 void MainWindow::goBack() {
740     if ( history->size() > 1 ) {
741         history->pop();
742         QWidget *widget = history->pop();
743         showWidget(widget);
744     }
745 }
746
747 void MainWindow::showWidget(QWidget* widget, bool transition) {
748
749     if (compactViewAct->isChecked())
750         compactViewAct->toggle();
751
752     setUpdatesEnabled(false);
753
754     // call hide method on the current view
755     View* oldView = dynamic_cast<View *> (views->currentWidget());
756     if (oldView) {
757         oldView->disappear();
758         views->currentWidget()->setEnabled(false);
759     } else qDebug() << "Cannot cast view";
760
761     // call show method on the new view
762     View* newView = dynamic_cast<View *> (widget);
763     if (newView) {
764         widget->setEnabled(true);
765         newView->appear();
766         QMap<QString,QVariant> metadata = newView->metadata();
767         QString windowTitle = metadata.value("title").toString();
768         if (windowTitle.length())
769             windowTitle += " - ";
770         setWindowTitle(windowTitle + Constants::NAME);
771         statusBar()->showMessage((metadata.value("description").toString()));
772     }
773
774     const bool isMediaView = widget == mediaView;
775
776     stopAct->setEnabled(isMediaView);
777     compactViewAct->setEnabled(isMediaView);
778     webPageAct->setEnabled(isMediaView);
779     copyPageAct->setEnabled(isMediaView);
780     copyLinkAct->setEnabled(isMediaView);
781     findVideoPartsAct->setEnabled(isMediaView);
782     toolbarSearch->setEnabled(widget == searchView || isMediaView || widget == downloadView);
783
784     if (widget == searchView) {
785         skipAct->setEnabled(false);
786         The::globalActions()->value("previous")->setEnabled(false);
787         The::globalActions()->value("download")->setEnabled(false);
788         The::globalActions()->value("stopafterthis")->setEnabled(false);
789     }
790
791     The::globalActions()->value("twitter")->setEnabled(isMediaView);
792     The::globalActions()->value("facebook")->setEnabled(isMediaView);
793     The::globalActions()->value("buffer")->setEnabled(isMediaView);
794     The::globalActions()->value("email")->setEnabled(isMediaView);
795
796     aboutAct->setEnabled(widget != aboutView);
797     The::globalActions()->value("downloads")->setChecked(widget == downloadView);
798
799     setUpdatesEnabled(true);
800
801     QWidget *oldWidget = views->currentWidget();
802     if (oldWidget)
803         oldWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
804
805     views->setCurrentWidget(widget);
806     widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
807
808 #ifndef Q_WS_X11
809     if (transition) Extra::fadeInWidget(oldWidget, widget);
810 #endif
811
812     history->push(widget);
813 }
814
815 void MainWindow::about() {
816     if (!aboutView) {
817         aboutView = new AboutView(this);
818         views->addWidget(aboutView);
819     }
820     showWidget(aboutView);
821 }
822
823 void MainWindow::visitSite() {
824     QUrl url(Constants::WEBSITE);
825     statusBar()->showMessage(QString(tr("Opening %1").arg(url.toString())));
826     QDesktopServices::openUrl(url);
827 }
828
829 void MainWindow::donate() {
830     QUrl url(QString(Constants::WEBSITE) + "#donate");
831     statusBar()->showMessage(QString(tr("Opening %1").arg(url.toString())));
832     QDesktopServices::openUrl(url);
833 }
834
835 void MainWindow::reportIssue() {
836     QUrl url("http://flavio.tordini.org/forums/forum/minitube-forums/minitube-troubleshooting");
837     QDesktopServices::openUrl(url);
838 }
839
840 void MainWindow::quit() {
841 #ifdef APP_MAC
842     if (!confirmQuit()) {
843         return;
844     }
845 #endif
846     // do not save geometry when in full screen or in compact mode
847     if (!m_fullscreen && !compactViewAct->isChecked()) {
848         writeSettings();
849     }
850     Temporary::deleteAll();
851     qApp->quit();
852 }
853
854 void MainWindow::closeEvent(QCloseEvent *event) {
855 #ifdef APP_MAC
856     mac::closeWindow(winId());
857     event->ignore();
858 #else
859     if (!confirmQuit()) {
860         event->ignore();
861         return;
862     }
863     QWidget::closeEvent(event);
864     quit();
865 #endif
866 }
867
868 bool MainWindow::confirmQuit() {
869     if (DownloadManager::instance()->activeItems() > 0) {
870         QMessageBox msgBox(this);
871         msgBox.setIconPixmap(QPixmap(":/images/app.png").scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
872         msgBox.setText(tr("Do you want to exit %1 with a download in progress?").arg(Constants::NAME));
873         msgBox.setInformativeText(tr("If you close %1 now, this download will be cancelled.").arg(Constants::NAME));
874         msgBox.setModal(true);
875         // make it a "sheet" on the Mac
876         msgBox.setWindowModality(Qt::WindowModal);
877
878         msgBox.addButton(tr("Close and cancel download"), QMessageBox::RejectRole);
879         QPushButton *waitButton = msgBox.addButton(tr("Wait for download to finish"), QMessageBox::ActionRole);
880
881         msgBox.exec();
882
883         if (msgBox.clickedButton() == waitButton) {
884             return false;
885         }
886     }
887     return true;
888 }
889
890 void MainWindow::showSearch(bool transition) {
891     showWidget(searchView, transition);
892     currentTime->clear();
893     totalTime->clear();
894 }
895
896 void MainWindow::showMedia(SearchParams *searchParams) {
897     mediaView->search(searchParams);
898     showWidget(mediaView);
899 }
900
901 void MainWindow::stateChanged(Phonon::State newState, Phonon::State /* oldState */) {
902
903     // qDebug() << "Phonon state: " << newState;
904
905     switch (newState) {
906
907     case Phonon::ErrorState:
908         if (mediaObject->errorType() == Phonon::FatalError) {
909             // Do not display because we try to play incomplete video files and sometimes trigger this
910             // We retry automatically (in MediaView) so no need to show it
911             // statusBar()->showMessage(tr("Fatal error: %1").arg(mediaObject->errorString()));
912         } else {
913             statusBar()->showMessage(tr("Error: %1").arg(mediaObject->errorString()));
914         }
915         break;
916
917          case Phonon::PlayingState:
918         pauseAct->setEnabled(true);
919         pauseAct->setIcon(QtIconLoader::icon("media-playback-pause"));
920         pauseAct->setText(tr("&Pause"));
921         pauseAct->setStatusTip(tr("Pause playback") + " (" +  pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
922         // stopAct->setEnabled(true);
923         break;
924
925          case Phonon::StoppedState:
926         pauseAct->setEnabled(false);
927         // stopAct->setEnabled(false);
928         break;
929
930          case Phonon::PausedState:
931         pauseAct->setEnabled(true);
932         pauseAct->setIcon(QtIconLoader::icon("media-playback-start"));
933         pauseAct->setText(tr("&Play"));
934         pauseAct->setStatusTip(tr("Resume playback") + " (" +  pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
935         // stopAct->setEnabled(true);
936         break;
937
938          case Phonon::BufferingState:
939          case Phonon::LoadingState:
940         pauseAct->setEnabled(false);
941         currentTime->clear();
942         totalTime->clear();
943         // stopAct->setEnabled(true);
944         break;
945
946          default:
947         ;
948     }
949 }
950
951 void MainWindow::stop() {
952     mediaView->stop();
953     showSearch();
954 }
955
956 void MainWindow::resizeEvent(QResizeEvent*) {
957 #ifdef Q_WS_MAC
958     if (mac::CanGoFullScreen(winId())) {
959         bool isFullscreen = mac::IsFullScreen(winId());
960         if (isFullscreen != m_fullscreen) {
961             if (compactViewAct->isChecked()) {
962                 compactViewAct->setChecked(false);
963                 compactView(false);
964             }
965             m_fullscreen = isFullscreen;
966             updateUIForFullscreen();
967         }
968     }
969 #endif
970 }
971
972 void MainWindow::fullscreen() {
973
974     if (compactViewAct->isChecked())
975         compactViewAct->toggle();
976
977 #ifdef Q_WS_MAC
978     WId handle = winId();
979     if (mac::CanGoFullScreen(handle)) {
980         mainToolBar->setVisible(true);
981         mac::ToggleFullScreen(handle);
982         return;
983     }
984 #endif
985
986     m_fullscreen = !m_fullscreen;
987
988     if (m_fullscreen) {
989         // Enter full screen
990
991         m_maximized = isMaximized();
992
993         // save geometry now, if the user quits when in full screen
994         // geometry won't be saved
995         writeSettings();
996
997 #ifdef Q_WS_MAC
998         MacSupport::enterFullScreen(this, views);
999 #else
1000         mainToolBar->hide();
1001         showFullScreen();
1002 #endif
1003
1004     } else {
1005         // Exit full screen
1006
1007 #ifdef Q_WS_MAC
1008         MacSupport::exitFullScreen(this, views);
1009 #else
1010         mainToolBar->show();
1011         if (m_maximized) showMaximized();
1012         else showNormal();
1013 #endif
1014
1015         // Make sure the window has focus
1016         activateWindow();
1017
1018     }
1019
1020     updateUIForFullscreen();
1021
1022 }
1023
1024 void MainWindow::updateUIForFullscreen() {
1025     static QList<QKeySequence> fsShortcuts;
1026     static QString fsText;
1027
1028     if (m_fullscreen) {
1029         fsShortcuts = fullscreenAct->shortcuts();
1030         fsText = fullscreenAct->text();
1031         fullscreenAct->setShortcuts(QList<QKeySequence>(fsShortcuts)
1032                                     << QKeySequence(Qt::Key_Escape));
1033         fullscreenAct->setText(tr("Leave &Full Screen"));
1034     } else {
1035         fullscreenAct->setShortcuts(fsShortcuts);
1036         fullscreenAct->setText(fsText);
1037     }
1038
1039     // No compact view action when in full screen
1040     compactViewAct->setVisible(!m_fullscreen);
1041     compactViewAct->setChecked(false);
1042
1043     // Hide anything but the video
1044     mediaView->setPlaylistVisible(!m_fullscreen);
1045     statusBar()->setVisible(!m_fullscreen);
1046
1047 #ifndef APP_MAC
1048     menuBar()->setVisible(!m_fullscreen);
1049 #endif
1050
1051     if (m_fullscreen) {
1052         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_MediaStop));
1053     } else {
1054         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Escape) << QKeySequence(Qt::Key_MediaStop));
1055     }
1056
1057 #ifdef Q_WS_MAC
1058     MacSupport::fullScreenActions(The::globalActions()->values(), m_fullscreen);
1059 #endif
1060
1061     if (views->currentWidget() == mediaView)
1062         mediaView->setFocus();
1063
1064     if (m_fullscreen) {
1065         hideMouse();
1066     } else {
1067         mouseTimer->stop();
1068         unsetCursor();
1069     }
1070 }
1071
1072 void MainWindow::compactView(bool enable) {
1073
1074     static QList<QKeySequence> compactShortcuts;
1075     static QList<QKeySequence> stopShortcuts;
1076
1077     const static QString key = "compactGeometry";
1078     QSettings settings;
1079
1080 #ifndef APP_MAC
1081     menuBar()->setVisible(!enable);
1082 #endif
1083
1084     if (enable) {
1085         setMinimumSize(160, 120);
1086 #ifdef Q_WS_MAC
1087         mac::RemoveFullScreenWindow(winId());
1088 #endif
1089         writeSettings();
1090
1091         if (settings.contains(key))
1092             restoreGeometry(settings.value(key).toByteArray());
1093         else
1094             resize(320, 240);
1095
1096         mainToolBar->setVisible(!enable);
1097         mediaView->setPlaylistVisible(!enable);
1098         statusBar()->setVisible(!enable);
1099
1100         compactShortcuts = compactViewAct->shortcuts();
1101         stopShortcuts = stopAct->shortcuts();
1102
1103         QList<QKeySequence> newStopShortcuts(stopShortcuts);
1104         newStopShortcuts.removeAll(QKeySequence(Qt::Key_Escape));
1105         stopAct->setShortcuts(newStopShortcuts);
1106         compactViewAct->setShortcuts(QList<QKeySequence>(compactShortcuts) << QKeySequence(Qt::Key_Escape));
1107
1108         // ensure focus does not end up to the search box
1109         // as it would steal the Space shortcut
1110         mediaView->setFocus();
1111
1112     } else {
1113         // unset minimum size
1114         setMinimumSize(0, 0);
1115 #ifdef Q_WS_MAC
1116         mac::SetupFullScreenWindow(winId());
1117 #endif
1118         settings.setValue(key, saveGeometry());
1119         mainToolBar->setVisible(!enable);
1120         mediaView->setPlaylistVisible(!enable);
1121         statusBar()->setVisible(!enable);
1122         readSettings();
1123
1124         compactViewAct->setShortcuts(compactShortcuts);
1125         stopAct->setShortcuts(stopShortcuts);
1126     }
1127
1128     // auto float on top
1129     floatOnTop(enable);
1130 }
1131
1132 void MainWindow::searchFocus() {
1133     toolbarSearch->selectAll();
1134     toolbarSearch->setFocus();
1135 }
1136
1137 void MainWindow::initPhonon() {
1138     // Phonon initialization
1139     if (mediaObject) delete mediaObject;
1140     if (audioOutput) delete audioOutput;
1141     mediaObject = new Phonon::MediaObject(this);
1142     mediaObject->setTickInterval(100);
1143     connect(mediaObject, SIGNAL(stateChanged(Phonon::State, Phonon::State)),
1144             this, SLOT(stateChanged(Phonon::State, Phonon::State)));
1145     connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(tick(qint64)));
1146     connect(mediaObject, SIGNAL(totalTimeChanged(qint64)), this, SLOT(totalTimeChanged(qint64)));
1147     seekSlider->setMediaObject(mediaObject);
1148     audioOutput = new Phonon::AudioOutput(Phonon::VideoCategory, this);
1149     connect(audioOutput, SIGNAL(volumeChanged(qreal)), this, SLOT(volumeChanged(qreal)));
1150     connect(audioOutput, SIGNAL(mutedChanged(bool)), this, SLOT(volumeMutedChanged(bool)));
1151     volumeSlider->setAudioOutput(audioOutput);
1152     Phonon::createPath(mediaObject, audioOutput);
1153 }
1154
1155 void MainWindow::tick(qint64 time) {
1156     if (time <= 0) {
1157         // the "if" is important because tick is continually called
1158         // and we don't want to paint the toolbar every 100ms
1159         if (!currentTime->text().isEmpty()) currentTime->clear();
1160         return;
1161     }
1162
1163     currentTime->setText(formatTime(time));
1164
1165     // remaining time
1166     const qint64 remainingTime = mediaObject->remainingTime();
1167     currentTime->setStatusTip(tr("Remaining time: %1").arg(formatTime(remainingTime)));
1168
1169     /*
1170     slider->blockSignals(true);
1171     slider->setValue(time/1000);
1172     slider->blockSignals(false);
1173     */
1174 }
1175
1176 void MainWindow::totalTimeChanged(qint64 time) {
1177     if (time <= 0) {
1178         totalTime->clear();
1179         return;
1180     }
1181     totalTime->setText(formatTime(time));
1182
1183     /*
1184     slider->blockSignals(true);
1185     slider->setMaximum(time/1000);
1186     slider->blockSignals(false);
1187     */
1188
1189 }
1190
1191 QString MainWindow::formatTime(qint64 time) {
1192     QTime displayTime;
1193     displayTime = displayTime.addMSecs(time);
1194     QString timeString;
1195     // 60 * 60 * 1000 = 3600000
1196     if (time > 3600000)
1197         timeString = displayTime.toString("h:mm:ss");
1198     else
1199         timeString = displayTime.toString("m:ss");
1200     return timeString;
1201 }
1202
1203 void MainWindow::volumeUp() {
1204     qreal newVolume = volumeSlider->audioOutput()->volume() + .1;
1205     if (newVolume > volumeSlider->maximumVolume())
1206         newVolume = volumeSlider->maximumVolume();
1207     volumeSlider->audioOutput()->setVolume(newVolume);
1208 }
1209
1210 void MainWindow::volumeDown() {
1211     qreal newVolume = volumeSlider->audioOutput()->volume() - .1;
1212     if (newVolume < 0)
1213         newVolume = 0;
1214     volumeSlider->audioOutput()->setVolume(newVolume);
1215 }
1216
1217 void MainWindow::volumeMute() {
1218     volumeSlider->audioOutput()->setMuted(!volumeSlider->audioOutput()->isMuted());
1219 }
1220
1221 void MainWindow::volumeChanged(qreal newVolume) {
1222     // automatically unmute when volume changes
1223     if (volumeSlider->audioOutput()->isMuted())
1224         volumeSlider->audioOutput()->setMuted(false);
1225     statusBar()->showMessage(tr("Volume at %1%").arg((int)(newVolume*100)));
1226 }
1227
1228 void MainWindow::volumeMutedChanged(bool muted) {
1229     if (muted) {
1230         volumeMuteAct->setIcon(QtIconLoader::icon("audio-volume-muted"));
1231         statusBar()->showMessage(tr("Volume is muted"));
1232     } else {
1233         volumeMuteAct->setIcon(QtIconLoader::icon("audio-volume-high"));
1234         statusBar()->showMessage(tr("Volume is unmuted"));
1235     }
1236 }
1237
1238 void MainWindow::setDefinitionMode(QString definitionName) {
1239     QAction *definitionAct = The::globalActions()->value("definition");
1240     definitionAct->setText(definitionName);
1241     definitionAct->setStatusTip(tr("Maximum video definition set to %1").arg(definitionAct->text())
1242                                 + " (" +  definitionAct->shortcut().toString(QKeySequence::NativeText) + ")");
1243     statusBar()->showMessage(definitionAct->statusTip());
1244     QSettings settings;
1245     settings.setValue("definition", definitionName);
1246 }
1247
1248 void MainWindow::toggleDefinitionMode() {
1249     QSettings settings;
1250     QString currentDefinition = settings.value("definition").toString();
1251     QStringList definitionNames = VideoDefinition::getDefinitionNames();
1252     int currentIndex = definitionNames.indexOf(currentDefinition);
1253     int nextIndex = 0;
1254     if (currentIndex != definitionNames.size() - 1) {
1255         nextIndex = currentIndex + 1;
1256     }
1257     QString nextDefinition = definitionNames.at(nextIndex);
1258     setDefinitionMode(nextDefinition);
1259 }
1260
1261 void MainWindow::showFullscreenToolbar(bool show) {
1262     if (!m_fullscreen) return;
1263     mainToolBar->setVisible(show);
1264 }
1265
1266 void MainWindow::showFullscreenPlaylist(bool show) {
1267     if (!m_fullscreen) return;
1268     mediaView->setPlaylistVisible(show);
1269 }
1270
1271 void MainWindow::clearRecentKeywords() {
1272     QSettings settings;
1273     settings.remove("recentKeywords");
1274     settings.remove("recentChannels");
1275     searchView->updateRecentKeywords();
1276     searchView->updateRecentChannels();
1277     statusBar()->showMessage(tr("Your privacy is now safe"));
1278 }
1279
1280 void MainWindow::setManualPlay(bool enabled) {
1281     QSettings settings;
1282     settings.setValue("manualplay", QVariant::fromValue(enabled));
1283     showActionInStatusBar(The::globalActions()->value("manualplay"), enabled);
1284 }
1285
1286 void MainWindow::updateDownloadMessage(QString message) {
1287     The::globalActions()->value("downloads")->setText(message);
1288 }
1289
1290 void MainWindow::downloadsFinished() {
1291     The::globalActions()->value("downloads")->setText(tr("&Downloads"));
1292     statusBar()->showMessage(tr("Downloads complete"));
1293 }
1294
1295 void MainWindow::toggleDownloads(bool show) {
1296
1297     if (show) {
1298         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_MediaStop));
1299         The::globalActions()->value("downloads")->setShortcuts(
1300                 QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_J)
1301                 << QKeySequence(Qt::Key_Escape));
1302     } else {
1303         The::globalActions()->value("downloads")->setShortcuts(
1304                 QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_J));
1305         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Escape) << QKeySequence(Qt::Key_MediaStop));
1306     }
1307
1308     if (!downloadView) {
1309         downloadView = new DownloadView(this);
1310         views->addWidget(downloadView);
1311     }
1312     if (show) showWidget(downloadView);
1313     else goBack();
1314 }
1315
1316 void MainWindow::startToolbarSearch(QString query) {
1317     query = query.trimmed();
1318
1319     // check for empty query
1320     if (query.length() == 0) {
1321         return;
1322     }
1323
1324     SearchParams *searchParams = new SearchParams();
1325     searchParams->setKeywords(query);
1326
1327     // go!
1328     showMedia(searchParams);
1329 }
1330
1331 void MainWindow::dragEnterEvent(QDragEnterEvent *event) {
1332     if (event->mimeData()->hasFormat("text/uri-list")) {
1333         QList<QUrl> urls = event->mimeData()->urls();
1334         if (urls.isEmpty())
1335             return;
1336         QUrl url = urls.first();
1337         QString videoId = YouTubeSearch::videoIdFromUrl(url.toString());
1338         if (!videoId.isNull())
1339             event->acceptProposedAction();
1340     }
1341 }
1342
1343 void MainWindow::dropEvent(QDropEvent *event) {
1344     QList<QUrl> urls = event->mimeData()->urls();
1345     if (urls.isEmpty())
1346         return;
1347     QUrl url = urls.first();
1348     QString videoId = YouTubeSearch::videoIdFromUrl(url.toString());
1349     if (!videoId.isNull()) {
1350         setWindowTitle(url.toString());
1351         SearchParams *searchParams = new SearchParams();
1352         searchParams->setKeywords(videoId);
1353         showMedia(searchParams);
1354     }
1355 }
1356
1357 void MainWindow::checkForUpdate() {
1358     static const QString updateCheckKey = "updateCheck";
1359
1360     // check every 24h
1361     QSettings settings;
1362     uint unixTime = QDateTime::currentDateTime().toTime_t();
1363     int lastCheck = settings.value(updateCheckKey).toInt();
1364     int secondsSinceLastCheck = unixTime - lastCheck;
1365     // qDebug() << "secondsSinceLastCheck" << unixTime << lastCheck << secondsSinceLastCheck;
1366     if (secondsSinceLastCheck < 86400) return;
1367
1368     // check it out
1369     if (updateChecker) delete updateChecker;
1370     updateChecker = new UpdateChecker();
1371     connect(updateChecker, SIGNAL(newVersion(QString)),
1372             this, SLOT(gotNewVersion(QString)));
1373     updateChecker->checkForUpdate();
1374     settings.setValue(updateCheckKey, unixTime);
1375 }
1376
1377 void MainWindow::gotNewVersion(QString version) {
1378     if (updateChecker) {
1379         delete updateChecker;
1380         updateChecker = 0;
1381     }
1382
1383     QSettings settings;
1384     QString checkedVersion = settings.value("checkedVersion").toString();
1385     if (checkedVersion == version) return;
1386
1387 #ifdef APP_SIMPLEUPDATE
1388     simpleUpdateDialog(version);
1389 #endif
1390 #if defined(APP_ACTIVATION) && !defined(APP_MAC)
1391     UpdateDialog *dialog = new UpdateDialog(version, this);
1392     dialog->show();
1393 #endif
1394 }
1395
1396 void MainWindow::simpleUpdateDialog(QString version) {
1397     QMessageBox msgBox(this);
1398     msgBox.setIconPixmap(
1399                 QPixmap(":/images/app.png")
1400                 .scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
1401     msgBox.setText(tr("%1 version %2 is now available.").arg(Constants::NAME, version));
1402     msgBox.setModal(true);
1403     msgBox.setWindowModality(Qt::WindowModal);
1404     msgBox.addButton(QMessageBox::Close);
1405     QPushButton* laterButton = msgBox.addButton(tr("Remind me later"), QMessageBox::RejectRole);
1406     QPushButton* updateButton = msgBox.addButton(tr("Update"), QMessageBox::AcceptRole);
1407     msgBox.exec();
1408     if (msgBox.clickedButton() != laterButton) {
1409         QSettings settings;
1410         settings.setValue("checkedVersion", version);
1411     }
1412     if (msgBox.clickedButton() == updateButton) visitSite();
1413 }
1414
1415 void MainWindow::floatOnTop(bool onTop) {
1416     showActionInStatusBar(The::globalActions()->value("ontop"), onTop);
1417 #ifdef APP_MAC
1418     mac::floatOnTop(winId(), onTop);
1419     return;
1420 #endif
1421     if (onTop) {
1422         setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
1423         show();
1424     } else {
1425         setWindowFlags(windowFlags() ^ Qt::WindowStaysOnTopHint);
1426         show();
1427     }
1428 }
1429
1430 void MainWindow::restore() {
1431 #ifdef APP_MAC
1432     mac::uncloseWindow(window()->winId());
1433 #endif
1434 }
1435
1436 void MainWindow::messageReceived(const QString &message) {
1437     if (message == "--toggle-playing") {
1438         if (pauseAct->isEnabled()) pauseAct->trigger();
1439     } else if (message == "--next") {
1440         if (skipAct->isEnabled()) skipAct->trigger();
1441     } else if (message == "--previous") {
1442         if (skipBackwardAct->isEnabled()) skipBackwardAct->trigger();
1443     }  else if (message.startsWith("--")) {
1444         MainWindow::printHelp();
1445     } else if (!message.isEmpty()) {
1446         SearchParams *searchParams = new SearchParams();
1447         searchParams->setKeywords(message);
1448         showMedia(searchParams);
1449     }
1450 }
1451
1452 void MainWindow::hideMouse() {
1453     setCursor(Qt::BlankCursor);
1454     mediaView->setPlaylistVisible(false);
1455 #ifndef APP_MAC
1456     mainToolBar->setVisible(false);
1457 #endif
1458 }
1459
1460 void MainWindow::printHelp() {
1461     QString msg = QString("%1 %2\n\n").arg(Constants::NAME, Constants::VERSION);
1462     msg += "Usage: minitube [options]\n";
1463     msg += "Options:\n";
1464     msg += "  --toggle-playing\t";
1465     msg += "Start or pause playback.\n";
1466     msg += "  --next\t\t";
1467     msg += "Skip to the next video.\n";
1468     msg += "  --previous\t\t";
1469     msg += "Go back to the previous video.\n";
1470     std::cout << msg.toLocal8Bit().data();
1471 }
1472
1473 void MainWindow::showMessage(QString message) {
1474     statusBar()->showMessage(message, 60000);
1475 }
1476
1477 #ifdef APP_ACTIVATION
1478 void MainWindow::showActivationView(bool transition) {
1479     QWidget *activationView = ActivationView::instance();
1480     if (views->currentWidget() == activationView) {
1481         buy();
1482         return;
1483     }
1484     views->addWidget(activationView);
1485     showWidget(activationView, transition);
1486 }
1487
1488 void MainWindow::showActivationDialog() {
1489     QTimer::singleShot(0, new ActivationDialog(this), SLOT(show()));
1490 }
1491
1492 void MainWindow::buy() {
1493     Extra::buy();
1494 }
1495
1496 void MainWindow::hideBuyAction() {
1497     QAction *action = The::globalActions()->value("buy");
1498     action->setVisible(false);
1499     action->setEnabled(false);
1500 }
1501 #endif