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