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