]> git.sur5r.net Git - minitube/blob - src/mainwindow.cpp
Merge tag 'upstream/2.5.2'
[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 #endif
769     toolbarSearch->setMinimumWidth(toolbarSearch->fontInfo().pixelSize()*15);
770     toolbarSearch->setSuggester(new YTSuggester(this));
771     connect(toolbarSearch, SIGNAL(search(const QString&)), SLOT(search(const QString&)));
772     connect(toolbarSearch, SIGNAL(suggestionAccepted(Suggestion*)), SLOT(suggestionAccepted(Suggestion*)));
773     toolbarSearch->setStatusTip(searchFocusAct->statusTip());
774
775     // Add widgets to toolbar
776
777 #ifdef APP_MAC_QMACTOOLBAR
778     currentTime->hide();
779     toolbarSearch->hide();
780     volumeSlider->hide();
781     seekSlider->hide();
782     MacToolbar::instance().createToolbar(this);
783     return;
784 #endif
785
786     mainToolBar = new QToolBar(this);
787     mainToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
788     mainToolBar->setFloatable(false);
789     mainToolBar->setMovable(false);
790 #if defined(APP_MAC) | defined(APP_WIN)
791     mainToolBar->setIconSize(QSize(32, 32));
792 #endif
793
794     mainToolBar->addAction(stopAct);
795     mainToolBar->addAction(pauseAct);
796     mainToolBar->addAction(skipAct);
797     mainToolBar->addAction(The::globalActions()->value("related-videos"));
798     mainToolBar->addAction(The::globalActions()->value("download"));
799
800     bool addFullScreenAct = true;
801 #ifdef Q_OS_MAC
802     addFullScreenAct = !mac::CanGoFullScreen(winId());
803 #endif
804     if (addFullScreenAct) mainToolBar->addAction(fullscreenAct);
805
806     mainToolBar->addWidget(new Spacer());
807     mainToolBar->addWidget(currentTime);
808     mainToolBar->addWidget(new Spacer());
809 #ifdef APP_PHONON_SEEK
810     mainToolBar->addWidget(seekSlider);
811 #else
812     mainToolBar->addWidget(slider);
813 #endif
814
815     /*
816     mainToolBar->addWidget(new Spacer());
817     totalTime = new QLabel(mainToolBar);
818     totalTime->setFont(smallerFont);
819     mainToolBar->addWidget(totalTime);
820     */
821
822     mainToolBar->addWidget(new Spacer());
823     mainToolBar->addAction(volumeMuteAct);
824 #ifdef APP_LINUX
825     QToolButton *volumeMuteButton = qobject_cast<QToolButton *>(mainToolBar->widgetForAction(volumeMuteAct));
826     volumeMuteButton->setIcon(volumeMuteButton->icon().pixmap(16));
827 #endif
828
829 #ifdef APP_PHONON
830     mainToolBar->addWidget(volumeSlider);
831 #endif
832
833     mainToolBar->addWidget(new Spacer());
834
835 #if defined(APP_MAC_SEARCHFIELD) && !defined(APP_MAC_QMACTOOLBAR)
836     mainToolBar->addWidget(searchWrapper);
837 #else
838     mainToolBar->addWidget(toolbarSearch);
839     mainToolBar->addWidget(new Spacer());
840 #endif
841
842     addToolBar(mainToolBar);
843 }
844
845 void MainWindow::createStatusBar() {
846     statusToolBar = new QToolBar(this);
847     statusToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
848     statusToolBar->setIconSize(QSize(16, 16));
849
850     regionAction = new QAction(this);
851     regionAction->setStatusTip(tr("Choose your content location"));
852
853     QAction *localAction = The::globalActions()->value("local-region");
854     if (!localAction->text().isEmpty()) {
855         QMenu *regionMenu = new QMenu(this);
856         regionMenu->addAction(The::globalActions()->value("worldwide-region"));
857         regionMenu->addAction(localAction);
858         regionMenu->addSeparator();
859         QAction *moreRegionsAction = The::globalActions()->value("more-region");
860         regionMenu->addAction(moreRegionsAction);
861         connect(moreRegionsAction, SIGNAL(triggered()), SLOT(showRegionsView()));
862         regionAction->setMenu(regionMenu);
863     } else {
864         connect(regionAction, SIGNAL(triggered()), SLOT(showRegionsView()));
865     }
866
867     /* Stupid code that generates the QRC items
868     foreach(YTRegion r, YTRegions::list())
869         qDebug() << QString("<file>flags/%1.png</file>").arg(r.id.toLower());
870     */
871
872     statusBar()->addPermanentWidget(statusToolBar);
873 }
874
875 void MainWindow::showStopAfterThisInStatusBar(bool show) {
876     QAction* action = The::globalActions()->value("stopafterthis");
877     showActionInStatusBar(action, show);
878 }
879
880 void MainWindow::showActionInStatusBar(QAction* action, bool show) {
881 #ifdef APP_EXTRA
882     Extra::fadeInWidget(statusBar(), statusBar());
883 #endif
884     if (show) {
885         statusToolBar->insertAction(statusToolBar->actions().first(), action);
886         if (statusBar()->isHidden() && !fullscreenFlag)
887             setStatusBarVisibility(true);
888     } else {
889         statusToolBar->removeAction(action);
890         if (statusBar()->isVisible() && !needStatusBar())
891             setStatusBarVisibility(false);
892     }
893 }
894
895 void MainWindow::setStatusBarVisibility(bool show) {
896     statusBar()->setVisible(show);
897     if (views->currentWidget() == mediaView)
898         QTimer::singleShot(0, mediaView, SLOT(maybeAdjustWindowSize()));
899 }
900
901 void MainWindow::adjustStatusBarVisibility() {
902     setStatusBarVisibility(needStatusBar());
903 }
904
905 void MainWindow::readSettings() {
906     QSettings settings;
907     if (settings.contains("geometry")) {
908         restoreGeometry(settings.value("geometry").toByteArray());
909 #ifdef APP_MAC
910         MacSupport::fixGeometry(this);
911 #endif
912     } else {
913         const QRect desktopSize = qApp->desktop()->availableGeometry();
914         int w = qMin(2000, desktopSize.width());
915         int h = qMin(w / 3, desktopSize.height());
916         setGeometry(
917                     QStyle::alignedRect(
918                         Qt::LeftToRight,
919                         Qt::AlignTop,
920                         QSize(w, h),
921                         desktopSize)
922                     );
923     }
924     const VideoDefinition& firstDefinition = VideoDefinition::getDefinitions().first();
925     setDefinitionMode(settings.value("definition", firstDefinition.getName()).toString());
926     The::globalActions()->value("manualplay")->setChecked(settings.value("manualplay", false).toBool());
927     The::globalActions()->value("adjustwindowsize")->setChecked(settings.value("adjustWindowSize", true).toBool());
928 }
929
930 void MainWindow::writeSettings() {
931     QSettings settings;
932
933     if (!isReallyFullScreen())
934         settings.setValue("geometry", saveGeometry());
935     mediaView->saveSplitterState();
936
937 #ifdef APP_PHONON
938     if (audioOutput->volume() > 0.1)
939         settings.setValue("volume", audioOutput->volume());
940     // settings.setValue("volumeMute", audioOutput->isMuted());
941 #endif
942
943     settings.setValue("manualplay", The::globalActions()->value("manualplay")->isChecked());
944 }
945
946 void MainWindow::goBack() {
947     if (history.size() > 1) {
948         history.pop();
949         QWidget *widget = history.pop();
950         showWidget(widget);
951     }
952 }
953
954 void MainWindow::showWidget(QWidget* widget, bool transition) {
955     Q_UNUSED(transition);
956
957     if (compactViewAct->isChecked())
958         compactViewAct->toggle();
959
960     // call hide method on the current view
961     View* oldView = qobject_cast<View *> (views->currentWidget());
962     if (oldView) {
963         oldView->disappear();
964         views->currentWidget()->setEnabled(false);
965     } else qDebug() << "Cannot cast view";
966
967     const bool isMediaView = widget == mediaView;
968
969     stopAct->setEnabled(isMediaView);
970     compactViewAct->setEnabled(isMediaView);
971     toolbarSearch->setEnabled(widget == homeView || isMediaView || widget == downloadView);
972
973     aboutAct->setEnabled(widget != aboutView);
974     The::globalActions()->value("downloads")->setChecked(widget == downloadView);
975
976     QWidget *oldWidget = views->currentWidget();
977     if (oldWidget)
978         oldWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
979
980     views->setCurrentWidget(widget);
981     widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
982
983     // call show method on the new view
984     View* newView = qobject_cast<View *> (widget);
985     if (newView) {
986         widget->setEnabled(true);
987         QHash<QString,QVariant> metadata = newView->metadata();
988
989         QString title = metadata.value("title").toString();
990         if (title.isEmpty()) title = Constants::NAME;
991         else title += QLatin1String(" - ") + Constants::NAME;
992         setWindowTitle(title);
993
994         statusToolBar->setUpdatesEnabled(false);
995
996         // dynamic view actions
997         foreach (QAction* action, viewActions)
998             showActionInStatusBar(action, false);
999         viewActions = newView->getViewActions();
1000         foreach (QAction* action, viewActions)
1001             showActionInStatusBar(action, true);
1002
1003         newView->appear();
1004
1005         adjustStatusBarVisibility();
1006         messageLabel->hide();
1007
1008         statusToolBar->setUpdatesEnabled(true);
1009
1010         /*
1011         QString desc = metadata.value("description").toString();
1012         if (!desc.isEmpty()) showMessage(desc);
1013         */
1014     }
1015
1016     history.push(widget);
1017 }
1018
1019 void MainWindow::about() {
1020     if (!aboutView) {
1021         aboutView = new AboutView(this);
1022         views->addWidget(aboutView);
1023     }
1024     showWidget(aboutView);
1025 }
1026
1027 void MainWindow::visitSite() {
1028     QUrl url(Constants::WEBSITE);
1029     showMessage(QString(tr("Opening %1").arg(url.toString())));
1030     QDesktopServices::openUrl(url);
1031 }
1032
1033 void MainWindow::donate() {
1034     QUrl url(QString(Constants::WEBSITE) + "#donate");
1035     showMessage(QString(tr("Opening %1").arg(url.toString())));
1036     QDesktopServices::openUrl(url);
1037 }
1038
1039 void MainWindow::reportIssue() {
1040     QUrl url("http://flavio.tordini.org/forums/forum/minitube-forums/minitube-troubleshooting");
1041     QDesktopServices::openUrl(url);
1042 }
1043
1044 void MainWindow::quit() {
1045 #ifdef APP_MAC
1046     if (!confirmQuit()) {
1047         return;
1048     }
1049 #endif
1050     // do not save geometry when in full screen or in compact mode
1051     if (!fullscreenFlag && !compactViewAct->isChecked()) {
1052         writeSettings();
1053     }
1054     // mediaView->stop();
1055     Temporary::deleteAll();
1056     ChannelAggregator::instance()->stop();
1057     ChannelAggregator::instance()->cleanup();
1058     Database::shutdown();
1059     qApp->quit();
1060 }
1061
1062 void MainWindow::closeEvent(QCloseEvent *e) {
1063 #ifdef APP_MAC
1064     mac::closeWindow(winId());
1065     e->ignore();
1066 #else
1067     if (!confirmQuit()) {
1068         e->ignore();
1069         return;
1070     }
1071     QWidget::closeEvent(e);
1072     quit();
1073 #endif
1074     messageLabel->hide();
1075 }
1076
1077 void MainWindow::showEvent(QShowEvent *e) {
1078     QWidget::showEvent(e);
1079 #ifdef APP_MAC
1080     restore();
1081 #endif
1082 }
1083
1084 bool MainWindow::confirmQuit() {
1085     if (DownloadManager::instance()->activeItems() > 0) {
1086         QMessageBox msgBox(this);
1087         msgBox.setIconPixmap(IconUtils::pixmap(":/images/app.png").scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
1088         msgBox.setText(tr("Do you want to exit %1 with a download in progress?").arg(Constants::NAME));
1089         msgBox.setInformativeText(tr("If you close %1 now, this download will be cancelled.").arg(Constants::NAME));
1090         msgBox.setModal(true);
1091         // make it a "sheet" on the Mac
1092         msgBox.setWindowModality(Qt::WindowModal);
1093
1094         msgBox.addButton(tr("Close and cancel download"), QMessageBox::RejectRole);
1095         QPushButton *waitButton = msgBox.addButton(tr("Wait for download to finish"), QMessageBox::ActionRole);
1096
1097         msgBox.exec();
1098
1099         if (msgBox.clickedButton() == waitButton) {
1100             return false;
1101         }
1102     }
1103     return true;
1104 }
1105
1106 void MainWindow::showHome(bool transition) {
1107     showWidget(homeView, transition);
1108     currentTime->clear();
1109     // totalTime->clear();
1110 }
1111
1112 void MainWindow::showMedia(SearchParams *searchParams) {
1113     showWidget(mediaView);
1114     mediaView->search(searchParams);
1115 }
1116
1117 void MainWindow::showMedia(VideoSource *videoSource) {
1118     showWidget(mediaView);
1119     mediaView->setVideoSource(videoSource);
1120 }
1121
1122 #ifdef APP_PHONON
1123 void MainWindow::stateChanged(Phonon::State newState, Phonon::State /* oldState */) {
1124
1125     // qDebug() << "Phonon state: " << newState;
1126
1127     switch (newState) {
1128
1129     case Phonon::ErrorState:
1130         if (mediaObject->errorType() == Phonon::FatalError) {
1131             // Do not display because we try to play incomplete video files and sometimes trigger this
1132             // We retry automatically (in MediaView) so no need to show it
1133             // showMessage(tr("Fatal error: %1").arg(mediaObject->errorString()));
1134         } else {
1135             showMessage(tr("Error: %1").arg(mediaObject->errorString()));
1136         }
1137         break;
1138
1139     case Phonon::PlayingState:
1140         pauseAct->setEnabled(true);
1141         pauseAct->setIcon(IconUtils::icon("media-playback-pause"));
1142         pauseAct->setText(tr("&Pause"));
1143         pauseAct->setStatusTip(tr("Pause playback") + " (" +  pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
1144         // stopAct->setEnabled(true);
1145         break;
1146
1147     case Phonon::StoppedState:
1148         pauseAct->setEnabled(false);
1149         pauseAct->setIcon(IconUtils::icon("media-playback-start"));
1150         pauseAct->setText(tr("&Play"));
1151         pauseAct->setStatusTip(tr("Resume playback") + " (" +  pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
1152         // stopAct->setEnabled(false);
1153         break;
1154
1155     case Phonon::PausedState:
1156         pauseAct->setEnabled(true);
1157         pauseAct->setIcon(IconUtils::icon("media-playback-start"));
1158         pauseAct->setText(tr("&Play"));
1159         pauseAct->setStatusTip(tr("Resume playback") + " (" +  pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
1160         // stopAct->setEnabled(true);
1161         break;
1162
1163     case Phonon::BufferingState:
1164         pauseAct->setEnabled(false);
1165         pauseAct->setIcon(IconUtils::icon("content-loading"));
1166         pauseAct->setText(tr("&Loading..."));
1167         pauseAct->setStatusTip(QString());
1168         break;
1169
1170     case Phonon::LoadingState:
1171         pauseAct->setEnabled(false);
1172         currentTime->clear();
1173         // totalTime->clear();
1174         // stopAct->setEnabled(true);
1175         break;
1176
1177     default:
1178         ;
1179     }
1180 }
1181 #endif
1182
1183 void MainWindow::stop() {
1184     showHome();
1185     mediaView->stop();
1186 }
1187
1188 void MainWindow::resizeEvent(QResizeEvent *e) {
1189     Q_UNUSED(e);
1190 #ifdef APP_MAC
1191     if (initialized && mac::CanGoFullScreen(winId())) {
1192         bool isFullscreen = mac::IsFullScreen(winId());
1193         if (isFullscreen != fullscreenFlag) {
1194             if (compactViewAct->isChecked()) {
1195                 compactViewAct->setChecked(false);
1196                 compactView(false);
1197             }
1198             fullscreenFlag = isFullscreen;
1199             updateUIForFullscreen();
1200         }
1201     }
1202 #endif
1203 #ifdef APP_MAC_QMACTOOLBAR
1204     toolbarSearch->move(width() - toolbarSearch->width() - 13, -38);
1205 #endif
1206     adjustMessageLabelPosition();
1207 }
1208
1209 void MainWindow::moveEvent(QMoveEvent *e) {
1210     Q_UNUSED(e);
1211     adjustMessageLabelPosition();
1212 }
1213
1214 void MainWindow::fullscreen() {
1215
1216     if (compactViewAct->isChecked())
1217         compactViewAct->toggle();
1218
1219 #ifdef APP_MAC
1220     WId handle = winId();
1221     if (mac::CanGoFullScreen(handle)) {
1222         if (mainToolBar) mainToolBar->setVisible(true);
1223         mac::ToggleFullScreen(handle);
1224         return;
1225     }
1226 #endif
1227
1228     fullscreenFlag = !fullscreenFlag;
1229
1230     if (fullscreenFlag) {
1231         // Enter full screen
1232
1233         m_maximized = isMaximized();
1234
1235         // save geometry now, if the user quits when in full screen
1236         // geometry won't be saved
1237         writeSettings();
1238
1239 #ifdef APP_MAC
1240         MacSupport::enterFullScreen(this, views);
1241 #else
1242         if (mainToolBar) mainToolBar->hide();
1243         showFullScreen();
1244 #endif
1245
1246     } else {
1247         // Exit full screen
1248
1249 #ifdef APP_MAC
1250         MacSupport::exitFullScreen(this, views);
1251 #else
1252         if (mainToolBar) mainToolBar->show();
1253         if (m_maximized) showMaximized();
1254         else showNormal();
1255 #endif
1256
1257         // Make sure the window has focus
1258         activateWindow();
1259
1260     }
1261
1262     updateUIForFullscreen();
1263
1264 }
1265
1266 void MainWindow::updateUIForFullscreen() {
1267     static QList<QKeySequence> fsShortcuts;
1268     static QString fsText;
1269
1270     if (fullscreenFlag) {
1271         fsShortcuts = fullscreenAct->shortcuts();
1272         fsText = fullscreenAct->text();
1273         if (fsText.isEmpty()) qDebug() << "[taking Empty!]";
1274         fullscreenAct->setShortcuts(QList<QKeySequence>(fsShortcuts)
1275                                     << QKeySequence(Qt::Key_Escape));
1276         fullscreenAct->setText(tr("Leave &Full Screen"));
1277         fullscreenAct->setIcon(IconUtils::icon("view-restore"));
1278         setStatusBarVisibility(false);
1279     } else {
1280         fullscreenAct->setShortcuts(fsShortcuts);
1281         if (fsText.isEmpty()) fsText = "[Empty!]";
1282         fullscreenAct->setText(fsText);
1283         fullscreenAct->setIcon(IconUtils::icon("view-fullscreen"));
1284
1285         if (needStatusBar()) setStatusBarVisibility(true);
1286     }
1287
1288     // No compact view action when in full screen
1289     compactViewAct->setVisible(!fullscreenFlag);
1290     compactViewAct->setChecked(false);
1291
1292     // Hide anything but the video
1293     mediaView->setPlaylistVisible(!fullscreenFlag);
1294     if (mainToolBar) mainToolBar->setVisible(!fullscreenFlag);
1295
1296 #ifndef APP_MAC
1297     menuBar()->setVisible(!fullscreenFlag);
1298 #endif
1299
1300     if (fullscreenFlag) {
1301         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_MediaStop));
1302     } else {
1303         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Escape) << QKeySequence(Qt::Key_MediaStop));
1304     }
1305
1306 #ifdef Q_OS_MAC
1307     MacSupport::fullScreenActions(The::globalActions()->values(), fullscreenFlag);
1308 #endif
1309
1310     if (views->currentWidget() == mediaView)
1311         mediaView->setFocus();
1312
1313     if (fullscreenFlag) {
1314         hideMouse();
1315     } else {
1316         mouseTimer->stop();
1317         unsetCursor();
1318     }
1319 }
1320
1321 bool MainWindow::isReallyFullScreen() {
1322 #ifdef Q_OS_MAC
1323     WId handle = winId();
1324     if (mac::CanGoFullScreen(handle)) return mac::IsFullScreen(handle);
1325     else return isFullScreen();
1326 #else
1327     return isFullScreen();
1328 #endif
1329 }
1330
1331 void MainWindow::compactView(bool enable) {
1332     m_compact = enable;
1333
1334     static QList<QKeySequence> compactShortcuts;
1335     static QList<QKeySequence> stopShortcuts;
1336
1337     const static QString key = "compactGeometry";
1338     QSettings settings;
1339
1340 #ifndef APP_MAC
1341     menuBar()->setVisible(!enable);
1342 #endif
1343
1344     if (enable) {
1345         setMinimumSize(320, 180);
1346 #ifdef Q_OS_MAC
1347         mac::RemoveFullScreenWindow(winId());
1348 #endif
1349         writeSettings();
1350
1351         if (settings.contains(key))
1352             restoreGeometry(settings.value(key).toByteArray());
1353         else
1354             resize(320, 180);
1355
1356 #ifdef APP_MAC_QMACTOOLBAR
1357         mac::showToolBar(winId(), !enable);
1358 #else
1359         mainToolBar->setVisible(!enable);
1360 #endif
1361         mediaView->setPlaylistVisible(!enable);
1362         statusBar()->hide();
1363
1364         compactShortcuts = compactViewAct->shortcuts();
1365         stopShortcuts = stopAct->shortcuts();
1366
1367         QList<QKeySequence> newStopShortcuts(stopShortcuts);
1368         newStopShortcuts.removeAll(QKeySequence(Qt::Key_Escape));
1369         stopAct->setShortcuts(newStopShortcuts);
1370         compactViewAct->setShortcuts(QList<QKeySequence>(compactShortcuts) << QKeySequence(Qt::Key_Escape));
1371
1372         // ensure focus does not end up to the search box
1373         // as it would steal the Space shortcut
1374         mediaView->setFocus();
1375
1376     } else {
1377         // unset minimum size
1378         setMinimumSize(0, 0);
1379 #ifdef Q_OS_MAC
1380         mac::SetupFullScreenWindow(winId());
1381 #endif
1382         settings.setValue(key, saveGeometry());
1383 #ifdef APP_MAC_QMACTOOLBAR
1384         mac::showToolBar(winId(), !enable);
1385 #else
1386         mainToolBar->setVisible(!enable);
1387 #endif
1388         mediaView->setPlaylistVisible(!enable);
1389         if (needStatusBar()) setStatusBarVisibility(true);
1390
1391         readSettings();
1392
1393         compactViewAct->setShortcuts(compactShortcuts);
1394         stopAct->setShortcuts(stopShortcuts);
1395     }
1396
1397     // auto float on top
1398     floatOnTop(enable, false);
1399
1400 #ifdef Q_OS_MAC
1401     mac::compactMode(winId(), enable);
1402 #endif
1403 }
1404
1405 void MainWindow::searchFocus() {
1406     toolbarSearch->selectAll();
1407     toolbarSearch->setFocus();
1408 }
1409
1410 #ifdef APP_PHONON
1411 void MainWindow::initPhonon() {
1412     // Phonon initialization
1413     if (mediaObject) delete mediaObject;
1414     if (audioOutput) delete audioOutput;
1415     mediaObject = new Phonon::MediaObject(this);
1416     mediaObject->setTickInterval(100);
1417     connect(mediaObject, SIGNAL(stateChanged(Phonon::State, Phonon::State)),
1418             SLOT(stateChanged(Phonon::State, Phonon::State)));
1419     connect(mediaObject, SIGNAL(tick(qint64)), SLOT(tick(qint64)));
1420     connect(mediaObject, SIGNAL(totalTimeChanged(qint64)), SLOT(totalTimeChanged(qint64)));
1421
1422     audioOutput = new Phonon::AudioOutput(Phonon::VideoCategory, this);
1423     connect(audioOutput, SIGNAL(volumeChanged(qreal)), SLOT(volumeChanged(qreal)));
1424     connect(audioOutput, SIGNAL(mutedChanged(bool)), SLOT(volumeMutedChanged(bool)));
1425     Phonon::createPath(mediaObject, audioOutput);
1426     volumeSlider->setAudioOutput(audioOutput);
1427
1428 #ifdef APP_PHONON_SEEK
1429     seekSlider->setMediaObject(mediaObject);
1430 #endif
1431
1432     QSettings settings;
1433     audioOutput->setVolume(settings.value("volume", 1.).toReal());
1434     // audioOutput->setMuted(settings.value("volumeMute").toBool());
1435
1436     mediaObject->stop();
1437 }
1438 #endif
1439
1440 void MainWindow::tick(qint64 time) {
1441     const QString s = formatTime(time);
1442     if (s != currentTime->text()) {
1443         currentTime->setText(s);
1444         emit currentTimeChanged(s);
1445     }
1446
1447     // remaining time
1448 #ifdef APP_PHONON
1449     const qint64 remainingTime = mediaObject->remainingTime();
1450     currentTime->setStatusTip(tr("Remaining time: %1").arg(formatTime(remainingTime)));
1451
1452 #ifndef APP_PHONON_SEEK
1453     const qint64 totalTime = mediaObject->totalTime();
1454     slider->blockSignals(true);
1455     // qWarning() << totalTime << time << time * 100 / totalTime;
1456     if (totalTime > 0 && time > 0 && !slider->isSliderDown() && mediaObject->state() == Phonon::PlayingState)
1457         slider->setValue(time * slider->maximum() / totalTime);
1458     slider->blockSignals(false);
1459 #endif
1460
1461 #endif
1462 }
1463
1464 void MainWindow::totalTimeChanged(qint64 time) {
1465     if (time <= 0) {
1466         // totalTime->clear();
1467         return;
1468     }
1469     // totalTime->setText(formatTime(time));
1470
1471     /*
1472     slider->blockSignals(true);
1473     slider->setMaximum(time/1000);
1474     slider->blockSignals(false);
1475     */
1476 }
1477
1478 QString MainWindow::formatTime(qint64 duration) {
1479     duration /= 1000;
1480     QString res;
1481     int seconds = (int) (duration % 60);
1482     duration /= 60;
1483     int minutes = (int) (duration % 60);
1484     duration /= 60;
1485     int hours = (int) (duration % 24);
1486     if (hours == 0)
1487         return res.sprintf("%02d:%02d", minutes, seconds);
1488     return res.sprintf("%02d:%02d:%02d", hours, minutes, seconds);
1489 }
1490
1491 void MainWindow::volumeUp() {
1492 #ifdef APP_PHONON
1493     qreal newVolume = volumeSlider->audioOutput()->volume() + .1;
1494     if (newVolume > volumeSlider->maximumVolume())
1495         newVolume = volumeSlider->maximumVolume();
1496     volumeSlider->audioOutput()->setVolume(newVolume);
1497 #endif
1498 }
1499
1500 void MainWindow::volumeDown() {
1501 #ifdef APP_PHONON
1502     qreal newVolume = volumeSlider->audioOutput()->volume() - .1;
1503     if (newVolume < 0.)
1504         newVolume = 0.;
1505     volumeSlider->audioOutput()->setVolume(newVolume);
1506 #endif
1507 }
1508
1509 void MainWindow::volumeMute() {
1510 #ifdef APP_PHONON
1511     bool muted = volumeSlider->audioOutput()->isMuted();
1512     volumeSlider->audioOutput()->setMuted(!muted);
1513     qApp->processEvents();
1514     if (muted && volumeSlider->audioOutput()->volume() == 0) {
1515         volumeSlider->audioOutput()->setVolume(volumeSlider->maximumVolume());
1516     }
1517     qDebug() << volumeSlider->audioOutput()->isMuted() << volumeSlider->audioOutput()->volume();
1518 #endif
1519 }
1520
1521 void MainWindow::volumeChanged(qreal newVolume) {
1522 #ifdef APP_PHONON
1523     // automatically unmute when volume changes
1524     if (volumeSlider->audioOutput()->isMuted()) volumeSlider->audioOutput()->setMuted(false);
1525
1526     bool isZero = volumeSlider->property("zero").toBool();
1527     bool styleChanged = false;
1528     if (newVolume == 0. && !isZero) {
1529         volumeSlider->setProperty("zero", true);
1530         styleChanged = true;
1531     } else if (newVolume > 0. && isZero) {
1532         volumeSlider->setProperty("zero", false);
1533         styleChanged = true;
1534     }
1535     if (styleChanged) {
1536         QSlider* volumeQSlider = volumeSlider->findChild<QSlider*>();
1537         style()->unpolish(volumeQSlider);
1538         style()->polish(volumeQSlider);
1539     }
1540 #endif
1541     showMessage(tr("Volume at %1%").arg((int)(newVolume*100)));
1542 }
1543
1544 void MainWindow::volumeMutedChanged(bool muted) {
1545     if (muted) {
1546         volumeMuteAct->setIcon(IconUtils::icon("audio-volume-muted"));
1547         showMessage(tr("Volume is muted"));
1548     } else {
1549         volumeMuteAct->setIcon(IconUtils::icon("audio-volume-high"));
1550         showMessage(tr("Volume is unmuted"));
1551     }
1552 #ifdef APP_LINUX
1553     QToolButton *volumeMuteButton = qobject_cast<QToolButton *>(mainToolBar->widgetForAction(volumeMuteAct));
1554     volumeMuteButton->setIcon(volumeMuteButton->icon().pixmap(16));
1555 #endif
1556 }
1557
1558 void MainWindow::setDefinitionMode(const QString &definitionName) {
1559     QAction *definitionAct = The::globalActions()->value("definition");
1560     definitionAct->setText(definitionName);
1561     definitionAct->setStatusTip(tr("Maximum video definition set to %1").arg(definitionAct->text())
1562                                 + " (" +  definitionAct->shortcut().toString(QKeySequence::NativeText) + ")");
1563     showMessage(definitionAct->statusTip());
1564     QSettings settings;
1565     settings.setValue("definition", definitionName);
1566 }
1567
1568 void MainWindow::toggleDefinitionMode() {
1569     const QString definitionName = QSettings().value("definition").toString();
1570     const QList<VideoDefinition>& definitions = VideoDefinition::getDefinitions();
1571     const VideoDefinition& currentDefinition = VideoDefinition::getDefinitionFor(definitionName);
1572     if (currentDefinition.isEmpty()) {
1573         setDefinitionMode(definitions.first().getName());
1574         return;
1575     }
1576
1577     int index = definitions.indexOf(currentDefinition);
1578     if (index != definitions.size() - 1) {
1579         index++;
1580     } else {
1581         index = 0;
1582     }
1583     // TODO: pass a VideoDefinition instead of QString.
1584     setDefinitionMode(definitions.at(index).getName());
1585 }
1586
1587 void MainWindow::showFullscreenToolbar(bool show) {
1588     if (!fullscreenFlag) return;
1589     mainToolBar->setVisible(show);
1590 }
1591
1592 void MainWindow::showFullscreenPlaylist(bool show) {
1593     if (!fullscreenFlag) return;
1594     mediaView->setPlaylistVisible(show);
1595 }
1596
1597 void MainWindow::clearRecentKeywords() {
1598     QSettings settings;
1599     settings.remove("recentKeywords");
1600     settings.remove("recentChannels");
1601     if (views->currentWidget() == homeView) {
1602         SearchView *searchView = homeView->getSearchView();
1603         searchView->updateRecentKeywords();
1604         searchView->updateRecentChannels();
1605     }
1606     QAbstractNetworkCache *cache = The::networkAccessManager()->cache();
1607     if (cache) cache->clear();
1608     showMessage(tr("Your privacy is now safe"));
1609 }
1610
1611 void MainWindow::setManualPlay(bool enabled) {
1612     QSettings settings;
1613     settings.setValue("manualplay", QVariant::fromValue(enabled));
1614     showActionInStatusBar(The::globalActions()->value("manualplay"), enabled);
1615 }
1616
1617 void MainWindow::updateDownloadMessage(const QString &message) {
1618     The::globalActions()->value("downloads")->setText(message);
1619 }
1620
1621 void MainWindow::downloadsFinished() {
1622     The::globalActions()->value("downloads")->setText(tr("&Downloads"));
1623     showMessage(tr("Downloads complete"));
1624 }
1625
1626 void MainWindow::toggleDownloads(bool show) {
1627
1628     if (show) {
1629         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_MediaStop));
1630         The::globalActions()->value("downloads")->setShortcuts(
1631                     QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_J)
1632                     << QKeySequence(Qt::Key_Escape));
1633     } else {
1634         The::globalActions()->value("downloads")->setShortcuts(
1635                     QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_J));
1636         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Escape) << QKeySequence(Qt::Key_MediaStop));
1637     }
1638
1639     if (!downloadView) {
1640         downloadView = new DownloadView(this);
1641         views->addWidget(downloadView);
1642     }
1643     if (show) showWidget(downloadView);
1644     else goBack();
1645 }
1646
1647 void MainWindow::suggestionAccepted(Suggestion *suggestion) {
1648     search(suggestion->value);
1649 }
1650
1651 void MainWindow::search(const QString &query) {
1652     QString q = query.trimmed();
1653     if (q.length() == 0) return;
1654     SearchParams *searchParams = new SearchParams();
1655     searchParams->setKeywords(q);
1656     showMedia(searchParams);
1657 }
1658
1659 void MainWindow::dragEnterEvent(QDragEnterEvent *e) {
1660     if (e->mimeData()->hasFormat("text/uri-list")) {
1661         QList<QUrl> urls = e->mimeData()->urls();
1662         if (urls.isEmpty()) return;
1663         QUrl url = urls.first();
1664         QString videoId = YTSearch::videoIdFromUrl(url.toString());
1665         if (!videoId.isEmpty())
1666             e->acceptProposedAction();
1667     }
1668 }
1669
1670 void MainWindow::dropEvent(QDropEvent *e) {
1671     if (!toolbarSearch->isEnabled()) return;
1672
1673     QList<QUrl> urls = e->mimeData()->urls();
1674     if (urls.isEmpty())
1675         return;
1676     QUrl url = urls.first();
1677     QString videoId = YTSearch::videoIdFromUrl(url.toString());
1678     if (!videoId.isEmpty()) {
1679         setWindowTitle(url.toString());
1680         SearchParams *searchParams = new SearchParams();
1681         searchParams->setKeywords(videoId);
1682         showMedia(searchParams);
1683     }
1684 }
1685
1686 void MainWindow::checkForUpdate() {
1687     static const QString updateCheckKey = "updateCheck";
1688
1689     // check every 24h
1690     QSettings settings;
1691     uint unixTime = QDateTime::currentDateTime().toTime_t();
1692     int lastCheck = settings.value(updateCheckKey).toInt();
1693     int secondsSinceLastCheck = unixTime - lastCheck;
1694     // qDebug() << "secondsSinceLastCheck" << unixTime << lastCheck << secondsSinceLastCheck;
1695     if (secondsSinceLastCheck < 86400) return;
1696
1697     // check it out
1698     if (updateChecker) delete updateChecker;
1699     updateChecker = new UpdateChecker();
1700     connect(updateChecker, SIGNAL(newVersion(QString)),
1701             this, SLOT(gotNewVersion(QString)));
1702     updateChecker->checkForUpdate();
1703     settings.setValue(updateCheckKey, unixTime);
1704 }
1705
1706 void MainWindow::gotNewVersion(const QString &version) {
1707     if (updateChecker) {
1708         delete updateChecker;
1709         updateChecker = 0;
1710     }
1711
1712     QSettings settings;
1713     QString checkedVersion = settings.value("checkedVersion").toString();
1714     if (checkedVersion == version) return;
1715
1716 #ifdef APP_EXTRA
1717 #ifndef APP_MAC
1718     UpdateDialog *dialog = new UpdateDialog(version, this);
1719     dialog->show();
1720 #endif
1721 #else
1722     simpleUpdateDialog(version);
1723 #endif
1724 }
1725
1726 void MainWindow::simpleUpdateDialog(const QString &version) {
1727     QMessageBox msgBox(this);
1728     msgBox.setIconPixmap(
1729                 IconUtils::pixmap(":/images/app.png")
1730                 .scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
1731     msgBox.setText(tr("%1 version %2 is now available.").arg(Constants::NAME, version));
1732     msgBox.setModal(true);
1733     msgBox.setWindowModality(Qt::WindowModal);
1734     msgBox.addButton(QMessageBox::Close);
1735     QPushButton* laterButton = msgBox.addButton(tr("Remind me later"), QMessageBox::RejectRole);
1736     QPushButton* updateButton = msgBox.addButton(tr("Update"), QMessageBox::AcceptRole);
1737     msgBox.exec();
1738     if (msgBox.clickedButton() != laterButton) {
1739         QSettings settings;
1740         settings.setValue("checkedVersion", version);
1741     }
1742     if (msgBox.clickedButton() == updateButton) visitSite();
1743 }
1744
1745 bool MainWindow::needStatusBar() {
1746     return !statusToolBar->actions().isEmpty();
1747 }
1748
1749 void MainWindow::adjustMessageLabelPosition() {
1750     if (messageLabel->parent() == this)
1751         messageLabel->move(0, height() - messageLabel->height());
1752     else
1753         messageLabel->move(mapToGlobal(QPoint(0, height() - messageLabel->height())));
1754 }
1755
1756 void MainWindow::floatOnTop(bool onTop, bool showAction) {
1757     if (showAction) showActionInStatusBar(The::globalActions()->value("ontop"), onTop);
1758 #ifdef APP_MAC
1759     mac::floatOnTop(winId(), onTop);
1760     return;
1761 #endif
1762     if (onTop) {
1763         setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
1764         show();
1765     } else {
1766         setWindowFlags(windowFlags() ^ Qt::WindowStaysOnTopHint);
1767         show();
1768     }
1769 }
1770
1771 void MainWindow::adjustWindowSizeChanged(bool enabled) {
1772     QSettings settings;
1773     settings.setValue("adjustWindowSize", enabled);
1774     if (enabled && views->currentWidget() == mediaView)
1775         mediaView->adjustWindowSize();
1776 }
1777
1778 void MainWindow::restore() {
1779 #ifdef APP_MAC
1780     mac::uncloseWindow(window()->winId());
1781 #endif
1782 }
1783
1784 void MainWindow::messageReceived(const QString &message) {
1785     if (message == QLatin1String("--toggle-playing")) {
1786         if (pauseAct->isEnabled()) pauseAct->trigger();
1787     } else if (message == QLatin1String("--next")) {
1788         if (skipAct->isEnabled()) skipAct->trigger();
1789     } else if (message == QLatin1String("--previous")) {
1790         if (skipBackwardAct->isEnabled()) skipBackwardAct->trigger();
1791     } else if (message == QLatin1String("--stop-after-this")) {
1792         The::globalActions()->value("stopafterthis")->toggle();
1793     }  else if (message.startsWith("--")) {
1794         MainWindow::printHelp();
1795     } else if (!message.isEmpty()) {
1796         SearchParams *searchParams = new SearchParams();
1797         searchParams->setKeywords(message);
1798         showMedia(searchParams);
1799     }
1800 }
1801
1802 void MainWindow::hideMouse() {
1803     setCursor(Qt::BlankCursor);
1804     mediaView->setPlaylistVisible(false);
1805 #ifndef APP_MAC
1806     mainToolBar->setVisible(false);
1807 #endif
1808 }
1809
1810 #ifdef APP_MAC_STORE
1811 void MainWindow::rateOnAppStore() {
1812     QDesktopServices::openUrl(QUrl("macappstore://userpub.itunes.apple.com"
1813                                    "/WebObjects/MZUserPublishing.woa/wa/addUserReview"
1814                                    "?id=422006190&type=Purple+Software"));
1815 }
1816 #endif
1817
1818 void MainWindow::printHelp() {
1819     QString msg = QString("%1 %2\n\n").arg(Constants::NAME, Constants::VERSION);
1820     msg += "Usage: minitube [options]\n";
1821     msg += "Options:\n";
1822     msg += "  --toggle-playing\t";
1823     msg += "Start or pause playback.\n";
1824     msg += "  --next\t\t";
1825     msg += "Skip to the next video.\n";
1826     msg += "  --previous\t\t";
1827     msg += "Go back to the previous video.\n";
1828     msg += "  --stop-after-this\t";
1829     msg += "Stop playback at the end of the video.\n";
1830     std::cout << msg.toLocal8Bit().data();
1831 }
1832
1833 void MainWindow::showMessage(const QString &message) {
1834     if (!isVisible()) return;
1835 #ifdef APP_MAC
1836     if (!mac::isVisible(winId())) return;
1837 #endif
1838     if (statusBar()->isVisible())
1839         statusBar()->showMessage(message, 60000);
1840     else {
1841         messageLabel->setText(message);
1842         messageLabel->resize(messageLabel->sizeHint());
1843         adjustMessageLabelPosition();
1844         messageLabel->show();
1845         messageTimer->start();
1846     }
1847 }
1848
1849 #ifdef APP_ACTIVATION
1850 void MainWindow::showActivationView(bool transition) {
1851     QWidget *activationView = ActivationView::instance();
1852     if (views->currentWidget() == activationView) {
1853         buy();
1854         return;
1855     }
1856     views->addWidget(activationView);
1857     showWidget(activationView, transition);
1858 }
1859
1860 void MainWindow::showActivationDialog() {
1861     QTimer::singleShot(0, new ActivationDialog(this), SLOT(show()));
1862 }
1863
1864 void MainWindow::buy() {
1865     Extra::buy();
1866 }
1867
1868 void MainWindow::hideBuyAction() {
1869     QAction *action = The::globalActions()->value("buy");
1870     action->setVisible(false);
1871     action->setEnabled(false);
1872 }
1873 #endif
1874
1875 void MainWindow::showRegionsView() {
1876     if (!regionsView) {
1877         regionsView = new RegionsView(this);
1878         connect(regionsView, SIGNAL(regionChanged()),
1879                 homeView->getStandardFeedsView(), SLOT(load()));
1880         views->addWidget(regionsView);
1881     }
1882     showWidget(regionsView);
1883 }