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