]> git.sur5r.net Git - minitube/blob - src/mediaview.cpp
332753416f6984fafe20799359e1ae936635676d
[minitube] / src / mediaview.cpp
1 /* $BEGIN_LICENSE
2
3 This file is part of Minitube.
4 Copyright 2009, Flavio Tordini <flavio.tordini@gmail.com>
5
6 Minitube is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 Minitube is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Minitube.  If not, see <http://www.gnu.org/licenses/>.
18
19 $END_LICENSE */
20
21 #include "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"
36 #ifdef APP_ACTIVATION
37 #include "activation.h"
38 #endif
39 #ifdef APP_EXTRA
40 #include "extra.h"
41 #endif
42 #include "videosource.h"
43 #include "ytsearch.h"
44 #include "searchparams.h"
45 #include "ytsinglevideosource.h"
46 #include "channelaggregator.h"
47 #include "iconutils.h"
48 #include "ytchannel.h"
49 #ifdef APP_SNAPSHOT
50 #include "snapshotsettings.h"
51 #endif
52 #include "datautils.h"
53 #include "compatibility/qurlqueryhelper.h"
54
55 namespace The {
56 NetworkAccess* http();
57 QHash<QString, QAction*>* globalActions();
58 QHash<QString, QMenu*>* globalMenus();
59 QNetworkAccessManager* networkAccessManager();
60 }
61
62 MediaView* MediaView::instance() {
63     static MediaView *i = new MediaView();
64     return i;
65 }
66
67 MediaView::MediaView(QWidget *parent) : QWidget(parent)
68   , stopped(false)
69   , downloadItem(0)
70   #ifdef APP_SNAPSHOT
71   , snapshotSettings(0)
72   #endif
73   , pauseTime(0)
74 { }
75
76 void MediaView::initialize() {
77     QBoxLayout *layout = new QVBoxLayout(this);
78     layout->setMargin(0);
79
80     splitter = new MiniSplitter();
81
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 &)));
86
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);
94
95     connect(playlistView->selectionModel(),
96             SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
97             SLOT(selectionChanged(const QItemSelection &, const QItemSelection &)));
98
99     connect(playlistView, SIGNAL(authorPushed(QModelIndex)), SLOT(authorPushed(QModelIndex)));
100
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);
110
111     videoAreaWidget = new VideoAreaWidget(this);
112     // videoAreaWidget->setMinimumSize(320,240);
113
114 #ifdef APP_PHONON
115     videoWidget = new Phonon::VideoWidget(this);
116     videoAreaWidget->setVideoWidget(videoWidget);
117 #endif
118     videoAreaWidget->setListModel(playlistModel);
119
120     loadingWidget = new LoadingWidget(this);
121     videoAreaWidget->setLoadingWidget(loadingWidget);
122
123     splitter->addWidget(videoAreaWidget);
124
125     splitter->setStretchFactor(0, 0);
126     splitter->setStretchFactor(1, 8);
127
128     // restore splitter state
129     QSettings settings;
130     splitter->restoreState(settings.value("splitter").toByteArray());
131     splitter->setChildrenCollapsible(false);
132     connect(splitter, SIGNAL(splitterMoved(int,int)), SLOT(maybeAdjustWindowSize()));
133
134     layout->addWidget(splitter);
135
136     errorTimer = new QTimer(this);
137     errorTimer->setSingleShot(true);
138     errorTimer->setInterval(3000);
139     connect(errorTimer, SIGNAL(timeout()), SLOT(skipVideo()));
140
141 #ifdef APP_ACTIVATION
142     demoTimer = new QTimer(this);
143     demoTimer->setSingleShot(true);
144     connect(demoTimer, SIGNAL(timeout()), SLOT(demoMessage()));
145 #endif
146
147     connect(videoAreaWidget, SIGNAL(doubleClicked()),
148             The::globalActions()->value("fullscreen"), SLOT(trigger()));
149
150     QAction* refineSearchAction = The::globalActions()->value("refine-search");
151     connect(refineSearchAction, SIGNAL(toggled(bool)),
152             sidebar, SLOT(toggleRefineSearch(bool)));
153
154     currentVideoActions
155             << The::globalActions()->value("webpage")
156             << The::globalActions()->value("pagelink")
157             << The::globalActions()->value("videolink")
158             << The::globalActions()->value("open-in-browser")
159            #ifdef APP_SNAPSHOT
160             << The::globalActions()->value("snapshot")
161            #endif
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");
172
173 #ifndef APP_PHONON_SEEK
174     QSlider *slider = MainWindow::instance()->getSlider();
175     connect(slider, SIGNAL(valueChanged(int)), SLOT(sliderMoved(int)));
176 #endif
177 }
178
179 #ifdef APP_PHONON
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()));
187 }
188 #endif
189
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();
195     }
196     return 0;
197 }
198
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);
208                 return;
209             }
210         }
211     }
212     YTSearch *ytSearch = new YTSearch(searchParams, this);
213     ytSearch->setAsyncDetails(true);
214     connect(ytSearch, SIGNAL(gotDetails()), playlistModel, SLOT(emitDataChanged()));
215     setVideoSource(ytSearch);
216 }
217
218 void MediaView::setVideoSource(VideoSource *videoSource, bool addToHistory, bool back) {
219     Q_UNUSED(back);
220     stopped = false;
221
222 #ifdef APP_ACTIVATION
223     demoTimer->stop();
224 #endif
225     errorTimer->stop();
226
227     // qDebug() << "Adding VideoSource" << videoSource->getName() << videoSource;
228
229     if (addToHistory) {
230         int currentIndex = getHistoryIndex();
231         if (currentIndex >= 0 && currentIndex < history.size() - 1) {
232             while (history.size() > currentIndex + 1) {
233                 VideoSource *vs = history.takeLast();
234                 if (!vs->parent()) {
235                     qDebug() << "Deleting VideoSource" << vs->getName() << vs;
236                     delete vs;
237                 }
238             }
239         }
240         history.append(videoSource);
241     }
242
243 #ifdef APP_EXTRA
244     if (history.size() > 1)
245         Extra::slideTransition(playlistView->viewport(), playlistView->viewport(), back);
246 #endif
247
248     playlistModel->setVideoSource(videoSource);
249
250     sidebar->showPlaylist();
251     sidebar->getRefineSearchWidget()->setSearchParams(getSearchParams());
252     sidebar->hideSuggestions();
253     sidebar->getHeader()->updateInfo();
254
255     SearchParams *searchParams = getSearchParams();
256     bool isChannel = searchParams && !searchParams->channelId().isEmpty();
257     playlistView->setClickableAuthors(!isChannel);
258
259
260 }
261
262 void MediaView::searchAgain() {
263     VideoSource *currentVideoSource = playlistModel->getVideoSource();
264     setVideoSource(currentVideoSource, false);
265 }
266
267 bool MediaView::canGoBack() {
268     return getHistoryIndex() > 0;
269 }
270
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);
277         }
278     }
279 }
280
281 bool MediaView::canGoForward() {
282     int currentIndex = getHistoryIndex();
283     return currentIndex >= 0 && currentIndex < history.size() - 1;
284 }
285
286 void MediaView::goForward() {
287     if (canGoForward()) {
288         int currentIndex = getHistoryIndex();
289         VideoSource *nextVideoSource = history.at(currentIndex + 1);
290         setVideoSource(nextVideoSource, false);
291     }
292 }
293
294 int MediaView::getHistoryIndex() {
295     return history.lastIndexOf(playlistModel->getVideoSource());
296 }
297
298 void MediaView::appear() {
299     Video *currentVideo = playlistModel->activeVideo();
300     if (currentVideo) {
301         MainWindow::instance()->setWindowTitle(
302                     currentVideo->title() + " - " + Constants::NAME);
303     }
304
305     // optimize window for 16:9 video
306     QTimer::singleShot(50, this, SLOT(maybeAdjustWindowSize()));
307
308     playlistView->setFocus();
309 }
310
311 void MediaView::disappear() {
312
313 }
314
315 void MediaView::handleError(const QString &message) {
316     qWarning() << __PRETTY_FUNCTION__ << message;
317 #ifdef APP_PHONON_SEEK
318     mediaObject->play();
319 #else
320     QTimer::singleShot(500, this, SLOT(startPlaying()));
321 #endif
322 }
323
324 #ifdef APP_PHONON
325 void MediaView::stateChanged(Phonon::State newState, Phonon::State /*oldState*/) {
326     if (pauseTime > 0 && (newState == Phonon::PlayingState || newState == Phonon::BufferingState)) {
327         mediaObject->seek(pauseTime);
328         pauseTime = 0;
329     }
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());
336     }
337 }
338 #endif
339
340 void MediaView::pause() {
341 #ifdef APP_PHONON
342     switch( mediaObject->state() ) {
343     case Phonon::PlayingState:
344         mediaObject->pause();
345         pauseTimer.start();
346         break;
347     default:
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();
353         break;
354     }
355 #endif
356 }
357
358 QRegExp MediaView::wordRE(const QString &s) {
359     return QRegExp("\\W" + s + "\\W?", Qt::CaseInsensitive);
360 }
361
362 void MediaView::stop() {
363     stopped = true;
364
365     while (!history.isEmpty()) {
366         VideoSource *videoSource = history.takeFirst();
367         if (!videoSource->parent()) delete videoSource;
368     }
369
370     playlistModel->abortSearch();
371     videoAreaWidget->clear();
372     videoAreaWidget->update();
373     errorTimer->stop();
374     playlistView->selectionModel()->clearSelection();
375     if (downloadItem) {
376         downloadItem->stop();
377         delete downloadItem;
378         downloadItem = 0;
379         currentVideoSize = 0;
380     }
381     The::globalActions()->value("refine-search")->setChecked(false);
382     updateSubscriptionAction(0, false);
383 #ifdef APP_ACTIVATION
384     demoTimer->stop();
385 #endif
386
387     foreach (QAction *action, currentVideoActions)
388         action->setEnabled(false);
389
390     QAction *a = The::globalActions()->value("download");
391     a->setEnabled(false);
392     a->setVisible(false);
393
394 #ifdef APP_PHONON
395     mediaObject->stop();
396 #endif
397     currentVideoId.clear();
398
399 #ifndef APP_PHONON_SEEK
400     QSlider *slider = MainWindow::instance()->getSlider();
401     slider->setEnabled(false);
402     slider->setValue(0);
403 #endif
404
405     if (snapshotSettings) {
406         delete snapshotSettings;
407         snapshotSettings = 0;
408     }
409 }
410
411 const QString & MediaView::getCurrentVideoId() {
412     return currentVideoId;
413 }
414
415 void MediaView::activeRowChanged(int row) {
416     if (stopped) return;
417
418     errorTimer->stop();
419
420 #ifdef APP_PHONON
421     mediaObject->stop();
422 #endif
423     if (downloadItem) {
424         downloadItem->stop();
425         delete downloadItem;
426         downloadItem = 0;
427         currentVideoSize = 0;
428     }
429
430     Video *video = playlistModel->videoAt(row);
431     if (!video) return;
432
433     videoAreaWidget->showLoading(video);
434
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();
440
441     // video title in titlebar
442     MainWindow::instance()->setWindowTitle(video->title() + " - " + Constants::NAME);
443
444     // ensure active item is visible
445     if (row != -1) {
446         QModelIndex index = playlistModel->index(row, 0, QModelIndex());
447         playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
448     }
449
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);
456
457     bool enableDownload = video->license() == Video::LicenseCC;
458 #ifdef APP_ACTIVATION
459     enableDownload = enableDownload || Activation::instance().isLegacy();
460 #endif
461 #ifdef APP_DOWNLOADS
462     enableDownload = true;
463 #endif
464     QAction *a = The::globalActions()->value("download");
465     a->setEnabled(enableDownload);
466     a->setVisible(enableDownload);
467
468     updateSubscriptionAction(video, YTChannel::isSubscribed(video->channelId()));
469
470     foreach (QAction *action, currentVideoActions)
471         action->setEnabled(true);
472
473 #ifndef APP_PHONON_SEEK
474     QSlider *slider = MainWindow::instance()->getSlider();
475     slider->setEnabled(false);
476     slider->setValue(0);
477 #endif
478
479     if (snapshotSettings) {
480         delete snapshotSettings;
481         snapshotSettings = 0;
482         MainWindow::instance()->adjustStatusBarVisibility();
483     }
484
485     // see you in gotStreamUrl...
486 }
487
488 void MediaView::gotStreamUrl(QUrl streamUrl) {
489     if (stopped) return;
490     if (!streamUrl.isValid()) {
491         skip();
492         return;
493     }
494
495     Video *video = static_cast<Video *>(sender());
496     if (!video) {
497         qDebug() << "Cannot get sender in" << __PRETTY_FUNCTION__;
498         return;
499     }
500     video->disconnect(this);
501
502     currentVideoId = video->id();
503
504 #ifdef APP_PHONON_SEEK
505     mediaObject->setCurrentSource(streamUrl);
506     mediaObject->play();
507 #else
508     startDownloading();
509 #endif
510
511     // ensure we always have videos ahead
512     playlistModel->searchNeeded();
513
514     // ensure active item is visible
515     int row = playlistModel->activeRow();
516     if (row != -1) {
517         QModelIndex index = playlistModel->index(row, 0, QModelIndex());
518         playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
519     }
520
521 #ifdef APP_ACTIVATION
522     if (!Activation::instance().isActivated())
523         demoTimer->start(180000);
524 #endif
525
526 #ifdef APP_EXTRA
527     Extra::notify(video->title(), video->channelTitle(), video->formattedDuration());
528 #endif
529
530     ChannelAggregator::instance()->videoWatched(video);
531 }
532
533 void MediaView::downloadStatusChanged() {
534     // qDebug() << __PRETTY_FUNCTION__;
535     switch(downloadItem->status()) {
536     case Downloading:
537         // qDebug() << "Downloading";
538         if (downloadItem->offset() == 0) startPlaying();
539         else {
540 #ifdef APP_PHONON
541             // qDebug() << "Seeking to" << downloadItem->offset();
542             mediaObject->seek(offsetToTime(downloadItem->offset()));
543             mediaObject->play();
544 #endif
545         }
546         break;
547     case Starting:
548         // qDebug() << "Starting";
549         break;
550     case Finished:
551         // qDebug() << "Finished" << mediaObject->state();
552 #ifdef APP_PHONON_SEEK
553         MainWindow::instance()->getSeekSlider()->setEnabled(mediaObject->isSeekable());
554 #endif
555         break;
556     case Failed:
557         // qDebug() << "Failed";
558         skip();
559         break;
560     case Idle:
561         // qDebug() << "Idle";
562         break;
563     }
564 }
565
566 void MediaView::startPlaying() {
567     // qDebug() << __PRETTY_FUNCTION__;
568     if (stopped) return;
569     if (!downloadItem) {
570         skip();
571         return;
572     }
573
574     if (downloadItem->offset() == 0) {
575         currentVideoSize = downloadItem->bytesTotal();
576         // qDebug() << "currentVideoSize" << currentVideoSize;
577     }
578
579     // go!
580     QString source = downloadItem->currentFilename();
581     qDebug() << "Playing" << source << QFile::exists(source);
582 #ifdef APP_PHONON
583     mediaObject->setCurrentSource(QUrl::fromLocalFile(source));
584     mediaObject->play();
585 #endif
586 #ifdef APP_PHONON_SEEK
587     MainWindow::instance()->getSeekSlider()->setEnabled(false);
588 #else
589     QSlider *slider = MainWindow::instance()->getSlider();
590     slider->setEnabled(true);
591 #endif
592 }
593
594 void MediaView::itemActivated(const QModelIndex &index) {
595     if (playlistModel->rowExists(index.row())) {
596
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);
602             sliderMoved(0);
603 #ifdef APP_PHONON
604             mediaObject->play();
605 #endif
606         } else playlistModel->setActiveRow(index.row());
607
608         // the user doubleclicked on the "Search More" item
609     } else {
610         playlistModel->searchMore();
611         playlistView->selectionModel()->clearSelection();
612     }
613 }
614
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
619     if (skippedVideo) {
620         if (playlistModel->activeVideo() != skippedVideo) {
621             qDebug() << "Skip of video canceled";
622             return;
623         }
624         int nextRow = playlistModel->rowForVideo(skippedVideo);
625         nextRow++;
626         if (nextRow == -1) return;
627         playlistModel->setActiveRow(nextRow);
628     }
629 }
630
631 void MediaView::skip() {
632     int nextRow = playlistModel->nextRow();
633     if (nextRow == -1) return;
634     playlistModel->setActiveRow(nextRow);
635 }
636
637 void MediaView::skipBackward() {
638     int prevRow = playlistModel->previousRow();
639     if (prevRow == -1) return;
640     playlistModel->setActiveRow(prevRow);
641 }
642
643 void MediaView::aboutToFinish() {
644 #ifdef APP_PHONON
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);
651         mediaObject->play();
652     }
653 #endif
654 }
655
656 void MediaView::playbackFinished() {
657     if (stopped) return;
658
659 #ifdef APP_PHONON
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()));
667     } else {
668         QAction* stopAfterThisAction = The::globalActions()->value("stopafterthis");
669         if (stopAfterThisAction->isChecked()) {
670             stopAfterThisAction->setChecked(false);
671         } else skip();
672     }
673 #endif
674 }
675
676 void MediaView::playbackResume() {
677     if (stopped) return;
678 #ifdef APP_PHONON
679     const qint64 currentTime = mediaObject->currentTime();
680     qDebug() << __PRETTY_FUNCTION__ << currentTime;
681     if (currentTime > 0)
682         mediaObject->seek(currentTime);
683     mediaObject->play();
684 #endif
685 }
686
687 void MediaView::openWebPage() {
688     Video* video = playlistModel->activeVideo();
689     if (!video) return;
690 #ifdef APP_PHONON
691     mediaObject->pause();
692 #endif
693     QString url = video->webpage() + QLatin1String("&t=") + QString::number(mediaObject->currentTime() / 1000);
694     QDesktopServices::openUrl(url);
695 }
696
697 void MediaView::copyWebPage() {
698     Video* video = playlistModel->activeVideo();
699     if (!video) return;
700     QString address = video->webpage();
701     QApplication::clipboard()->setText(address);
702     QString message = tr("You can now paste the YouTube link into another application");
703     MainWindow::instance()->showMessage(message);
704 }
705
706 void MediaView::copyVideoLink() {
707     Video* video = playlistModel->activeVideo();
708     if (!video) return;
709     QApplication::clipboard()->setText(video->getStreamUrl().toEncoded());
710     QString message = tr("You can now paste the video stream URL into another application")
711             + ". " + tr("The link will be valid only for a limited time.");
712     MainWindow::instance()->showMessage(message);
713 }
714
715 void MediaView::openInBrowser() {
716     Video* video = playlistModel->activeVideo();
717     if (!video) return;
718 #ifdef APP_PHONON
719     mediaObject->pause();
720 #endif
721     QDesktopServices::openUrl(video->getStreamUrl());
722 }
723
724 void MediaView::removeSelected() {
725     if (!playlistView->selectionModel()->hasSelection()) return;
726     QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
727     playlistModel->removeIndexes(indexes);
728 }
729
730 void MediaView::selectVideos(QList<Video*> videos) {
731     foreach (Video *video, videos) {
732         QModelIndex index = playlistModel->indexForVideo(video);
733         playlistView->selectionModel()->select(index, QItemSelectionModel::Select);
734         playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
735     }
736 }
737
738 void MediaView::selectionChanged(const QItemSelection & /*selected*/,
739                                  const QItemSelection & /*deselected*/) {
740     const bool gotSelection = playlistView->selectionModel()->hasSelection();
741     The::globalActions()->value("remove")->setEnabled(gotSelection);
742     The::globalActions()->value("moveUp")->setEnabled(gotSelection);
743     The::globalActions()->value("moveDown")->setEnabled(gotSelection);
744 }
745
746 void MediaView::moveUpSelected() {
747     if (!playlistView->selectionModel()->hasSelection()) return;
748
749     QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
750     qStableSort(indexes.begin(), indexes.end());
751     playlistModel->move(indexes, true);
752
753     // set current index after row moves to something more intuitive
754     int row = indexes.first().row();
755     playlistView->selectionModel()->setCurrentIndex(playlistModel->index(row>1?row:1),
756                                                     QItemSelectionModel::NoUpdate);
757 }
758
759 void MediaView::moveDownSelected() {
760     if (!playlistView->selectionModel()->hasSelection()) return;
761
762     QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
763     qStableSort(indexes.begin(), indexes.end(), qGreater<QModelIndex>());
764     playlistModel->move(indexes, false);
765
766     // set current index after row moves to something more intuitive
767     // (respect 1 static item on bottom)
768     int row = indexes.first().row()+1, max = playlistModel->rowCount() - 2;
769     playlistView->selectionModel()->setCurrentIndex(
770                 playlistModel->index(row>max?max:row), QItemSelectionModel::NoUpdate);
771 }
772
773 void MediaView::setPlaylistVisible(bool visible) {
774     if (splitter->widget(0)->isVisible() == visible) return;
775     splitter->widget(0)->setVisible(visible);
776     playlistView->setFocus();
777 }
778
779 bool MediaView::isPlaylistVisible() {
780     return splitter->widget(0)->isVisible();
781 }
782
783 void MediaView::saveSplitterState() {
784     QSettings settings;
785     settings.setValue("splitter", splitter->saveState());
786 }
787
788 #ifdef APP_ACTIVATION
789
790 static QPushButton *continueButton;
791
792 void MediaView::demoMessage() {
793 #ifdef APP_PHONON
794     if (mediaObject->state() != Phonon::PlayingState) return;
795     mediaObject->pause();
796 #endif
797
798     QMessageBox msgBox(this);
799     msgBox.setIconPixmap(QPixmap(":/images/app.png").scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
800     msgBox.setText(tr("This is just the demo version of %1.").arg(Constants::NAME));
801     msgBox.setInformativeText(tr("It allows you to test the application and see if it works for you."));
802     msgBox.setModal(true);
803     // make it a "sheet" on the Mac
804     msgBox.setWindowModality(Qt::WindowModal);
805
806     continueButton = msgBox.addButton("5", QMessageBox::RejectRole);
807     continueButton->setEnabled(false);
808     QPushButton *buyButton = msgBox.addButton(tr("Get the full version"), QMessageBox::ActionRole);
809
810     QTimeLine *timeLine = new QTimeLine(6000, this);
811     timeLine->setCurveShape(QTimeLine::LinearCurve);
812     timeLine->setFrameRange(5, 0);
813     connect(timeLine, SIGNAL(frameChanged(int)), SLOT(updateContinueButton(int)));
814     timeLine->start();
815
816     msgBox.exec();
817
818     if (msgBox.clickedButton() == buyButton) {
819         MainWindow::instance()->showActivationView();
820     } else {
821 #ifdef APP_PHONON
822         mediaObject->play();
823 #endif
824         demoTimer->start(600000);
825     }
826
827     delete timeLine;
828
829 }
830
831 void MediaView::updateContinueButton(int value) {
832     if (value == 0) {
833         continueButton->setText(tr("Continue"));
834         continueButton->setEnabled(true);
835     } else {
836         continueButton->setText(QString::number(value));
837     }
838 }
839
840 #endif
841
842 void MediaView::downloadVideo() {
843     Video* video = playlistModel->activeVideo();
844     if (!video) return;
845     DownloadManager::instance()->addItem(video);
846     MainWindow::instance()->showActionInStatusBar(The::globalActions()->value("downloads"), true);
847     QString message = tr("Downloading %1").arg(video->title());
848     MainWindow::instance()->showMessage(message);
849 }
850
851 #ifdef APP_SNAPSHOT
852 void MediaView::snapshot() {
853     qint64 currentTime = mediaObject->currentTime() / 1000;
854
855     QImage image = videoWidget->snapshot();
856     if (image.isNull()) {
857         qWarning() << "Null snapshot";
858         return;
859     }
860
861     // QPixmap pixmap = QPixmap::grabWindow(videoWidget->winId());
862     QPixmap pixmap = QPixmap::fromImage(image.scaled(videoWidget->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
863     videoAreaWidget->showSnapshotPreview(pixmap);
864
865     Video* video = playlistModel->activeVideo();
866     if (!video) return;
867
868     QString location = SnapshotSettings::getCurrentLocation();
869     QDir dir(location);
870     if (!dir.exists()) dir.mkpath(location);
871     QString basename = video->title();
872     QString format = video->duration() > 3600 ? "h_mm_ss" : "m_ss";
873     basename += " (" + QTime().addSecs(currentTime).toString(format) + ")";
874     basename = DataUtils::stringToFilename(basename);
875     QString filename = location + "/" + basename + ".png";
876     qDebug() << filename;
877     image.save(filename, "PNG");
878
879     if (snapshotSettings) delete snapshotSettings;
880     snapshotSettings = new SnapshotSettings(videoWidget);
881     snapshotSettings->setSnapshot(pixmap, filename);
882     QStatusBar *statusBar = MainWindow::instance()->statusBar();
883 #ifdef APP_EXTRA
884     Extra::fadeInWidget(statusBar, statusBar);
885 #endif
886     statusBar->insertPermanentWidget(0, snapshotSettings);
887     snapshotSettings->show();
888     MainWindow::instance()->setStatusBarVisibility(true);
889 }
890 #endif
891
892 void MediaView::fullscreen() {
893     videoAreaWidget->setParent(0);
894     videoAreaWidget->showFullScreen();
895 }
896
897 void MediaView::startDownloading() {
898     Video *video = playlistModel->activeVideo();
899     if (!video) return;
900     Video *videoCopy = video->clone();
901     if (downloadItem) {
902         downloadItem->stop();
903         delete downloadItem;
904     }
905     QString tempFile = Temporary::filename();
906     downloadItem = new DownloadItem(videoCopy, video->getStreamUrl(), tempFile, this);
907     connect(downloadItem, SIGNAL(statusChanged()),
908             SLOT(downloadStatusChanged()), Qt::UniqueConnection);
909     connect(downloadItem, SIGNAL(bufferProgress(int)),
910             loadingWidget, SLOT(bufferStatus(int)), Qt::UniqueConnection);
911     // connect(downloadItem, SIGNAL(finished()), SLOT(itemFinished()));
912     connect(video, SIGNAL(errorStreamUrl(QString)),
913             SLOT(handleError(QString)), Qt::UniqueConnection);
914     connect(downloadItem, SIGNAL(error(QString)),
915             SLOT(handleError(QString)), Qt::UniqueConnection);
916     downloadItem->start();
917 }
918
919 void MediaView::resumeWithNewStreamUrl(const QUrl &streamUrl) {
920     pauseTime = mediaObject->currentTime();
921     mediaObject->setCurrentSource(streamUrl);
922     mediaObject->play();
923
924     Video *video = static_cast<Video *>(sender());
925     if (!video) {
926         qDebug() << "Cannot get sender in" << __PRETTY_FUNCTION__;
927         return;
928     }
929     video->disconnect(this);
930 }
931
932 void MediaView::maybeAdjustWindowSize() {
933     QSettings settings;
934     if (settings.value("adjustWindowSize", true).toBool())
935         adjustWindowSize();
936 }
937
938 void MediaView::sliderMoved(int value) {
939     Q_UNUSED(value);
940 #ifdef APP_PHONON
941 #ifndef APP_PHONON_SEEK
942
943     if (currentVideoSize <= 0 || !downloadItem || !mediaObject->isSeekable())
944         return;
945
946     QSlider *slider = MainWindow::instance()->getSlider();
947     if (slider->isSliderDown()) return;
948
949     qint64 offset = (currentVideoSize * value) / slider->maximum();
950
951     bool needsDownload = downloadItem->needsDownload(offset);
952     if (needsDownload) {
953         if (downloadItem->isBuffered(offset)) {
954             qint64 realOffset = downloadItem->blankAtOffset(offset);
955             if (offset < currentVideoSize)
956                 downloadItem->seekTo(realOffset, false);
957             mediaObject->seek(offsetToTime(offset));
958         } else {
959             mediaObject->pause();
960             downloadItem->seekTo(offset);
961         }
962     } else {
963         // qDebug() << "simple seek";
964         mediaObject->seek(offsetToTime(offset));
965     }
966 #endif
967 #endif
968 }
969
970 qint64 MediaView::offsetToTime(qint64 offset) {
971 #ifdef APP_PHONON
972     const qint64 totalTime = mediaObject->totalTime();
973     return ((offset * totalTime) / currentVideoSize);
974 #endif
975 }
976
977 void MediaView::findVideoParts() {
978
979     // parts
980     Video* video = playlistModel->activeVideo();
981     if (!video) return;
982
983     QString query = video->title();
984
985     static QString optionalSpace = "\\s*";
986     static QString staticCounterSeparators = "[\\/\\-]";
987     QString counterSeparators = "( of | " +
988             tr("of", "Used in video parts, as in '2 of 3'") +
989             " |" + staticCounterSeparators + ")";
990
991     // numbers from 1 to 15
992     static QString counterNumber = "([1-9]|1[0-5])";
993
994     // query.remove(QRegExp(counterSeparators + optionalSpace + counterNumber));
995     query.remove(QRegExp(counterNumber + optionalSpace +
996                          counterSeparators + optionalSpace + counterNumber));
997     query.remove(wordRE("pr?t\\.?" + optionalSpace + counterNumber));
998     query.remove(wordRE("ep\\.?" + optionalSpace + counterNumber));
999     query.remove(wordRE("part" + optionalSpace + counterNumber));
1000     query.remove(wordRE("episode" + optionalSpace + counterNumber));
1001     query.remove(wordRE(tr("part", "This is for video parts, as in 'Cool video - part 1'") +
1002                         optionalSpace + counterNumber));
1003     query.remove(wordRE(tr("episode",
1004                            "This is for video parts, as in 'Cool series - episode 1'") +
1005                         optionalSpace + counterNumber));
1006     query.remove(QRegExp("[\\(\\)\\[\\]]"));
1007
1008 #define NUMBERS "one|two|three|four|five|six|seven|eight|nine|ten"
1009
1010     QRegExp englishNumberRE = QRegExp(QLatin1String(".*(") + NUMBERS + ").*",
1011                                       Qt::CaseInsensitive);
1012     // bool numberAsWords = englishNumberRE.exactMatch(query);
1013     query.remove(englishNumberRE);
1014
1015     QRegExp localizedNumberRE = QRegExp(QLatin1String(".*(") + tr(NUMBERS) + ").*",
1016                                         Qt::CaseInsensitive);
1017     // if (!numberAsWords) numberAsWords = localizedNumberRE.exactMatch(query);
1018     query.remove(localizedNumberRE);
1019
1020     SearchParams *searchParams = new SearchParams();
1021     searchParams->setTransient(true);
1022     searchParams->setKeywords(query);
1023     searchParams->setChannelId(video->channelId());
1024
1025     /*
1026     if (!numberAsWords) {
1027         qDebug() << "We don't have number as words";
1028         // searchParams->setSortBy(SearchParams::SortByNewest);
1029         // TODO searchParams->setReverseOrder(true);
1030         // TODO searchParams->setMax(50);
1031     }
1032     */
1033
1034     search(searchParams);
1035
1036 }
1037
1038 void MediaView::relatedVideos() {
1039     Video* video = playlistModel->activeVideo();
1040     if (!video) return;
1041     YTSingleVideoSource *singleVideoSource = new YTSingleVideoSource();
1042     singleVideoSource->setVideo(video->clone());
1043     singleVideoSource->setAsyncDetails(true);
1044     setVideoSource(singleVideoSource);
1045     The::globalActions()->value("related-videos")->setEnabled(false);
1046 }
1047
1048 void MediaView::shareViaTwitter() {
1049     Video* video = playlistModel->activeVideo();
1050     if (!video) return;
1051     QUrl url("https://twitter.com/intent/tweet");
1052     {
1053         QUrlQueryHelper urlHelper(url);
1054         urlHelper.addQueryItem("via", "minitubeapp");
1055         urlHelper.addQueryItem("text", video->title());
1056         urlHelper.addQueryItem("url", video->webpage());
1057     }
1058     QDesktopServices::openUrl(url);
1059 }
1060
1061 void MediaView::shareViaFacebook() {
1062     Video* video = playlistModel->activeVideo();
1063     if (!video) return;
1064     QUrl url("https://www.facebook.com/sharer.php");
1065     {
1066         QUrlQueryHelper urlHelper(url);
1067         urlHelper.addQueryItem("t", video->title());
1068         urlHelper.addQueryItem("u", video->webpage());
1069     }
1070     QDesktopServices::openUrl(url);
1071 }
1072
1073 void MediaView::shareViaBuffer() {
1074     Video* video = playlistModel->activeVideo();
1075     if (!video) return;
1076     QUrl url("http://bufferapp.com/add");
1077     {
1078         QUrlQueryHelper urlHelper(url);
1079         urlHelper.addQueryItem("via", "minitubeapp");
1080         urlHelper.addQueryItem("text", video->title());
1081         urlHelper.addQueryItem("url", video->webpage());
1082         urlHelper.addQueryItem("picture", video->thumbnailUrl());
1083     }
1084     QDesktopServices::openUrl(url);
1085 }
1086
1087 void MediaView::shareViaEmail() {
1088     Video* video = playlistModel->activeVideo();
1089     if (!video) return;
1090     QUrl url("mailto:");
1091     {
1092         QUrlQueryHelper urlHelper(url);
1093         urlHelper.addQueryItem("subject", video->title());
1094         const QString body = video->title() + "\n" +
1095                 video->webpage() + "\n\n" +
1096                 tr("Sent from %1").arg(Constants::NAME) + "\n" +
1097                 Constants::WEBSITE;
1098         urlHelper.addQueryItem("body", body);
1099     }
1100     QDesktopServices::openUrl(url);
1101 }
1102
1103 void MediaView::authorPushed(QModelIndex index) {
1104     Video* video = playlistModel->videoAt(index.row());
1105     if (!video) return;
1106
1107     QString channelId = video->channelId();
1108     // if (channelId.isEmpty()) channelId = video->channelTitle();
1109     if (channelId.isEmpty()) return;
1110
1111     SearchParams *searchParams = new SearchParams();
1112     searchParams->setChannelId(channelId);
1113     searchParams->setSortBy(SearchParams::SortByNewest);
1114
1115     // go!
1116     search(searchParams);
1117 }
1118
1119 void MediaView::updateSubscriptionAction(Video *video, bool subscribed) {
1120     QAction *subscribeAction = The::globalActions()->value("subscribe-channel");
1121
1122     QString subscribeTip;
1123     QString subscribeText;
1124     if (!video) {
1125         subscribeText = subscribeAction->property("originalText").toString();
1126         subscribeAction->setEnabled(false);
1127     } else if (subscribed) {
1128         subscribeText = tr("Unsubscribe from %1").arg(video->channelTitle());
1129         subscribeTip = subscribeText;
1130         subscribeAction->setEnabled(true);
1131     } else {
1132         subscribeText = tr("Subscribe to %1").arg(video->channelTitle());
1133         subscribeTip = subscribeText;
1134         subscribeAction->setEnabled(true);
1135     }
1136     subscribeAction->setText(subscribeText);
1137     subscribeAction->setStatusTip(subscribeTip);
1138
1139     if (subscribed) {
1140 #ifdef APP_LINUX
1141         static QIcon tintedIcon;
1142         if (tintedIcon.isNull()) {
1143             QList<QSize> sizes;
1144             sizes << QSize(16, 16);
1145             tintedIcon = IconUtils::tintedIcon("bookmark-new", QColor(254, 240, 0), sizes);
1146         }
1147         subscribeAction->setIcon(tintedIcon);
1148 #else
1149         subscribeAction->setIcon(IconUtils::icon("bookmark-remove"));
1150 #endif
1151     } else {
1152         subscribeAction->setIcon(IconUtils::icon("bookmark-new"));
1153     }
1154
1155     IconUtils::setupAction(subscribeAction);
1156 }
1157
1158 void MediaView::toggleSubscription() {
1159     Video *video = playlistModel->activeVideo();
1160     if (!video) return;
1161     QString userId = video->channelId();
1162     if (userId.isEmpty()) return;
1163     bool subscribed = YTChannel::isSubscribed(userId);
1164     if (subscribed) {
1165         YTChannel::unsubscribe(userId);
1166         MainWindow::instance()->showMessage(tr("Unsubscribed from %1").arg(video->channelTitle()));
1167     } else {
1168         YTChannel::subscribe(userId);
1169         MainWindow::instance()->showMessage(tr("Subscribed to %1").arg(video->channelTitle()));
1170     }
1171     updateSubscriptionAction(video, !subscribed);
1172 }
1173
1174 void MediaView::adjustWindowSize() {
1175     if (!MainWindow::instance()->isMaximized() && !MainWindow::instance()->isFullScreen()) {
1176         const double ratio = 16. / 9.;
1177         const int w = videoAreaWidget->width();
1178         const int h = videoAreaWidget->height();
1179         const double currentVideoRatio = (double)w / (double)h;
1180         if (currentVideoRatio != ratio) {
1181             if (false && currentVideoRatio > ratio) {
1182                 // we have vertical black bars
1183                 int newWidth = (MainWindow::instance()->width() - w) + (h * ratio);
1184                 MainWindow::instance()->resize(newWidth, MainWindow::instance()->height());
1185             } else {
1186                 // horizontal black bars
1187                 int newHeight = (MainWindow::instance()->height() - h) + (w / ratio);
1188                 MainWindow::instance()->resize(MainWindow::instance()->width(), newHeight);
1189             }
1190         }
1191     }
1192 }