]> git.sur5r.net Git - minitube/blob - src/mainwindow.cpp
3fcf2fe8684ef4ec2f056d4144a9a14a63a46343
[minitube] / src / mainwindow.cpp
1 /* $BEGIN_LICENSE
2
3 This file is part of Minitube.
4 Copyright 2009, Flavio Tordini <flavio.tordini@gmail.com>
5
6 Minitube is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 Minitube is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Minitube.  If not, see <http://www.gnu.org/licenses/>.
18
19 $END_LICENSE */
20
21 #include "mainwindow.h"
22
23 #include "aboutview.h"
24 #include "downloadview.h"
25 #include "homeview.h"
26 #include "mediaview.h"
27 #include "regionsview.h"
28 #include "searchview.h"
29 #include "standardfeedsview.h"
30
31 #include "constants.h"
32 #include "fontutils.h"
33 #include "globalshortcuts.h"
34 #include "iconutils.h"
35 #include "searchparams.h"
36 #include "spacer.h"
37 #include "videodefinition.h"
38 #include "videosource.h"
39 #include "ytsearch.h"
40 #ifdef APP_LINUX
41 #include "gnomeglobalshortcutbackend.h"
42 #endif
43 #ifdef Q_OS_MAC
44 #include "mac_startup.h"
45 #include "macfullscreen.h"
46 #include "macsupport.h"
47 #include "macutils.h"
48 #endif
49 #include "downloadmanager.h"
50 #include "temporary.h"
51 #include "updatechecker.h"
52 #include "ytsuggester.h"
53 #if defined(APP_MAC_SEARCHFIELD) && !defined(APP_MAC_QMACTOOLBAR)
54 #include "searchlineedit_mac.h"
55 #else
56 #include "searchlineedit.h"
57 #endif
58 #ifdef APP_MAC_QMACTOOLBAR
59 #include "mactoolbar.h"
60 #endif
61 #include <iostream>
62 #ifdef APP_EXTRA
63 #include "extra.h"
64 #include "updatedialog.h"
65 #endif
66 #ifdef APP_ACTIVATION
67 #include "activation.h"
68 #include "activationview.h"
69 #endif
70 #include "channelaggregator.h"
71 #include "database.h"
72 #include "httputils.h"
73 #include "jsfunctions.h"
74 #include "seekslider.h"
75 #include "sidebarwidget.h"
76 #include "toolbarmenu.h"
77 #include "videoareawidget.h"
78 #include "yt3.h"
79 #include "ytregions.h"
80
81 namespace {
82 static MainWindow *mainWindowInstance;
83 }
84
85 MainWindow *MainWindow::instance() {
86     return mainWindowInstance;
87 }
88
89 MainWindow::MainWindow()
90     : updateChecker(0), aboutView(0), downloadView(0), regionsView(0), mainToolBar(0),
91 #ifdef APP_PHONON
92       mediaObject(0), audioOutput(0),
93 #endif
94       fullScreenActive(false), compactModeActive(false), initialized(false), toolbarMenu(0) {
95
96     mainWindowInstance = this;
97
98     // views mechanism
99     views = new QStackedWidget();
100     views->hide();
101     setCentralWidget(views);
102
103 #ifdef APP_EXTRA
104     Extra::windowSetup(this);
105 #endif
106
107     messageLabel = new QLabel();
108     messageLabel->setWindowFlags(Qt::ToolTip | Qt::FramelessWindowHint);
109     messageLabel->setStyleSheet("padding:5px;border:1px solid #808080;background:palette(window)");
110     messageLabel->hide();
111     adjustMessageLabelPosition();
112     messageTimer = new QTimer(this);
113     messageTimer->setInterval(5000);
114     messageTimer->setSingleShot(true);
115     connect(messageTimer, SIGNAL(timeout()), SLOT(hideMessage()));
116
117     // views
118     homeView = new HomeView(this);
119     views->addWidget(homeView);
120
121     // TODO make this lazy
122     mediaView = MediaView::instance();
123     mediaView->setEnabled(false);
124     views->addWidget(mediaView);
125
126     // build ui
127     createActions();
128     createMenus();
129     createToolBars();
130     hideToolbar();
131     createStatusBar();
132
133     // remove that useless menu/toolbar context menu
134     this->setContextMenuPolicy(Qt::NoContextMenu);
135
136     // event filter to block ugly toolbar tooltips
137     qApp->installEventFilter(this);
138
139     setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
140
141     // restore window position
142     readSettings();
143
144     // fix stacked widget minimum size
145     for (int i = 0; i < views->count(); i++)
146         views->widget(i)->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
147     setMinimumWidth(0);
148
149     views->show();
150
151 #ifdef APP_ACTIVATION
152     Activation::instance().initialCheck();
153 #else
154     showHome();
155 #endif
156
157     QTimer::singleShot(100, this, &MainWindow::lazyInit);
158 }
159
160 void MainWindow::lazyInit() {
161 #ifdef APP_PHONON
162     initPhonon();
163 #endif
164     mediaView->initialize();
165 #ifdef APP_PHONON
166     mediaView->setMediaObject(mediaObject);
167 #endif
168     qApp->processEvents();
169
170     // CLI
171     if (qApp->arguments().size() > 1) {
172         QString query = qApp->arguments().at(1);
173         if (query.startsWith(QLatin1String("--"))) {
174             messageReceived(query);
175             qApp->quit();
176         } else {
177             SearchParams *searchParams = new SearchParams();
178             searchParams->setKeywords(query);
179             showMedia(searchParams);
180         }
181     }
182
183     // Global shortcuts
184     GlobalShortcuts &shortcuts = GlobalShortcuts::instance();
185 #ifdef APP_LINUX
186     if (GnomeGlobalShortcutBackend::IsGsdAvailable())
187         shortcuts.setBackend(new GnomeGlobalShortcutBackend(&shortcuts));
188 #endif
189 #ifdef Q_OS_MAC
190     mac::MacSetup();
191 #endif
192     connect(&shortcuts, SIGNAL(PlayPause()), pauseAct, SLOT(trigger()));
193     connect(&shortcuts, SIGNAL(Stop()), this, SLOT(stop()));
194     connect(&shortcuts, SIGNAL(Next()), skipAct, SLOT(trigger()));
195     connect(&shortcuts, SIGNAL(Previous()), skipBackwardAct, SLOT(trigger()));
196     // connect(&shortcuts, SIGNAL(StopAfter()), getAction("stopafterthis"), SLOT(toggle()));
197
198     connect(DownloadManager::instance(), SIGNAL(statusMessageChanged(QString)),
199             SLOT(updateDownloadMessage(QString)));
200     connect(DownloadManager::instance(), SIGNAL(finished()), SLOT(downloadsFinished()));
201
202     setAcceptDrops(true);
203
204     fullscreenTimer = new QTimer(this);
205     fullscreenTimer->setInterval(3000);
206     fullscreenTimer->setSingleShot(true);
207     connect(fullscreenTimer, SIGNAL(timeout()), SLOT(hideFullscreenUI()));
208
209     JsFunctions::instance();
210
211     // Hack to give focus to searchlineedit
212     View *view = qobject_cast<View *>(views->currentWidget());
213     if (view == homeView) {
214         QMetaObject::invokeMethod(views->currentWidget(), "appear");
215         const QString &desc = view->getDescription();
216         if (!desc.isEmpty()) showMessage(desc);
217     }
218
219     ChannelAggregator::instance()->start();
220
221     checkForUpdate();
222
223     initialized = true;
224 }
225
226 void MainWindow::changeEvent(QEvent *e) {
227 #ifdef APP_MAC
228     if (e->type() == QEvent::WindowStateChange) {
229         getAction("minimize")->setEnabled(!isMinimized());
230     }
231 #endif
232     QMainWindow::changeEvent(e);
233 }
234
235 bool MainWindow::eventFilter(QObject *obj, QEvent *e) {
236     const QEvent::Type t = e->type();
237
238 #ifndef APP_MAC
239     static bool altPressed = false;
240     if (t == QEvent::KeyRelease && altPressed) {
241         altPressed = false;
242         QKeyEvent *ke = static_cast<QKeyEvent *>(e);
243         if (ke->key() == Qt::Key_Alt) {
244             toggleMenuVisibility();
245             return true;
246         }
247     } else if (t == QEvent::KeyPress) {
248         QKeyEvent *ke = static_cast<QKeyEvent *>(e);
249         altPressed = ke->key() == Qt::Key_Alt;
250     }
251 #endif
252
253     if (fullScreenActive && views->currentWidget() == mediaView && t == QEvent::MouseMove &&
254         obj->isWidgetType() && qobject_cast<QWidget *>(obj)->window() == this) {
255         QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(e);
256
257         bool toolBarVisible = mainToolBar && mainToolBar->isVisible();
258         bool sidebarVisible = mediaView->isSidebarVisible();
259
260         if (!sidebarVisible && !toolBarVisible) {
261             const int x = mouseEvent->pos().x();
262             if (x >= 0 && x < 5) {
263 #ifndef APP_MAC
264                 SidebarWidget *sidebar = mediaView->getSidebar();
265                 sidebar->resize(sidebar->width(), height());
266 #endif
267                 mediaView->setSidebarVisibility(true);
268                 sidebarVisible = true;
269             }
270         }
271
272 #ifndef APP_MAC
273         if (!toolBarVisible && !sidebarVisible) {
274             const int y = mouseEvent->pos().y();
275             if (y >= 0 && y < 5) {
276                 mainToolBar->resize(width(), mainToolBar->sizeHint().height());
277                 mainToolBar->setVisible(true);
278             }
279         }
280 #endif
281
282         // show the normal cursor
283         unsetCursor();
284         // then hide it again after a few seconds
285         fullscreenTimer->start();
286     }
287
288     if (t == QEvent::ToolTip) {
289         // kill tooltips
290         return true;
291     }
292
293     if (t == QEvent::Show && obj == toolbarMenu) {
294 #ifdef APP_MAC
295         int x = width() - toolbarMenu->sizeHint().width();
296         int y = views->y();
297 #else
298         int x = toolbarMenuButton->x() + toolbarMenuButton->width() -
299                 toolbarMenu->sizeHint().width();
300         int y = toolbarMenuButton->y() + toolbarMenuButton->height();
301 #endif
302         QPoint p(x, y);
303         toolbarMenu->move(mapToGlobal(p));
304     }
305
306     // standard event processing
307     return QMainWindow::eventFilter(obj, e);
308 }
309
310 void MainWindow::createActions() {
311     stopAct = new QAction(IconUtils::icon("media-playback-stop"), tr("&Stop"), this);
312     stopAct->setStatusTip(tr("Stop playback and go back to the search view"));
313     stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Escape)
314                                                 << QKeySequence(Qt::Key_MediaStop));
315     stopAct->setEnabled(false);
316     actionMap.insert("stop", stopAct);
317     connect(stopAct, SIGNAL(triggered()), SLOT(stop()));
318
319     skipBackwardAct = new QAction(IconUtils::icon("media-skip-backward"), tr("P&revious"), this);
320     skipBackwardAct->setStatusTip(tr("Go back to the previous track"));
321     skipBackwardAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Left));
322     skipBackwardAct->setEnabled(false);
323     actionMap.insert("previous", skipBackwardAct);
324     connect(skipBackwardAct, SIGNAL(triggered()), mediaView, SLOT(skipBackward()));
325
326     skipAct = new QAction(IconUtils::icon("media-skip-forward"), tr("S&kip"), this);
327     skipAct->setStatusTip(tr("Skip to the next video"));
328     skipAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_Right)
329                                                 << QKeySequence(Qt::Key_MediaNext));
330     skipAct->setEnabled(false);
331     actionMap.insert("skip", skipAct);
332     connect(skipAct, SIGNAL(triggered()), mediaView, SLOT(skip()));
333
334     pauseAct = new QAction(IconUtils::icon("media-playback-start"), tr("&Play"), this);
335     pauseAct->setStatusTip(tr("Resume playback"));
336     pauseAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Space)
337                                                  << QKeySequence(Qt::Key_MediaPlay));
338     pauseAct->setEnabled(false);
339     actionMap.insert("pause", pauseAct);
340     connect(pauseAct, SIGNAL(triggered()), mediaView, SLOT(pause()));
341
342     fullscreenAct = new QAction(IconUtils::icon("view-fullscreen"), tr("&Full Screen"), this);
343     fullscreenAct->setStatusTip(tr("Go full screen"));
344     QList<QKeySequence> fsShortcuts;
345 #ifdef APP_MAC
346     fsShortcuts << QKeySequence(Qt::CTRL + Qt::META + Qt::Key_F);
347 #else
348     fsShortcuts << QKeySequence(Qt::Key_F11) << QKeySequence(Qt::ALT + Qt::Key_Return);
349 #endif
350     fullscreenAct->setShortcuts(fsShortcuts);
351     fullscreenAct->setShortcutContext(Qt::ApplicationShortcut);
352     fullscreenAct->setPriority(QAction::LowPriority);
353     actionMap.insert("fullscreen", fullscreenAct);
354     connect(fullscreenAct, SIGNAL(triggered()), SLOT(toggleFullscreen()));
355
356     compactViewAct = new QAction(tr("&Compact Mode"), this);
357     compactViewAct->setStatusTip(tr("Hide the playlist and the toolbar"));
358 #ifdef APP_MAC
359     compactViewAct->setShortcut(QKeySequence(Qt::CTRL + Qt::META + Qt::Key_C));
360 #else
361     compactViewAct->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C));
362 #endif
363     compactViewAct->setCheckable(true);
364     compactViewAct->setChecked(false);
365     compactViewAct->setEnabled(false);
366     actionMap.insert("compactView", compactViewAct);
367     connect(compactViewAct, SIGNAL(toggled(bool)), this, SLOT(compactView(bool)));
368
369     webPageAct = new QAction(tr("Open the &YouTube Page"), this);
370     webPageAct->setStatusTip(tr("Go to the YouTube video page and pause playback"));
371     webPageAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Y));
372     webPageAct->setEnabled(false);
373     actionMap.insert("webpage", webPageAct);
374     connect(webPageAct, SIGNAL(triggered()), mediaView, SLOT(openWebPage()));
375
376     copyPageAct = new QAction(IconUtils::icon("link"), tr("Copy the YouTube &Link"), this);
377     copyPageAct->setStatusTip(tr("Copy the current video YouTube link to the clipboard"));
378     copyPageAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
379     copyPageAct->setEnabled(false);
380     actionMap.insert("pagelink", copyPageAct);
381     connect(copyPageAct, SIGNAL(triggered()), mediaView, SLOT(copyWebPage()));
382
383     copyLinkAct = new QAction(tr("Copy the Video Stream &URL"), this);
384     copyLinkAct->setStatusTip(tr("Copy the current video stream URL to the clipboard"));
385     copyLinkAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_U));
386     copyLinkAct->setEnabled(false);
387     actionMap.insert("videolink", copyLinkAct);
388     connect(copyLinkAct, SIGNAL(triggered()), mediaView, SLOT(copyVideoLink()));
389
390     findVideoPartsAct = new QAction(tr("Find Video &Parts"), this);
391     findVideoPartsAct->setStatusTip(tr("Find other video parts hopefully in the right order"));
392     findVideoPartsAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_P));
393     findVideoPartsAct->setEnabled(false);
394     connect(findVideoPartsAct, SIGNAL(triggered()), mediaView, SLOT(findVideoParts()));
395     actionMap.insert("findVideoParts", findVideoPartsAct);
396
397     removeAct = new QAction(tr("&Remove"), this);
398     removeAct->setStatusTip(tr("Remove the selected videos from the playlist"));
399     removeAct->setShortcuts(QList<QKeySequence>() << QKeySequence("Del")
400                                                   << QKeySequence("Backspace"));
401     removeAct->setEnabled(false);
402     actionMap.insert("remove", removeAct);
403     connect(removeAct, SIGNAL(triggered()), mediaView, SLOT(removeSelected()));
404
405     moveUpAct = new QAction(tr("Move &Up"), this);
406     moveUpAct->setStatusTip(tr("Move up the selected videos in the playlist"));
407     moveUpAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Up));
408     moveUpAct->setEnabled(false);
409     actionMap.insert("moveUp", moveUpAct);
410     connect(moveUpAct, SIGNAL(triggered()), mediaView, SLOT(moveUpSelected()));
411
412     moveDownAct = new QAction(tr("Move &Down"), this);
413     moveDownAct->setStatusTip(tr("Move down the selected videos in the playlist"));
414     moveDownAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Down));
415     moveDownAct->setEnabled(false);
416     actionMap.insert("moveDown", moveDownAct);
417     connect(moveDownAct, SIGNAL(triggered()), mediaView, SLOT(moveDownSelected()));
418
419     clearAct = new QAction(tr("&Clear Recent Searches"), this);
420     clearAct->setMenuRole(QAction::ApplicationSpecificRole);
421     clearAct->setShortcuts(QList<QKeySequence>()
422                            << QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Delete)
423                            << QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Backspace));
424     clearAct->setStatusTip(tr("Clear the search history. Cannot be undone."));
425     clearAct->setEnabled(true);
426     actionMap.insert("clearRecentKeywords", clearAct);
427     connect(clearAct, SIGNAL(triggered()), SLOT(clearRecentKeywords()));
428
429     quitAct = new QAction(tr("&Quit"), this);
430     quitAct->setMenuRole(QAction::QuitRole);
431     quitAct->setShortcut(QKeySequence(QKeySequence::Quit));
432     quitAct->setStatusTip(tr("Bye"));
433     actionMap.insert("quit", quitAct);
434     connect(quitAct, SIGNAL(triggered()), SLOT(quit()));
435
436     siteAct = new QAction(tr("&Website"), this);
437     siteAct->setShortcut(QKeySequence::HelpContents);
438     siteAct->setStatusTip(tr("%1 on the Web").arg(Constants::NAME));
439     actionMap.insert("site", siteAct);
440     connect(siteAct, SIGNAL(triggered()), this, SLOT(visitSite()));
441
442 #if !defined(APP_MAC) && !defined(APP_WIN)
443     donateAct = new QAction(tr("Make a &Donation"), this);
444     donateAct->setStatusTip(
445             tr("Please support the continued development of %1").arg(Constants::NAME));
446     actionMap.insert("donate", donateAct);
447     connect(donateAct, SIGNAL(triggered()), this, SLOT(donate()));
448 #endif
449
450     aboutAct = new QAction(tr("&About"), this);
451     aboutAct->setMenuRole(QAction::AboutRole);
452     aboutAct->setStatusTip(tr("Info about %1").arg(Constants::NAME));
453     actionMap.insert("about", aboutAct);
454     connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
455
456     // Invisible actions
457
458     searchFocusAct = new QAction(this);
459     searchFocusAct->setShortcut(QKeySequence::Find);
460     searchFocusAct->setStatusTip(tr("Search"));
461     actionMap.insert("search", searchFocusAct);
462     connect(searchFocusAct, SIGNAL(triggered()), this, SLOT(searchFocus()));
463     addAction(searchFocusAct);
464
465     volumeUpAct = new QAction(this);
466     volumeUpAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_Plus));
467     actionMap.insert("volumeUp", volumeUpAct);
468     connect(volumeUpAct, SIGNAL(triggered()), this, SLOT(volumeUp()));
469     addAction(volumeUpAct);
470
471     volumeDownAct = new QAction(this);
472     volumeDownAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_Minus));
473     actionMap.insert("volumeDown", volumeDownAct);
474     connect(volumeDownAct, SIGNAL(triggered()), this, SLOT(volumeDown()));
475     addAction(volumeDownAct);
476
477     volumeMuteAct = new QAction(this);
478     volumeMuteAct->setIcon(IconUtils::icon("audio-volume-high"));
479     volumeMuteAct->setStatusTip(tr("Mute volume"));
480     volumeMuteAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_K));
481     actionMap.insert("volumeMute", volumeMuteAct);
482     connect(volumeMuteAct, SIGNAL(triggered()), SLOT(volumeMute()));
483     addAction(volumeMuteAct);
484
485     QAction *definitionAct = new QAction(this);
486     definitionAct->setIcon(IconUtils::icon("video-display"));
487     definitionAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_D));
488     actionMap.insert("definition", definitionAct);
489     connect(definitionAct, SIGNAL(triggered()), SLOT(toggleDefinitionMode()));
490     addAction(definitionAct);
491
492     QAction *action;
493
494     action = new QAction(IconUtils::icon("media-playback-start"), tr("&Manually Start Playing"),
495                          this);
496     action->setStatusTip(tr("Manually start playing videos"));
497     action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_T));
498     action->setCheckable(true);
499     connect(action, SIGNAL(toggled(bool)), SLOT(setManualPlay(bool)));
500     actionMap.insert("manualplay", action);
501
502     action = new QAction(tr("&Downloads"), this);
503     action->setStatusTip(tr("Show details about video downloads"));
504     action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_J));
505     action->setCheckable(true);
506     action->setIcon(IconUtils::icon("document-save"));
507     connect(action, SIGNAL(toggled(bool)), SLOT(toggleDownloads(bool)));
508     actionMap.insert("downloads", action);
509
510     action = new QAction(tr("&Download"), this);
511     action->setStatusTip(tr("Download the current video"));
512     action->setShortcut(QKeySequence::Save);
513     action->setIcon(IconUtils::icon("document-save"));
514     action->setEnabled(false);
515     action->setVisible(false);
516     action->setPriority(QAction::LowPriority);
517     connect(action, SIGNAL(triggered()), mediaView, SLOT(downloadVideo()));
518     actionMap.insert("download", action);
519
520 #ifdef APP_SNAPSHOT
521     action = new QAction(tr("Take &Snapshot"), this);
522     action->setShortcut(QKeySequence(Qt::Key_F9));
523     action->setEnabled(false);
524     actionMap.insert("snapshot", action);
525     connect(action, SIGNAL(triggered()), mediaView, SLOT(snapshot()));
526 #endif
527
528     action = new QAction(tr("&Subscribe to Channel"), this);
529     action->setProperty("originalText", action->text());
530     action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_S));
531     action->setEnabled(false);
532     connect(action, SIGNAL(triggered()), mediaView, SLOT(toggleSubscription()));
533     actionMap.insert("subscribeChannel", action);
534     mediaView->updateSubscriptionAction(0, false);
535
536     QString shareTip = tr("Share the current video using %1");
537
538     action = new QAction(IconUtils::icon("twitter"), "&Twitter", this);
539     action->setStatusTip(shareTip.arg("Twitter"));
540     action->setEnabled(false);
541     actionMap.insert("twitter", action);
542     connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaTwitter()));
543
544     action = new QAction(IconUtils::icon("facebook"), "&Facebook", this);
545     action->setStatusTip(shareTip.arg("Facebook"));
546     action->setEnabled(false);
547     actionMap.insert("facebook", action);
548     connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaFacebook()));
549
550     action = new QAction(IconUtils::icon("email"), tr("&Email"), this);
551     action->setStatusTip(shareTip.arg(tr("Email")));
552     action->setEnabled(false);
553     actionMap.insert("email", action);
554     connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaEmail()));
555
556     action = new QAction(tr("&Close"), this);
557     action->setShortcut(QKeySequence(QKeySequence::Close));
558     actionMap.insert("close", action);
559     connect(action, SIGNAL(triggered()), SLOT(close()));
560
561     action = new QAction(Constants::NAME, this);
562     action->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_1));
563     actionMap.insert("restore", action);
564     connect(action, SIGNAL(triggered()), SLOT(restore()));
565
566     action = new QAction(IconUtils::icon("go-top"), tr("&Float on Top"), this);
567     action->setCheckable(true);
568     actionMap.insert("ontop", action);
569     connect(action, SIGNAL(toggled(bool)), SLOT(floatOnTop(bool)));
570
571     action =
572             new QAction(IconUtils::icon("media-playback-stop"), tr("&Stop After This Video"), this);
573     action->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Escape));
574     action->setCheckable(true);
575     action->setEnabled(false);
576     actionMap.insert("stopafterthis", action);
577     connect(action, SIGNAL(toggled(bool)), SLOT(showStopAfterThisInStatusBar(bool)));
578
579     action = new QAction(tr("&Report an Issue..."), this);
580     actionMap.insert("reportIssue", action);
581     connect(action, SIGNAL(triggered()), SLOT(reportIssue()));
582
583     action = new QAction(tr("&Refine Search..."), this);
584     action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_E));
585     action->setCheckable(true);
586     action->setEnabled(false);
587     actionMap.insert("refineSearch", action);
588
589     action = new QAction(YTRegions::worldwideRegion().name, this);
590     actionMap.insert("worldwideRegion", action);
591
592     action = new QAction(YTRegions::localRegion().name, this);
593     actionMap.insert("localRegion", action);
594
595     action = new QAction(tr("More..."), this);
596     actionMap.insert("moreRegion", action);
597
598     action = new QAction(IconUtils::icon("view-list"), tr("&Related Videos"), this);
599     action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R));
600     action->setStatusTip(tr("Watch videos related to the current one"));
601     action->setEnabled(false);
602     action->setPriority(QAction::LowPriority);
603     connect(action, SIGNAL(triggered()), mediaView, SLOT(relatedVideos()));
604     actionMap.insert("relatedVideos", action);
605
606     action = new QAction(tr("Open in &Browser..."), this);
607     action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_B));
608     action->setEnabled(false);
609     actionMap.insert("openInBrowser", action);
610     connect(action, SIGNAL(triggered()), mediaView, SLOT(openInBrowser()));
611
612     action = new QAction(IconUtils::icon("safesearch"), tr("Restricted Mode"), this);
613     action->setStatusTip(tr("Hide videos that may contain inappropriate content"));
614     action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_K));
615     action->setCheckable(true);
616     actionMap.insert("safeSearch", action);
617
618     action = new QAction(tr("Toggle &Menu Bar"), this);
619     connect(action, SIGNAL(triggered()), SLOT(toggleMenuVisibilityWithMessage()));
620     actionMap.insert("toggleMenu", action);
621
622     action = new QAction(IconUtils::icon("view-more"), tr("Menu"), this);
623     connect(action, SIGNAL(triggered()), SLOT(toggleToolbarMenu()));
624     actionMap.insert("toolbarMenu", action);
625
626 #ifdef APP_MAC_STORE
627     action = new QAction(tr("&Love %1? Rate it!").arg(Constants::NAME), this);
628     actionMap.insert("appStore", action);
629     connect(action, SIGNAL(triggered()), SLOT(rateOnAppStore()));
630 #endif
631
632 #ifdef APP_ACTIVATION
633     ActivationView::createActivationAction(tr("Buy %1...").arg(Constants::NAME));
634 #endif
635
636     // common action properties
637     for (QAction *action : actionMap) {
638         // add actions to the MainWindow so that they work
639         // when the menu is hidden
640         addAction(action);
641         IconUtils::setupAction(action);
642     }
643 }
644
645 void MainWindow::createMenus() {
646     fileMenu = menuBar()->addMenu(tr("&Application"));
647 #ifdef APP_ACTIVATION
648     QAction *buyAction = getAction("buy");
649     if (buyAction) fileMenu->addAction(buyAction);
650 #ifndef APP_MAC
651     fileMenu->addSeparator();
652 #endif
653 #endif
654     fileMenu->addAction(clearAct);
655 #ifndef APP_MAC
656     fileMenu->addSeparator();
657 #endif
658     fileMenu->addAction(quitAct);
659
660     QMenu *playbackMenu = menuBar()->addMenu(tr("&Playback"));
661     menuMap.insert("playback", playbackMenu);
662     playbackMenu->addAction(pauseAct);
663     playbackMenu->addAction(stopAct);
664     playbackMenu->addAction(getAction("stopafterthis"));
665     playbackMenu->addSeparator();
666     playbackMenu->addAction(skipAct);
667     playbackMenu->addAction(skipBackwardAct);
668     playbackMenu->addSeparator();
669     playbackMenu->addAction(getAction("manualplay"));
670 #ifdef APP_MAC
671     MacSupport::dockMenu(playbackMenu);
672 #endif
673
674     playlistMenu = menuBar()->addMenu(tr("&Playlist"));
675     menuMap.insert("playlist", playlistMenu);
676     playlistMenu->addAction(removeAct);
677     playlistMenu->addSeparator();
678     playlistMenu->addAction(moveUpAct);
679     playlistMenu->addAction(moveDownAct);
680     playlistMenu->addSeparator();
681     playlistMenu->addAction(getAction("refineSearch"));
682
683     QMenu *videoMenu = menuBar()->addMenu(tr("&Video"));
684     menuMap.insert("video", videoMenu);
685     videoMenu->addAction(getAction("relatedVideos"));
686     videoMenu->addAction(findVideoPartsAct);
687     videoMenu->addSeparator();
688     videoMenu->addAction(getAction("subscribeChannel"));
689 #ifdef APP_SNAPSHOT
690     videoMenu->addSeparator();
691     videoMenu->addAction(getAction("snapshot"));
692 #endif
693     videoMenu->addSeparator();
694     videoMenu->addAction(webPageAct);
695     videoMenu->addAction(copyLinkAct);
696     videoMenu->addAction(getAction("openInBrowser"));
697     videoMenu->addAction(getAction("download"));
698
699     QMenu *shareMenu = menuBar()->addMenu(tr("&Share"));
700     menuMap.insert("share", shareMenu);
701     shareMenu->addAction(copyPageAct);
702     shareMenu->addSeparator();
703     shareMenu->addAction(getAction("twitter"));
704     shareMenu->addAction(getAction("facebook"));
705     shareMenu->addSeparator();
706     shareMenu->addAction(getAction("email"));
707
708     QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
709     menuMap.insert("view", viewMenu);
710     viewMenu->addAction(getAction("ontop"));
711     viewMenu->addAction(compactViewAct);
712 #ifndef APP_MAC
713     viewMenu->addAction(fullscreenAct);
714     viewMenu->addAction(getAction("toggleMenu"));
715 #endif
716
717 #ifdef APP_MAC
718     MacSupport::windowMenu(this);
719 #endif
720
721     helpMenu = menuBar()->addMenu(tr("&Help"));
722     menuMap.insert("help", helpMenu);
723     helpMenu->addAction(siteAct);
724 #if !defined(APP_MAC) && !defined(APP_WIN)
725     helpMenu->addAction(donateAct);
726 #endif
727     helpMenu->addAction(getAction("reportIssue"));
728     helpMenu->addAction(aboutAct);
729
730 #ifdef APP_MAC_STORE
731     helpMenu->addSeparator();
732     helpMenu->addAction(getAction("appStore"));
733 #endif
734 }
735
736 void MainWindow::createToolBars() {
737     // Create widgets
738
739     currentTimeLabel = new QLabel("00:00");
740     currentTimeLabel->setFont(FontUtils::small());
741
742 #ifdef APP_PHONON_SEEK
743     seekSlider = new Phonon::SeekSlider();
744 #if APP_LINUX
745     seekSlider->setTracking(false);
746 #else
747     seekSlider->setTracking(true);
748 #endif
749     // Phonon freezes the application with streaming videos if
750     // tracking is set to true and the seek slider is dragged.
751     seekSlider->setIconVisible(false);
752     seekSlider->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
753 #else
754     slider = new SeekSlider(this);
755     slider->setEnabled(false);
756     slider->setTracking(false);
757     slider->setMaximum(1000);
758     slider->setOrientation(Qt::Horizontal);
759     slider->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
760 #endif
761
762 #ifdef APP_PHONON
763     volumeSlider = new Phonon::VolumeSlider();
764     volumeSlider->setMuteVisible(false);
765     // qDebug() << volumeSlider->children();
766     // status tip for the volume slider
767     QSlider *volumeQSlider = volumeSlider->findChild<QSlider *>();
768     if (volumeQSlider)
769         volumeQSlider->setStatusTip(
770                 tr("Press %1 to raise the volume, %2 to lower it")
771                         .arg(volumeUpAct->shortcut().toString(QKeySequence::NativeText),
772                              volumeDownAct->shortcut().toString(QKeySequence::NativeText)));
773     // this makes the volume slider smaller
774     volumeSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
775 #endif
776
777 #if defined(APP_MAC_SEARCHFIELD) && !defined(APP_MAC_QMACTOOLBAR)
778     SearchWrapper *searchWrapper = new SearchWrapper(this);
779     toolbarSearch = searchWrapper->getSearchLineEdit();
780 #else
781     toolbarSearch = new SearchLineEdit(this);
782 #endif
783     toolbarSearch->setMinimumWidth(toolbarSearch->fontInfo().pixelSize() * 15);
784     toolbarSearch->setSuggester(new YTSuggester(this));
785     connect(toolbarSearch, SIGNAL(search(const QString &)), SLOT(search(const QString &)));
786     connect(toolbarSearch, SIGNAL(suggestionAccepted(Suggestion *)),
787             SLOT(suggestionAccepted(Suggestion *)));
788     toolbarSearch->setStatusTip(searchFocusAct->statusTip());
789
790 // Add widgets to toolbar
791
792 #ifdef APP_MAC_QMACTOOLBAR
793     currentTimeLabel->hide();
794     toolbarSearch->hide();
795     volumeSlider->hide();
796     seekSlider->hide();
797     MacToolbar::instance().createToolbar(this);
798     return;
799 #endif
800
801     mainToolBar = new QToolBar(this);
802     mainToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
803     mainToolBar->setFloatable(false);
804     mainToolBar->setMovable(false);
805 #ifndef APP_LINUX
806     mainToolBar->setIconSize(QSize(32, 32));
807 #endif
808     mainToolBar->addAction(stopAct);
809     QToolButton *stopToolButton =
810             qobject_cast<QToolButton *>(mainToolBar->widgetForAction(stopAct));
811     if (stopToolButton) {
812         QMenu *stopMenu = new QMenu(this);
813         stopMenu->addAction(getAction("stopafterthis"));
814         stopToolButton->setMenu(stopMenu);
815         stopToolButton->setPopupMode(QToolButton::DelayedPopup);
816     }
817     mainToolBar->addAction(pauseAct);
818     mainToolBar->addAction(skipAct);
819     mainToolBar->addAction(getAction("relatedVideos"));
820
821     bool addFullScreenAct = true;
822 #ifdef Q_OS_MAC
823     addFullScreenAct = !mac::CanGoFullScreen(winId());
824 #endif
825     if (addFullScreenAct) mainToolBar->addAction(fullscreenAct);
826
827     mainToolBar->addWidget(new Spacer());
828
829     mainToolBar->addWidget(currentTimeLabel);
830     mainToolBar->addWidget(new Spacer(this, currentTimeLabel->sizeHint().height() / 2));
831 #ifdef APP_PHONON_SEEK
832     mainToolBar->addWidget(seekSlider);
833 #else
834     mainToolBar->addWidget(slider);
835 #endif
836
837     /*
838     mainToolBar->addWidget(new Spacer());
839     totalTime = new QLabel(mainToolBar);
840     totalTime->setFont(smallerFont);
841     mainToolBar->addWidget(totalTime);
842     */
843
844     mainToolBar->addWidget(new Spacer());
845     mainToolBar->addAction(volumeMuteAct);
846 #ifdef APP_LINUX
847     QToolButton *volumeMuteButton =
848             qobject_cast<QToolButton *>(mainToolBar->widgetForAction(volumeMuteAct));
849     volumeMuteButton->setIcon(volumeMuteButton->icon().pixmap(16));
850 #endif
851
852 #ifdef APP_PHONON
853     mainToolBar->addWidget(volumeSlider);
854 #endif
855
856     mainToolBar->addWidget(new Spacer());
857
858 #if defined(APP_MAC_SEARCHFIELD) && !defined(APP_MAC_QMACTOOLBAR)
859     mainToolBar->addWidget(searchWrapper);
860 #else
861     mainToolBar->addWidget(toolbarSearch);
862     mainToolBar->addWidget(new Spacer(this, toolbarSearch->height() / 2));
863
864     QAction *toolbarMenuAction = getAction("toolbarMenu");
865     mainToolBar->addAction(toolbarMenuAction);
866     toolbarMenuButton =
867             qobject_cast<QToolButton *>(mainToolBar->widgetForAction(toolbarMenuAction));
868 #endif
869
870     addToolBar(mainToolBar);
871 }
872
873 void MainWindow::createStatusBar() {
874     statusToolBar = new QToolBar(statusBar());
875     statusToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
876     statusToolBar->setIconSize(QSize(16, 16));
877
878     regionAction = new QAction(this);
879     regionAction->setStatusTip(tr("Choose your content location"));
880
881     QAction *localAction = getAction("localRegion");
882     if (!localAction->text().isEmpty()) {
883         QMenu *regionMenu = new QMenu(this);
884         regionMenu->addAction(getAction("worldwideRegion"));
885         regionMenu->addAction(localAction);
886         regionMenu->addSeparator();
887         QAction *moreRegionsAction = getAction("moreRegion");
888         regionMenu->addAction(moreRegionsAction);
889         connect(moreRegionsAction, SIGNAL(triggered()), SLOT(showRegionsView()));
890         regionAction->setMenu(regionMenu);
891     } else {
892         connect(regionAction, SIGNAL(triggered()), SLOT(showRegionsView()));
893     }
894
895     /* Stupid code that generates the QRC items
896     foreach(YTRegion r, YTRegions::list())
897         qDebug() << QString("<file>flags/%1.png</file>").arg(r.id.toLower());
898     */
899
900     statusBar()->addPermanentWidget(statusToolBar);
901     statusBar()->hide();
902 }
903
904 void MainWindow::showStopAfterThisInStatusBar(bool show) {
905     QAction *action = getAction("stopafterthis");
906     showActionInStatusBar(action, show);
907 }
908
909 void MainWindow::showActionInStatusBar(QAction *action, bool show) {
910 #ifdef APP_EXTRA
911     Extra::fadeInWidget(statusBar(), statusBar());
912 #endif
913     if (show) {
914         if (statusToolBar->actions().contains(action)) return;
915         if (statusToolBar->actions().isEmpty()) {
916             statusToolBar->addAction(action);
917         } else {
918             statusToolBar->insertAction(statusToolBar->actions().at(0), action);
919         }
920         if (statusBar()->isHidden() && !fullScreenActive) setStatusBarVisibility(true);
921     } else {
922         statusToolBar->removeAction(action);
923         if (statusBar()->isVisible() && !needStatusBar()) setStatusBarVisibility(false);
924     }
925 }
926
927 void MainWindow::setStatusBarVisibility(bool show) {
928     statusBar()->setVisible(show);
929     if (views->currentWidget() == mediaView)
930         QTimer::singleShot(0, mediaView, SLOT(adjustWindowSize()));
931 }
932
933 void MainWindow::adjustStatusBarVisibility() {
934     setStatusBarVisibility(needStatusBar());
935 }
936
937 void MainWindow::hideToolbar() {
938 #ifdef APP_MAC
939     mac::showToolBar(winId(), false);
940 #else
941     mainToolBar->hide();
942 #endif
943 }
944
945 void MainWindow::showToolbar() {
946 #ifdef APP_MAC
947     mac::showToolBar(winId(), true);
948 #else
949     mainToolBar->show();
950 #endif
951 }
952
953 void MainWindow::readSettings() {
954     QSettings settings;
955     if (settings.contains("geometry")) {
956         restoreGeometry(settings.value("geometry").toByteArray());
957     } else {
958         const QRect desktopSize = qApp->desktop()->availableGeometry();
959         int w = desktopSize.width() * .9;
960         int h = qMin(w / 2, desktopSize.height());
961         setGeometry(
962                 QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, QSize(w, h), desktopSize));
963     }
964     const VideoDefinition &firstDefinition = VideoDefinition::getDefinitions().at(0);
965     setDefinitionMode(settings.value("definition", firstDefinition.getName()).toString());
966     getAction("manualplay")->setChecked(settings.value("manualplay", false).toBool());
967     getAction("safeSearch")->setChecked(settings.value("safeSearch", false).toBool());
968 #ifndef APP_MAC
969     menuBar()->setVisible(settings.value("menuBar", false).toBool());
970 #endif
971 }
972
973 void MainWindow::writeSettings() {
974     QSettings settings;
975
976     if (!isReallyFullScreen()) {
977         settings.setValue("geometry", saveGeometry());
978         mediaView->saveSplitterState();
979     }
980
981     settings.setValue("manualplay", getAction("manualplay")->isChecked());
982     settings.setValue("safeSearch", getAction("safeSearch")->isChecked());
983 #ifndef APP_MAC
984     settings.setValue("menuBar", menuBar()->isVisible());
985 #endif
986 }
987
988 void MainWindow::goBack() {
989     if (history.size() > 1) {
990         history.pop();
991         QWidget *widget = history.pop();
992         showWidget(widget);
993     }
994 }
995
996 void MainWindow::showWidget(QWidget *widget, bool transition) {
997     Q_UNUSED(transition);
998
999     setUpdatesEnabled(false);
1000
1001     if (compactViewAct->isChecked()) compactViewAct->toggle();
1002
1003     // call hide method on the current view
1004     View *oldView = qobject_cast<View *>(views->currentWidget());
1005     if (oldView) {
1006         oldView->disappear();
1007         views->currentWidget()->setEnabled(false);
1008     } else
1009         qDebug() << "Cannot cast view";
1010
1011     const bool isMediaView = widget == mediaView;
1012
1013     stopAct->setEnabled(isMediaView);
1014     compactViewAct->setEnabled(isMediaView);
1015     toolbarSearch->setEnabled(widget == homeView || isMediaView || widget == downloadView);
1016
1017     aboutAct->setEnabled(widget != aboutView);
1018     getAction("downloads")->setChecked(widget == downloadView);
1019
1020     QWidget *oldWidget = views->currentWidget();
1021     if (oldWidget) oldWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
1022
1023     views->setCurrentWidget(widget);
1024     widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
1025
1026     // call show method on the new view
1027     View *newView = qobject_cast<View *>(widget);
1028     if (newView) {
1029         widget->setEnabled(true);
1030
1031         QString title = newView->getTitle();
1032         if (title.isEmpty())
1033             title = Constants::NAME;
1034         else
1035             title += QLatin1String(" - ") + Constants::NAME;
1036         setWindowTitle(title);
1037
1038         statusToolBar->setUpdatesEnabled(false);
1039
1040         // dynamic view actions
1041         /* Not currently used by any view
1042         foreach (QAction* action, viewActions)
1043             showActionInStatusBar(action, false);
1044         viewActions = newView->getViewActions();
1045         foreach (QAction* action, viewActions)
1046             showActionInStatusBar(action, true);
1047         */
1048
1049         adjustStatusBarVisibility();
1050         messageLabel->hide();
1051
1052         newView->appear();
1053
1054         statusToolBar->setUpdatesEnabled(true);
1055
1056         /*
1057         QString desc = metadata.value("description").toString();
1058         if (!desc.isEmpty()) showMessage(desc);
1059         */
1060     }
1061
1062     setUpdatesEnabled(true);
1063
1064 #ifdef APP_MAC
1065     // Workaround cursor bug on macOS
1066     unsetCursor();
1067     mac::uncloseWindow(winId());
1068 #endif
1069
1070     history.push(widget);
1071     emit viewChanged();
1072 }
1073
1074 void MainWindow::about() {
1075     if (!aboutView) {
1076         aboutView = new AboutView(this);
1077         views->addWidget(aboutView);
1078     }
1079     showWidget(aboutView);
1080 }
1081
1082 void MainWindow::visitSite() {
1083     QUrl url(Constants::WEBSITE);
1084     showMessage(QString(tr("Opening %1").arg(url.toString())));
1085     QDesktopServices::openUrl(url);
1086 }
1087
1088 void MainWindow::donate() {
1089     QUrl url(QString(Constants::WEBSITE) + "#donate");
1090     showMessage(QString(tr("Opening %1").arg(url.toString())));
1091     QDesktopServices::openUrl(url);
1092 }
1093
1094 void MainWindow::reportIssue() {
1095     QUrl url("http://flavio.tordini.org/forums/forum/minitube-forums/minitube-troubleshooting");
1096     QDesktopServices::openUrl(url);
1097 }
1098
1099 void MainWindow::quit() {
1100 #ifdef APP_MAC
1101     if (!confirmQuit()) {
1102         return;
1103     }
1104 #endif
1105     // do not save geometry when in full screen or in compact mode
1106     if (!fullScreenActive && !compactViewAct->isChecked()) {
1107         writeSettings();
1108     }
1109     // mediaView->stop();
1110     Temporary::deleteAll();
1111     ChannelAggregator::instance()->stop();
1112     ChannelAggregator::instance()->cleanup();
1113     Database::shutdown();
1114     qApp->quit();
1115 }
1116
1117 void MainWindow::closeEvent(QCloseEvent *e) {
1118 #ifdef APP_MAC
1119     mac::closeWindow(winId());
1120     e->ignore();
1121 #else
1122     if (!confirmQuit()) {
1123         e->ignore();
1124         return;
1125     }
1126     QWidget::closeEvent(e);
1127     quit();
1128 #endif
1129     messageLabel->hide();
1130 }
1131
1132 void MainWindow::showEvent(QShowEvent *e) {
1133     QWidget::showEvent(e);
1134 #ifdef APP_MAC
1135     restore();
1136 #endif
1137 }
1138
1139 bool MainWindow::confirmQuit() {
1140     if (DownloadManager::instance()->activeItems() > 0) {
1141         QMessageBox msgBox(this);
1142         msgBox.setIconPixmap(IconUtils::pixmap(":/images/64x64/app.png"));
1143         msgBox.setText(
1144                 tr("Do you want to exit %1 with a download in progress?").arg(Constants::NAME));
1145         msgBox.setInformativeText(
1146                 tr("If you close %1 now, this download will be cancelled.").arg(Constants::NAME));
1147         msgBox.setModal(true);
1148         // make it a "sheet" on the Mac
1149         msgBox.setWindowModality(Qt::WindowModal);
1150
1151         msgBox.addButton(tr("Close and cancel download"), QMessageBox::RejectRole);
1152         QPushButton *waitButton =
1153                 msgBox.addButton(tr("Wait for download to finish"), QMessageBox::ActionRole);
1154
1155         msgBox.exec();
1156
1157         if (msgBox.clickedButton() == waitButton) {
1158             return false;
1159         }
1160     }
1161     return true;
1162 }
1163
1164 void MainWindow::showHome() {
1165     showWidget(homeView);
1166     currentTimeLabel->clear();
1167 }
1168
1169 void MainWindow::showMedia(SearchParams *searchParams) {
1170     showWidget(mediaView);
1171     if (getAction("safeSearch")->isChecked())
1172         searchParams->setSafeSearch(SearchParams::Strict);
1173     else
1174         searchParams->setSafeSearch(SearchParams::None);
1175     mediaView->search(searchParams);
1176 }
1177
1178 void MainWindow::showMedia(VideoSource *videoSource) {
1179     showWidget(mediaView);
1180     mediaView->setVideoSource(videoSource);
1181 }
1182
1183 #ifdef APP_PHONON
1184 void MainWindow::stateChanged(Phonon::State newState, Phonon::State /* oldState */) {
1185     // qDebug() << "Phonon state: " << newState;
1186
1187     switch (newState) {
1188     case Phonon::ErrorState:
1189         if (mediaObject->errorType() == Phonon::FatalError) {
1190             // Do not display because we try to play incomplete video files and sometimes trigger
1191             // this
1192             // We retry automatically (in MediaView) so no need to show it
1193             // showMessage(tr("Fatal error: %1").arg(mediaObject->errorString()));
1194         } else {
1195             showMessage(tr("Error: %1").arg(mediaObject->errorString()));
1196         }
1197         break;
1198
1199     case Phonon::PlayingState:
1200         pauseAct->setEnabled(true);
1201         pauseAct->setIcon(IconUtils::icon("media-playback-pause"));
1202         pauseAct->setText(tr("&Pause"));
1203         pauseAct->setStatusTip(tr("Pause playback") + " (" +
1204                                pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
1205         // stopAct->setEnabled(true);
1206         break;
1207
1208     case Phonon::StoppedState:
1209         pauseAct->setEnabled(false);
1210         pauseAct->setIcon(IconUtils::icon("media-playback-start"));
1211         pauseAct->setText(tr("&Play"));
1212         pauseAct->setStatusTip(tr("Resume playback") + " (" +
1213                                pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
1214         // stopAct->setEnabled(false);
1215         break;
1216
1217     case Phonon::PausedState:
1218         pauseAct->setEnabled(true);
1219         pauseAct->setIcon(IconUtils::icon("media-playback-start"));
1220         pauseAct->setText(tr("&Play"));
1221         pauseAct->setStatusTip(tr("Resume playback") + " (" +
1222                                pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
1223         // stopAct->setEnabled(true);
1224         break;
1225
1226     case Phonon::BufferingState:
1227         pauseAct->setEnabled(false);
1228         pauseAct->setIcon(IconUtils::icon("content-loading"));
1229         pauseAct->setText(tr("&Loading..."));
1230         pauseAct->setStatusTip(QString());
1231         break;
1232
1233     case Phonon::LoadingState:
1234         pauseAct->setEnabled(false);
1235         currentTimeLabel->clear();
1236         // totalTime->clear();
1237         // stopAct->setEnabled(true);
1238         break;
1239
1240     default:;
1241     }
1242 }
1243 #endif
1244
1245 void MainWindow::stop() {
1246     showHome();
1247     mediaView->stop();
1248 }
1249
1250 void MainWindow::resizeEvent(QResizeEvent *e) {
1251     Q_UNUSED(e);
1252 #ifdef APP_MAC
1253     if (initialized && mac::CanGoFullScreen(winId())) {
1254         bool isFullscreen = mac::IsFullScreen(winId());
1255         if (isFullscreen != fullScreenActive) {
1256             if (compactViewAct->isChecked()) {
1257                 compactViewAct->setChecked(false);
1258                 compactView(false);
1259             }
1260             fullScreenActive = isFullscreen;
1261             updateUIForFullscreen();
1262         }
1263     }
1264 #endif
1265 #ifdef APP_MAC_QMACTOOLBAR
1266     int moreButtonWidth = 40;
1267     toolbarSearch->move(width() - toolbarSearch->width() - moreButtonWidth - 7, -38);
1268 #endif
1269     hideMessage();
1270 }
1271
1272 void MainWindow::moveEvent(QMoveEvent *e) {
1273     Q_UNUSED(e);
1274     hideMessage();
1275 }
1276
1277 void MainWindow::enterEvent(QEvent *e) {
1278     Q_UNUSED(e);
1279 #ifdef APP_MAC
1280     // Workaround cursor bug on macOS
1281     unsetCursor();
1282 #endif
1283 }
1284
1285 void MainWindow::leaveEvent(QEvent *e) {
1286     Q_UNUSED(e);
1287     if (fullScreenActive) hideFullscreenUI();
1288 }
1289
1290 void MainWindow::toggleFullscreen() {
1291     if (compactViewAct->isChecked()) compactViewAct->toggle();
1292
1293 #ifdef APP_MAC
1294     WId handle = winId();
1295     if (mac::CanGoFullScreen(handle)) {
1296         if (mainToolBar) mainToolBar->setVisible(true);
1297         mac::ToggleFullScreen(handle);
1298         return;
1299     }
1300 #endif
1301
1302     fullScreenActive = !fullScreenActive;
1303
1304     if (fullScreenActive) {
1305         // Enter full screen
1306
1307         maximizedBeforeFullScreen = isMaximized();
1308
1309         // save geometry now, if the user quits when in full screen
1310         // geometry won't be saved
1311         writeSettings();
1312
1313 #ifdef APP_MAC
1314         MacSupport::enterFullScreen(this, views);
1315 #else
1316         menuVisibleBeforeFullScreen = menuBar()->isVisible();
1317         menuBar()->hide();
1318         if (mainToolBar) mainToolBar->hide();
1319         showFullScreen();
1320 #endif
1321
1322     } else {
1323 // Exit full screen
1324
1325 #ifdef APP_MAC
1326         MacSupport::exitFullScreen(this, views);
1327 #else
1328         menuBar()->setVisible(menuVisibleBeforeFullScreen);
1329         if (mainToolBar) mainToolBar->setVisible(views->currentWidget() == mediaView);
1330         if (maximizedBeforeFullScreen)
1331             showMaximized();
1332         else
1333             showNormal();
1334 #endif
1335
1336         // Make sure the window has focus
1337         activateWindow();
1338     }
1339
1340     qApp->processEvents();
1341     updateUIForFullscreen();
1342 }
1343
1344 void MainWindow::updateUIForFullscreen() {
1345     static QList<QKeySequence> fsShortcuts;
1346     static QString fsText;
1347
1348     if (fullScreenActive) {
1349         fsShortcuts = fullscreenAct->shortcuts();
1350         fsText = fullscreenAct->text();
1351         if (fsText.isEmpty()) qDebug() << "[taking Empty!]";
1352         fullscreenAct->setShortcuts(QList<QKeySequence>(fsShortcuts)
1353                                     << QKeySequence(Qt::Key_Escape));
1354         fullscreenAct->setText(tr("Leave &Full Screen"));
1355         fullscreenAct->setIcon(IconUtils::icon("view-restore"));
1356         setStatusBarVisibility(false);
1357
1358         if (mainToolBar) {
1359             removeToolBar(mainToolBar);
1360             mainToolBar->move(0, 0);
1361         }
1362
1363         mediaView->removeSidebar();
1364
1365     } else {
1366         fullscreenAct->setShortcuts(fsShortcuts);
1367         if (fsText.isEmpty()) fsText = "[Empty!]";
1368         fullscreenAct->setText(fsText);
1369         fullscreenAct->setIcon(IconUtils::icon("view-fullscreen"));
1370
1371         if (needStatusBar()) setStatusBarVisibility(true);
1372
1373         if (mainToolBar) {
1374             addToolBar(mainToolBar);
1375         }
1376
1377         mediaView->restoreSidebar();
1378     }
1379
1380     // No compact view action when in full screen
1381     compactViewAct->setVisible(!fullScreenActive);
1382     compactViewAct->setChecked(false);
1383
1384     // Hide anything but the video
1385     mediaView->setSidebarVisibility(!fullScreenActive);
1386
1387     if (fullScreenActive) {
1388         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_MediaStop));
1389     } else {
1390         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Escape)
1391                                                     << QKeySequence(Qt::Key_MediaStop));
1392     }
1393
1394 #ifdef Q_OS_MAC
1395     MacSupport::fullScreenActions(actionMap, fullScreenActive);
1396 #endif
1397
1398     if (views->currentWidget() == mediaView) mediaView->setFocus();
1399
1400     if (fullScreenActive) {
1401         if (views->currentWidget() == mediaView) hideFullscreenUI();
1402     } else {
1403         fullscreenTimer->stop();
1404         unsetCursor();
1405     }
1406 }
1407
1408 bool MainWindow::isReallyFullScreen() {
1409 #ifdef Q_OS_MAC
1410     WId handle = winId();
1411     if (mac::CanGoFullScreen(handle))
1412         return mac::IsFullScreen(handle);
1413     else
1414         return isFullScreen();
1415 #else
1416     return isFullScreen();
1417 #endif
1418 }
1419
1420 void MainWindow::missingKeyWarning() {
1421     QMessageBox msgBox(this);
1422     msgBox.setIconPixmap(IconUtils::pixmap(":/images/64x64/app.png"));
1423     msgBox.setText(QString("%1 was built without a Google API key.").arg(Constants::NAME));
1424     msgBox.setInformativeText(QString("It won't work unless you enter one."
1425                                       "<p>In alternative you can get %1 from the developer site.")
1426                                       .arg(Constants::NAME));
1427     msgBox.setModal(true);
1428     msgBox.setWindowModality(Qt::WindowModal);
1429     QPushButton *enterKeyButton =
1430             msgBox.addButton(QString("Enter API key..."), QMessageBox::AcceptRole);
1431     QPushButton *devButton = msgBox.addButton(QString("Get from %1").arg(Constants::WEBSITE),
1432                                               QMessageBox::AcceptRole);
1433     QPushButton *helpButton = msgBox.addButton(QMessageBox::Help);
1434     msgBox.exec();
1435     if (msgBox.clickedButton() == helpButton) {
1436         QDesktopServices::openUrl(QUrl(
1437                 "https://github.com/flaviotordini/minitube/blob/master/README.md#google-api-key"));
1438     } else if (msgBox.clickedButton() == enterKeyButton) {
1439         bool ok;
1440         QString text = QInputDialog::getText(this, QString(), "Google API key:", QLineEdit::Normal,
1441                                              QString(), &ok);
1442         if (ok && !text.isEmpty()) {
1443             QSettings settings;
1444             settings.setValue("googleApiKey", text);
1445             YT3::instance().initApiKeys();
1446         }
1447     } else if (msgBox.clickedButton() == devButton) {
1448         QDesktopServices::openUrl(QUrl(Constants::WEBSITE));
1449     }
1450 }
1451
1452 void MainWindow::compactView(bool enable) {
1453     compactModeActive = enable;
1454
1455     static QList<QKeySequence> compactShortcuts;
1456     static QList<QKeySequence> stopShortcuts;
1457
1458     const QString key = "compactGeometry";
1459     QSettings settings;
1460
1461     if (enable) {
1462         setMinimumSize(320, 180);
1463 #ifdef Q_OS_MAC
1464         mac::RemoveFullScreenWindow(winId());
1465 #endif
1466         writeSettings();
1467
1468         if (settings.contains(key))
1469             restoreGeometry(settings.value(key).toByteArray());
1470         else
1471             resize(320, 180);
1472
1473 #ifdef APP_MAC_QMACTOOLBAR
1474         mac::showToolBar(winId(), !enable);
1475 #else
1476         mainToolBar->setVisible(!enable);
1477 #endif
1478         mediaView->setSidebarVisibility(!enable);
1479         statusBar()->hide();
1480
1481         compactShortcuts = compactViewAct->shortcuts();
1482         stopShortcuts = stopAct->shortcuts();
1483
1484         QList<QKeySequence> newStopShortcuts(stopShortcuts);
1485         newStopShortcuts.removeAll(QKeySequence(Qt::Key_Escape));
1486         stopAct->setShortcuts(newStopShortcuts);
1487         compactViewAct->setShortcuts(QList<QKeySequence>(compactShortcuts)
1488                                      << QKeySequence(Qt::Key_Escape));
1489
1490         // ensure focus does not end up to the search box
1491         // as it would steal the Space shortcut
1492         mediaView->setFocus();
1493
1494     } else {
1495         // unset minimum size
1496         setMinimumSize(0, 0);
1497 #ifdef Q_OS_MAC
1498         mac::SetupFullScreenWindow(winId());
1499 #endif
1500         settings.setValue(key, saveGeometry());
1501 #ifdef APP_MAC_QMACTOOLBAR
1502         mac::showToolBar(winId(), !enable);
1503 #else
1504         mainToolBar->setVisible(!enable);
1505 #endif
1506         mediaView->setSidebarVisibility(!enable);
1507         if (needStatusBar()) setStatusBarVisibility(true);
1508
1509         readSettings();
1510
1511         compactViewAct->setShortcuts(compactShortcuts);
1512         stopAct->setShortcuts(stopShortcuts);
1513     }
1514
1515     // auto float on top
1516     floatOnTop(enable, false);
1517
1518 #ifdef APP_MAC
1519     mac::compactMode(winId(), enable);
1520 #else
1521     if (enable) {
1522         menuVisibleBeforeCompactMode = menuBar()->isVisible();
1523         menuBar()->hide();
1524     } else {
1525         menuBar()->setVisible(menuVisibleBeforeCompactMode);
1526     }
1527 #endif
1528 }
1529
1530 void MainWindow::toggleToolbarMenu() {
1531     if (!toolbarMenu) toolbarMenu = new ToolbarMenu(this);
1532     if (toolbarMenu->isVisible())
1533         toolbarMenu->hide();
1534     else
1535         toolbarMenu->show();
1536 }
1537
1538 void MainWindow::searchFocus() {
1539     toolbarSearch->selectAll();
1540     toolbarSearch->setFocus();
1541 }
1542
1543 #ifdef APP_PHONON
1544 void MainWindow::initPhonon() {
1545     // Phonon initialization
1546     if (mediaObject) delete mediaObject;
1547     if (audioOutput) delete audioOutput;
1548     mediaObject = new Phonon::MediaObject(this);
1549     mediaObject->setTickInterval(100);
1550     connect(mediaObject, SIGNAL(stateChanged(Phonon::State, Phonon::State)),
1551             SLOT(stateChanged(Phonon::State, Phonon::State)));
1552     connect(mediaObject, SIGNAL(tick(qint64)), SLOT(tick(qint64)));
1553     connect(mediaObject, SIGNAL(totalTimeChanged(qint64)), SLOT(totalTimeChanged(qint64)));
1554
1555     audioOutput = new Phonon::AudioOutput(Phonon::VideoCategory, this);
1556     connect(audioOutput, SIGNAL(mutedChanged(bool)), SLOT(volumeMutedChanged(bool)));
1557     Phonon::createPath(mediaObject, audioOutput);
1558     volumeSlider->setAudioOutput(audioOutput);
1559
1560 #ifdef APP_PHONON_SEEK
1561     seekSlider->setMediaObject(mediaObject);
1562 #endif
1563
1564     QSettings settings;
1565     audioOutput->setVolume(settings.value("volume", 1.).toReal());
1566     // audioOutput->setMuted(settings.value("volumeMute").toBool());
1567
1568     mediaObject->stop();
1569 }
1570 #endif
1571
1572 void MainWindow::tick(qint64 time) {
1573     const QString s = formatTime(time);
1574     if (s != currentTimeLabel->text()) {
1575         currentTimeLabel->setText(s);
1576         emit currentTimeChanged(s);
1577     }
1578
1579 // remaining time
1580 #ifdef APP_PHONON
1581     const qint64 remainingTime = mediaObject->remainingTime();
1582     currentTimeLabel->setStatusTip(tr("Remaining time: %1").arg(formatTime(remainingTime)));
1583
1584 #ifndef APP_PHONON_SEEK
1585     const qint64 totalTime = mediaObject->totalTime();
1586     slider->blockSignals(true);
1587     // qWarning() << totalTime << time << time * 100 / totalTime;
1588     if (totalTime > 0 && time > 0 && !slider->isSliderDown() &&
1589         mediaObject->state() == Phonon::PlayingState)
1590         slider->setValue(time * slider->maximum() / totalTime);
1591     slider->blockSignals(false);
1592 #endif
1593
1594 #endif
1595 }
1596
1597 void MainWindow::totalTimeChanged(qint64 time) {
1598     if (time <= 0) {
1599         // totalTime->clear();
1600         return;
1601     }
1602     // totalTime->setText(formatTime(time));
1603
1604     /*
1605     slider->blockSignals(true);
1606     slider->setMaximum(time/1000);
1607     slider->blockSignals(false);
1608     */
1609 }
1610
1611 QString MainWindow::formatTime(qint64 duration) {
1612     duration /= 1000;
1613     QString res;
1614     int seconds = (int)(duration % 60);
1615     duration /= 60;
1616     int minutes = (int)(duration % 60);
1617     duration /= 60;
1618     int hours = (int)(duration % 24);
1619     if (hours == 0) return res.sprintf("%02d:%02d", minutes, seconds);
1620     return res.sprintf("%02d:%02d:%02d", hours, minutes, seconds);
1621 }
1622
1623 void MainWindow::volumeUp() {
1624 #ifdef APP_PHONON
1625     qreal newVolume = volumeSlider->audioOutput()->volume() + .1;
1626     if (newVolume > volumeSlider->maximumVolume()) newVolume = volumeSlider->maximumVolume();
1627     volumeSlider->audioOutput()->setVolume(newVolume);
1628 #endif
1629 }
1630
1631 void MainWindow::volumeDown() {
1632 #ifdef APP_PHONON
1633     qreal newVolume = volumeSlider->audioOutput()->volume() - .1;
1634     if (newVolume < 0.) newVolume = 0.;
1635     volumeSlider->audioOutput()->setVolume(newVolume);
1636 #endif
1637 }
1638
1639 void MainWindow::volumeMute() {
1640 #ifdef APP_PHONON
1641     bool muted = volumeSlider->audioOutput()->isMuted();
1642     volumeSlider->audioOutput()->setMuted(!muted);
1643     qApp->processEvents();
1644     if (muted && volumeSlider->audioOutput()->volume() == 0.) {
1645         volumeSlider->audioOutput()->setVolume(volumeSlider->maximumVolume());
1646     }
1647     qDebug() << volumeSlider->audioOutput()->isMuted() << volumeSlider->audioOutput()->volume();
1648 #endif
1649 }
1650
1651 void MainWindow::volumeMutedChanged(bool muted) {
1652     if (muted) {
1653         volumeMuteAct->setIcon(IconUtils::icon("audio-volume-muted"));
1654         showMessage(tr("Volume is muted"));
1655     } else {
1656         volumeMuteAct->setIcon(IconUtils::icon("audio-volume-high"));
1657         showMessage(tr("Volume is unmuted"));
1658     }
1659 #ifdef APP_LINUX
1660     QToolButton *volumeMuteButton =
1661             qobject_cast<QToolButton *>(mainToolBar->widgetForAction(volumeMuteAct));
1662     volumeMuteButton->setIcon(volumeMuteButton->icon().pixmap(16));
1663 #endif
1664 }
1665
1666 void MainWindow::setDefinitionMode(const QString &definitionName) {
1667     QAction *definitionAct = getAction("definition");
1668     definitionAct->setText(definitionName);
1669     definitionAct->setStatusTip(
1670             tr("Maximum video definition set to %1").arg(definitionAct->text()) + " (" +
1671             definitionAct->shortcut().toString(QKeySequence::NativeText) + ")");
1672     showMessage(definitionAct->statusTip());
1673     QSettings settings;
1674     settings.setValue("definition", definitionName);
1675 }
1676
1677 void MainWindow::toggleDefinitionMode() {
1678     const QString definitionName = QSettings().value("definition").toString();
1679     const QVector<VideoDefinition> &definitions = VideoDefinition::getDefinitions();
1680     const VideoDefinition &currentDefinition = VideoDefinition::forName(definitionName);
1681     if (currentDefinition.isEmpty()) {
1682         setDefinitionMode(definitions.at(0).getName());
1683         return;
1684     }
1685
1686     int index = definitions.indexOf(currentDefinition);
1687     if (index != definitions.size() - 1) {
1688         index++;
1689     } else {
1690         index = 0;
1691     }
1692     // TODO: pass a VideoDefinition instead of QString.
1693     setDefinitionMode(definitions.at(index).getName());
1694 }
1695
1696 void MainWindow::clearRecentKeywords() {
1697     QSettings settings;
1698     settings.remove("recentKeywords");
1699     settings.remove("recentChannels");
1700     if (views->currentWidget() == homeView) {
1701         SearchView *searchView = homeView->getSearchView();
1702         searchView->updateRecentKeywords();
1703         searchView->updateRecentChannels();
1704     }
1705     HttpUtils::clearCaches();
1706     showMessage(tr("Your privacy is now safe"));
1707 }
1708
1709 void MainWindow::setManualPlay(bool enabled) {
1710     QSettings settings;
1711     settings.setValue("manualplay", QVariant::fromValue(enabled));
1712     if (views->currentWidget() == homeView &&
1713         homeView->currentWidget() == homeView->getSearchView())
1714         return;
1715     showActionInStatusBar(getAction("manualplay"), enabled);
1716 }
1717
1718 void MainWindow::updateDownloadMessage(const QString &message) {
1719     getAction("downloads")->setText(message);
1720 }
1721
1722 void MainWindow::downloadsFinished() {
1723     getAction("downloads")->setText(tr("&Downloads"));
1724     showMessage(tr("Downloads complete"));
1725 }
1726
1727 void MainWindow::toggleDownloads(bool show) {
1728     if (show) {
1729         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_MediaStop));
1730         getAction("downloads")
1731                 ->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_J)
1732                                                      << QKeySequence(Qt::Key_Escape));
1733     } else {
1734         getAction("downloads")
1735                 ->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_J));
1736         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Escape)
1737                                                     << QKeySequence(Qt::Key_MediaStop));
1738     }
1739
1740     if (!downloadView) {
1741         downloadView = new DownloadView(this);
1742         views->addWidget(downloadView);
1743     }
1744     if (show)
1745         showWidget(downloadView);
1746     else
1747         goBack();
1748 }
1749
1750 void MainWindow::suggestionAccepted(Suggestion *suggestion) {
1751     search(suggestion->value);
1752 }
1753
1754 void MainWindow::search(const QString &query) {
1755     QString q = query.simplified();
1756     if (q.isEmpty()) return;
1757     SearchParams *searchParams = new SearchParams();
1758     searchParams->setKeywords(q);
1759     showMedia(searchParams);
1760 }
1761
1762 void MainWindow::dragEnterEvent(QDragEnterEvent *e) {
1763     if (e->mimeData()->hasFormat("text/uri-list")) {
1764         QList<QUrl> urls = e->mimeData()->urls();
1765         if (urls.isEmpty()) return;
1766         const QUrl &url = urls.at(0);
1767         QString videoId = YTSearch::videoIdFromUrl(url.toString());
1768         if (!videoId.isEmpty()) e->acceptProposedAction();
1769     }
1770 }
1771
1772 void MainWindow::dropEvent(QDropEvent *e) {
1773     if (!toolbarSearch->isEnabled()) return;
1774
1775     QList<QUrl> urls = e->mimeData()->urls();
1776     if (urls.isEmpty()) return;
1777     const QUrl &url = urls.at(0);
1778     QString videoId = YTSearch::videoIdFromUrl(url.toString());
1779     if (!videoId.isEmpty()) {
1780         setWindowTitle(url.toString());
1781         SearchParams *searchParams = new SearchParams();
1782         searchParams->setKeywords(videoId);
1783         showMedia(searchParams);
1784     }
1785 }
1786
1787 void MainWindow::checkForUpdate() {
1788     static const QString updateCheckKey = "updateCheck";
1789
1790     // check every 24h
1791     QSettings settings;
1792     uint unixTime = QDateTime::currentDateTime().toTime_t();
1793     int lastCheck = settings.value(updateCheckKey).toInt();
1794     int secondsSinceLastCheck = unixTime - lastCheck;
1795     // qDebug() << "secondsSinceLastCheck" << unixTime << lastCheck << secondsSinceLastCheck;
1796     if (secondsSinceLastCheck < 86400) return;
1797
1798     // check it out
1799     if (updateChecker) delete updateChecker;
1800     updateChecker = new UpdateChecker();
1801     connect(updateChecker, SIGNAL(newVersion(QString)), this, SLOT(gotNewVersion(QString)));
1802     updateChecker->checkForUpdate();
1803     settings.setValue(updateCheckKey, unixTime);
1804 }
1805
1806 void MainWindow::gotNewVersion(const QString &version) {
1807     if (updateChecker) {
1808         delete updateChecker;
1809         updateChecker = 0;
1810     }
1811
1812     QSettings settings;
1813     QString checkedVersion = settings.value("checkedVersion").toString();
1814     if (checkedVersion == version) return;
1815
1816 #ifdef APP_EXTRA
1817 #ifndef APP_MAC
1818     UpdateDialog *dialog = new UpdateDialog(version, this);
1819     dialog->show();
1820 #endif
1821 #else
1822     simpleUpdateDialog(version);
1823 #endif
1824 }
1825
1826 void MainWindow::simpleUpdateDialog(const QString &version) {
1827     QMessageBox msgBox(this);
1828     msgBox.setIconPixmap(IconUtils::pixmap(":/images/64x64/app.png"));
1829     msgBox.setText(tr("%1 version %2 is now available.").arg(Constants::NAME, version));
1830     msgBox.setModal(true);
1831     msgBox.setWindowModality(Qt::WindowModal);
1832     msgBox.addButton(QMessageBox::Close);
1833     QPushButton *laterButton = msgBox.addButton(tr("Remind me later"), QMessageBox::RejectRole);
1834     QPushButton *updateButton = msgBox.addButton(tr("Update"), QMessageBox::AcceptRole);
1835     msgBox.exec();
1836     if (msgBox.clickedButton() != laterButton) {
1837         QSettings settings;
1838         settings.setValue("checkedVersion", version);
1839     }
1840     if (msgBox.clickedButton() == updateButton) visitSite();
1841 }
1842
1843 bool MainWindow::needStatusBar() {
1844     return !statusToolBar->actions().isEmpty();
1845 }
1846
1847 void MainWindow::adjustMessageLabelPosition() {
1848     if (messageLabel->parent() == this)
1849         messageLabel->move(0, height() - messageLabel->height());
1850     else
1851         messageLabel->move(mapToGlobal(QPoint(0, height() - messageLabel->height())));
1852 }
1853
1854 void MainWindow::floatOnTop(bool onTop, bool showAction) {
1855     if (showAction) showActionInStatusBar(getAction("ontop"), onTop);
1856 #ifdef APP_MAC
1857     mac::floatOnTop(winId(), onTop);
1858 #else
1859     if (onTop) {
1860         setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
1861         show();
1862     } else {
1863         setWindowFlags(windowFlags() ^ Qt::WindowStaysOnTopHint);
1864         show();
1865     }
1866 #endif
1867 }
1868
1869 void MainWindow::restore() {
1870 #ifdef APP_MAC
1871     mac::uncloseWindow(winId());
1872 #endif
1873 }
1874
1875 void MainWindow::messageReceived(const QString &message) {
1876     if (message == QLatin1String("--toggle-playing")) {
1877         if (pauseAct->isEnabled()) pauseAct->trigger();
1878     } else if (message == QLatin1String("--next")) {
1879         if (skipAct->isEnabled()) skipAct->trigger();
1880     } else if (message == QLatin1String("--previous")) {
1881         if (skipBackwardAct->isEnabled()) skipBackwardAct->trigger();
1882     } else if (message == QLatin1String("--stop-after-this")) {
1883         getAction("stopafterthis")->toggle();
1884     } else if (message.startsWith("--")) {
1885         MainWindow::printHelp();
1886     } else if (!message.isEmpty()) {
1887         SearchParams *searchParams = new SearchParams();
1888         searchParams->setKeywords(message);
1889         showMedia(searchParams);
1890     }
1891 }
1892
1893 void MainWindow::hideFullscreenUI() {
1894     if (views->currentWidget() != mediaView) return;
1895     setCursor(Qt::BlankCursor);
1896
1897     QPoint p = mapFromGlobal(QCursor::pos());
1898     const int x = p.x();
1899
1900     if (x > mediaView->getSidebar()->width()) mediaView->setSidebarVisibility(false);
1901
1902 #ifndef APP_MAC
1903     const int y = p.y();
1904     bool shouldHideToolbar = !toolbarSearch->hasFocus() && y > mainToolBar->height();
1905     if (shouldHideToolbar) mainToolBar->setVisible(false);
1906 #endif
1907 }
1908
1909 void MainWindow::toggleMenuVisibility() {
1910     bool show = !menuBar()->isVisible();
1911     menuBar()->setVisible(show);
1912 }
1913
1914 void MainWindow::toggleMenuVisibilityWithMessage() {
1915     bool show = !menuBar()->isVisible();
1916     menuBar()->setVisible(show);
1917     if (!show) {
1918         QMessageBox msgBox(this);
1919         msgBox.setText(tr("You can still access the menu bar by pressing the ALT key"));
1920         msgBox.setModal(true);
1921         msgBox.setWindowModality(Qt::WindowModal);
1922         msgBox.exec();
1923     }
1924 }
1925
1926 #ifdef APP_MAC_STORE
1927 void MainWindow::rateOnAppStore() {
1928     QDesktopServices::openUrl(QUrl("macappstore://userpub.itunes.apple.com"
1929                                    "/WebObjects/MZUserPublishing.woa/wa/addUserReview"
1930                                    "?id=422006190&type=Purple+Software"));
1931 }
1932 #endif
1933
1934 void MainWindow::printHelp() {
1935     QString msg = QString("%1 %2\n\n").arg(Constants::NAME, Constants::VERSION);
1936     msg += "Usage: minitube [options]\n";
1937     msg += "Options:\n";
1938     msg += "  --toggle-playing\t";
1939     msg += "Start or pause playback.\n";
1940     msg += "  --next\t\t";
1941     msg += "Skip to the next video.\n";
1942     msg += "  --previous\t\t";
1943     msg += "Go back to the previous video.\n";
1944     msg += "  --stop-after-this\t";
1945     msg += "Stop playback at the end of the video.\n";
1946     std::cout << msg.toLocal8Bit().data();
1947 }
1948
1949 QAction *MainWindow::getAction(const char *name) {
1950     return actionMap.value(QByteArray::fromRawData(name, strlen(name)));
1951 }
1952
1953 void MainWindow::addNamedAction(const QByteArray &name, QAction *action) {
1954     actionMap.insert(name, action);
1955 }
1956
1957 QMenu *MainWindow::getMenu(const char *name) {
1958     return menuMap.value(QByteArray::fromRawData(name, strlen(name)));
1959 }
1960
1961 void MainWindow::showMessage(const QString &message) {
1962     if (!isVisible()) return;
1963 #ifdef APP_MAC
1964     if (!mac::isVisible(winId())) return;
1965 #endif
1966     if (statusBar()->isVisible())
1967         statusBar()->showMessage(message, 60000);
1968     else {
1969         messageLabel->setText(message);
1970         QSize size = messageLabel->sizeHint();
1971         // round width to nearest 10 to avoid flicker with fast changing messages (e.g. volume
1972         // changes)
1973         int w = size.width();
1974         const int multiple = 10;
1975         w = w + multiple / 2;
1976         w -= w % multiple;
1977         size.setWidth(w);
1978         messageLabel->resize(size);
1979         if (messageLabel->isHidden()) {
1980             adjustMessageLabelPosition();
1981             messageLabel->show();
1982         }
1983         messageTimer->start();
1984     }
1985 }
1986
1987 void MainWindow::hideMessage() {
1988     if (messageLabel->isVisible()) {
1989         messageLabel->hide();
1990         messageLabel->clear();
1991     }
1992 }
1993
1994 #ifdef APP_ACTIVATION
1995 void MainWindow::showActivationView() {
1996     QWidget *activationView = ActivationView::instance();
1997     views->addWidget(activationView);
1998     if (views->currentWidget() != activationView) showWidget(activationView);
1999 }
2000 #endif
2001
2002 void MainWindow::showRegionsView() {
2003     if (!regionsView) {
2004         regionsView = new RegionsView(this);
2005         connect(regionsView, SIGNAL(regionChanged()), homeView->getStandardFeedsView(),
2006                 SLOT(load()));
2007         views->addWidget(regionsView);
2008     }
2009     showWidget(regionsView);
2010 }