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