]> git.sur5r.net Git - minitube/blob - src/mainwindow.cpp
Qt5 fixes
[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 "utils.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(Utils::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()), this, SLOT(stop()));
273
274     skipBackwardAct = new QAction(
275                 Utils::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(Utils::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(Utils::icon("media-playback-pause"), tr("&Pause"), this);
291     pauseAct->setStatusTip(tr("Pause 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(Utils::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(Utils::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(Utils::tintedIcon("video-display", QColor(0, 0, 0),
441                                              QList<QSize>() << QSize(16, 16)));
442 #else
443     definitionAct->setIcon(Utils::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(Utils::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_B));
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(Utils::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(Utils::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     /*
486     action = new QAction(tr("&Snapshot"), this);
487     action->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_S));
488     actions->insert("snapshot", action);
489     connect(action, SIGNAL(triggered()), mediaView, SLOT(snapshot()));
490     */
491
492     action = new QAction(tr("&Subscribe to Channel"), this);
493     action->setProperty("originalText", action->text());
494     action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_S));
495     action->setEnabled(false);
496     connect(action, SIGNAL(triggered()), mediaView, SLOT(toggleSubscription()));
497     actions->insert("subscribe-channel", action);
498     mediaView->updateSubscriptionAction(0, false);
499
500     QString shareTip = tr("Share the current video using %1");
501
502     action = new QAction("&Twitter", this);
503     action->setStatusTip(shareTip.arg("Twitter"));
504     action->setEnabled(false);
505     actions->insert("twitter", action);
506     connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaTwitter()));
507
508     action = new QAction("&Facebook", this);
509     action->setStatusTip(shareTip.arg("Facebook"));
510     action->setEnabled(false);
511     actions->insert("facebook", action);
512     connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaFacebook()));
513
514     action = new QAction("&Buffer", this);
515     action->setStatusTip(shareTip.arg("Buffer"));
516     action->setEnabled(false);
517     actions->insert("buffer", action);
518     connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaBuffer()));
519
520     action = new QAction(tr("&Email"), this);
521     action->setStatusTip(shareTip.arg(tr("Email")));
522     action->setEnabled(false);
523     actions->insert("email", action);
524     connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaEmail()));
525
526     action = new QAction(tr("&Close"), this);
527     action->setShortcut(QKeySequence(QKeySequence::Close));
528     actions->insert("close", action);
529     connect(action, SIGNAL(triggered()), SLOT(close()));
530
531     action = new QAction(Constants::NAME, this);
532     action->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_1));
533     actions->insert("restore", action);
534     connect(action, SIGNAL(triggered()), SLOT(restore()));
535
536     action = new QAction(Utils::icon("go-top"), tr("&Float on Top"), this);
537     action->setCheckable(true);
538     actions->insert("ontop", action);
539     connect(action, SIGNAL(toggled(bool)), SLOT(floatOnTop(bool)));
540
541     action = new QAction(Utils::icon("media-playback-stop"), tr("&Stop After This Video"), this);
542     action->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Escape));
543     action->setCheckable(true);
544     action->setEnabled(false);
545     actions->insert("stopafterthis", action);
546     connect(action, SIGNAL(toggled(bool)), SLOT(showStopAfterThisInStatusBar(bool)));
547
548     action = new QAction(tr("&Report an Issue..."), this);
549     actions->insert("report-issue", action);
550     connect(action, SIGNAL(triggered()), SLOT(reportIssue()));
551
552     action = new QAction(tr("&Refine Search..."), this);
553     action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_E));
554     action->setCheckable(true);
555     action->setEnabled(false);
556     actions->insert("refine-search", action);
557
558     action = new QAction(YTRegions::worldwideRegion().name, this);
559     actions->insert("worldwide-region", action);
560
561     action = new QAction(YTRegions::localRegion().name, this);
562     actions->insert("local-region", action);
563
564     action = new QAction(tr("More..."), this);
565     actions->insert("more-region", action);
566
567     action = new QAction(Utils::icon(QStringList() << "view-list-symbolic" << "view-list" << "format-justify-fill"), tr("&Related Videos"), this);
568     action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R));
569     action->setStatusTip(tr("Watch videos related to the current one"));
570     action->setEnabled(false);
571     action->setPriority(QAction::LowPriority);
572     connect(action, SIGNAL(triggered()), mediaView, SLOT(relatedVideos()));
573     actions->insert("related-videos", action);
574
575     action = new QAction(tr("Open in &Browser..."), this);
576     action->setEnabled(false);
577     actions->insert("open-in-browser", action);
578     connect(action, SIGNAL(triggered()), mediaView, SLOT(openInBrowser()));
579
580 #ifdef APP_MAC_STORE
581     action = new QAction(tr("&Love %1? Rate it!").arg(Constants::NAME), this);
582     actions->insert("app-store", action);
583     connect(action, SIGNAL(triggered()), SLOT(rateOnAppStore()));
584 #endif
585
586 #ifdef APP_ACTIVATION
587     Extra::createActivationAction(tr("Buy %1...").arg(Constants::NAME));
588 #endif
589
590     // common action properties
591     foreach (QAction *action, actions->values()) {
592         // add actions to the MainWindow so that they work
593         // when the menu is hidden
594         addAction(action);
595         Utils::setupAction(action);
596     }
597 }
598
599 void MainWindow::createMenus() {
600
601     QHash<QString, QMenu*> *menus = The::globalMenus();
602
603     fileMenu = menuBar()->addMenu(tr("&Application"));
604 #ifdef APP_ACTIVATION
605     QAction *buyAction = The::globalActions()->value("buy");
606     if (buyAction) fileMenu->addAction(buyAction);
607 #ifndef APP_MAC
608     fileMenu->addSeparator();
609 #endif
610 #endif
611     fileMenu->addAction(clearAct);
612 #ifndef APP_MAC
613     fileMenu->addSeparator();
614 #endif
615     fileMenu->addAction(quitAct);
616
617     QMenu* playbackMenu = menuBar()->addMenu(tr("&Playback"));
618     menus->insert("playback", playbackMenu);
619     playbackMenu->addAction(pauseAct);
620     playbackMenu->addAction(stopAct);
621     playbackMenu->addAction(The::globalActions()->value("stopafterthis"));
622     playbackMenu->addSeparator();
623     playbackMenu->addAction(skipAct);
624     playbackMenu->addAction(skipBackwardAct);
625     playbackMenu->addSeparator();
626     playbackMenu->addAction(The::globalActions()->value("manualplay"));
627 #ifdef APP_MAC
628     MacSupport::dockMenu(playbackMenu);
629 #endif
630
631     playlistMenu = menuBar()->addMenu(tr("&Playlist"));
632     menus->insert("playlist", playlistMenu);
633     playlistMenu->addAction(removeAct);
634     playlistMenu->addSeparator();
635     playlistMenu->addAction(moveUpAct);
636     playlistMenu->addAction(moveDownAct);
637     playlistMenu->addSeparator();
638     playlistMenu->addAction(The::globalActions()->value("refine-search"));
639
640     QMenu* videoMenu = menuBar()->addMenu(tr("&Video"));
641     menus->insert("video", videoMenu);
642     videoMenu->addAction(The::globalActions()->value("related-videos"));
643     videoMenu->addAction(findVideoPartsAct);
644     videoMenu->addSeparator();
645     videoMenu->addAction(webPageAct);
646     videoMenu->addSeparator();
647     videoMenu->addAction(The::globalActions()->value("subscribe-channel"));
648     videoMenu->addSeparator();
649     videoMenu->addAction(The::globalActions()->value("download"));
650     videoMenu->addAction(copyLinkAct);
651     videoMenu->addAction(The::globalActions()->value("open-in-browser"));
652     // videoMenu->addAction(The::globalActions()->value("snapshot"));
653
654     QMenu* viewMenu = menuBar()->addMenu(tr("&View"));
655     menus->insert("view", viewMenu);
656     viewMenu->addAction(fullscreenAct);
657     viewMenu->addAction(compactViewAct);
658     viewMenu->addSeparator();
659     viewMenu->addAction(The::globalActions()->value("ontop"));
660
661     QMenu* shareMenu = menuBar()->addMenu(tr("&Share"));
662     menus->insert("share", shareMenu);
663     shareMenu->addAction(copyPageAct);
664     shareMenu->addSeparator();
665     shareMenu->addAction(The::globalActions()->value("twitter"));
666     shareMenu->addAction(The::globalActions()->value("facebook"));
667     shareMenu->addAction(The::globalActions()->value("buffer"));
668     shareMenu->addSeparator();
669     shareMenu->addAction(The::globalActions()->value("email"));
670
671 #ifdef APP_MAC
672     MacSupport::windowMenu(this);
673 #endif
674
675     helpMenu = menuBar()->addMenu(tr("&Help"));
676     helpMenu->addAction(siteAct);
677 #if !defined(APP_MAC) && !defined(APP_WIN)
678     helpMenu->addAction(donateAct);
679 #endif
680     helpMenu->addAction(The::globalActions()->value("report-issue"));
681     helpMenu->addAction(aboutAct);
682
683 #ifdef APP_MAC_STORE
684     helpMenu->addSeparator();
685     helpMenu->addAction(The::globalActions()->value("app-store"));
686 #endif
687 }
688
689 void MainWindow::createToolBars() {
690
691     setUnifiedTitleAndToolBarOnMac(true);
692
693     mainToolBar = new QToolBar(this);
694     mainToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
695     mainToolBar->setFloatable(false);
696     mainToolBar->setMovable(false);
697
698 #if defined(APP_MAC) | defined(APP_WIN)
699     mainToolBar->setIconSize(QSize(32, 32));
700 #endif
701
702     mainToolBar->addAction(stopAct);
703     mainToolBar->addAction(pauseAct);
704     mainToolBar->addAction(skipAct);
705
706     mainToolBar->addAction(The::globalActions()->value("related-videos"));
707     mainToolBar->addAction(The::globalActions()->value("download"));
708
709     bool addFullScreenAct = true;
710 #ifdef Q_OS_MAC
711     addFullScreenAct = !mac::CanGoFullScreen(winId());
712 #endif
713     if (addFullScreenAct) mainToolBar->addAction(fullscreenAct);
714
715     mainToolBar->addWidget(new Spacer());
716
717     QFont smallerFont = FontUtils::small();
718     currentTime = new QLabel(mainToolBar);
719     currentTime->setFont(smallerFont);
720     mainToolBar->addWidget(currentTime);
721
722 #ifdef APP_PHONON_SEEK
723     mainToolBar->addWidget(new Spacer());
724     seekSlider = new Phonon::SeekSlider(this);
725     seekSlider->setVisible(false);
726     seekSlider->setIconVisible(false);
727     seekSlider->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
728     mainToolBar->addWidget(seekSlider);
729 #endif
730
731     mainToolBar->addWidget(new Spacer());
732     slider = new SeekSlider(this);
733     slider->setEnabled(false);
734     slider->setTracking(false);
735     slider->setMaximum(1000);
736     slider->setOrientation(Qt::Horizontal);
737     slider->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
738     mainToolBar->addWidget(slider);
739
740     mainToolBar->addWidget(new Spacer());
741
742     totalTime = new QLabel(mainToolBar);
743     totalTime->setFont(smallerFont);
744     mainToolBar->addWidget(totalTime);
745
746     mainToolBar->addWidget(new Spacer());
747
748     mainToolBar->addAction(volumeMuteAct);
749
750 #ifdef APP_PHONON
751     volumeSlider = new Phonon::VolumeSlider(this);
752     volumeSlider->setMuteVisible(false);
753     // qDebug() << volumeSlider->children();
754     // status tip for the volume slider
755     QSlider* volumeQSlider = volumeSlider->findChild<QSlider*>();
756     if (volumeQSlider)
757         volumeQSlider->setStatusTip(tr("Press %1 to raise the volume, %2 to lower it").arg(
758                                         volumeUpAct->shortcut().toString(QKeySequence::NativeText), volumeDownAct->shortcut().toString(QKeySequence::NativeText)));
759     // this makes the volume slider smaller
760     volumeSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
761     mainToolBar->addWidget(volumeSlider);
762 #endif
763
764     mainToolBar->addWidget(new Spacer());
765
766 #ifdef APP_MAC
767     SearchWrapper* searchWrapper = new SearchWrapper(this);
768     toolbarSearch = searchWrapper->getSearchLineEdit();
769 #else
770     toolbarSearch = new SearchLineEdit(this);
771 #endif
772     toolbarSearch->setMinimumWidth(toolbarSearch->fontInfo().pixelSize()*15);
773     toolbarSearch->setSuggester(new YTSuggester(this));
774     connect(toolbarSearch, SIGNAL(search(const QString&)), this, SLOT(startToolbarSearch(const QString&)));
775     connect(toolbarSearch, SIGNAL(suggestionAccepted(const QString&)), SLOT(startToolbarSearch(const QString&)));
776     toolbarSearch->setStatusTip(searchFocusAct->statusTip());
777 #ifdef APP_MAC
778     mainToolBar->addWidget(searchWrapper);
779 #else
780     mainToolBar->addWidget(toolbarSearch);
781     mainToolBar->addWidget(new Spacer());
782 #endif
783
784     addToolBar(mainToolBar);
785 }
786
787 void MainWindow::createStatusBar() {
788     statusToolBar = new QToolBar(this);
789     statusToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
790     statusToolBar->setIconSize(QSize(16, 16));
791     statusToolBar->addAction(The::globalActions()->value("downloads"));
792
793     regionButton = new QToolButton(this);
794     regionButton->setStatusTip(tr("Choose your content location"));
795     regionButton->setIconSize(QSize(16, 16));
796     regionButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
797     regionAction = statusToolBar->addWidget(regionButton);
798     regionAction->setVisible(false);
799
800     QAction *localAction = The::globalActions()->value("local-region");
801     if (!localAction->text().isEmpty()) {
802         regionButton->setPopupMode(QToolButton::InstantPopup);
803         QMenu *regionMenu = new QMenu(this);
804         regionMenu->addAction(The::globalActions()->value("worldwide-region"));
805         regionMenu->addAction(localAction);
806         regionMenu->addSeparator();
807         QAction *moreRegionsAction = The::globalActions()->value("more-region");
808         regionMenu->addAction(moreRegionsAction);
809         connect(moreRegionsAction, SIGNAL(triggered()), SLOT(showRegionsView()));
810         regionButton->setMenu(regionMenu);
811     } else {
812         connect(regionButton, SIGNAL(clicked()), SLOT(showRegionsView()));
813     }
814
815     /* Stupid code that generates the QRC items
816     foreach(YTRegion r, YTRegions::list())
817         qDebug() << QString("<file>flags/%1.png</file>").arg(r.id.toLower());
818     */
819
820     statusToolBar->addAction(The::globalActions()->value("definition"));
821
822     statusBar()->addPermanentWidget(statusToolBar);
823     statusBar()->show();
824 }
825
826 void MainWindow::showStopAfterThisInStatusBar(bool show) {
827     QAction* action = The::globalActions()->value("stopafterthis");
828     showActionInStatusBar(action, show);
829 }
830
831 void MainWindow::showActionInStatusBar(QAction* action, bool show) {
832 #ifdef APP_EXTRA
833     Extra::fadeInWidget(statusBar(), statusBar());
834 #endif
835     if (show) {
836         statusToolBar->insertAction(statusToolBar->actions().first(), action);
837     } else {
838         statusToolBar->removeAction(action);
839     }
840 }
841
842 void MainWindow::readSettings() {
843     QSettings settings;
844     if (settings.contains("geometry")) {
845         restoreGeometry(settings.value("geometry").toByteArray());
846 #ifdef APP_MAC
847         MacSupport::fixGeometry(this);
848 #endif
849     } else {
850         setGeometry(100, 100, 1000, 500);
851     }
852     setDefinitionMode(settings.value("definition", VideoDefinition::getDefinitionNames().first()).toString());
853     The::globalActions()->value("manualplay")->setChecked(settings.value("manualplay", false).toBool());
854 }
855
856 void MainWindow::writeSettings() {
857     QSettings settings;
858
859     settings.setValue("geometry", saveGeometry());
860     mediaView->saveSplitterState();
861
862 #ifdef APP_PHONON
863     if (audioOutput->volume() > 0.1)
864         settings.setValue("volume", audioOutput->volume());
865     // settings.setValue("volumeMute", audioOutput->isMuted());
866 #endif
867
868     settings.setValue("manualplay", The::globalActions()->value("manualplay")->isChecked());
869 }
870
871 void MainWindow::goBack() {
872     if ( history->size() > 1 ) {
873         history->pop();
874         QWidget *widget = history->pop();
875         showWidget(widget);
876     }
877 }
878
879 void MainWindow::showWidget(QWidget* widget, bool transition) {
880
881     if (compactViewAct->isChecked())
882         compactViewAct->toggle();
883
884     setUpdatesEnabled(false);
885
886     // call hide method on the current view
887     View* oldView = dynamic_cast<View *> (views->currentWidget());
888     if (oldView) {
889         oldView->disappear();
890         views->currentWidget()->setEnabled(false);
891     } else qDebug() << "Cannot cast view";
892
893     // call show method on the new view
894     View* newView = dynamic_cast<View *> (widget);
895     if (newView) {
896         widget->setEnabled(true);
897         QHash<QString,QVariant> metadata = newView->metadata();
898         QString title = metadata.value("title").toString();
899         if (title.isEmpty()) title = Constants::NAME;
900         else title += QLatin1String(" - ") + Constants::NAME;
901         setWindowTitle(title);
902         QString desc = metadata.value("description").toString();
903         if (!desc.isEmpty()) showMessage(desc);
904         newView->appear();
905
906         // dynamic view actions
907         foreach (QAction* action, viewActions)
908             showActionInStatusBar(action, false);
909         viewActions = newView->getViewActions();
910         foreach (QAction* action, viewActions)
911             showActionInStatusBar(action, true);
912
913     }
914
915     const bool isMediaView = widget == mediaView;
916
917     stopAct->setEnabled(isMediaView);
918     compactViewAct->setEnabled(isMediaView);
919     toolbarSearch->setEnabled(widget == homeView || isMediaView || widget == downloadView);
920
921     aboutAct->setEnabled(widget != aboutView);
922     The::globalActions()->value("downloads")->setChecked(widget == downloadView);
923
924     QWidget *oldWidget = views->currentWidget();
925     if (oldWidget)
926         oldWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
927
928     views->setCurrentWidget(widget);
929     widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
930
931     setUpdatesEnabled(true);
932
933 #ifdef APP_EXTRA
934     if (transition && (oldWidget != mediaView ||
935                        !mediaView->getVideoArea()->isVideoShown()))
936         Extra::fadeInWidget(oldWidget, widget);
937 #endif
938
939     history->push(widget);
940 }
941
942 void MainWindow::about() {
943     if (!aboutView) {
944         aboutView = new AboutView(this);
945         views->addWidget(aboutView);
946     }
947     showWidget(aboutView);
948 }
949
950 void MainWindow::visitSite() {
951     QUrl url(Constants::WEBSITE);
952     statusBar()->showMessage(QString(tr("Opening %1").arg(url.toString())));
953     QDesktopServices::openUrl(url);
954 }
955
956 void MainWindow::donate() {
957     QUrl url(QString(Constants::WEBSITE) + "#donate");
958     statusBar()->showMessage(QString(tr("Opening %1").arg(url.toString())));
959     QDesktopServices::openUrl(url);
960 }
961
962 void MainWindow::reportIssue() {
963     QUrl url("http://flavio.tordini.org/forums/forum/minitube-forums/minitube-troubleshooting");
964     QDesktopServices::openUrl(url);
965 }
966
967 void MainWindow::quit() {
968 #ifdef APP_MAC
969     if (!confirmQuit()) {
970         return;
971     }
972 #endif
973     // do not save geometry when in full screen or in compact mode
974     if (!m_fullscreen && !compactViewAct->isChecked()) {
975         writeSettings();
976     }
977     mediaView->stop();
978     Temporary::deleteAll();
979     ChannelAggregator::instance()->stop();
980     ChannelAggregator::instance()->cleanup();
981     Database::shutdown();
982     qApp->quit();
983 }
984
985 void MainWindow::closeEvent(QCloseEvent *event) {
986 #ifdef APP_MAC
987     mac::closeWindow(winId());
988     event->ignore();
989 #else
990     if (!confirmQuit()) {
991         event->ignore();
992         return;
993     }
994     QWidget::closeEvent(event);
995     quit();
996 #endif
997 }
998
999 bool MainWindow::confirmQuit() {
1000     if (DownloadManager::instance()->activeItems() > 0) {
1001         QMessageBox msgBox(this);
1002         msgBox.setIconPixmap(QPixmap(":/images/app.png").scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
1003         msgBox.setText(tr("Do you want to exit %1 with a download in progress?").arg(Constants::NAME));
1004         msgBox.setInformativeText(tr("If you close %1 now, this download will be cancelled.").arg(Constants::NAME));
1005         msgBox.setModal(true);
1006         // make it a "sheet" on the Mac
1007         msgBox.setWindowModality(Qt::WindowModal);
1008
1009         msgBox.addButton(tr("Close and cancel download"), QMessageBox::RejectRole);
1010         QPushButton *waitButton = msgBox.addButton(tr("Wait for download to finish"), QMessageBox::ActionRole);
1011
1012         msgBox.exec();
1013
1014         if (msgBox.clickedButton() == waitButton) {
1015             return false;
1016         }
1017     }
1018     return true;
1019 }
1020
1021 void MainWindow::showHome(bool transition) {
1022     showWidget(homeView, transition);
1023     currentTime->clear();
1024     totalTime->clear();
1025 }
1026
1027 void MainWindow::showMedia(SearchParams *searchParams) {
1028     showWidget(mediaView);
1029     mediaView->search(searchParams);
1030 }
1031
1032 void MainWindow::showMedia(VideoSource *videoSource) {
1033     showWidget(mediaView);
1034     mediaView->setVideoSource(videoSource);
1035 }
1036
1037 #ifdef APP_PHONON
1038 void MainWindow::stateChanged(Phonon::State newState, Phonon::State /* oldState */) {
1039
1040     // qDebug() << "Phonon state: " << newState;
1041
1042     switch (newState) {
1043
1044     case Phonon::ErrorState:
1045         if (mediaObject->errorType() == Phonon::FatalError) {
1046             // Do not display because we try to play incomplete video files and sometimes trigger this
1047             // We retry automatically (in MediaView) so no need to show it
1048             // statusBar()->showMessage(tr("Fatal error: %1").arg(mediaObject->errorString()));
1049         } else {
1050             statusBar()->showMessage(tr("Error: %1").arg(mediaObject->errorString()));
1051         }
1052         break;
1053
1054     case Phonon::PlayingState:
1055         pauseAct->setEnabled(true);
1056         pauseAct->setIcon(Utils::icon("media-playback-pause"));
1057         pauseAct->setText(tr("&Pause"));
1058         pauseAct->setStatusTip(tr("Pause playback") + " (" +  pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
1059         // stopAct->setEnabled(true);
1060         break;
1061
1062     case Phonon::StoppedState:
1063         pauseAct->setEnabled(false);
1064         // stopAct->setEnabled(false);
1065         break;
1066
1067     case Phonon::PausedState:
1068         pauseAct->setEnabled(true);
1069         pauseAct->setIcon(Utils::icon("media-playback-start"));
1070         pauseAct->setText(tr("&Play"));
1071         pauseAct->setStatusTip(tr("Resume playback") + " (" +  pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
1072         // stopAct->setEnabled(true);
1073         break;
1074
1075     case Phonon::BufferingState:
1076     case Phonon::LoadingState:
1077         pauseAct->setEnabled(false);
1078         currentTime->clear();
1079         totalTime->clear();
1080         // stopAct->setEnabled(true);
1081         break;
1082
1083     default:
1084         ;
1085     }
1086 }
1087 #endif
1088
1089 void MainWindow::stop() {
1090     mediaView->stop();
1091     showHome();
1092 }
1093
1094 void MainWindow::resizeEvent(QResizeEvent*) {
1095 #ifdef Q_OS_MAC
1096     if (mac::CanGoFullScreen(winId())) {
1097         bool isFullscreen = mac::IsFullScreen(winId());
1098         if (isFullscreen != m_fullscreen) {
1099             if (compactViewAct->isChecked()) {
1100                 compactViewAct->setChecked(false);
1101                 compactView(false);
1102             }
1103             m_fullscreen = isFullscreen;
1104             updateUIForFullscreen();
1105         }
1106     }
1107 #endif
1108 }
1109
1110 void MainWindow::fullscreen() {
1111
1112     if (compactViewAct->isChecked())
1113         compactViewAct->toggle();
1114
1115 #ifdef Q_OS_MAC
1116     WId handle = winId();
1117     if (mac::CanGoFullScreen(handle)) {
1118         mainToolBar->setVisible(true);
1119         mac::ToggleFullScreen(handle);
1120         return;
1121     }
1122 #endif
1123
1124     m_fullscreen = !m_fullscreen;
1125
1126     if (m_fullscreen) {
1127         // Enter full screen
1128
1129         m_maximized = isMaximized();
1130
1131         // save geometry now, if the user quits when in full screen
1132         // geometry won't be saved
1133         writeSettings();
1134
1135 #ifdef Q_OS_MAC
1136         MacSupport::enterFullScreen(this, views);
1137 #else
1138         mainToolBar->hide();
1139         showFullScreen();
1140 #endif
1141
1142     } else {
1143         // Exit full screen
1144
1145 #ifdef Q_OS_MAC
1146         MacSupport::exitFullScreen(this, views);
1147 #else
1148         mainToolBar->show();
1149         if (m_maximized) showMaximized();
1150         else showNormal();
1151 #endif
1152
1153         // Make sure the window has focus
1154         activateWindow();
1155
1156     }
1157
1158     updateUIForFullscreen();
1159
1160 }
1161
1162 void MainWindow::updateUIForFullscreen() {
1163     static QList<QKeySequence> fsShortcuts;
1164     static QString fsText;
1165
1166     if (m_fullscreen) {
1167         fsShortcuts = fullscreenAct->shortcuts();
1168         fsText = fullscreenAct->text();
1169         fullscreenAct->setShortcuts(QList<QKeySequence>(fsShortcuts)
1170                                     << QKeySequence(Qt::Key_Escape));
1171         fullscreenAct->setText(tr("Leave &Full Screen"));
1172         fullscreenAct->setIcon(Utils::icon("view-restore"));
1173     } else {
1174         fullscreenAct->setShortcuts(fsShortcuts);
1175         fullscreenAct->setText(fsText);
1176         fullscreenAct->setIcon(Utils::icon("view-fullscreen"));
1177     }
1178
1179     // No compact view action when in full screen
1180     compactViewAct->setVisible(!m_fullscreen);
1181     compactViewAct->setChecked(false);
1182
1183     // Hide anything but the video
1184     mediaView->setPlaylistVisible(!m_fullscreen);
1185     statusBar()->setVisible(!m_fullscreen);
1186
1187 #ifndef APP_MAC
1188     menuBar()->setVisible(!m_fullscreen);
1189 #endif
1190
1191     if (m_fullscreen) {
1192         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_MediaStop));
1193     } else {
1194         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Escape) << QKeySequence(Qt::Key_MediaStop));
1195     }
1196
1197 #ifdef Q_OS_MAC
1198     MacSupport::fullScreenActions(The::globalActions()->values(), m_fullscreen);
1199 #endif
1200
1201     if (views->currentWidget() == mediaView)
1202         mediaView->setFocus();
1203
1204     if (m_fullscreen) {
1205         hideMouse();
1206     } else {
1207         mouseTimer->stop();
1208         unsetCursor();
1209     }
1210 }
1211
1212 bool MainWindow::isReallyFullScreen() {
1213 #ifdef Q_OS_MAC
1214     WId handle = winId();
1215     if (mac::CanGoFullScreen(handle)) return mac::IsFullScreen(handle);
1216     else return isFullScreen();
1217 #else
1218     return isFullScreen();
1219 #endif
1220 }
1221
1222 void MainWindow::compactView(bool enable) {
1223     m_compact = enable;
1224
1225     static QList<QKeySequence> compactShortcuts;
1226     static QList<QKeySequence> stopShortcuts;
1227
1228     const static QString key = "compactGeometry";
1229     QSettings settings;
1230
1231 #ifndef APP_MAC
1232     menuBar()->setVisible(!enable);
1233 #endif
1234
1235     if (enable) {
1236         setMinimumSize(320, 180);
1237 #ifdef Q_OS_MAC
1238         mac::RemoveFullScreenWindow(winId());
1239 #endif
1240         writeSettings();
1241
1242         if (settings.contains(key))
1243             restoreGeometry(settings.value(key).toByteArray());
1244         else
1245             resize(320, 180);
1246
1247         mainToolBar->setVisible(!enable);
1248         mediaView->setPlaylistVisible(!enable);
1249         statusBar()->setVisible(!enable);
1250
1251         compactShortcuts = compactViewAct->shortcuts();
1252         stopShortcuts = stopAct->shortcuts();
1253
1254         QList<QKeySequence> newStopShortcuts(stopShortcuts);
1255         newStopShortcuts.removeAll(QKeySequence(Qt::Key_Escape));
1256         stopAct->setShortcuts(newStopShortcuts);
1257         compactViewAct->setShortcuts(QList<QKeySequence>(compactShortcuts) << QKeySequence(Qt::Key_Escape));
1258
1259         // ensure focus does not end up to the search box
1260         // as it would steal the Space shortcut
1261         mediaView->setFocus();
1262
1263     } else {
1264         // unset minimum size
1265         setMinimumSize(0, 0);
1266 #ifdef Q_OS_MAC
1267         mac::SetupFullScreenWindow(winId());
1268 #endif
1269         settings.setValue(key, saveGeometry());
1270         mainToolBar->setVisible(!enable);
1271         mediaView->setPlaylistVisible(!enable);
1272         statusBar()->setVisible(!enable);
1273         readSettings();
1274
1275         compactViewAct->setShortcuts(compactShortcuts);
1276         stopAct->setShortcuts(stopShortcuts);
1277     }
1278
1279     // auto float on top
1280     floatOnTop(enable);
1281
1282 #ifdef Q_OS_MAC
1283     mac::compactMode(winId(), enable);
1284 #endif
1285 }
1286
1287 void MainWindow::searchFocus() {
1288     toolbarSearch->selectAll();
1289     toolbarSearch->setFocus();
1290 }
1291
1292 #ifdef APP_PHONON
1293 void MainWindow::initPhonon() {
1294     // Phonon initialization
1295     if (mediaObject) delete mediaObject;
1296     if (audioOutput) delete audioOutput;
1297     mediaObject = new Phonon::MediaObject(this);
1298     mediaObject->setTickInterval(100);
1299     connect(mediaObject, SIGNAL(stateChanged(Phonon::State, Phonon::State)),
1300             this, SLOT(stateChanged(Phonon::State, Phonon::State)));
1301     connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(tick(qint64)));
1302     connect(mediaObject, SIGNAL(totalTimeChanged(qint64)), this, SLOT(totalTimeChanged(qint64)));
1303 #ifdef APP_PHONON_SEEK
1304     seekSlider->setMediaObject(mediaObject);
1305 #endif
1306     audioOutput = new Phonon::AudioOutput(Phonon::VideoCategory, this);
1307     connect(audioOutput, SIGNAL(volumeChanged(qreal)), this, SLOT(volumeChanged(qreal)));
1308     connect(audioOutput, SIGNAL(mutedChanged(bool)), this, SLOT(volumeMutedChanged(bool)));
1309     volumeSlider->setAudioOutput(audioOutput);
1310     Phonon::createPath(mediaObject, audioOutput);
1311     QSettings settings;
1312     audioOutput->setVolume(settings.value("volume", 1).toDouble());
1313     // audioOutput->setMuted(settings.value("volumeMute").toBool());
1314 }
1315 #endif
1316
1317 void MainWindow::tick(qint64 time) {
1318     if (time <= 0) {
1319         // the "if" is important because tick is continually called
1320         // and we don't want to paint the toolbar every 100ms
1321         if (!currentTime->text().isEmpty()) currentTime->clear();
1322         return;
1323     }
1324
1325     currentTime->setText(formatTime(time));
1326
1327     // remaining time
1328 #ifdef APP_PHONON
1329     const qint64 remainingTime = mediaObject->remainingTime();
1330     currentTime->setStatusTip(tr("Remaining time: %1").arg(formatTime(remainingTime)));
1331
1332     slider->blockSignals(true);
1333     const qint64 totalTime = mediaObject->totalTime();
1334     // qWarning() << totalTime << time << time * 100 / totalTime;
1335     if (totalTime > 0 && time > 0 && !slider->isSliderDown() && mediaObject->state() == Phonon::PlayingState)
1336         slider->setValue(time * slider->maximum() / totalTime);
1337     slider->blockSignals(false);
1338 #endif
1339 }
1340
1341 void MainWindow::totalTimeChanged(qint64 time) {
1342     if (time <= 0) {
1343         totalTime->clear();
1344         return;
1345     }
1346     totalTime->setText(formatTime(time));
1347
1348     /*
1349     slider->blockSignals(true);
1350     slider->setMaximum(time/1000);
1351     slider->blockSignals(false);
1352     */
1353
1354 }
1355
1356 QString MainWindow::formatTime(qint64 time) {
1357     QTime displayTime;
1358     displayTime = displayTime.addMSecs(time);
1359     QString timeString;
1360     // 60 * 60 * 1000 = 3600000
1361     if (time > 3600000)
1362         timeString = displayTime.toString("h:mm:ss");
1363     else
1364         timeString = displayTime.toString("m:ss");
1365     return timeString;
1366 }
1367
1368 void MainWindow::volumeUp() {
1369 #ifdef APP_PHONON
1370     qreal newVolume = volumeSlider->audioOutput()->volume() + .1;
1371     if (newVolume > volumeSlider->maximumVolume())
1372         newVolume = volumeSlider->maximumVolume();
1373     volumeSlider->audioOutput()->setVolume(newVolume);
1374 #endif
1375 }
1376
1377 void MainWindow::volumeDown() {
1378 #ifdef APP_PHONON
1379     qreal newVolume = volumeSlider->audioOutput()->volume() - .1;
1380     if (newVolume < 0)
1381         newVolume = 0;
1382     volumeSlider->audioOutput()->setVolume(newVolume);
1383 #endif
1384 }
1385
1386 void MainWindow::volumeMute() {
1387 #ifdef APP_PHONON
1388     volumeSlider->audioOutput()->setMuted(!volumeSlider->audioOutput()->isMuted());
1389 #endif
1390 }
1391
1392 void MainWindow::volumeChanged(qreal newVolume) {
1393 #ifdef APP_PHONON
1394     // automatically unmute when volume changes
1395     if (volumeSlider->audioOutput()->isMuted())
1396         volumeSlider->audioOutput()->setMuted(false);
1397 #endif
1398     statusBar()->showMessage(tr("Volume at %1%").arg((int)(newVolume*100)));
1399 }
1400
1401 void MainWindow::volumeMutedChanged(bool muted) {
1402     if (muted) {
1403         volumeMuteAct->setIcon(Utils::icon("audio-volume-muted"));
1404         statusBar()->showMessage(tr("Volume is muted"));
1405     } else {
1406         volumeMuteAct->setIcon(Utils::icon("audio-volume-high"));
1407         statusBar()->showMessage(tr("Volume is unmuted"));
1408     }
1409 }
1410
1411 void MainWindow::setDefinitionMode(QString definitionName) {
1412     QAction *definitionAct = The::globalActions()->value("definition");
1413     definitionAct->setText(definitionName);
1414     definitionAct->setStatusTip(tr("Maximum video definition set to %1").arg(definitionAct->text())
1415                                 + " (" +  definitionAct->shortcut().toString(QKeySequence::NativeText) + ")");
1416     statusBar()->showMessage(definitionAct->statusTip());
1417     QSettings settings;
1418     settings.setValue("definition", definitionName);
1419 }
1420
1421 void MainWindow::toggleDefinitionMode() {
1422     QSettings settings;
1423     QString currentDefinition = settings.value("definition").toString();
1424     QStringList definitionNames = VideoDefinition::getDefinitionNames();
1425     int currentIndex = definitionNames.indexOf(currentDefinition);
1426     int nextIndex = 0;
1427     if (currentIndex != definitionNames.size() - 1) {
1428         nextIndex = currentIndex + 1;
1429     }
1430     QString nextDefinition = definitionNames.at(nextIndex);
1431     setDefinitionMode(nextDefinition);
1432 }
1433
1434 void MainWindow::showFullscreenToolbar(bool show) {
1435     if (!m_fullscreen) return;
1436     mainToolBar->setVisible(show);
1437 }
1438
1439 void MainWindow::showFullscreenPlaylist(bool show) {
1440     if (!m_fullscreen) return;
1441     mediaView->setPlaylistVisible(show);
1442 }
1443
1444 void MainWindow::clearRecentKeywords() {
1445     QSettings settings;
1446     settings.remove("recentKeywords");
1447     settings.remove("recentChannels");
1448     if (views->currentWidget() == homeView) {
1449         SearchView *searchView = homeView->getSearchView();
1450         searchView->updateRecentKeywords();
1451         searchView->updateRecentChannels();
1452     }
1453     QAbstractNetworkCache *cache = The::networkAccessManager()->cache();
1454     if (cache) cache->clear();
1455     showMessage(tr("Your privacy is now safe"));
1456 }
1457
1458 void MainWindow::setManualPlay(bool enabled) {
1459     QSettings settings;
1460     settings.setValue("manualplay", QVariant::fromValue(enabled));
1461     showActionInStatusBar(The::globalActions()->value("manualplay"), enabled);
1462 }
1463
1464 void MainWindow::updateDownloadMessage(QString message) {
1465     The::globalActions()->value("downloads")->setText(message);
1466 }
1467
1468 void MainWindow::downloadsFinished() {
1469     The::globalActions()->value("downloads")->setText(tr("&Downloads"));
1470     statusBar()->showMessage(tr("Downloads complete"));
1471 }
1472
1473 void MainWindow::toggleDownloads(bool show) {
1474
1475     if (show) {
1476         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_MediaStop));
1477         The::globalActions()->value("downloads")->setShortcuts(
1478                     QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_J)
1479                     << QKeySequence(Qt::Key_Escape));
1480     } else {
1481         The::globalActions()->value("downloads")->setShortcuts(
1482                     QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_J));
1483         stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_Escape) << QKeySequence(Qt::Key_MediaStop));
1484     }
1485
1486     if (!downloadView) {
1487         downloadView = new DownloadView(this);
1488         views->addWidget(downloadView);
1489     }
1490     if (show) showWidget(downloadView);
1491     else goBack();
1492 }
1493
1494 void MainWindow::startToolbarSearch(QString query) {
1495     query = query.trimmed();
1496
1497     // check for empty query
1498     if (query.length() == 0) {
1499         return;
1500     }
1501
1502     SearchParams *searchParams = new SearchParams();
1503     searchParams->setKeywords(query);
1504
1505     // go!
1506     showMedia(searchParams);
1507 }
1508
1509 void MainWindow::dragEnterEvent(QDragEnterEvent *event) {
1510     if (event->mimeData()->hasFormat("text/uri-list")) {
1511         QList<QUrl> urls = event->mimeData()->urls();
1512         if (urls.isEmpty())
1513             return;
1514         QUrl url = urls.first();
1515         QString videoId = YTSearch::videoIdFromUrl(url.toString());
1516         if (!videoId.isNull())
1517             event->acceptProposedAction();
1518     }
1519 }
1520
1521 void MainWindow::dropEvent(QDropEvent *event) {
1522     if (!toolbarSearch->isEnabled()) return;
1523
1524     QList<QUrl> urls = event->mimeData()->urls();
1525     if (urls.isEmpty())
1526         return;
1527     QUrl url = urls.first();
1528     QString videoId = YTSearch::videoIdFromUrl(url.toString());
1529     if (!videoId.isNull()) {
1530         setWindowTitle(url.toString());
1531         SearchParams *searchParams = new SearchParams();
1532         searchParams->setKeywords(videoId);
1533         showMedia(searchParams);
1534     }
1535 }
1536
1537 void MainWindow::checkForUpdate() {
1538     static const QString updateCheckKey = "updateCheck";
1539
1540     // check every 24h
1541     QSettings settings;
1542     uint unixTime = QDateTime::currentDateTime().toTime_t();
1543     int lastCheck = settings.value(updateCheckKey).toInt();
1544     int secondsSinceLastCheck = unixTime - lastCheck;
1545     // qDebug() << "secondsSinceLastCheck" << unixTime << lastCheck << secondsSinceLastCheck;
1546     if (secondsSinceLastCheck < 86400) return;
1547
1548     // check it out
1549     if (updateChecker) delete updateChecker;
1550     updateChecker = new UpdateChecker();
1551     connect(updateChecker, SIGNAL(newVersion(QString)),
1552             this, SLOT(gotNewVersion(QString)));
1553     updateChecker->checkForUpdate();
1554     settings.setValue(updateCheckKey, unixTime);
1555 }
1556
1557 void MainWindow::gotNewVersion(QString version) {
1558     if (updateChecker) {
1559         delete updateChecker;
1560         updateChecker = 0;
1561     }
1562
1563     QSettings settings;
1564     QString checkedVersion = settings.value("checkedVersion").toString();
1565     if (checkedVersion == version) return;
1566
1567 #ifdef APP_SIMPLEUPDATE
1568     simpleUpdateDialog(version);
1569 #elif defined(APP_ACTIVATION) && !defined(APP_MAC)
1570     UpdateDialog *dialog = new UpdateDialog(version, this);
1571     dialog->show();
1572 #endif
1573 }
1574
1575 void MainWindow::simpleUpdateDialog(QString version) {
1576     QMessageBox msgBox(this);
1577     msgBox.setIconPixmap(
1578                 QPixmap(":/images/app.png")
1579                 .scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
1580     msgBox.setText(tr("%1 version %2 is now available.").arg(Constants::NAME, version));
1581     msgBox.setModal(true);
1582     msgBox.setWindowModality(Qt::WindowModal);
1583     msgBox.addButton(QMessageBox::Close);
1584     QPushButton* laterButton = msgBox.addButton(tr("Remind me later"), QMessageBox::RejectRole);
1585     QPushButton* updateButton = msgBox.addButton(tr("Update"), QMessageBox::AcceptRole);
1586     msgBox.exec();
1587     if (msgBox.clickedButton() != laterButton) {
1588         QSettings settings;
1589         settings.setValue("checkedVersion", version);
1590     }
1591     if (msgBox.clickedButton() == updateButton) visitSite();
1592 }
1593
1594 void MainWindow::floatOnTop(bool onTop) {
1595     showActionInStatusBar(The::globalActions()->value("ontop"), onTop);
1596 #ifdef APP_MAC
1597     mac::floatOnTop(winId(), onTop);
1598     return;
1599 #endif
1600     if (onTop) {
1601         setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
1602         show();
1603     } else {
1604         setWindowFlags(windowFlags() ^ Qt::WindowStaysOnTopHint);
1605         show();
1606     }
1607 }
1608
1609 void MainWindow::restore() {
1610 #ifdef APP_MAC
1611     mac::uncloseWindow(window()->winId());
1612 #endif
1613 }
1614
1615 void MainWindow::messageReceived(const QString &message) {
1616     if (message == QLatin1String("--toggle-playing")) {
1617         if (pauseAct->isEnabled()) pauseAct->trigger();
1618     } else if (message == QLatin1String("--next")) {
1619         if (skipAct->isEnabled()) skipAct->trigger();
1620     } else if (message == QLatin1String("--previous")) {
1621         if (skipBackwardAct->isEnabled()) skipBackwardAct->trigger();
1622     } else if (message == QLatin1String("--stop-after-this")) {
1623         The::globalActions()->value("stopafterthis")->toggle();
1624     }  else if (message.startsWith("--")) {
1625         MainWindow::printHelp();
1626     } else if (!message.isEmpty()) {
1627         SearchParams *searchParams = new SearchParams();
1628         searchParams->setKeywords(message);
1629         showMedia(searchParams);
1630     }
1631 }
1632
1633 void MainWindow::hideMouse() {
1634     setCursor(Qt::BlankCursor);
1635     mediaView->setPlaylistVisible(false);
1636 #ifndef APP_MAC
1637     mainToolBar->setVisible(false);
1638 #endif
1639 }
1640
1641 #ifdef APP_MAC_STORE
1642 void MainWindow::rateOnAppStore() {
1643     QDesktopServices::openUrl(QUrl("macappstore://userpub.itunes.apple.com"
1644                                    "/WebObjects/MZUserPublishing.woa/wa/addUserReview"
1645                                    "?id=422006190&type=Purple+Software"));
1646 }
1647 #endif
1648
1649 void MainWindow::printHelp() {
1650     QString msg = QString("%1 %2\n\n").arg(Constants::NAME, Constants::VERSION);
1651     msg += "Usage: minitube [options]\n";
1652     msg += "Options:\n";
1653     msg += "  --toggle-playing\t";
1654     msg += "Start or pause playback.\n";
1655     msg += "  --next\t\t";
1656     msg += "Skip to the next video.\n";
1657     msg += "  --previous\t\t";
1658     msg += "Go back to the previous video.\n";
1659     msg += "  --stop-after-this\t";
1660     msg += "Stop playback at the end of the video.\n";
1661     std::cout << msg.toLocal8Bit().data();
1662 }
1663
1664 void MainWindow::showMessage(QString message) {
1665     statusBar()->showMessage(message, 60000);
1666 }
1667
1668 #ifdef APP_ACTIVATION
1669 void MainWindow::showActivationView(bool transition) {
1670     QWidget *activationView = ActivationView::instance();
1671     if (views->currentWidget() == activationView) {
1672         buy();
1673         return;
1674     }
1675     views->addWidget(activationView);
1676     showWidget(activationView, transition);
1677 }
1678
1679 void MainWindow::showActivationDialog() {
1680     QTimer::singleShot(0, new ActivationDialog(this), SLOT(show()));
1681 }
1682
1683 void MainWindow::buy() {
1684     Extra::buy();
1685 }
1686
1687 void MainWindow::hideBuyAction() {
1688     QAction *action = The::globalActions()->value("buy");
1689     action->setVisible(false);
1690     action->setEnabled(false);
1691 }
1692 #endif
1693
1694 void MainWindow::showRegionsView() {
1695     if (!regionsView) {
1696         regionsView = new RegionsView(this);
1697         connect(regionsView, SIGNAL(regionChanged()),
1698                 homeView->getStandardFeedsView(), SLOT(load()));
1699         views->addWidget(regionsView);
1700     }
1701     showWidget(regionsView);
1702 }