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 "mediaview.h"
22 #include "playlistmodel.h"
23 #include "playlistview.h"
24 #include "loadingwidget.h"
25 #include "videoareawidget.h"
26 #include "networkaccess.h"
27 #include "minisplitter.h"
28 #include "constants.h"
29 #include "downloadmanager.h"
30 #include "downloaditem.h"
31 #include "mainwindow.h"
32 #include "temporary.h"
33 #include "refinesearchwidget.h"
34 #include "sidebarwidget.h"
35 #include "sidebarheader.h"
37 #include "activation.h"
42 #include "videosource.h"
44 #include "searchparams.h"
45 #include "ytsinglevideosource.h"
46 #include "channelaggregator.h"
47 #include "iconutils.h"
48 #include "ytchannel.h"
50 #include "snapshotsettings.h"
52 #include "datautils.h"
53 #include "compatibility/qurlqueryhelper.h"
56 NetworkAccess* http();
57 QHash<QString, QAction*>* globalActions();
58 QHash<QString, QMenu*>* globalMenus();
59 QNetworkAccessManager* networkAccessManager();
62 MediaView* MediaView::instance() {
63 static MediaView *i = new MediaView();
67 MediaView::MediaView(QWidget *parent) : QWidget(parent)
76 void MediaView::initialize() {
77 QBoxLayout *layout = new QVBoxLayout(this);
80 splitter = new MiniSplitter();
82 playlistView = new PlaylistView(this);
83 // respond to the user doubleclicking a playlist item
84 connect(playlistView, SIGNAL(activated(const QModelIndex &)),
85 SLOT(itemActivated(const QModelIndex &)));
87 playlistModel = new PlaylistModel();
88 connect(playlistModel, SIGNAL(activeRowChanged(int)),
89 SLOT(activeRowChanged(int)));
90 // needed to restore the selection after dragndrop
91 connect(playlistModel, SIGNAL(needSelectionFor(QList<Video*>)),
92 SLOT(selectVideos(QList<Video*>)));
93 playlistView->setModel(playlistModel);
95 connect(playlistView->selectionModel(),
96 SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
97 SLOT(selectionChanged(const QItemSelection &, const QItemSelection &)));
99 connect(playlistView, SIGNAL(authorPushed(QModelIndex)), SLOT(authorPushed(QModelIndex)));
101 sidebar = new SidebarWidget(this);
102 sidebar->setPlaylist(playlistView);
103 connect(sidebar->getRefineSearchWidget(), SIGNAL(searchRefined()),
104 SLOT(searchAgain()));
105 connect(playlistModel, SIGNAL(haveSuggestions(const QStringList &)),
106 sidebar, SLOT(showSuggestions(const QStringList &)));
107 connect(sidebar, SIGNAL(suggestionAccepted(QString)),
108 MainWindow::instance(), SLOT(search(QString)));
109 splitter->addWidget(sidebar);
111 videoAreaWidget = new VideoAreaWidget(this);
112 // videoAreaWidget->setMinimumSize(320,240);
115 videoWidget = new Phonon::VideoWidget(this);
116 videoAreaWidget->setVideoWidget(videoWidget);
118 videoAreaWidget->setListModel(playlistModel);
120 loadingWidget = new LoadingWidget(this);
121 videoAreaWidget->setLoadingWidget(loadingWidget);
123 splitter->addWidget(videoAreaWidget);
125 splitter->setStretchFactor(0, 0);
126 splitter->setStretchFactor(1, 8);
128 // restore splitter state
130 splitter->restoreState(settings.value("splitter").toByteArray());
131 splitter->setChildrenCollapsible(false);
132 connect(splitter, SIGNAL(splitterMoved(int,int)), SLOT(maybeAdjustWindowSize()));
134 layout->addWidget(splitter);
136 errorTimer = new QTimer(this);
137 errorTimer->setSingleShot(true);
138 errorTimer->setInterval(3000);
139 connect(errorTimer, SIGNAL(timeout()), SLOT(skipVideo()));
141 #ifdef APP_ACTIVATION
142 demoTimer = new QTimer(this);
143 demoTimer->setSingleShot(true);
144 connect(demoTimer, SIGNAL(timeout()), SLOT(demoMessage()));
147 connect(videoAreaWidget, SIGNAL(doubleClicked()),
148 The::globalActions()->value("fullscreen"), SLOT(trigger()));
150 QAction* refineSearchAction = The::globalActions()->value("refine-search");
151 connect(refineSearchAction, SIGNAL(toggled(bool)),
152 sidebar, SLOT(toggleRefineSearch(bool)));
155 << The::globalActions()->value("webpage")
156 << The::globalActions()->value("pagelink")
157 << The::globalActions()->value("videolink")
158 << The::globalActions()->value("open-in-browser")
160 << The::globalActions()->value("snapshot")
162 << The::globalActions()->value("findVideoParts")
163 << The::globalActions()->value("skip")
164 << The::globalActions()->value("previous")
165 << The::globalActions()->value("stopafterthis")
166 << The::globalActions()->value("related-videos")
167 << The::globalActions()->value("refine-search")
168 << The::globalActions()->value("twitter")
169 << The::globalActions()->value("facebook")
170 << The::globalActions()->value("buffer")
171 << The::globalActions()->value("email");
173 #ifndef APP_PHONON_SEEK
174 QSlider *slider = MainWindow::instance()->getSlider();
175 connect(slider, SIGNAL(valueChanged(int)), SLOT(sliderMoved(int)));
180 void MediaView::setMediaObject(Phonon::MediaObject *mediaObject) {
181 this->mediaObject = mediaObject;
182 Phonon::createPath(mediaObject, videoWidget);
183 connect(mediaObject, SIGNAL(finished()), SLOT(playbackFinished()));
184 connect(mediaObject, SIGNAL(stateChanged(Phonon::State, Phonon::State)),
185 SLOT(stateChanged(Phonon::State, Phonon::State)));
186 connect(mediaObject, SIGNAL(aboutToFinish()), SLOT(aboutToFinish()));
190 SearchParams* MediaView::getSearchParams() {
191 VideoSource *videoSource = playlistModel->getVideoSource();
192 if (videoSource && videoSource->metaObject()->className() == QLatin1String("YTSearch")) {
193 YTSearch *search = dynamic_cast<YTSearch *>(videoSource);
194 return search->getSearchParams();
199 void MediaView::search(SearchParams *searchParams) {
200 if (!searchParams->keywords().isEmpty()) {
201 if (searchParams->keywords().startsWith("http://") ||
202 searchParams->keywords().startsWith("https://")) {
203 QString videoId = YTSearch::videoIdFromUrl(searchParams->keywords());
204 if (!videoId.isEmpty()) {
205 YTSingleVideoSource *singleVideoSource = new YTSingleVideoSource(this);
206 singleVideoSource->setVideoId(videoId);
207 setVideoSource(singleVideoSource);
212 YTSearch *ytSearch = new YTSearch(searchParams, this);
213 ytSearch->setAsyncDetails(true);
214 connect(ytSearch, SIGNAL(gotDetails()), playlistModel, SLOT(emitDataChanged()));
215 setVideoSource(ytSearch);
218 void MediaView::setVideoSource(VideoSource *videoSource, bool addToHistory, bool back) {
222 #ifdef APP_ACTIVATION
227 // qDebug() << "Adding VideoSource" << videoSource->getName() << videoSource;
230 int currentIndex = getHistoryIndex();
231 if (currentIndex >= 0 && currentIndex < history.size() - 1) {
232 while (history.size() > currentIndex + 1) {
233 VideoSource *vs = history.takeLast();
235 qDebug() << "Deleting VideoSource" << vs->getName() << vs;
240 history.append(videoSource);
244 if (history.size() > 1)
245 Extra::slideTransition(playlistView->viewport(), playlistView->viewport(), back);
248 playlistModel->setVideoSource(videoSource);
250 sidebar->showPlaylist();
251 sidebar->getRefineSearchWidget()->setSearchParams(getSearchParams());
252 sidebar->hideSuggestions();
253 sidebar->getHeader()->updateInfo();
255 SearchParams *searchParams = getSearchParams();
256 bool isChannel = searchParams && !searchParams->channelId().isEmpty();
257 playlistView->setClickableAuthors(!isChannel);
262 void MediaView::searchAgain() {
263 VideoSource *currentVideoSource = playlistModel->getVideoSource();
264 setVideoSource(currentVideoSource, false);
267 bool MediaView::canGoBack() {
268 return getHistoryIndex() > 0;
271 void MediaView::goBack() {
272 if (history.size() > 1) {
273 int currentIndex = getHistoryIndex();
274 if (currentIndex > 0) {
275 VideoSource *previousVideoSource = history.at(currentIndex - 1);
276 setVideoSource(previousVideoSource, false, true);
281 bool MediaView::canGoForward() {
282 int currentIndex = getHistoryIndex();
283 return currentIndex >= 0 && currentIndex < history.size() - 1;
286 void MediaView::goForward() {
287 if (canGoForward()) {
288 int currentIndex = getHistoryIndex();
289 VideoSource *nextVideoSource = history.at(currentIndex + 1);
290 setVideoSource(nextVideoSource, false);
294 int MediaView::getHistoryIndex() {
295 return history.lastIndexOf(playlistModel->getVideoSource());
298 void MediaView::appear() {
299 Video *currentVideo = playlistModel->activeVideo();
301 MainWindow::instance()->setWindowTitle(
302 currentVideo->title() + " - " + Constants::NAME);
305 // optimize window for 16:9 video
306 QTimer::singleShot(50, this, SLOT(maybeAdjustWindowSize()));
308 playlistView->setFocus();
311 void MediaView::disappear() {
315 void MediaView::handleError(const QString &message) {
316 qWarning() << __PRETTY_FUNCTION__ << message;
317 #ifdef APP_PHONON_SEEK
320 QTimer::singleShot(500, this, SLOT(startPlaying()));
325 void MediaView::stateChanged(Phonon::State newState, Phonon::State /*oldState*/) {
326 if (pauseTime > 0 && (newState == Phonon::PlayingState || newState == Phonon::BufferingState)) {
327 mediaObject->seek(pauseTime);
330 if (newState == Phonon::PlayingState) {
331 videoAreaWidget->showVideo();
332 } else if (newState == Phonon::ErrorState) {
333 qWarning() << "Phonon error:" << mediaObject->errorString() << mediaObject->errorType();
334 if (mediaObject->errorType() == Phonon::FatalError)
335 handleError(mediaObject->errorString());
340 void MediaView::pause() {
342 switch( mediaObject->state() ) {
343 case Phonon::PlayingState:
344 mediaObject->pause();
348 if (pauseTimer.hasExpired(60000)) {
349 pauseTimer.invalidate();
350 connect(playlistModel->activeVideo(), SIGNAL(gotStreamUrl(QUrl)), SLOT(resumeWithNewStreamUrl(QUrl)));
351 playlistModel->activeVideo()->loadStreamUrl();
352 } else mediaObject->play();
358 QRegExp MediaView::wordRE(const QString &s) {
359 return QRegExp("\\W" + s + "\\W?", Qt::CaseInsensitive);
362 void MediaView::stop() {
365 while (!history.isEmpty()) {
366 VideoSource *videoSource = history.takeFirst();
367 if (!videoSource->parent()) delete videoSource;
370 playlistModel->abortSearch();
371 videoAreaWidget->clear();
372 videoAreaWidget->update();
374 playlistView->selectionModel()->clearSelection();
376 downloadItem->stop();
379 currentVideoSize = 0;
381 The::globalActions()->value("refine-search")->setChecked(false);
382 updateSubscriptionAction(0, false);
383 #ifdef APP_ACTIVATION
387 foreach (QAction *action, currentVideoActions)
388 action->setEnabled(false);
390 QAction *a = The::globalActions()->value("download");
391 a->setEnabled(false);
392 a->setVisible(false);
397 currentVideoId.clear();
399 #ifndef APP_PHONON_SEEK
400 QSlider *slider = MainWindow::instance()->getSlider();
401 slider->setEnabled(false);
405 if (snapshotSettings) {
406 delete snapshotSettings;
407 snapshotSettings = 0;
411 const QString & MediaView::getCurrentVideoId() {
412 return currentVideoId;
415 void MediaView::activeRowChanged(int row) {
424 downloadItem->stop();
427 currentVideoSize = 0;
430 Video *video = playlistModel->videoAt(row);
433 videoAreaWidget->showLoading(video);
435 connect(video, SIGNAL(gotStreamUrl(QUrl)),
436 SLOT(gotStreamUrl(QUrl)), Qt::UniqueConnection);
437 connect(video, SIGNAL(errorStreamUrl(QString)),
438 SLOT(skip()), Qt::UniqueConnection);
439 video->loadStreamUrl();
441 // video title in titlebar
442 MainWindow::instance()->setWindowTitle(video->title() + " - " + Constants::NAME);
444 // ensure active item is visible
446 QModelIndex index = playlistModel->index(row, 0, QModelIndex());
447 playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
450 // enable/disable actions
451 The::globalActions()->value("download")->setEnabled(
452 DownloadManager::instance()->itemForVideo(video) == 0);
453 The::globalActions()->value("previous")->setEnabled(row > 0);
454 The::globalActions()->value("stopafterthis")->setEnabled(true);
455 The::globalActions()->value("related-videos")->setEnabled(true);
457 bool enableDownload = video->license() == Video::LicenseCC;
458 #ifdef APP_ACTIVATION
459 enableDownload = enableDownload || Activation::instance().isLegacy();
462 enableDownload = true;
464 QAction *a = The::globalActions()->value("download");
465 a->setEnabled(enableDownload);
466 a->setVisible(enableDownload);
468 updateSubscriptionAction(video, YTChannel::isSubscribed(video->channelId()));
470 foreach (QAction *action, currentVideoActions)
471 action->setEnabled(true);
473 #ifndef APP_PHONON_SEEK
474 QSlider *slider = MainWindow::instance()->getSlider();
475 slider->setEnabled(false);
479 if (snapshotSettings) {
480 delete snapshotSettings;
481 snapshotSettings = 0;
482 MainWindow::instance()->adjustStatusBarVisibility();
485 // see you in gotStreamUrl...
488 void MediaView::gotStreamUrl(QUrl streamUrl) {
490 if (!streamUrl.isValid()) {
495 Video *video = static_cast<Video *>(sender());
497 qDebug() << "Cannot get sender in" << __PRETTY_FUNCTION__;
500 video->disconnect(this);
502 currentVideoId = video->id();
504 #ifdef APP_PHONON_SEEK
505 mediaObject->setCurrentSource(streamUrl);
511 // ensure we always have videos ahead
512 playlistModel->searchNeeded();
514 // ensure active item is visible
515 int row = playlistModel->activeRow();
517 QModelIndex index = playlistModel->index(row, 0, QModelIndex());
518 playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
521 #ifdef APP_ACTIVATION
522 if (!Activation::instance().isActivated())
523 demoTimer->start(180000);
527 Extra::notify(video->title(), video->channelTitle(), video->formattedDuration());
530 ChannelAggregator::instance()->videoWatched(video);
533 void MediaView::downloadStatusChanged() {
534 // qDebug() << __PRETTY_FUNCTION__;
535 switch(downloadItem->status()) {
537 // qDebug() << "Downloading";
538 if (downloadItem->offset() == 0) startPlaying();
541 // qDebug() << "Seeking to" << downloadItem->offset();
542 mediaObject->seek(offsetToTime(downloadItem->offset()));
548 // qDebug() << "Starting";
551 // qDebug() << "Finished" << mediaObject->state();
552 #ifdef APP_PHONON_SEEK
553 MainWindow::instance()->getSeekSlider()->setEnabled(mediaObject->isSeekable());
557 // qDebug() << "Failed";
561 // qDebug() << "Idle";
566 void MediaView::startPlaying() {
567 // qDebug() << __PRETTY_FUNCTION__;
574 if (downloadItem->offset() == 0) {
575 currentVideoSize = downloadItem->bytesTotal();
576 // qDebug() << "currentVideoSize" << currentVideoSize;
580 QString source = downloadItem->currentFilename();
581 qDebug() << "Playing" << source << QFile::exists(source);
583 mediaObject->setCurrentSource(QUrl::fromLocalFile(source));
586 #ifdef APP_PHONON_SEEK
587 MainWindow::instance()->getSeekSlider()->setEnabled(false);
589 QSlider *slider = MainWindow::instance()->getSlider();
590 slider->setEnabled(true);
594 void MediaView::itemActivated(const QModelIndex &index) {
595 if (playlistModel->rowExists(index.row())) {
597 // if it's the current video, just rewind and play
598 Video *activeVideo = playlistModel->activeVideo();
599 Video *video = playlistModel->videoAt(index.row());
600 if (activeVideo && video && activeVideo == video) {
601 // mediaObject->seek(0);
606 } else playlistModel->setActiveRow(index.row());
608 // the user doubleclicked on the "Search More" item
610 playlistModel->searchMore();
611 playlistView->selectionModel()->clearSelection();
615 void MediaView::skipVideo() {
616 // skippedVideo is useful for DELAYED skip operations
617 // in order to be sure that we're skipping the video we wanted
618 // and not another one
620 if (playlistModel->activeVideo() != skippedVideo) {
621 qDebug() << "Skip of video canceled";
624 int nextRow = playlistModel->rowForVideo(skippedVideo);
626 if (nextRow == -1) return;
627 playlistModel->setActiveRow(nextRow);
631 void MediaView::skip() {
632 int nextRow = playlistModel->nextRow();
633 if (nextRow == -1) return;
634 playlistModel->setActiveRow(nextRow);
637 void MediaView::skipBackward() {
638 int prevRow = playlistModel->previousRow();
639 if (prevRow == -1) return;
640 playlistModel->setActiveRow(prevRow);
643 void MediaView::aboutToFinish() {
645 qint64 currentTime = mediaObject->currentTime();
646 qint64 totalTime = mediaObject->totalTime();
647 qDebug() << __PRETTY_FUNCTION__ << currentTime << totalTime;
648 if (totalTime < 1 || currentTime + 10000 < totalTime) {
649 // QTimer::singleShot(500, this, SLOT(playbackResume()));
650 mediaObject->seek(currentTime);
656 void MediaView::playbackFinished() {
660 const qint64 totalTime = mediaObject->totalTime();
661 const qint64 currentTime = mediaObject->currentTime();
662 qDebug() << __PRETTY_FUNCTION__ << mediaObject->currentTime() << totalTime;
663 // add 10 secs for imprecise Phonon backends (VLC, Xine)
664 if (currentTime > 0 && currentTime + 10000 < totalTime) {
665 // mediaObject->seek(currentTime);
666 QTimer::singleShot(500, this, SLOT(playbackResume()));
668 QAction* stopAfterThisAction = The::globalActions()->value("stopafterthis");
669 if (stopAfterThisAction->isChecked()) {
670 stopAfterThisAction->setChecked(false);
676 void MediaView::playbackResume() {
679 const qint64 currentTime = mediaObject->currentTime();
680 qDebug() << __PRETTY_FUNCTION__ << currentTime;
682 mediaObject->seek(currentTime);
687 void MediaView::openWebPage() {
688 Video* video = playlistModel->activeVideo();
691 mediaObject->pause();
693 QDesktopServices::openUrl(video->webpage());
696 void MediaView::copyWebPage() {
697 Video* video = playlistModel->activeVideo();
699 QString address = video->webpage();
700 QApplication::clipboard()->setText(address);
701 QString message = tr("You can now paste the YouTube link into another application");
702 MainWindow::instance()->showMessage(message);
705 void MediaView::copyVideoLink() {
706 Video* video = playlistModel->activeVideo();
708 QApplication::clipboard()->setText(video->getStreamUrl().toEncoded());
709 QString message = tr("You can now paste the video stream URL into another application")
710 + ". " + tr("The link will be valid only for a limited time.");
711 MainWindow::instance()->showMessage(message);
714 void MediaView::openInBrowser() {
715 Video* video = playlistModel->activeVideo();
718 mediaObject->pause();
720 QDesktopServices::openUrl(video->getStreamUrl());
723 void MediaView::removeSelected() {
724 if (!playlistView->selectionModel()->hasSelection()) return;
725 QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
726 playlistModel->removeIndexes(indexes);
729 void MediaView::selectVideos(QList<Video*> videos) {
730 foreach (Video *video, videos) {
731 QModelIndex index = playlistModel->indexForVideo(video);
732 playlistView->selectionModel()->select(index, QItemSelectionModel::Select);
733 playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
737 void MediaView::selectionChanged(const QItemSelection & /*selected*/,
738 const QItemSelection & /*deselected*/) {
739 const bool gotSelection = playlistView->selectionModel()->hasSelection();
740 The::globalActions()->value("remove")->setEnabled(gotSelection);
741 The::globalActions()->value("moveUp")->setEnabled(gotSelection);
742 The::globalActions()->value("moveDown")->setEnabled(gotSelection);
745 void MediaView::moveUpSelected() {
746 if (!playlistView->selectionModel()->hasSelection()) return;
748 QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
749 qStableSort(indexes.begin(), indexes.end());
750 playlistModel->move(indexes, true);
752 // set current index after row moves to something more intuitive
753 int row = indexes.first().row();
754 playlistView->selectionModel()->setCurrentIndex(playlistModel->index(row>1?row:1),
755 QItemSelectionModel::NoUpdate);
758 void MediaView::moveDownSelected() {
759 if (!playlistView->selectionModel()->hasSelection()) return;
761 QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
762 qStableSort(indexes.begin(), indexes.end(), qGreater<QModelIndex>());
763 playlistModel->move(indexes, false);
765 // set current index after row moves to something more intuitive
766 // (respect 1 static item on bottom)
767 int row = indexes.first().row()+1, max = playlistModel->rowCount() - 2;
768 playlistView->selectionModel()->setCurrentIndex(
769 playlistModel->index(row>max?max:row), QItemSelectionModel::NoUpdate);
772 void MediaView::setPlaylistVisible(bool visible) {
773 if (splitter->widget(0)->isVisible() == visible) return;
774 splitter->widget(0)->setVisible(visible);
775 playlistView->setFocus();
778 bool MediaView::isPlaylistVisible() {
779 return splitter->widget(0)->isVisible();
782 void MediaView::saveSplitterState() {
784 settings.setValue("splitter", splitter->saveState());
787 #ifdef APP_ACTIVATION
789 static QPushButton *continueButton;
791 void MediaView::demoMessage() {
793 if (mediaObject->state() != Phonon::PlayingState) return;
794 mediaObject->pause();
797 QMessageBox msgBox(this);
798 msgBox.setIconPixmap(QPixmap(":/images/app.png").scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
799 msgBox.setText(tr("This is just the demo version of %1.").arg(Constants::NAME));
800 msgBox.setInformativeText(tr("It allows you to test the application and see if it works for you."));
801 msgBox.setModal(true);
802 // make it a "sheet" on the Mac
803 msgBox.setWindowModality(Qt::WindowModal);
805 continueButton = msgBox.addButton("5", QMessageBox::RejectRole);
806 continueButton->setEnabled(false);
807 QPushButton *buyButton = msgBox.addButton(tr("Get the full version"), QMessageBox::ActionRole);
809 QTimeLine *timeLine = new QTimeLine(6000, this);
810 timeLine->setCurveShape(QTimeLine::LinearCurve);
811 timeLine->setFrameRange(5, 0);
812 connect(timeLine, SIGNAL(frameChanged(int)), SLOT(updateContinueButton(int)));
817 if (msgBox.clickedButton() == buyButton) {
818 MainWindow::instance()->showActivationView();
823 demoTimer->start(600000);
830 void MediaView::updateContinueButton(int value) {
832 continueButton->setText(tr("Continue"));
833 continueButton->setEnabled(true);
835 continueButton->setText(QString::number(value));
841 void MediaView::downloadVideo() {
842 Video* video = playlistModel->activeVideo();
844 DownloadManager::instance()->addItem(video);
845 The::globalActions()->value("downloads")->setVisible(true);
846 QString message = tr("Downloading %1").arg(video->title());
847 MainWindow::instance()->showMessage(message);
851 void MediaView::snapshot() {
852 qint64 currentTime = mediaObject->currentTime() / 1000;
854 QImage image = videoWidget->snapshot();
855 if (image.isNull()) {
856 qWarning() << "Null snapshot";
860 // QPixmap pixmap = QPixmap::grabWindow(videoWidget->winId());
861 QPixmap pixmap = QPixmap::fromImage(image.scaled(videoWidget->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
862 videoAreaWidget->showSnapshotPreview(pixmap);
864 Video* video = playlistModel->activeVideo();
867 QString location = SnapshotSettings::getCurrentLocation();
869 if (!dir.exists()) dir.mkpath(location);
870 QString basename = video->title();
871 QString format = video->duration() > 3600 ? "h_mm_ss" : "m_ss";
872 basename += " (" + QTime().addSecs(currentTime).toString(format) + ")";
873 basename = DataUtils::stringToFilename(basename);
874 QString filename = location + "/" + basename + ".png";
875 qDebug() << filename;
876 image.save(filename, "PNG");
878 if (snapshotSettings) delete snapshotSettings;
879 snapshotSettings = new SnapshotSettings(videoWidget);
880 snapshotSettings->setSnapshot(pixmap, filename);
881 QStatusBar *statusBar = MainWindow::instance()->statusBar();
883 Extra::fadeInWidget(statusBar, statusBar);
885 statusBar->insertPermanentWidget(0, snapshotSettings);
886 snapshotSettings->show();
887 MainWindow::instance()->setStatusBarVisibility(true);
891 void MediaView::fullscreen() {
892 videoAreaWidget->setParent(0);
893 videoAreaWidget->showFullScreen();
896 void MediaView::startDownloading() {
897 Video *video = playlistModel->activeVideo();
899 Video *videoCopy = video->clone();
901 downloadItem->stop();
904 QString tempFile = Temporary::filename();
905 downloadItem = new DownloadItem(videoCopy, video->getStreamUrl(), tempFile, this);
906 connect(downloadItem, SIGNAL(statusChanged()),
907 SLOT(downloadStatusChanged()), Qt::UniqueConnection);
908 connect(downloadItem, SIGNAL(bufferProgress(int)),
909 loadingWidget, SLOT(bufferStatus(int)), Qt::UniqueConnection);
910 // connect(downloadItem, SIGNAL(finished()), SLOT(itemFinished()));
911 connect(video, SIGNAL(errorStreamUrl(QString)),
912 SLOT(handleError(QString)), Qt::UniqueConnection);
913 connect(downloadItem, SIGNAL(error(QString)),
914 SLOT(handleError(QString)), Qt::UniqueConnection);
915 downloadItem->start();
918 void MediaView::resumeWithNewStreamUrl(const QUrl &streamUrl) {
919 pauseTime = mediaObject->currentTime();
920 mediaObject->setCurrentSource(streamUrl);
923 Video *video = static_cast<Video *>(sender());
925 qDebug() << "Cannot get sender in" << __PRETTY_FUNCTION__;
928 video->disconnect(this);
931 void MediaView::maybeAdjustWindowSize() {
933 if (settings.value("adjustWindowSize", true).toBool())
937 void MediaView::sliderMoved(int value) {
940 #ifndef APP_PHONON_SEEK
942 if (currentVideoSize <= 0 || !downloadItem || !mediaObject->isSeekable())
945 QSlider *slider = MainWindow::instance()->getSlider();
946 if (slider->isSliderDown()) return;
948 qint64 offset = (currentVideoSize * value) / slider->maximum();
950 bool needsDownload = downloadItem->needsDownload(offset);
952 if (downloadItem->isBuffered(offset)) {
953 qint64 realOffset = downloadItem->blankAtOffset(offset);
954 if (offset < currentVideoSize)
955 downloadItem->seekTo(realOffset, false);
956 mediaObject->seek(offsetToTime(offset));
958 mediaObject->pause();
959 downloadItem->seekTo(offset);
962 // qDebug() << "simple seek";
963 mediaObject->seek(offsetToTime(offset));
969 qint64 MediaView::offsetToTime(qint64 offset) {
971 const qint64 totalTime = mediaObject->totalTime();
972 return ((offset * totalTime) / currentVideoSize);
976 void MediaView::findVideoParts() {
979 Video* video = playlistModel->activeVideo();
982 QString query = video->title();
984 static QString optionalSpace = "\\s*";
985 static QString staticCounterSeparators = "[\\/\\-]";
986 QString counterSeparators = "( of | " +
987 tr("of", "Used in video parts, as in '2 of 3'") +
988 " |" + staticCounterSeparators + ")";
990 // numbers from 1 to 15
991 static QString counterNumber = "([1-9]|1[0-5])";
993 // query.remove(QRegExp(counterSeparators + optionalSpace + counterNumber));
994 query.remove(QRegExp(counterNumber + optionalSpace +
995 counterSeparators + optionalSpace + counterNumber));
996 query.remove(wordRE("pr?t\\.?" + optionalSpace + counterNumber));
997 query.remove(wordRE("ep\\.?" + optionalSpace + counterNumber));
998 query.remove(wordRE("part" + optionalSpace + counterNumber));
999 query.remove(wordRE("episode" + optionalSpace + counterNumber));
1000 query.remove(wordRE(tr("part", "This is for video parts, as in 'Cool video - part 1'") +
1001 optionalSpace + counterNumber));
1002 query.remove(wordRE(tr("episode",
1003 "This is for video parts, as in 'Cool series - episode 1'") +
1004 optionalSpace + counterNumber));
1005 query.remove(QRegExp("[\\(\\)\\[\\]]"));
1007 #define NUMBERS "one|two|three|four|five|six|seven|eight|nine|ten"
1009 QRegExp englishNumberRE = QRegExp(QLatin1String(".*(") + NUMBERS + ").*",
1010 Qt::CaseInsensitive);
1011 // bool numberAsWords = englishNumberRE.exactMatch(query);
1012 query.remove(englishNumberRE);
1014 QRegExp localizedNumberRE = QRegExp(QLatin1String(".*(") + tr(NUMBERS) + ").*",
1015 Qt::CaseInsensitive);
1016 // if (!numberAsWords) numberAsWords = localizedNumberRE.exactMatch(query);
1017 query.remove(localizedNumberRE);
1019 SearchParams *searchParams = new SearchParams();
1020 searchParams->setTransient(true);
1021 searchParams->setKeywords(query);
1022 searchParams->setChannelId(video->channelId());
1025 if (!numberAsWords) {
1026 qDebug() << "We don't have number as words";
1027 // searchParams->setSortBy(SearchParams::SortByNewest);
1028 // TODO searchParams->setReverseOrder(true);
1029 // TODO searchParams->setMax(50);
1033 search(searchParams);
1037 void MediaView::relatedVideos() {
1038 Video* video = playlistModel->activeVideo();
1040 YTSingleVideoSource *singleVideoSource = new YTSingleVideoSource();
1041 singleVideoSource->setVideo(video->clone());
1042 singleVideoSource->setAsyncDetails(true);
1043 setVideoSource(singleVideoSource);
1044 The::globalActions()->value("related-videos")->setEnabled(false);
1047 void MediaView::shareViaTwitter() {
1048 Video* video = playlistModel->activeVideo();
1050 QUrl url("https://twitter.com/intent/tweet");
1052 QUrlQueryHelper urlHelper(url);
1053 urlHelper.addQueryItem("via", "minitubeapp");
1054 urlHelper.addQueryItem("text", video->title());
1055 urlHelper.addQueryItem("url", video->webpage());
1057 QDesktopServices::openUrl(url);
1060 void MediaView::shareViaFacebook() {
1061 Video* video = playlistModel->activeVideo();
1063 QUrl url("https://www.facebook.com/sharer.php");
1065 QUrlQueryHelper urlHelper(url);
1066 urlHelper.addQueryItem("t", video->title());
1067 urlHelper.addQueryItem("u", video->webpage());
1069 QDesktopServices::openUrl(url);
1072 void MediaView::shareViaBuffer() {
1073 Video* video = playlistModel->activeVideo();
1075 QUrl url("http://bufferapp.com/add");
1077 QUrlQueryHelper urlHelper(url);
1078 urlHelper.addQueryItem("via", "minitubeapp");
1079 urlHelper.addQueryItem("text", video->title());
1080 urlHelper.addQueryItem("url", video->webpage());
1081 urlHelper.addQueryItem("picture", video->thumbnailUrl());
1083 QDesktopServices::openUrl(url);
1086 void MediaView::shareViaEmail() {
1087 Video* video = playlistModel->activeVideo();
1089 QUrl url("mailto:");
1091 QUrlQueryHelper urlHelper(url);
1092 urlHelper.addQueryItem("subject", video->title());
1093 const QString body = video->title() + "\n" +
1094 video->webpage() + "\n\n" +
1095 tr("Sent from %1").arg(Constants::NAME) + "\n" +
1097 urlHelper.addQueryItem("body", body);
1099 QDesktopServices::openUrl(url);
1102 void MediaView::authorPushed(QModelIndex index) {
1103 Video* video = playlistModel->videoAt(index.row());
1106 QString channelId = video->channelId();
1107 // if (channelId.isEmpty()) channelId = video->channelTitle();
1108 if (channelId.isEmpty()) return;
1110 SearchParams *searchParams = new SearchParams();
1111 searchParams->setChannelId(channelId);
1112 searchParams->setSortBy(SearchParams::SortByNewest);
1115 search(searchParams);
1118 void MediaView::updateSubscriptionAction(Video *video, bool subscribed) {
1119 QAction *subscribeAction = The::globalActions()->value("subscribe-channel");
1121 QString subscribeTip;
1122 QString subscribeText;
1124 subscribeText = subscribeAction->property("originalText").toString();
1125 subscribeAction->setEnabled(false);
1126 } else if (subscribed) {
1127 subscribeText = tr("Unsubscribe from %1").arg(video->channelTitle());
1128 subscribeTip = subscribeText;
1129 subscribeAction->setEnabled(true);
1131 subscribeText = tr("Subscribe to %1").arg(video->channelTitle());
1132 subscribeTip = subscribeText;
1133 subscribeAction->setEnabled(true);
1135 subscribeAction->setText(subscribeText);
1136 subscribeAction->setStatusTip(subscribeTip);
1140 static QIcon tintedIcon;
1141 if (tintedIcon.isNull()) {
1143 sizes << QSize(16, 16);
1144 tintedIcon = IconUtils::tintedIcon("bookmark-new", QColor(254, 240, 0), sizes);
1146 subscribeAction->setIcon(tintedIcon);
1148 subscribeAction->setIcon(IconUtils::icon("bookmark-remove"));
1151 subscribeAction->setIcon(IconUtils::icon("bookmark-new"));
1154 IconUtils::setupAction(subscribeAction);
1157 void MediaView::toggleSubscription() {
1158 Video *video = playlistModel->activeVideo();
1160 QString userId = video->channelId();
1161 if (userId.isEmpty()) return;
1162 bool subscribed = YTChannel::isSubscribed(userId);
1163 if (subscribed) YTChannel::unsubscribe(userId);
1164 else YTChannel::subscribe(userId);
1165 updateSubscriptionAction(video, !subscribed);
1168 void MediaView::adjustWindowSize() {
1169 if (!MainWindow::instance()->isMaximized() && !MainWindow::instance()->isFullScreen()) {
1170 const double ratio = 16. / 9.;
1171 const int w = videoAreaWidget->width();
1172 const int h = videoAreaWidget->height();
1173 const double currentVideoRatio = (double)w / (double)h;
1174 if (currentVideoRatio != ratio) {
1175 if (false && currentVideoRatio > ratio) {
1176 // we have vertical black bars
1177 int newWidth = (MainWindow::instance()->width() - w) + (h * ratio);
1178 MainWindow::instance()->resize(newWidth, MainWindow::instance()->height());
1180 // horizontal black bars
1181 int newHeight = (MainWindow::instance()->height() - h) + (w / ratio);
1182 MainWindow::instance()->resize(MainWindow::instance()->width(), newHeight);