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