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