3 This file is part of Minitube.
4 Copyright 2009, Flavio Tordini <flavio.tordini@gmail.com>
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.
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.
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/>.
21 #include "mainwindow.h"
23 #include "aboutview.h"
24 #include "downloadview.h"
26 #include "mediaview.h"
27 #include "regionsview.h"
28 #include "searchview.h"
29 #include "standardfeedsview.h"
31 #include "constants.h"
32 #include "fontutils.h"
33 #include "globalshortcuts.h"
34 #include "iconutils.h"
35 #include "searchparams.h"
37 #include "videodefinition.h"
38 #include "videosource.h"
41 #include "gnomeglobalshortcutbackend.h"
44 #include "mac_startup.h"
45 #include "macfullscreen.h"
46 #include "macsupport.h"
49 #include "downloadmanager.h"
50 #include "temporary.h"
51 #include "updatechecker.h"
52 #include "ytsuggester.h"
53 #if defined(APP_MAC_SEARCHFIELD) && !defined(APP_MAC_QMACTOOLBAR)
54 #include "searchlineedit_mac.h"
56 #include "searchlineedit.h"
58 #ifdef APP_MAC_QMACTOOLBAR
59 #include "mactoolbar.h"
63 #include "compositefader.h"
65 #include "updatedialog.h"
68 #include "activation.h"
69 #include "activationview.h"
71 #include "channelaggregator.h"
73 #include "httputils.h"
74 #include "jsfunctions.h"
75 #include "seekslider.h"
76 #include "sidebarwidget.h"
77 #include "toolbarmenu.h"
78 #include "videoarea.h"
80 #include "ytregions.h"
83 #include "mediaqtav.h"
90 MainWindow *mainWindowInstance;
93 MainWindow *MainWindow::instance() {
94 return mainWindowInstance;
97 MainWindow::MainWindow()
98 : aboutView(nullptr), downloadView(nullptr), regionsView(nullptr), mainToolBar(nullptr),
99 fullScreenActive(false), compactModeActive(false), initialized(false), toolbarMenu(nullptr),
101 mainWindowInstance = this;
104 views = new QStackedWidget();
105 setCentralWidget(views);
108 Extra::windowSetup(this);
111 messageLabel = new QLabel(this);
112 messageLabel->setWordWrap(false);
113 messageLabel->setStyleSheet("padding:5px;border:0;background:palette(window)");
114 messageLabel->setAlignment(Qt::AlignCenter);
115 messageLabel->hide();
116 adjustMessageLabelPosition();
117 messageTimer = new QTimer(this);
118 messageTimer->setInterval(5000);
119 messageTimer->setSingleShot(true);
120 connect(messageTimer, SIGNAL(timeout()), SLOT(hideMessage()));
123 homeView = new HomeView(this);
124 views->addWidget(homeView);
126 // TODO make this lazy
127 mediaView = MediaView::instance();
128 mediaView->setEnabled(false);
129 views->addWidget(mediaView);
138 // remove that useless menu/toolbar context menu
139 this->setContextMenuPolicy(Qt::NoContextMenu);
141 // event filter to block ugly toolbar tooltips
142 qApp->installEventFilter(this);
144 setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
146 // restore window position
149 // fix stacked widget minimum size
150 for (int i = 0; i < views->count(); i++)
151 views->widget(i)->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
154 #ifdef APP_ACTIVATION
155 Activation::instance().initialCheck();
160 QTimer::singleShot(1000, this, &MainWindow::lazyInit);
163 void MainWindow::lazyInit() {
164 mediaView->initialize();
166 qApp->processEvents();
169 if (qApp->arguments().size() > 1) {
170 QString query = qApp->arguments().at(1);
171 if (query.startsWith(QLatin1String("--"))) {
172 messageReceived(query);
175 SearchParams *searchParams = new SearchParams();
176 searchParams->setKeywords(query);
177 showMedia(searchParams);
182 GlobalShortcuts &shortcuts = GlobalShortcuts::instance();
184 if (GnomeGlobalShortcutBackend::IsGsdAvailable())
185 shortcuts.setBackend(new GnomeGlobalShortcutBackend(&shortcuts));
190 connect(&shortcuts, SIGNAL(PlayPause()), pauseAct, SLOT(trigger()));
191 connect(&shortcuts, SIGNAL(Stop()), this, SLOT(stop()));
192 connect(&shortcuts, SIGNAL(Next()), skipAct, SLOT(trigger()));
193 connect(&shortcuts, SIGNAL(Previous()), skipBackwardAct, SLOT(trigger()));
194 // connect(&shortcuts, SIGNAL(StopAfter()), getAction("stopafterthis"), SLOT(toggle()));
196 connect(DownloadManager::instance(), SIGNAL(statusMessageChanged(QString)),
197 SLOT(updateDownloadMessage(QString)));
198 connect(DownloadManager::instance(), SIGNAL(finished()), SLOT(downloadsFinished()));
200 setAcceptDrops(true);
202 fullscreenTimer = new QTimer(this);
203 fullscreenTimer->setInterval(3000);
204 fullscreenTimer->setSingleShot(true);
205 connect(fullscreenTimer, SIGNAL(timeout()), SLOT(hideFullscreenUI()));
207 JsFunctions::instance();
209 // Hack to give focus to searchlineedit
210 View *view = qobject_cast<View *>(views->currentWidget());
211 if (view == homeView) {
212 QMetaObject::invokeMethod(views->currentWidget(), "appear");
213 const QString &desc = view->getDescription();
214 if (!desc.isEmpty()) showMessage(desc);
217 ChannelAggregator::instance()->start();
224 void MainWindow::changeEvent(QEvent *e) {
226 if (e->type() == QEvent::WindowStateChange) {
227 getAction("minimize")->setEnabled(!isMinimized());
230 if (messageLabel->isVisible()) {
231 if (e->type() == QEvent::ActivationChange || e->type() == QEvent::WindowStateChange ||
232 e->type() == QEvent::WindowDeactivate || e->type() == QEvent::ApplicationStateChange) {
236 QMainWindow::changeEvent(e);
239 bool MainWindow::eventFilter(QObject *obj, QEvent *e) {
240 const QEvent::Type t = e->type();
243 static bool altPressed = false;
244 if (t == QEvent::KeyRelease && altPressed) {
246 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
247 if (ke->key() == Qt::Key_Alt) {
248 toggleMenuVisibility();
251 } else if (t == QEvent::KeyPress) {
252 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
253 altPressed = ke->key() == Qt::Key_Alt;
257 if (fullScreenActive && views->currentWidget() == mediaView && t == QEvent::MouseMove &&
258 obj->isWidgetType() && qobject_cast<QWidget *>(obj)->window() == this) {
259 QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(e);
261 bool toolBarVisible = mainToolBar && mainToolBar->isVisible();
262 bool sidebarVisible = mediaView->isSidebarVisible();
264 if (!sidebarVisible && !toolBarVisible) {
265 const int x = mouseEvent->pos().x();
266 if (x >= 0 && x < 5) {
268 SidebarWidget *sidebar = mediaView->getSidebar();
269 sidebar->resize(sidebar->width(), height());
271 mediaView->setSidebarVisibility(true);
272 sidebarVisible = true;
277 if (!toolBarVisible && !sidebarVisible) {
278 const int y = mouseEvent->pos().y();
279 if (y >= 0 && y < 5) {
280 mainToolBar->resize(width(), mainToolBar->sizeHint().height());
281 mainToolBar->setVisible(true);
286 // show the normal cursor
288 // then hide it again after a few seconds
289 fullscreenTimer->start();
292 if (t == QEvent::ToolTip) {
297 if (t == QEvent::Show && obj == toolbarMenu) {
299 int x = width() - toolbarMenu->sizeHint().width();
302 int x = toolbarMenuButton->x() + toolbarMenuButton->width() -
303 toolbarMenu->sizeHint().width();
304 int y = toolbarMenuButton->y() + toolbarMenuButton->height();
307 toolbarMenu->move(mapToGlobal(p));
310 if (obj == this && t == QEvent::StyleChange) {
311 qDebug() << "Style change detected";
312 qApp->paletteChanged(qApp->palette());
316 // standard event processing
317 return QMainWindow::eventFilter(obj, e);
320 void MainWindow::createActions() {
321 stopAct = new QAction(tr("&Stop"), this);
322 IconUtils::setIcon(stopAct, "media-playback-stop");
323 stopAct->setStatusTip(tr("Stop playback and go back to the search view"));
324 stopAct->setShortcuts(QList<QKeySequence>()
325 << QKeySequence(Qt::Key_Escape) << QKeySequence(Qt::Key_MediaStop));
326 stopAct->setEnabled(false);
327 actionMap.insert("stop", stopAct);
328 connect(stopAct, SIGNAL(triggered()), SLOT(stop()));
330 skipBackwardAct = new QAction(tr("P&revious"), this);
331 skipBackwardAct->setStatusTip(tr("Go back to the previous track"));
332 skipBackwardAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Left));
333 skipBackwardAct->setEnabled(false);
334 actionMap.insert("previous", skipBackwardAct);
335 connect(skipBackwardAct, SIGNAL(triggered()), mediaView, SLOT(skipBackward()));
337 skipAct = new QAction(tr("S&kip"), this);
338 IconUtils::setIcon(skipAct, "media-skip-forward");
339 skipAct->setStatusTip(tr("Skip to the next video"));
340 skipAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_Right)
341 << QKeySequence(Qt::Key_MediaNext));
342 skipAct->setEnabled(false);
343 actionMap.insert("skip", skipAct);
344 connect(skipAct, SIGNAL(triggered()), mediaView, SLOT(skip()));
346 pauseAct = new QAction(tr("&Play"), this);
347 IconUtils::setIcon(pauseAct, "media-playback-start");
348 pauseAct->setStatusTip(tr("Resume playback"));
349 pauseAct->setShortcuts(QList<QKeySequence>()
350 << QKeySequence(Qt::Key_Space) << QKeySequence(Qt::Key_MediaPlay));
351 pauseAct->setEnabled(false);
352 actionMap.insert("pause", pauseAct);
353 connect(pauseAct, SIGNAL(triggered()), mediaView, SLOT(pause()));
355 fullscreenAct = new QAction(tr("&Full Screen"), this);
356 IconUtils::setIcon(fullscreenAct, "view-fullscreen");
357 fullscreenAct->setStatusTip(tr("Go full screen"));
358 QList<QKeySequence> fsShortcuts;
360 fsShortcuts << QKeySequence(Qt::CTRL + Qt::META + Qt::Key_F);
362 fsShortcuts << QKeySequence(Qt::Key_F11) << QKeySequence(Qt::ALT + Qt::Key_Return);
364 fullscreenAct->setShortcuts(fsShortcuts);
365 fullscreenAct->setShortcutContext(Qt::ApplicationShortcut);
366 fullscreenAct->setPriority(QAction::LowPriority);
367 actionMap.insert("fullscreen", fullscreenAct);
368 connect(fullscreenAct, SIGNAL(triggered()), SLOT(toggleFullscreen()));
370 compactViewAct = new QAction(tr("&Compact Mode"), this);
371 compactViewAct->setStatusTip(tr("Hide the playlist and the toolbar"));
372 compactViewAct->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C));
373 compactViewAct->setCheckable(true);
374 compactViewAct->setChecked(false);
375 compactViewAct->setEnabled(false);
376 actionMap.insert("compactView", compactViewAct);
377 connect(compactViewAct, SIGNAL(toggled(bool)), this, SLOT(compactView(bool)));
379 webPageAct = new QAction(tr("Open the &YouTube Page"), this);
380 webPageAct->setStatusTip(tr("Go to the YouTube video page and pause playback"));
381 webPageAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Y));
382 webPageAct->setEnabled(false);
383 actionMap.insert("webpage", webPageAct);
384 connect(webPageAct, SIGNAL(triggered()), mediaView, SLOT(openWebPage()));
386 copyPageAct = new QAction(tr("Copy the YouTube &Link"), this);
387 IconUtils::setIcon(copyPageAct, "link");
388 copyPageAct->setStatusTip(tr("Copy the current video YouTube link to the clipboard"));
389 copyPageAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
390 copyPageAct->setEnabled(false);
391 actionMap.insert("pagelink", copyPageAct);
392 connect(copyPageAct, SIGNAL(triggered()), mediaView, SLOT(copyWebPage()));
394 copyLinkAct = new QAction(tr("Copy the Video Stream &URL"), this);
395 copyLinkAct->setStatusTip(tr("Copy the current video stream URL to the clipboard"));
396 copyLinkAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_U));
397 copyLinkAct->setEnabled(false);
398 actionMap.insert("videolink", copyLinkAct);
399 connect(copyLinkAct, SIGNAL(triggered()), mediaView, SLOT(copyVideoLink()));
401 findVideoPartsAct = new QAction(tr("Find Video &Parts"), this);
402 findVideoPartsAct->setStatusTip(tr("Find other video parts hopefully in the right order"));
403 findVideoPartsAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_P));
404 findVideoPartsAct->setEnabled(false);
405 connect(findVideoPartsAct, SIGNAL(triggered()), mediaView, SLOT(findVideoParts()));
406 actionMap.insert("findVideoParts", findVideoPartsAct);
408 removeAct = new QAction(tr("&Remove"), this);
409 removeAct->setStatusTip(tr("Remove the selected videos from the playlist"));
410 removeAct->setShortcuts(QList<QKeySequence>()
411 << QKeySequence("Del") << QKeySequence("Backspace"));
412 removeAct->setEnabled(false);
413 actionMap.insert("remove", removeAct);
414 connect(removeAct, SIGNAL(triggered()), mediaView, SLOT(removeSelected()));
416 moveUpAct = new QAction(tr("Move &Up"), this);
417 moveUpAct->setStatusTip(tr("Move up the selected videos in the playlist"));
418 moveUpAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Up));
419 moveUpAct->setEnabled(false);
420 actionMap.insert("moveUp", moveUpAct);
421 connect(moveUpAct, SIGNAL(triggered()), mediaView, SLOT(moveUpSelected()));
423 moveDownAct = new QAction(tr("Move &Down"), this);
424 moveDownAct->setStatusTip(tr("Move down the selected videos in the playlist"));
425 moveDownAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Down));
426 moveDownAct->setEnabled(false);
427 actionMap.insert("moveDown", moveDownAct);
428 connect(moveDownAct, SIGNAL(triggered()), mediaView, SLOT(moveDownSelected()));
430 clearAct = new QAction(tr("&Clear Recent Searches"), this);
431 clearAct->setMenuRole(QAction::ApplicationSpecificRole);
432 clearAct->setShortcuts(QList<QKeySequence>()
433 << QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Delete)
434 << QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Backspace));
435 clearAct->setStatusTip(tr("Clear the search history. Cannot be undone."));
436 clearAct->setEnabled(true);
437 actionMap.insert("clearRecentKeywords", clearAct);
438 connect(clearAct, SIGNAL(triggered()), SLOT(clearRecentKeywords()));
440 quitAct = new QAction(tr("&Quit"), this);
441 quitAct->setMenuRole(QAction::QuitRole);
442 quitAct->setShortcut(QKeySequence(QKeySequence::Quit));
443 quitAct->setStatusTip(tr("Bye"));
444 actionMap.insert("quit", quitAct);
445 connect(quitAct, SIGNAL(triggered()), SLOT(quit()));
447 siteAct = new QAction(tr("&Website"), this);
448 siteAct->setShortcut(QKeySequence::HelpContents);
449 siteAct->setStatusTip(tr("%1 on the Web").arg(Constants::NAME));
450 actionMap.insert("site", siteAct);
451 connect(siteAct, SIGNAL(triggered()), this, SLOT(visitSite()));
453 #if !defined(APP_MAC) && !defined(APP_WIN)
454 donateAct = new QAction(tr("Make a &Donation"), this);
455 donateAct->setStatusTip(
456 tr("Please support the continued development of %1").arg(Constants::NAME));
457 actionMap.insert("donate", donateAct);
458 connect(donateAct, SIGNAL(triggered()), this, SLOT(donate()));
461 aboutAct = new QAction(tr("&About"), this);
462 aboutAct->setMenuRole(QAction::AboutRole);
463 aboutAct->setStatusTip(tr("Info about %1").arg(Constants::NAME));
464 actionMap.insert("about", aboutAct);
465 connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
469 searchFocusAct = new QAction(this);
470 searchFocusAct->setShortcut(QKeySequence::Find);
471 searchFocusAct->setStatusTip(tr("Search"));
472 actionMap.insert("search", searchFocusAct);
473 connect(searchFocusAct, SIGNAL(triggered()), this, SLOT(searchFocus()));
474 addAction(searchFocusAct);
476 volumeUpAct = new QAction(this);
477 volumeUpAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_Plus));
478 actionMap.insert("volumeUp", volumeUpAct);
479 connect(volumeUpAct, SIGNAL(triggered()), this, SLOT(volumeUp()));
480 addAction(volumeUpAct);
482 volumeDownAct = new QAction(this);
483 volumeDownAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_Minus));
484 actionMap.insert("volumeDown", volumeDownAct);
485 connect(volumeDownAct, SIGNAL(triggered()), this, SLOT(volumeDown()));
486 addAction(volumeDownAct);
488 volumeMuteAct = new QAction(this);
489 IconUtils::setIcon(volumeMuteAct, "audio-volume-high");
490 volumeMuteAct->setStatusTip(tr("Mute volume"));
491 volumeMuteAct->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_M));
492 actionMap.insert("volumeMute", volumeMuteAct);
493 connect(volumeMuteAct, SIGNAL(triggered()), SLOT(toggleVolumeMute()));
494 addAction(volumeMuteAct);
496 QToolButton *definitionButton = new QToolButton(this);
497 definitionButton->setText(YT3::instance().maxVideoDefinition().getName());
498 IconUtils::setIcon(definitionButton, "video-display");
499 definitionButton->setIconSize(QSize(16, 16));
500 definitionButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
501 definitionButton->setPopupMode(QToolButton::InstantPopup);
502 QMenu *definitionMenu = new QMenu(this);
503 QActionGroup *group = new QActionGroup(this);
504 for (auto &defName : VideoDefinition::getDefinitionNames()) {
505 QAction *a = new QAction(defName);
506 a->setCheckable(true);
507 a->setActionGroup(group);
508 a->setChecked(defName == YT3::instance().maxVideoDefinition().getName());
509 connect(a, &QAction::triggered, this, [this, defName, definitionButton] {
510 setDefinitionMode(defName);
511 definitionButton->setText(defName);
513 connect(&YT3::instance(), &YT3::maxVideoDefinitionChanged, this,
514 [defName, definitionButton](const QString &name) {
515 if (defName == name) definitionButton->setChecked(true);
517 definitionMenu->addAction(a);
519 definitionButton->setMenu(definitionMenu);
520 QWidgetAction *definitionAct = new QWidgetAction(this);
521 definitionAct->setDefaultWidget(definitionButton);
522 definitionAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_D));
523 actionMap.insert("definition", definitionAct);
524 addAction(definitionAct);
528 action = new QAction(tr("&Manually Start Playing"), this);
529 IconUtils::setIcon(action, "media-playback-start");
530 action->setStatusTip(tr("Manually start playing videos"));
531 action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_T));
532 action->setCheckable(true);
533 connect(action, SIGNAL(toggled(bool)), SLOT(setManualPlay(bool)));
534 actionMap.insert("manualplay", action);
536 action = new QAction(tr("&Downloads"), this);
537 IconUtils::setIcon(action, "document-save");
538 action->setStatusTip(tr("Show details about video downloads"));
539 action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_J));
540 action->setCheckable(true);
541 connect(action, SIGNAL(toggled(bool)), SLOT(toggleDownloads(bool)));
542 actionMap.insert("downloads", action);
544 action = new QAction(tr("&Download"), this);
545 IconUtils::setIcon(action, "document-save");
546 action->setStatusTip(tr("Download the current video"));
547 action->setShortcut(QKeySequence::Save);
548 action->setEnabled(false);
549 action->setVisible(false);
550 action->setPriority(QAction::LowPriority);
551 connect(action, SIGNAL(triggered()), mediaView, SLOT(downloadVideo()));
552 actionMap.insert("download", action);
555 action = new QAction(tr("Take &Snapshot"), this);
556 action->setShortcut(QKeySequence(Qt::Key_F9));
557 action->setEnabled(false);
558 actionMap.insert("snapshot", action);
559 connect(action, SIGNAL(triggered()), mediaView, SLOT(snapshot()));
562 action = new QAction(tr("&Subscribe to Channel"), this);
563 action->setProperty("originalText", action->text());
564 action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_S));
565 action->setEnabled(false);
566 connect(action, SIGNAL(triggered()), mediaView, SLOT(toggleSubscription()));
567 actionMap.insert("subscribeChannel", action);
568 mediaView->updateSubscriptionActionForVideo(0, false);
570 QString shareTip = tr("Share the current video using %1");
572 action = new QAction("&Twitter", this);
573 IconUtils::setIcon(action, "twitter");
574 action->setStatusTip(shareTip.arg("Twitter"));
575 action->setEnabled(false);
576 actionMap.insert("twitter", action);
577 connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaTwitter()));
579 action = new QAction("&Facebook", this);
580 IconUtils::setIcon(action, "facebook");
581 action->setStatusTip(shareTip.arg("Facebook"));
582 action->setEnabled(false);
583 actionMap.insert("facebook", action);
584 connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaFacebook()));
586 action = new QAction(tr("&Email"), this);
587 IconUtils::setIcon(action, "email");
588 action->setStatusTip(shareTip.arg(tr("Email")));
589 action->setEnabled(false);
590 actionMap.insert("email", action);
591 connect(action, SIGNAL(triggered()), mediaView, SLOT(shareViaEmail()));
593 action = new QAction(tr("&Close"), this);
594 action->setShortcut(QKeySequence(QKeySequence::Close));
595 actionMap.insert("close", action);
596 connect(action, SIGNAL(triggered()), SLOT(close()));
598 action = new QAction(Constants::NAME, this);
599 action->setShortcut(QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_1));
600 actionMap.insert("restore", action);
601 connect(action, SIGNAL(triggered()), SLOT(restore()));
603 action = new QAction(tr("&Float on Top"), this);
604 IconUtils::setIcon(action, "go-top");
605 action->setCheckable(true);
606 actionMap.insert("ontop", action);
607 connect(action, SIGNAL(toggled(bool)), SLOT(floatOnTop(bool)));
609 action = new QAction(tr("&Stop After This Video"), this);
610 IconUtils::setIcon(action, "media-playback-stop");
611 action->setShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Escape));
612 action->setCheckable(true);
613 action->setEnabled(false);
614 actionMap.insert("stopafterthis", action);
615 connect(action, SIGNAL(toggled(bool)), SLOT(showStopAfterThisInStatusBar(bool)));
617 action = new QAction(tr("&Report an Issue..."), this);
618 actionMap.insert("reportIssue", action);
619 connect(action, SIGNAL(triggered()), SLOT(reportIssue()));
621 action = new QAction(tr("&Refine Search..."), this);
622 action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_E));
623 action->setCheckable(true);
624 action->setEnabled(false);
625 actionMap.insert("refineSearch", action);
627 action = new QAction(YTRegions::worldwideRegion().name, this);
628 actionMap.insert("worldwideRegion", action);
630 action = new QAction(YTRegions::localRegion().name, this);
631 actionMap.insert("localRegion", action);
633 action = new QAction(tr("More..."), this);
634 actionMap.insert("moreRegion", action);
636 action = new QAction(tr("&Related Videos"), this);
637 IconUtils::setIcon(action, "view-list");
638 action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R));
639 action->setStatusTip(tr("Watch videos related to the current one"));
640 action->setEnabled(false);
641 action->setPriority(QAction::LowPriority);
642 connect(action, SIGNAL(triggered()), mediaView, SLOT(relatedVideos()));
643 actionMap.insert("relatedVideos", action);
645 action = new QAction(tr("Open in &Browser..."), this);
646 action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_B));
647 action->setEnabled(false);
648 actionMap.insert("openInBrowser", action);
649 connect(action, SIGNAL(triggered()), mediaView, SLOT(openInBrowser()));
651 action = new QAction(tr("Restricted Mode"), this);
652 IconUtils::setIcon(action, "safesearch");
653 action->setStatusTip(tr("Hide videos that may contain inappropriate content"));
654 action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_K));
655 action->setCheckable(true);
656 actionMap.insert("safeSearch", action);
658 action = new QAction(tr("Toggle &Menu Bar"), this);
659 connect(action, SIGNAL(triggered()), SLOT(toggleMenuVisibilityWithMessage()));
660 actionMap.insert("toggleMenu", action);
662 action = new QAction(tr("Menu"), this);
663 IconUtils::setIcon(action, "open-menu");
664 connect(action, SIGNAL(triggered()), SLOT(toggleToolbarMenu()));
665 actionMap.insert("toolbarMenu", action);
668 action = new QAction(tr("&Love %1? Rate it!").arg(Constants::NAME), this);
669 actionMap.insert("appStore", action);
670 connect(action, SIGNAL(triggered()), SLOT(rateOnAppStore()));
673 #ifdef APP_ACTIVATION
674 ActivationView::createActivationAction(tr("Buy %1...").arg(Constants::NAME));
677 // common action properties
678 for (QAction *action : qAsConst(actionMap)) {
679 // add actions to the MainWindow so that they work
680 // when the menu is hidden
682 MainWindow::instance()->setupAction(action);
686 void MainWindow::createMenus() {
687 fileMenu = menuBar()->addMenu(tr("&Application"));
688 #ifdef APP_ACTIVATION
689 QAction *buyAction = getAction("buy");
690 if (buyAction) fileMenu->addAction(buyAction);
692 fileMenu->addSeparator();
695 fileMenu->addAction(clearAct);
697 fileMenu->addSeparator();
699 fileMenu->addAction(quitAct);
701 QMenu *playbackMenu = menuBar()->addMenu(tr("&Playback"));
702 menuMap.insert("playback", playbackMenu);
703 playbackMenu->addAction(pauseAct);
704 playbackMenu->addAction(stopAct);
705 playbackMenu->addAction(getAction("stopafterthis"));
706 playbackMenu->addSeparator();
707 playbackMenu->addAction(skipAct);
708 playbackMenu->addAction(skipBackwardAct);
709 playbackMenu->addSeparator();
710 playbackMenu->addAction(getAction("manualplay"));
712 MacSupport::dockMenu(playbackMenu);
715 playlistMenu = menuBar()->addMenu(tr("&Playlist"));
716 menuMap.insert("playlist", playlistMenu);
717 playlistMenu->addAction(removeAct);
718 playlistMenu->addSeparator();
719 playlistMenu->addAction(moveUpAct);
720 playlistMenu->addAction(moveDownAct);
721 playlistMenu->addSeparator();
722 playlistMenu->addAction(getAction("refineSearch"));
724 QMenu *videoMenu = menuBar()->addMenu(tr("&Video"));
725 menuMap.insert("video", videoMenu);
726 videoMenu->addAction(getAction("relatedVideos"));
727 videoMenu->addAction(findVideoPartsAct);
728 videoMenu->addSeparator();
729 videoMenu->addAction(getAction("subscribeChannel"));
731 videoMenu->addSeparator();
732 videoMenu->addAction(getAction("snapshot"));
734 videoMenu->addSeparator();
735 videoMenu->addAction(webPageAct);
736 videoMenu->addAction(copyLinkAct);
737 videoMenu->addAction(getAction("openInBrowser"));
738 videoMenu->addAction(getAction("download"));
740 QMenu *shareMenu = menuBar()->addMenu(tr("&Share"));
741 menuMap.insert("share", shareMenu);
742 shareMenu->addAction(copyPageAct);
743 shareMenu->addSeparator();
744 shareMenu->addAction(getAction("twitter"));
745 shareMenu->addAction(getAction("facebook"));
746 shareMenu->addSeparator();
747 shareMenu->addAction(getAction("email"));
749 QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
750 menuMap.insert("view", viewMenu);
751 viewMenu->addAction(getAction("ontop"));
752 viewMenu->addAction(compactViewAct);
753 viewMenu->addSeparator();
754 viewMenu->addAction(fullscreenAct);
756 viewMenu->addSeparator();
757 viewMenu->addAction(getAction("toggleMenu"));
761 MacSupport::windowMenu(this);
764 helpMenu = menuBar()->addMenu(tr("&Help"));
765 menuMap.insert("help", helpMenu);
766 helpMenu->addAction(siteAct);
767 #if !defined(APP_MAC) && !defined(APP_WIN)
768 helpMenu->addAction(donateAct);
770 helpMenu->addAction(getAction("reportIssue"));
771 helpMenu->addAction(aboutAct);
774 helpMenu->addSeparator();
775 helpMenu->addAction(getAction("appStore"));
779 void MainWindow::createToolBar() {
781 currentTimeLabel = new QLabel("00:00", this);
783 seekSlider = new SeekSlider(this);
784 seekSlider->setEnabled(false);
785 seekSlider->setTracking(false);
786 seekSlider->setMaximum(1000);
787 volumeSlider = new SeekSlider(this);
788 volumeSlider->setValue(volumeSlider->maximum());
790 #if defined(APP_MAC_SEARCHFIELD) && !defined(APP_MAC_QMACTOOLBAR)
791 SearchWrapper *searchWrapper = new SearchWrapper(this);
792 toolbarSearch = searchWrapper->getSearchLineEdit();
794 toolbarSearch = new SearchLineEdit(this);
796 toolbarSearch->setMinimumWidth(toolbarSearch->fontInfo().pixelSize() * 15);
797 toolbarSearch->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
798 toolbarSearch->setSuggester(new YTSuggester(this));
799 connect(toolbarSearch, SIGNAL(search(const QString &)), SLOT(search(const QString &)));
800 connect(toolbarSearch, SIGNAL(suggestionAccepted(Suggestion *)),
801 SLOT(suggestionAccepted(Suggestion *)));
802 toolbarSearch->setStatusTip(searchFocusAct->statusTip());
804 // Add widgets to toolbar
806 #ifdef APP_MAC_QMACTOOLBAR
807 currentTimeLabel->hide();
808 toolbarSearch->hide();
809 volumeSlider->hide();
811 MacToolbar::instance().createToolbar(this);
815 mainToolBar = new QToolBar(this);
816 mainToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
817 mainToolBar->setFloatable(false);
818 mainToolBar->setMovable(false);
820 mainToolBar->setIconSize(QSize(32, 32));
822 mainToolBar->addAction(stopAct);
823 QToolButton *stopToolButton =
824 qobject_cast<QToolButton *>(mainToolBar->widgetForAction(stopAct));
825 if (stopToolButton) {
826 QMenu *stopMenu = new QMenu(this);
827 stopMenu->addAction(getAction("stopafterthis"));
828 stopToolButton->setMenu(stopMenu);
829 stopToolButton->setPopupMode(QToolButton::DelayedPopup);
831 mainToolBar->addAction(pauseAct);
832 mainToolBar->addAction(skipAct);
833 mainToolBar->addAction(getAction("relatedVideos"));
835 bool addFullScreenAct = true;
837 addFullScreenAct = !mac::CanGoFullScreen(winId());
839 if (addFullScreenAct) mainToolBar->addAction(fullscreenAct);
841 mainToolBar->addWidget(new Spacer());
843 currentTimeLabel->setFont(FontUtils::small());
844 currentTimeLabel->setMinimumWidth(currentTimeLabel->fontInfo().pixelSize() * 4);
845 currentTimeLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
846 mainToolBar->addWidget(currentTimeLabel);
849 mainToolBar->addWidget(new Spacer(nullptr, 10));
852 seekSlider->setOrientation(Qt::Horizontal);
853 seekSlider->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
854 seekSlider->setFocusPolicy(Qt::NoFocus);
855 mainToolBar->addWidget(seekSlider);
857 mainToolBar->addWidget(new Spacer());
859 mainToolBar->addAction(volumeMuteAct);
860 #ifndef APP_MAC_QMACTOOLBAR
861 QToolButton *volumeMuteButton =
862 qobject_cast<QToolButton *>(mainToolBar->widgetForAction(volumeMuteAct));
863 volumeMuteButton->setIconSize(QSize(16, 16));
864 auto fixVolumeMuteIconSize = [volumeMuteButton] {
865 volumeMuteButton->setIcon(volumeMuteButton->icon().pixmap(16));
867 fixVolumeMuteIconSize();
868 volumeMuteButton->connect(volumeMuteAct, &QAction::changed, volumeMuteButton,
869 fixVolumeMuteIconSize);
872 volumeSlider->setStatusTip(
873 tr("Press %1 to raise the volume, %2 to lower it")
874 .arg(volumeUpAct->shortcut().toString(QKeySequence::NativeText),
875 volumeDownAct->shortcut().toString(QKeySequence::NativeText)));
877 volumeSlider->setOrientation(Qt::Horizontal);
878 // this makes the volume slider smaller
879 volumeSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
880 volumeSlider->setFocusPolicy(Qt::NoFocus);
881 mainToolBar->addWidget(volumeSlider);
883 mainToolBar->addWidget(new Spacer());
885 #if defined(APP_MAC_SEARCHFIELD) && !defined(APP_MAC_QMACTOOLBAR)
886 mainToolBar->addWidget(searchWrapper);
888 mainToolBar->addWidget(toolbarSearch);
889 mainToolBar->addWidget(new Spacer(this, toolbarSearch->height() / 2));
891 QAction *toolbarMenuAction = getAction("toolbarMenu");
892 mainToolBar->addAction(toolbarMenuAction);
894 qobject_cast<QToolButton *>(mainToolBar->widgetForAction(toolbarMenuAction));
897 addToolBar(mainToolBar);
900 void MainWindow::createStatusBar() {
901 statusToolBar = new QToolBar(statusBar());
902 statusToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
903 statusToolBar->setIconSize(QSize(16, 16));
905 regionAction = new QAction(this);
906 regionAction->setStatusTip(tr("Choose your content location"));
908 QAction *localAction = getAction("localRegion");
909 if (!localAction->text().isEmpty()) {
910 QMenu *regionMenu = new QMenu(this);
911 regionMenu->addAction(getAction("worldwideRegion"));
912 regionMenu->addAction(localAction);
913 regionMenu->addSeparator();
914 QAction *moreRegionsAction = getAction("moreRegion");
915 regionMenu->addAction(moreRegionsAction);
916 connect(moreRegionsAction, SIGNAL(triggered()), SLOT(showRegionsView()));
917 regionAction->setMenu(regionMenu);
919 connect(regionAction, SIGNAL(triggered()), SLOT(showRegionsView()));
921 /* Stupid code that generates the QRC items
922 foreach(YTRegion r, YTRegions::list())
923 qDebug() << QString("<file>flags/%1.png</file>").arg(r.id.toLower());
926 statusBar()->addPermanentWidget(statusToolBar);
930 void MainWindow::showStopAfterThisInStatusBar(bool show) {
931 QAction *action = getAction("stopafterthis");
932 showActionsInStatusBar({action}, show);
935 void MainWindow::showActionsInStatusBar(const QVector<QAction *> &actions, bool show) {
937 Extra::fadeInWidget(statusBar(), statusBar());
939 for (auto action : actions) {
941 if (statusToolBar->actions().contains(action)) continue;
942 if (statusToolBar->actions().isEmpty()) {
943 statusToolBar->addAction(action);
945 statusToolBar->insertAction(statusToolBar->actions().at(0), action);
948 statusToolBar->removeAction(action);
953 if (statusBar()->isHidden() && !fullScreenActive) setStatusBarVisibility(true);
955 if (statusBar()->isVisible() && !needStatusBar()) setStatusBarVisibility(false);
959 void MainWindow::setStatusBarVisibility(bool show) {
960 if (statusBar()->isVisible() != show) {
961 statusBar()->setVisible(show);
962 if (views->currentWidget() == mediaView)
963 QTimer::singleShot(0, mediaView, SLOT(adjustWindowSize()));
967 void MainWindow::adjustStatusBarVisibility() {
968 setStatusBarVisibility(needStatusBar());
971 void MainWindow::hideToolbar() {
973 mac::showToolBar(winId(), false);
979 void MainWindow::showToolbar() {
981 mac::showToolBar(winId(), true);
987 void MainWindow::readSettings() {
989 QByteArray geometrySettings = settings.value("geometry").toByteArray();
990 if (!geometrySettings.isEmpty()) {
991 restoreGeometry(geometrySettings);
993 const QRect desktopSize = QGuiApplication::primaryScreen()->availableGeometry();
994 int w = desktopSize.width() * .9;
995 int h = qMin(w / 2, desktopSize.height());
997 QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, QSize(w, h), desktopSize));
999 setDefinitionMode(settings.value("definition", YT3::instance().maxVideoDefinition().getName())
1001 getAction("manualplay")->setChecked(settings.value("manualplay", false).toBool());
1002 getAction("safeSearch")->setChecked(settings.value("safeSearch", false).toBool());
1004 menuBar()->setVisible(settings.value("menuBar", false).toBool());
1008 void MainWindow::writeSettings() {
1011 if (!isReallyFullScreen()) {
1012 settings.setValue("geometry", saveGeometry());
1013 if (mediaView) mediaView->saveSplitterState();
1016 settings.setValue("manualplay", getAction("manualplay")->isChecked());
1017 settings.setValue("safeSearch", getAction("safeSearch")->isChecked());
1019 settings.setValue("menuBar", menuBar()->isVisible());
1023 void MainWindow::goBack() {
1024 if (history.size() > 1) {
1026 showView(history.pop());
1030 void MainWindow::showView(View *view, bool transition) {
1031 if (!history.isEmpty() && view == history.top()) {
1032 qDebug() << "Attempting to show same view" << view;
1037 if (transition && !history.isEmpty()) CompositeFader::go(this, this->grab());
1040 if (compactViewAct->isChecked()) compactViewAct->toggle();
1042 // call hide method on the current view
1043 View *oldView = qobject_cast<View *>(views->currentWidget());
1045 oldView->disappear();
1046 oldView->setEnabled(false);
1047 oldView->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
1049 qDebug() << "Cannot cast old view";
1051 view->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
1052 view->setEnabled(true);
1053 views->setCurrentWidget(view);
1056 QString title = view->getTitle();
1057 if (title.isEmpty())
1058 title = Constants::NAME;
1060 title += QLatin1String(" - ") + Constants::NAME;
1061 setWindowTitle(title);
1063 const bool isMediaView = view == mediaView;
1064 stopAct->setEnabled(isMediaView);
1065 compactViewAct->setEnabled(isMediaView);
1066 toolbarSearch->setEnabled(isMediaView);
1067 aboutAct->setEnabled(view != aboutView);
1068 getAction("downloads")->setChecked(view == downloadView);
1070 // dynamic view actions
1071 /* Not currently used by any view
1072 showActionsInStatusBar(viewActions, false);
1073 viewActions = newView->getViewActions();
1074 showActionsInStatusBar(viewActions, true);
1081 void MainWindow::about() {
1083 aboutView = new AboutView(this);
1084 views->addWidget(aboutView);
1086 showView(aboutView);
1089 void MainWindow::visitSite() {
1090 QUrl url(Constants::WEBSITE);
1091 showMessage(QString(tr("Opening %1").arg(url.toString())));
1092 QDesktopServices::openUrl(url);
1095 void MainWindow::donate() {
1096 QUrl url(QString(Constants::WEBSITE) + "#donate");
1097 showMessage(QString(tr("Opening %1").arg(url.toString())));
1098 QDesktopServices::openUrl(url);
1101 void MainWindow::reportIssue() {
1102 QUrl url("https://flavio.tordini.org/forums/forum/minitube-forums/minitube-troubleshooting");
1103 QDesktopServices::openUrl(url);
1106 void MainWindow::quit() {
1108 if (!confirmQuit()) {
1112 // do not save geometry when in full screen or in compact mode
1113 if (!fullScreenActive && !compactViewAct->isChecked()) {
1119 // mediaView->stop();
1120 Temporary::deleteAll();
1121 ChannelAggregator::instance()->stop();
1122 ChannelAggregator::instance()->cleanup();
1123 Database::shutdown();
1124 HttpUtils::clearCaches();
1128 void MainWindow::closeEvent(QCloseEvent *e) {
1130 mac::closeWindow(winId());
1133 if (!confirmQuit()) {
1137 QWidget::closeEvent(e);
1140 messageLabel->hide();
1143 void MainWindow::showEvent(QShowEvent *e) {
1144 QWidget::showEvent(e);
1150 bool MainWindow::confirmQuit() {
1151 if (DownloadManager::instance()->activeItems() > 0) {
1152 QMessageBox msgBox(this);
1153 msgBox.setIconPixmap(IconUtils::pixmap(":/images/64x64/app.png", devicePixelRatioF()));
1155 tr("Do you want to exit %1 with a download in progress?").arg(Constants::NAME));
1156 msgBox.setInformativeText(
1157 tr("If you close %1 now, this download will be cancelled.").arg(Constants::NAME));
1158 msgBox.setModal(true);
1159 // make it a "sheet" on the Mac
1160 msgBox.setWindowModality(Qt::WindowModal);
1162 msgBox.addButton(tr("Close and cancel download"), QMessageBox::RejectRole);
1163 QPushButton *waitButton =
1164 msgBox.addButton(tr("Wait for download to finish"), QMessageBox::ActionRole);
1168 if (msgBox.clickedButton() == waitButton) {
1175 void MainWindow::showHome() {
1177 currentTimeLabel->clear();
1178 seekSlider->setValue(0);
1181 void MainWindow::showMedia(SearchParams *searchParams) {
1182 showView(mediaView);
1183 if (getAction("safeSearch")->isChecked())
1184 searchParams->setSafeSearch(SearchParams::Strict);
1186 searchParams->setSafeSearch(SearchParams::None);
1187 mediaView->search(searchParams);
1190 void MainWindow::showMedia(VideoSource *videoSource) {
1191 showView(mediaView);
1192 mediaView->setVideoSource(videoSource);
1195 void MainWindow::stateChanged(Media::State newState) {
1196 qDebug() << newState;
1198 seekSlider->setEnabled(newState != Media::StoppedState);
1201 case Media::ErrorState:
1202 showMessage(tr("Error: %1").arg(media->errorString()));
1205 case Media::PlayingState:
1206 pauseAct->setEnabled(true);
1207 pauseAct->setIcon(IconUtils::icon("media-playback-pause"));
1208 pauseAct->setText(tr("&Pause"));
1209 pauseAct->setStatusTip(tr("Pause playback") + " (" +
1210 pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
1213 case Media::StoppedState:
1214 pauseAct->setEnabled(false);
1215 pauseAct->setIcon(IconUtils::icon("media-playback-start"));
1216 pauseAct->setText(tr("&Play"));
1217 pauseAct->setStatusTip(tr("Resume playback") + " (" +
1218 pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
1221 case Media::PausedState:
1222 pauseAct->setEnabled(true);
1223 pauseAct->setIcon(IconUtils::icon("media-playback-start"));
1224 pauseAct->setText(tr("&Play"));
1225 pauseAct->setStatusTip(tr("Resume playback") + " (" +
1226 pauseAct->shortcut().toString(QKeySequence::NativeText) + ")");
1229 case Media::BufferingState:
1230 pauseAct->setEnabled(false);
1231 pauseAct->setIcon(IconUtils::icon("content-loading"));
1232 pauseAct->setText(tr("&Loading..."));
1233 pauseAct->setStatusTip(QString());
1236 case Media::LoadingState:
1237 pauseAct->setEnabled(false);
1238 currentTimeLabel->clear();
1245 void MainWindow::stop() {
1250 void MainWindow::resizeEvent(QResizeEvent *e) {
1253 if (initialized && mac::CanGoFullScreen(winId())) {
1254 bool isFullscreen = mac::IsFullScreen(winId());
1255 if (isFullscreen != fullScreenActive) {
1256 if (compactViewAct->isChecked()) {
1257 compactViewAct->setChecked(false);
1260 fullScreenActive = isFullscreen;
1261 updateUIForFullscreen();
1265 #ifdef APP_MAC_QMACTOOLBAR
1266 int moreButtonWidth = 40;
1267 toolbarSearch->move(width() - toolbarSearch->width() - moreButtonWidth - 7, -34);
1272 void MainWindow::enterEvent(QEvent *e) {
1275 // Workaround cursor bug on macOS
1280 void MainWindow::leaveEvent(QEvent *e) {
1282 if (fullScreenActive) hideFullscreenUI();
1285 void MainWindow::toggleFullscreen() {
1286 if (compactViewAct->isChecked()) compactViewAct->toggle();
1289 WId handle = winId();
1290 if (mac::CanGoFullScreen(handle)) {
1291 if (mainToolBar) mainToolBar->setVisible(true);
1292 mac::ToggleFullScreen(handle);
1297 fullScreenActive = !fullScreenActive;
1299 if (fullScreenActive) {
1300 // Enter full screen
1302 maximizedBeforeFullScreen = isMaximized();
1304 // save geometry now, if the user quits when in full screen
1305 // geometry won't be saved
1309 MacSupport::enterFullScreen(this, views);
1311 menuVisibleBeforeFullScreen = menuBar()->isVisible();
1313 if (mainToolBar) mainToolBar->hide();
1321 MacSupport::exitFullScreen(this, views);
1323 menuBar()->setVisible(menuVisibleBeforeFullScreen);
1324 if (mainToolBar) mainToolBar->setVisible(views->currentWidget() == mediaView);
1325 if (maximizedBeforeFullScreen)
1331 // Make sure the window has focus
1335 qApp->processEvents();
1336 updateUIForFullscreen();
1339 void MainWindow::updateUIForFullscreen() {
1340 static QList<QKeySequence> fsShortcuts;
1341 static QString fsText;
1343 if (fullScreenActive) {
1344 fsShortcuts = fullscreenAct->shortcuts();
1345 fsText = fullscreenAct->text();
1346 if (fsText.isEmpty()) qDebug() << "[taking Empty!]";
1347 fullscreenAct->setShortcuts(QList<QKeySequence>(fsShortcuts)
1348 << QKeySequence(Qt::Key_Escape));
1349 fullscreenAct->setText(tr("Leave &Full Screen"));
1350 fullscreenAct->setIcon(IconUtils::icon("view-restore"));
1351 setStatusBarVisibility(false);
1354 removeToolBar(mainToolBar);
1355 mainToolBar->move(0, 0);
1358 mediaView->removeSidebar();
1361 fullscreenAct->setShortcuts(fsShortcuts);
1362 if (fsText.isEmpty()) fsText = "[Empty!]";
1363 fullscreenAct->setText(fsText);
1364 fullscreenAct->setIcon(IconUtils::icon("view-fullscreen"));
1366 if (needStatusBar()) setStatusBarVisibility(true);
1369 addToolBar(mainToolBar);
1372 mediaView->restoreSidebar();
1375 // No compact view action when in full screen
1376 compactViewAct->setVisible(!fullScreenActive);
1377 compactViewAct->setChecked(false);
1379 // Hide anything but the video
1380 mediaView->setSidebarVisibility(!fullScreenActive);
1382 if (fullScreenActive) {
1383 stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_MediaStop));
1385 stopAct->setShortcuts(QList<QKeySequence>()
1386 << QKeySequence(Qt::Key_Escape) << QKeySequence(Qt::Key_MediaStop));
1390 MacSupport::fullScreenActions(actionMap, fullScreenActive);
1393 if (views->currentWidget() == mediaView) mediaView->setFocus();
1395 if (fullScreenActive) {
1396 if (views->currentWidget() == mediaView) hideFullscreenUI();
1398 fullscreenTimer->stop();
1403 bool MainWindow::isReallyFullScreen() {
1405 WId handle = winId();
1406 if (mac::CanGoFullScreen(handle))
1407 return mac::IsFullScreen(handle);
1409 return isFullScreen();
1411 return isFullScreen();
1415 void MainWindow::missingKeyWarning() {
1416 static bool shown = false;
1419 QMessageBox msgBox(this);
1420 msgBox.setIconPixmap(IconUtils::pixmap(":/images/64x64/app.png", devicePixelRatioF()));
1421 msgBox.setText(QString("%1 was built without a Google API key.").arg(Constants::NAME));
1422 msgBox.setInformativeText(QString("It won't work unless you enter one."
1423 "<p>In alternative you can get %1 from the developer site.")
1424 .arg(Constants::NAME));
1425 msgBox.setModal(true);
1426 msgBox.setWindowModality(Qt::WindowModal);
1427 msgBox.addButton(QMessageBox::Close);
1428 QPushButton *enterKeyButton =
1429 msgBox.addButton(QString("Enter API key..."), QMessageBox::AcceptRole);
1430 QPushButton *devButton = msgBox.addButton(QString("Get from %1").arg(Constants::WEBSITE),
1431 QMessageBox::AcceptRole);
1432 QPushButton *helpButton = msgBox.addButton(QMessageBox::Help);
1436 if (msgBox.clickedButton() == helpButton) {
1437 QDesktopServices::openUrl(QUrl("https://github.com/flaviotordini/minitube/blob/master/"
1438 "README.md#google-api-key"));
1439 } else if (msgBox.clickedButton() == enterKeyButton) {
1441 QString text = QInputDialog::getText(this, QString(), "Google API key:", QLineEdit::Normal,
1443 if (ok && !text.isEmpty()) {
1445 settings.setValue("googleApiKey", text);
1446 YT3::instance().initApiKeys();
1448 } else if (msgBox.clickedButton() == devButton) {
1449 QDesktopServices::openUrl(QUrl(Constants::WEBSITE));
1454 void MainWindow::compactView(bool enable) {
1455 setUpdatesEnabled(false);
1457 compactModeActive = enable;
1459 static QList<QKeySequence> compactShortcuts;
1460 static QList<QKeySequence> stopShortcuts;
1462 const QString key = "compactGeometry";
1466 setMinimumSize(320, 180);
1468 mac::RemoveFullScreenWindow(winId());
1472 if (settings.contains(key))
1473 restoreGeometry(settings.value(key).toByteArray());
1477 #ifdef APP_MAC_QMACTOOLBAR
1478 mac::showToolBar(winId(), !enable);
1480 mainToolBar->setVisible(!enable);
1482 mediaView->setSidebarVisibility(!enable);
1483 statusBar()->hide();
1485 compactShortcuts = compactViewAct->shortcuts();
1486 stopShortcuts = stopAct->shortcuts();
1488 QList<QKeySequence> newStopShortcuts(stopShortcuts);
1489 newStopShortcuts.removeAll(QKeySequence(Qt::Key_Escape));
1490 stopAct->setShortcuts(newStopShortcuts);
1491 compactViewAct->setShortcuts(QList<QKeySequence>(compactShortcuts)
1492 << QKeySequence(Qt::Key_Escape));
1494 // ensure focus does not end up to the search box
1495 // as it would steal the Space shortcut
1496 mediaView->setFocus();
1499 settings.setValue(key, saveGeometry());
1501 // unset minimum size
1502 setMinimumSize(0, 0);
1505 mac::SetupFullScreenWindow(winId());
1507 #ifdef APP_MAC_QMACTOOLBAR
1508 mac::showToolBar(winId(), !enable);
1510 mainToolBar->setVisible(!enable);
1512 mediaView->setSidebarVisibility(!enable);
1513 if (needStatusBar()) setStatusBarVisibility(true);
1517 compactViewAct->setShortcuts(compactShortcuts);
1518 stopAct->setShortcuts(stopShortcuts);
1521 // auto float on top
1522 floatOnTop(enable, false);
1525 mac::compactMode(winId(), enable);
1528 menuVisibleBeforeCompactMode = menuBar()->isVisible();
1531 menuBar()->setVisible(menuVisibleBeforeCompactMode);
1535 setUpdatesEnabled(true);
1538 void MainWindow::toggleToolbarMenu() {
1539 if (!toolbarMenu) toolbarMenu = new ToolbarMenu(this);
1540 if (toolbarMenu->isVisible())
1541 toolbarMenu->hide();
1543 toolbarMenu->show();
1546 void MainWindow::searchFocus() {
1547 toolbarSearch->selectAll();
1548 toolbarSearch->setFocus();
1551 void MainWindow::initMedia() {
1553 qFatal("QtAV has a showstopper bug. Audio stops randomly. See bug "
1554 "https://github.com/wang-bin/QtAV/issues/1184");
1555 media = new MediaQtAV(this);
1556 #elif defined MEDIA_MPV
1557 media = new MediaMPV();
1559 qFatal("No media backend defined");
1562 media->setUserAgent(HttpUtils::stealthUserAgent());
1565 qreal volume = settings.value("volume", 1.).toReal();
1566 media->setVolume(volume);
1568 connect(media, &Media::error, this, &MainWindow::handleError);
1569 connect(media, &Media::stateChanged, this, &MainWindow::stateChanged);
1570 connect(media, &Media::positionChanged, this, &MainWindow::tick);
1572 connect(seekSlider, &QSlider::sliderMoved, this, [this](int value) {
1573 // value : maxValue = posit ion : duration
1574 qint64 ms = (value * media->duration()) / seekSlider->maximum();
1575 qDebug() << "Seeking to" << ms;
1577 if (media->state() == Media::PausedState) media->play();
1579 connect(seekSlider, &QSlider::sliderPressed, this, [this]() {
1580 // value : maxValue = position : duration
1581 qint64 ms = (seekSlider->value() * media->duration()) / seekSlider->maximum();
1583 if (media->state() == Media::PausedState) media->play();
1585 connect(media, &Media::started, this, [this]() { seekSlider->setValue(0); });
1587 connect(media, &Media::volumeChanged, this, &MainWindow::volumeChanged);
1588 connect(media, &Media::volumeMutedChanged, this, &MainWindow::volumeMutedChanged);
1589 connect(volumeSlider, &QSlider::sliderMoved, this, [this](int value) {
1590 qreal volume = (qreal)value / volumeSlider->maximum();
1591 media->setVolume(volume);
1593 connect(volumeSlider, &QSlider::sliderPressed, this, [this]() {
1594 qreal volume = (qreal)volumeSlider->value() / volumeSlider->maximum();
1595 media->setVolume(volume);
1598 mediaView->setMedia(media);
1601 void MainWindow::tick(qint64 time) {
1603 bool isDown = seekSlider->property("down").isValid();
1605 bool isDown = seekSlider->isSliderDown();
1607 if (!isDown && media->state() == Media::PlayingState) {
1608 // value : maxValue = position : duration
1609 qint64 duration = media->duration();
1610 if (duration <= 0) return;
1611 int value = (seekSlider->maximum() * media->position()) / duration;
1612 seekSlider->setValue(value);
1615 const QString s = formatTime(time);
1616 if (s != currentTimeLabel->text()) {
1617 currentTimeLabel->setText(s);
1618 emit currentTimeChanged(s);
1621 const qint64 remainingTime = media->remainingTime();
1622 currentTimeLabel->setStatusTip(tr("Remaining time: %1").arg(formatTime(remainingTime)));
1626 QString MainWindow::formatTime(qint64 duration) {
1629 int seconds = (int)(duration % 60);
1631 int minutes = (int)(duration % 60);
1633 int hours = (int)(duration % 24);
1634 if (hours == 0) return res.sprintf("%02d:%02d", minutes, seconds);
1635 return res.sprintf("%02d:%02d:%02d", hours, minutes, seconds);
1638 void MainWindow::volumeUp() {
1639 qreal newVolume = media->volume() + .1;
1640 if (newVolume > 1.) newVolume = 1.;
1641 media->setVolume(newVolume);
1644 void MainWindow::volumeDown() {
1645 qreal newVolume = media->volume() - .1;
1646 if (newVolume < 0) newVolume = 0;
1647 media->setVolume(newVolume);
1650 void MainWindow::toggleVolumeMute() {
1651 bool muted = media->volumeMuted();
1652 media->setVolumeMuted(!muted);
1655 void MainWindow::volumeChanged(qreal newVolume) {
1656 // automatically unmute when volume changes
1657 if (media->volumeMuted()) media->setVolumeMuted(false);
1658 showMessage(tr("Volume at %1%").arg((int)(newVolume * 100)));
1659 // newVolume : 1.0 = x : 1000
1660 int value = newVolume * volumeSlider->maximum();
1661 volumeSlider->blockSignals(true);
1662 volumeSlider->setValue(value);
1663 volumeSlider->blockSignals(false);
1666 void MainWindow::volumeMutedChanged(bool muted) {
1668 volumeMuteAct->setIcon(IconUtils::icon("audio-volume-muted"));
1669 showMessage(tr("Volume is muted"));
1671 volumeMuteAct->setIcon(IconUtils::icon("audio-volume-high"));
1672 showMessage(tr("Volume is unmuted"));
1676 void MainWindow::setDefinitionMode(const QString &definitionName) {
1677 QAction *definitionAct = getAction("definition");
1678 definitionAct->setText(definitionName);
1679 definitionAct->setStatusTip(
1680 tr("Maximum video definition set to %1").arg(definitionAct->text()) + " (" +
1681 definitionAct->shortcut().toString(QKeySequence::NativeText) + ")");
1682 showMessage(definitionAct->statusTip());
1683 YT3::instance().setMaxVideoDefinition(definitionName);
1684 if (views->currentWidget() == mediaView) {
1685 mediaView->reloadCurrentVideo();
1689 void MainWindow::toggleDefinitionMode() {
1690 const QVector<VideoDefinition> &definitions = VideoDefinition::getDefinitions();
1691 const VideoDefinition ¤tDefinition = YT3::instance().maxVideoDefinition();
1693 int index = definitions.indexOf(currentDefinition);
1694 if (index != definitions.size() - 1) {
1699 setDefinitionMode(definitions.at(index).getName());
1702 void MainWindow::clearRecentKeywords() {
1704 settings.remove("recentKeywords");
1705 settings.remove("recentChannels");
1706 if (views->currentWidget() == homeView) {
1707 SearchView *searchView = homeView->getSearchView();
1708 searchView->updateRecentKeywords();
1709 searchView->updateRecentChannels();
1711 HttpUtils::clearCaches();
1712 showMessage(tr("Your privacy is now safe"));
1715 void MainWindow::setManualPlay(bool enabled) {
1717 settings.setValue("manualplay", QVariant::fromValue(enabled));
1718 if (views->currentWidget() == homeView &&
1719 homeView->currentWidget() == homeView->getSearchView())
1721 showActionsInStatusBar({getAction("manualplay")}, enabled);
1724 void MainWindow::updateDownloadMessage(const QString &message) {
1725 getAction("downloads")->setText(message);
1728 void MainWindow::downloadsFinished() {
1729 getAction("downloads")->setText(tr("&Downloads"));
1730 showMessage(tr("Downloads complete"));
1733 void MainWindow::toggleDownloads(bool show) {
1735 stopAct->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::Key_MediaStop));
1736 getAction("downloads")
1737 ->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_J)
1738 << QKeySequence(Qt::Key_Escape));
1740 getAction("downloads")
1741 ->setShortcuts(QList<QKeySequence>() << QKeySequence(Qt::CTRL + Qt::Key_J));
1742 stopAct->setShortcuts(QList<QKeySequence>()
1743 << QKeySequence(Qt::Key_Escape) << QKeySequence(Qt::Key_MediaStop));
1746 if (!downloadView) {
1747 downloadView = new DownloadView(this);
1748 views->addWidget(downloadView);
1751 showView(downloadView);
1756 void MainWindow::suggestionAccepted(Suggestion *suggestion) {
1757 search(suggestion->value);
1760 void MainWindow::search(const QString &query) {
1761 QString q = query.simplified();
1762 if (q.isEmpty()) return;
1763 SearchParams *searchParams = new SearchParams();
1764 searchParams->setKeywords(q);
1765 showMedia(searchParams);
1768 void MainWindow::dragEnterEvent(QDragEnterEvent *e) {
1769 if (e->mimeData()->hasFormat("text/uri-list")) {
1770 QList<QUrl> urls = e->mimeData()->urls();
1771 if (urls.isEmpty()) return;
1772 const QUrl &url = urls.at(0);
1773 QString videoId = YTSearch::videoIdFromUrl(url.toString());
1774 if (!videoId.isEmpty()) e->acceptProposedAction();
1778 void MainWindow::dropEvent(QDropEvent *e) {
1779 if (!toolbarSearch->isEnabled()) return;
1781 QList<QUrl> urls = e->mimeData()->urls();
1782 if (urls.isEmpty()) return;
1783 const QUrl &url = urls.at(0);
1784 QString videoId = YTSearch::videoIdFromUrl(url.toString());
1785 if (!videoId.isEmpty()) {
1786 setWindowTitle(url.toString());
1787 SearchParams *searchParams = new SearchParams();
1788 searchParams->setKeywords(videoId);
1789 showMedia(searchParams);
1793 void MainWindow::checkForUpdate() {
1794 static const QString updateCheckKey = "updateCheck";
1798 uint unixTime = QDateTime::currentDateTime().toTime_t();
1799 int lastCheck = settings.value(updateCheckKey).toInt();
1800 int secondsSinceLastCheck = unixTime - lastCheck;
1801 // qDebug() << "secondsSinceLastCheck" << unixTime << lastCheck << secondsSinceLastCheck;
1802 if (secondsSinceLastCheck < 86400) return;
1805 UpdateChecker *updateChecker = new UpdateChecker();
1806 connect(updateChecker, &UpdateChecker::newVersion, this,
1807 [this, updateChecker](const QString &version) {
1808 updateChecker->deleteLater();
1810 QString checkedVersion = settings.value("checkedVersion").toString();
1811 if (checkedVersion == version) return;
1812 #ifdef APP_SIMPLEUPDATE
1813 simpleUpdateDialog(version);
1814 #elif defined(APP_EXTRA) && !defined(APP_MAC)
1815 UpdateDialog *dialog = new UpdateDialog(version, this);
1819 updateChecker->checkForUpdate();
1820 settings.setValue(updateCheckKey, unixTime);
1823 void MainWindow::simpleUpdateDialog(const QString &version) {
1824 QMessageBox msgBox(this);
1825 msgBox.setIconPixmap(IconUtils::pixmap(":/images/64x64/app.png", devicePixelRatioF()));
1826 msgBox.setText(tr("%1 version %2 is now available.").arg(Constants::NAME, version));
1827 msgBox.setModal(true);
1828 msgBox.setWindowModality(Qt::WindowModal);
1829 msgBox.addButton(QMessageBox::Close);
1830 QPushButton *laterButton = msgBox.addButton(tr("Remind me later"), QMessageBox::RejectRole);
1831 QPushButton *updateButton = msgBox.addButton(tr("Update"), QMessageBox::AcceptRole);
1833 if (msgBox.clickedButton() != laterButton) {
1835 settings.setValue("checkedVersion", version);
1837 if (msgBox.clickedButton() == updateButton) visitSite();
1840 bool MainWindow::needStatusBar() {
1841 return !statusToolBar->actions().isEmpty();
1844 void MainWindow::adjustMessageLabelPosition() {
1845 if (messageLabel->parent() == this)
1846 messageLabel->move(0, height() - messageLabel->height());
1848 messageLabel->move(mapToGlobal(QPoint(0, height() - messageLabel->height())));
1851 void MainWindow::floatOnTop(bool onTop, bool showAction) {
1852 if (showAction) showActionsInStatusBar({getAction("ontop")}, onTop);
1854 mac::floatOnTop(winId(), onTop);
1857 setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
1860 setWindowFlags(windowFlags() ^ Qt::WindowStaysOnTopHint);
1866 void MainWindow::restore() {
1868 mac::uncloseWindow(winId());
1872 void MainWindow::messageReceived(const QString &message) {
1873 if (message == QLatin1String("--toggle-playing")) {
1874 if (pauseAct->isEnabled()) pauseAct->trigger();
1875 } else if (message == QLatin1String("--next")) {
1876 if (skipAct->isEnabled()) skipAct->trigger();
1877 } else if (message == QLatin1String("--previous")) {
1878 if (skipBackwardAct->isEnabled()) skipBackwardAct->trigger();
1879 } else if (message == QLatin1String("--stop-after-this")) {
1880 getAction("stopafterthis")->toggle();
1881 } else if (message.startsWith("--")) {
1882 MainWindow::printHelp();
1883 } else if (!message.isEmpty()) {
1884 SearchParams *searchParams = new SearchParams();
1885 searchParams->setKeywords(message);
1886 showMedia(searchParams);
1890 void MainWindow::hideFullscreenUI() {
1891 if (views->currentWidget() != mediaView) return;
1892 setCursor(Qt::BlankCursor);
1894 QPoint p = mapFromGlobal(QCursor::pos());
1895 const int x = p.x();
1897 if (x > mediaView->getSidebar()->width()) mediaView->setSidebarVisibility(false);
1900 const int y = p.y();
1901 bool shouldHideToolbar = !toolbarSearch->hasFocus() && y > mainToolBar->height();
1902 if (shouldHideToolbar) mainToolBar->setVisible(false);
1906 void MainWindow::toggleMenuVisibility() {
1907 bool show = !menuBar()->isVisible();
1908 menuBar()->setVisible(show);
1911 void MainWindow::toggleMenuVisibilityWithMessage() {
1912 bool show = !menuBar()->isVisible();
1913 menuBar()->setVisible(show);
1915 QMessageBox msgBox(this);
1916 msgBox.setText(tr("You can still access the menu bar by pressing the ALT key"));
1917 msgBox.setModal(true);
1918 msgBox.setWindowModality(Qt::WindowModal);
1923 #ifdef APP_MAC_STORE
1924 void MainWindow::rateOnAppStore() {
1925 QDesktopServices::openUrl(QUrl("macappstore://userpub.itunes.apple.com"
1926 "/WebObjects/MZUserPublishing.woa/wa/addUserReview"
1927 "?id=422006190&type=Purple+Software"));
1931 void MainWindow::printHelp() {
1932 QString msg = QString("%1 %2\n\n").arg(Constants::NAME, Constants::VERSION);
1933 msg += "Usage: minitube [options]\n";
1934 msg += "Options:\n";
1935 msg += " --toggle-playing\t";
1936 msg += "Start or pause playback.\n";
1937 msg += " --next\t\t";
1938 msg += "Skip to the next video.\n";
1939 msg += " --previous\t\t";
1940 msg += "Go back to the previous video.\n";
1941 msg += " --stop-after-this\t";
1942 msg += "Stop playback at the end of the video.\n";
1943 std::cout << msg.toLocal8Bit().data();
1946 void MainWindow::setupAction(QAction *action) {
1947 // never autorepeat.
1948 // unexperienced users tend to keep keys pressed for a "long" time
1949 action->setAutoRepeat(false);
1951 // show keyboard shortcuts in the status bar
1952 if (!action->shortcut().isEmpty())
1953 action->setStatusTip(action->statusTip() + QLatin1String(" (") +
1954 action->shortcut().toString(QKeySequence::NativeText) +
1955 QLatin1String(")"));
1958 QAction *MainWindow::getAction(const char *name) {
1959 return actionMap.value(QByteArray::fromRawData(name, strlen(name)));
1962 void MainWindow::addNamedAction(const QByteArray &name, QAction *action) {
1963 actionMap.insert(name, action);
1966 QMenu *MainWindow::getMenu(const char *name) {
1967 return menuMap.value(QByteArray::fromRawData(name, strlen(name)));
1970 void MainWindow::showMessage(const QString &message) {
1971 if (!isVisible()) return;
1973 if (!mac::isVisible(winId())) return;
1975 if (statusBar()->isVisible())
1976 statusBar()->showMessage(message, 60000);
1977 else if (isActiveWindow()) {
1978 messageLabel->setText(message);
1979 QSize size = messageLabel->sizeHint();
1980 // round width to avoid flicker with fast changing messages (e.g. volume
1982 int w = size.width() + 10;
1983 const int multiple = 15;
1984 w = w + multiple / 2;
1987 messageLabel->resize(size);
1988 if (messageLabel->isHidden()) {
1989 adjustMessageLabelPosition();
1990 messageLabel->show();
1992 messageTimer->start();
1996 void MainWindow::hideMessage() {
1997 if (messageLabel->isVisible()) {
1998 messageLabel->hide();
1999 messageLabel->clear();
2003 void MainWindow::handleError(const QString &message) {
2004 qWarning() << message;
2005 showMessage(message);
2008 #ifdef APP_ACTIVATION
2009 void MainWindow::showActivationView() {
2010 View *activationView = ActivationView::instance();
2011 views->addWidget(activationView);
2012 if (views->currentWidget() != activationView) showView(activationView);
2016 void MainWindow::showRegionsView() {
2018 regionsView = new RegionsView(this);
2019 connect(regionsView, SIGNAL(regionChanged()), homeView->getStandardFeedsView(),
2021 views->addWidget(regionsView);
2023 showView(regionsView);