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