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