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