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