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