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