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