]> git.sur5r.net Git - minitube/blob - src/mediaview.cpp
Removed debug statements
[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) : View(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 = qobject_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 #else
404     Phonon::SeekSlider *slider = MainWindow::instance()->getSeekSlider();
405 #endif
406
407     if (snapshotSettings) {
408         delete snapshotSettings;
409         snapshotSettings = 0;
410     }
411 }
412
413 const QString & MediaView::getCurrentVideoId() {
414     return currentVideoId;
415 }
416
417 void MediaView::activeRowChanged(int row) {
418     if (stopped) return;
419
420     errorTimer->stop();
421
422 #ifdef APP_PHONON
423     mediaObject->stop();
424 #endif
425     if (downloadItem) {
426         downloadItem->stop();
427         delete downloadItem;
428         downloadItem = 0;
429         currentVideoSize = 0;
430     }
431
432     Video *video = playlistModel->videoAt(row);
433     if (!video) return;
434
435     videoAreaWidget->showLoading(video);
436
437     connect(video, SIGNAL(gotStreamUrl(QUrl)),
438             SLOT(gotStreamUrl(QUrl)), Qt::UniqueConnection);
439     connect(video, SIGNAL(errorStreamUrl(QString)),
440             SLOT(skip()), Qt::UniqueConnection);
441     video->loadStreamUrl();
442
443     // video title in titlebar
444     MainWindow::instance()->setWindowTitle(video->title() + " - " + Constants::NAME);
445
446     // ensure active item is visible
447     if (row != -1) {
448         QModelIndex index = playlistModel->index(row, 0, QModelIndex());
449         playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
450     }
451
452     // enable/disable actions
453     The::globalActions()->value("download")->setEnabled(
454                 DownloadManager::instance()->itemForVideo(video) == 0);
455     The::globalActions()->value("previous")->setEnabled(row > 0);
456     The::globalActions()->value("stopafterthis")->setEnabled(true);
457     The::globalActions()->value("related-videos")->setEnabled(true);
458
459     bool enableDownload = video->license() == Video::LicenseCC;
460 #ifdef APP_ACTIVATION
461     enableDownload = enableDownload || Activation::instance().isLegacy();
462 #endif
463 #ifdef APP_DOWNLOADS
464     enableDownload = true;
465 #endif
466     QAction *a = The::globalActions()->value("download");
467     a->setEnabled(enableDownload);
468     a->setVisible(enableDownload);
469
470     updateSubscriptionAction(video, YTChannel::isSubscribed(video->channelId()));
471
472     foreach (QAction *action, currentVideoActions)
473         action->setEnabled(true);
474
475 #ifndef APP_PHONON_SEEK
476     QSlider *slider = MainWindow::instance()->getSlider();
477     slider->setEnabled(false);
478     slider->setValue(0);
479 #endif
480
481     if (snapshotSettings) {
482         delete snapshotSettings;
483         snapshotSettings = 0;
484         MainWindow::instance()->adjustStatusBarVisibility();
485     }
486
487     // see you in gotStreamUrl...
488 }
489
490 void MediaView::gotStreamUrl(QUrl streamUrl) {
491     if (stopped) return;
492     if (!streamUrl.isValid()) {
493         skip();
494         return;
495     }
496
497     Video *video = static_cast<Video *>(sender());
498     if (!video) {
499         qDebug() << "Cannot get sender in" << __PRETTY_FUNCTION__;
500         return;
501     }
502     video->disconnect(this);
503
504     currentVideoId = video->id();
505
506 #ifdef APP_PHONON_SEEK
507     mediaObject->setCurrentSource(streamUrl);
508     mediaObject->play();
509 #else
510     startDownloading();
511 #endif
512
513     // ensure we always have videos ahead
514     playlistModel->searchNeeded();
515
516     // ensure active item is visible
517     int row = playlistModel->activeRow();
518     if (row != -1) {
519         QModelIndex index = playlistModel->index(row, 0, QModelIndex());
520         playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
521     }
522
523 #ifdef APP_ACTIVATION
524     if (!Activation::instance().isActivated())
525         demoTimer->start(180000);
526 #endif
527
528 #ifdef APP_EXTRA
529     Extra::notify(video->title(), video->channelTitle(), video->formattedDuration());
530 #endif
531
532     ChannelAggregator::instance()->videoWatched(video);
533 }
534
535 void MediaView::downloadStatusChanged() {
536     // qDebug() << __PRETTY_FUNCTION__;
537     switch(downloadItem->status()) {
538     case Downloading:
539         // qDebug() << "Downloading";
540         if (downloadItem->offset() == 0) startPlaying();
541         else {
542 #ifdef APP_PHONON
543             // qDebug() << "Seeking to" << downloadItem->offset();
544             mediaObject->seek(offsetToTime(downloadItem->offset()));
545             mediaObject->play();
546 #endif
547         }
548         break;
549     case Starting:
550         // qDebug() << "Starting";
551         break;
552     case Finished:
553         // qDebug() << "Finished" << mediaObject->state();
554 #ifdef APP_PHONON_SEEK
555         MainWindow::instance()->getSeekSlider()->setEnabled(mediaObject->isSeekable());
556 #endif
557         break;
558     case Failed:
559         // qDebug() << "Failed";
560         skip();
561         break;
562     case Idle:
563         // qDebug() << "Idle";
564         break;
565     }
566 }
567
568 void MediaView::startPlaying() {
569     // qDebug() << __PRETTY_FUNCTION__;
570     if (stopped) return;
571     if (!downloadItem) {
572         skip();
573         return;
574     }
575
576     if (downloadItem->offset() == 0) {
577         currentVideoSize = downloadItem->bytesTotal();
578         // qDebug() << "currentVideoSize" << currentVideoSize;
579     }
580
581     // go!
582     QString source = downloadItem->currentFilename();
583     qDebug() << "Playing" << source << QFile::exists(source);
584 #ifdef APP_PHONON
585     mediaObject->setCurrentSource(QUrl::fromLocalFile(source));
586     mediaObject->play();
587 #endif
588 #ifdef APP_PHONON_SEEK
589     MainWindow::instance()->getSeekSlider()->setEnabled(false);
590 #else
591     QSlider *slider = MainWindow::instance()->getSlider();
592     slider->setEnabled(true);
593 #endif
594 }
595
596 void MediaView::itemActivated(const QModelIndex &index) {
597     if (playlistModel->rowExists(index.row())) {
598
599         // if it's the current video, just rewind and play
600         Video *activeVideo = playlistModel->activeVideo();
601         Video *video = playlistModel->videoAt(index.row());
602         if (activeVideo && video && activeVideo == video) {
603             // mediaObject->seek(0);
604             sliderMoved(0);
605 #ifdef APP_PHONON
606             mediaObject->play();
607 #endif
608         } else playlistModel->setActiveRow(index.row());
609
610         // the user doubleclicked on the "Search More" item
611     } else {
612         playlistModel->searchMore();
613         playlistView->selectionModel()->clearSelection();
614     }
615 }
616
617 void MediaView::skipVideo() {
618     // skippedVideo is useful for DELAYED skip operations
619     // in order to be sure that we're skipping the video we wanted
620     // and not another one
621     if (skippedVideo) {
622         if (playlistModel->activeVideo() != skippedVideo) {
623             qDebug() << "Skip of video canceled";
624             return;
625         }
626         int nextRow = playlistModel->rowForVideo(skippedVideo);
627         nextRow++;
628         if (nextRow == -1) return;
629         playlistModel->setActiveRow(nextRow);
630     }
631 }
632
633 void MediaView::skip() {
634     int nextRow = playlistModel->nextRow();
635     if (nextRow == -1) return;
636     playlistModel->setActiveRow(nextRow);
637 }
638
639 void MediaView::skipBackward() {
640     int prevRow = playlistModel->previousRow();
641     if (prevRow == -1) return;
642     playlistModel->setActiveRow(prevRow);
643 }
644
645 void MediaView::aboutToFinish() {
646 #ifdef APP_PHONON
647     qint64 currentTime = mediaObject->currentTime();
648     qint64 totalTime = mediaObject->totalTime();
649     // qDebug() << __PRETTY_FUNCTION__ << currentTime << totalTime;
650     if (totalTime < 1 || currentTime + 10000 < totalTime) {
651         // QTimer::singleShot(500, this, SLOT(playbackResume()));
652         mediaObject->seek(currentTime);
653         mediaObject->play();
654     }
655 #endif
656 }
657
658 void MediaView::playbackFinished() {
659     if (stopped) return;
660
661 #ifdef APP_PHONON
662     const qint64 totalTime = mediaObject->totalTime();
663     const qint64 currentTime = mediaObject->currentTime();
664     // qDebug() << __PRETTY_FUNCTION__ << mediaObject->currentTime() << totalTime;
665     // add 10 secs for imprecise Phonon backends (VLC, Xine)
666     if (currentTime > 0 && currentTime + 10000 < totalTime) {
667         // mediaObject->seek(currentTime);
668         QTimer::singleShot(500, this, SLOT(playbackResume()));
669     } else {
670         QAction* stopAfterThisAction = The::globalActions()->value("stopafterthis");
671         if (stopAfterThisAction->isChecked()) {
672             stopAfterThisAction->setChecked(false);
673         } else skip();
674     }
675 #endif
676 }
677
678 void MediaView::playbackResume() {
679     if (stopped) return;
680 #ifdef APP_PHONON
681     const qint64 currentTime = mediaObject->currentTime();
682     // qDebug() << __PRETTY_FUNCTION__ << currentTime;
683     if (currentTime > 0)
684         mediaObject->seek(currentTime);
685     mediaObject->play();
686 #endif
687 }
688
689 void MediaView::openWebPage() {
690     Video* video = playlistModel->activeVideo();
691     if (!video) return;
692 #ifdef APP_PHONON
693     mediaObject->pause();
694 #endif
695     QString url = video->webpage() + QLatin1String("&t=") + QString::number(mediaObject->currentTime() / 1000);
696     QDesktopServices::openUrl(url);
697 }
698
699 void MediaView::copyWebPage() {
700     Video* video = playlistModel->activeVideo();
701     if (!video) return;
702     QString address = video->webpage();
703     QApplication::clipboard()->setText(address);
704     QString message = tr("You can now paste the YouTube link into another application");
705     MainWindow::instance()->showMessage(message);
706 }
707
708 void MediaView::copyVideoLink() {
709     Video* video = playlistModel->activeVideo();
710     if (!video) return;
711     QApplication::clipboard()->setText(video->getStreamUrl().toEncoded());
712     QString message = tr("You can now paste the video stream URL into another application")
713             + ". " + tr("The link will be valid only for a limited time.");
714     MainWindow::instance()->showMessage(message);
715 }
716
717 void MediaView::openInBrowser() {
718     Video* video = playlistModel->activeVideo();
719     if (!video) return;
720 #ifdef APP_PHONON
721     mediaObject->pause();
722 #endif
723     QDesktopServices::openUrl(video->getStreamUrl());
724 }
725
726 void MediaView::removeSelected() {
727     if (!playlistView->selectionModel()->hasSelection()) return;
728     QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
729     playlistModel->removeIndexes(indexes);
730 }
731
732 void MediaView::selectVideos(QList<Video*> videos) {
733     foreach (Video *video, videos) {
734         QModelIndex index = playlistModel->indexForVideo(video);
735         playlistView->selectionModel()->select(index, QItemSelectionModel::Select);
736         playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
737     }
738 }
739
740 void MediaView::selectionChanged(const QItemSelection & /*selected*/,
741                                  const QItemSelection & /*deselected*/) {
742     const bool gotSelection = playlistView->selectionModel()->hasSelection();
743     The::globalActions()->value("remove")->setEnabled(gotSelection);
744     The::globalActions()->value("moveUp")->setEnabled(gotSelection);
745     The::globalActions()->value("moveDown")->setEnabled(gotSelection);
746 }
747
748 void MediaView::moveUpSelected() {
749     if (!playlistView->selectionModel()->hasSelection()) return;
750
751     QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
752     qStableSort(indexes.begin(), indexes.end());
753     playlistModel->move(indexes, true);
754
755     // set current index after row moves to something more intuitive
756     int row = indexes.first().row();
757     playlistView->selectionModel()->setCurrentIndex(playlistModel->index(row>1?row:1),
758                                                     QItemSelectionModel::NoUpdate);
759 }
760
761 void MediaView::moveDownSelected() {
762     if (!playlistView->selectionModel()->hasSelection()) return;
763
764     QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
765     qStableSort(indexes.begin(), indexes.end(), qGreater<QModelIndex>());
766     playlistModel->move(indexes, false);
767
768     // set current index after row moves to something more intuitive
769     // (respect 1 static item on bottom)
770     int row = indexes.first().row()+1, max = playlistModel->rowCount() - 2;
771     playlistView->selectionModel()->setCurrentIndex(
772                 playlistModel->index(row>max?max:row), QItemSelectionModel::NoUpdate);
773 }
774
775 void MediaView::setPlaylistVisible(bool visible) {
776     if (splitter->widget(0)->isVisible() == visible) return;
777     splitter->widget(0)->setVisible(visible);
778     playlistView->setFocus();
779 }
780
781 bool MediaView::isPlaylistVisible() {
782     return splitter->widget(0)->isVisible();
783 }
784
785 void MediaView::saveSplitterState() {
786     QSettings settings;
787     settings.setValue("splitter", splitter->saveState());
788 }
789
790 #ifdef APP_ACTIVATION
791
792 static QPushButton *continueButton;
793
794 void MediaView::demoMessage() {
795 #ifdef APP_PHONON
796     if (mediaObject->state() != Phonon::PlayingState) return;
797     mediaObject->pause();
798 #endif
799
800     QMessageBox msgBox(this);
801     msgBox.setIconPixmap(IconUtils::pixmap(":/images/app.png").scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
802     msgBox.setText(tr("This is just the demo version of %1.").arg(Constants::NAME));
803     msgBox.setInformativeText(tr("It allows you to test the application and see if it works for you."));
804     msgBox.setModal(true);
805     // make it a "sheet" on the Mac
806     msgBox.setWindowModality(Qt::WindowModal);
807
808     continueButton = msgBox.addButton("5", QMessageBox::RejectRole);
809     continueButton->setEnabled(false);
810     QPushButton *buyButton = msgBox.addButton(tr("Get the full version"), QMessageBox::ActionRole);
811
812     QTimeLine *timeLine = new QTimeLine(6000, this);
813     timeLine->setCurveShape(QTimeLine::LinearCurve);
814     timeLine->setFrameRange(5, 0);
815     connect(timeLine, SIGNAL(frameChanged(int)), SLOT(updateContinueButton(int)));
816     timeLine->start();
817
818     msgBox.exec();
819
820     if (msgBox.clickedButton() == buyButton) {
821         MainWindow::instance()->showActivationView();
822     } else {
823 #ifdef APP_PHONON
824         mediaObject->play();
825 #endif
826         demoTimer->start(600000);
827     }
828
829     delete timeLine;
830
831 }
832
833 void MediaView::updateContinueButton(int value) {
834     if (value == 0) {
835         continueButton->setText(tr("Continue"));
836         continueButton->setEnabled(true);
837     } else {
838         continueButton->setText(QString::number(value));
839     }
840 }
841
842 #endif
843
844 void MediaView::downloadVideo() {
845     Video* video = playlistModel->activeVideo();
846     if (!video) return;
847     DownloadManager::instance()->addItem(video);
848     MainWindow::instance()->showActionInStatusBar(The::globalActions()->value("downloads"), true);
849     QString message = tr("Downloading %1").arg(video->title());
850     MainWindow::instance()->showMessage(message);
851 }
852
853 #ifdef APP_SNAPSHOT
854 void MediaView::snapshot() {
855     qint64 currentTime = mediaObject->currentTime() / 1000;
856
857     QImage image = videoWidget->snapshot();
858     if (image.isNull()) {
859         qWarning() << "Null snapshot";
860         return;
861     }
862
863     // QPixmap pixmap = QPixmap::grabWindow(videoWidget->winId());
864     QPixmap pixmap = QPixmap::fromImage(image.scaled(videoWidget->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
865     videoAreaWidget->showSnapshotPreview(pixmap);
866
867     Video* video = playlistModel->activeVideo();
868     if (!video) return;
869
870     QString location = SnapshotSettings::getCurrentLocation();
871     QDir dir(location);
872     if (!dir.exists()) dir.mkpath(location);
873     QString basename = video->title();
874     QString format = video->duration() > 3600 ? "h_mm_ss" : "m_ss";
875     basename += " (" + QTime().addSecs(currentTime).toString(format) + ")";
876     basename = DataUtils::stringToFilename(basename);
877     QString filename = location + "/" + basename + ".png";
878     qDebug() << filename;
879     image.save(filename, "PNG");
880
881     if (snapshotSettings) delete snapshotSettings;
882     snapshotSettings = new SnapshotSettings(videoWidget);
883     snapshotSettings->setSnapshot(pixmap, filename);
884     QStatusBar *statusBar = MainWindow::instance()->statusBar();
885 #ifdef APP_EXTRA
886     Extra::fadeInWidget(statusBar, statusBar);
887 #endif
888     statusBar->insertPermanentWidget(0, snapshotSettings);
889     snapshotSettings->show();
890     MainWindow::instance()->setStatusBarVisibility(true);
891 }
892 #endif
893
894 void MediaView::fullscreen() {
895     videoAreaWidget->setParent(0);
896     videoAreaWidget->showFullScreen();
897 }
898
899 void MediaView::startDownloading() {
900     Video *video = playlistModel->activeVideo();
901     if (!video) return;
902     Video *videoCopy = video->clone();
903     if (downloadItem) {
904         downloadItem->stop();
905         delete downloadItem;
906     }
907     QString tempFile = Temporary::filename();
908     downloadItem = new DownloadItem(videoCopy, video->getStreamUrl(), tempFile, this);
909     connect(downloadItem, SIGNAL(statusChanged()),
910             SLOT(downloadStatusChanged()), Qt::UniqueConnection);
911     connect(downloadItem, SIGNAL(bufferProgress(int)),
912             loadingWidget, SLOT(bufferStatus(int)), Qt::UniqueConnection);
913     // connect(downloadItem, SIGNAL(finished()), SLOT(itemFinished()));
914     connect(video, SIGNAL(errorStreamUrl(QString)),
915             SLOT(handleError(QString)), Qt::UniqueConnection);
916     connect(downloadItem, SIGNAL(error(QString)),
917             SLOT(handleError(QString)), Qt::UniqueConnection);
918     downloadItem->start();
919 }
920
921 void MediaView::resumeWithNewStreamUrl(const QUrl &streamUrl) {
922     pauseTime = mediaObject->currentTime();
923     mediaObject->setCurrentSource(streamUrl);
924     mediaObject->play();
925
926     Video *video = static_cast<Video *>(sender());
927     if (!video) {
928         qDebug() << "Cannot get sender in" << __PRETTY_FUNCTION__;
929         return;
930     }
931     video->disconnect(this);
932 }
933
934 void MediaView::maybeAdjustWindowSize() {
935     QSettings settings;
936     if (settings.value("adjustWindowSize", true).toBool())
937         adjustWindowSize();
938 }
939
940 void MediaView::sliderMoved(int value) {
941     Q_UNUSED(value);
942 #ifdef APP_PHONON
943 #ifndef APP_PHONON_SEEK
944
945     if (currentVideoSize <= 0 || !downloadItem || !mediaObject->isSeekable())
946         return;
947
948     QSlider *slider = MainWindow::instance()->getSlider();
949     if (slider->isSliderDown()) return;
950
951     qint64 offset = (currentVideoSize * value) / slider->maximum();
952
953     bool needsDownload = downloadItem->needsDownload(offset);
954     if (needsDownload) {
955         if (downloadItem->isBuffered(offset)) {
956             qint64 realOffset = downloadItem->blankAtOffset(offset);
957             if (offset < currentVideoSize)
958                 downloadItem->seekTo(realOffset, false);
959             mediaObject->seek(offsetToTime(offset));
960         } else {
961             mediaObject->pause();
962             downloadItem->seekTo(offset);
963         }
964     } else {
965         // qDebug() << "simple seek";
966         mediaObject->seek(offsetToTime(offset));
967     }
968 #endif
969 #endif
970 }
971
972 qint64 MediaView::offsetToTime(qint64 offset) {
973 #ifdef APP_PHONON
974     const qint64 totalTime = mediaObject->totalTime();
975     return ((offset * totalTime) / currentVideoSize);
976 #endif
977 }
978
979 void MediaView::findVideoParts() {
980
981     // parts
982     Video* video = playlistModel->activeVideo();
983     if (!video) return;
984
985     QString query = video->title();
986
987     static QString optionalSpace = "\\s*";
988     static QString staticCounterSeparators = "[\\/\\-]";
989     QString counterSeparators = "( of | " +
990             tr("of", "Used in video parts, as in '2 of 3'") +
991             " |" + staticCounterSeparators + ")";
992
993     // numbers from 1 to 15
994     static QString counterNumber = "([1-9]|1[0-5])";
995
996     // query.remove(QRegExp(counterSeparators + optionalSpace + counterNumber));
997     query.remove(QRegExp(counterNumber + optionalSpace +
998                          counterSeparators + optionalSpace + counterNumber));
999     query.remove(wordRE("pr?t\\.?" + optionalSpace + counterNumber));
1000     query.remove(wordRE("ep\\.?" + optionalSpace + counterNumber));
1001     query.remove(wordRE("part" + optionalSpace + counterNumber));
1002     query.remove(wordRE("episode" + optionalSpace + counterNumber));
1003     query.remove(wordRE(tr("part", "This is for video parts, as in 'Cool video - part 1'") +
1004                         optionalSpace + counterNumber));
1005     query.remove(wordRE(tr("episode",
1006                            "This is for video parts, as in 'Cool series - episode 1'") +
1007                         optionalSpace + counterNumber));
1008     query.remove(QRegExp("[\\(\\)\\[\\]]"));
1009
1010 #define NUMBERS "one|two|three|four|five|six|seven|eight|nine|ten"
1011
1012     QRegExp englishNumberRE = QRegExp(QLatin1String(".*(") + NUMBERS + ").*",
1013                                       Qt::CaseInsensitive);
1014     // bool numberAsWords = englishNumberRE.exactMatch(query);
1015     query.remove(englishNumberRE);
1016
1017     QRegExp localizedNumberRE = QRegExp(QLatin1String(".*(") + tr(NUMBERS) + ").*",
1018                                         Qt::CaseInsensitive);
1019     // if (!numberAsWords) numberAsWords = localizedNumberRE.exactMatch(query);
1020     query.remove(localizedNumberRE);
1021
1022     SearchParams *searchParams = new SearchParams();
1023     searchParams->setTransient(true);
1024     searchParams->setKeywords(query);
1025     searchParams->setChannelId(video->channelId());
1026
1027     /*
1028     if (!numberAsWords) {
1029         qDebug() << "We don't have number as words";
1030         // searchParams->setSortBy(SearchParams::SortByNewest);
1031         // TODO searchParams->setReverseOrder(true);
1032         // TODO searchParams->setMax(50);
1033     }
1034     */
1035
1036     search(searchParams);
1037
1038 }
1039
1040 void MediaView::relatedVideos() {
1041     Video* video = playlistModel->activeVideo();
1042     if (!video) return;
1043     YTSingleVideoSource *singleVideoSource = new YTSingleVideoSource();
1044     singleVideoSource->setVideo(video->clone());
1045     singleVideoSource->setAsyncDetails(true);
1046     setVideoSource(singleVideoSource);
1047     The::globalActions()->value("related-videos")->setEnabled(false);
1048 }
1049
1050 void MediaView::shareViaTwitter() {
1051     Video* video = playlistModel->activeVideo();
1052     if (!video) return;
1053     QUrl url("https://twitter.com/intent/tweet");
1054     {
1055         QUrlQueryHelper urlHelper(url);
1056         urlHelper.addQueryItem("via", "minitubeapp");
1057         urlHelper.addQueryItem("text", video->title());
1058         urlHelper.addQueryItem("url", video->webpage());
1059     }
1060     QDesktopServices::openUrl(url);
1061 }
1062
1063 void MediaView::shareViaFacebook() {
1064     Video* video = playlistModel->activeVideo();
1065     if (!video) return;
1066     QUrl url("https://www.facebook.com/sharer.php");
1067     {
1068         QUrlQueryHelper urlHelper(url);
1069         urlHelper.addQueryItem("t", video->title());
1070         urlHelper.addQueryItem("u", video->webpage());
1071     }
1072     QDesktopServices::openUrl(url);
1073 }
1074
1075 void MediaView::shareViaBuffer() {
1076     Video* video = playlistModel->activeVideo();
1077     if (!video) return;
1078     QUrl url("http://bufferapp.com/add");
1079     {
1080         QUrlQueryHelper urlHelper(url);
1081         urlHelper.addQueryItem("via", "minitubeapp");
1082         urlHelper.addQueryItem("text", video->title());
1083         urlHelper.addQueryItem("url", video->webpage());
1084         urlHelper.addQueryItem("picture", video->thumbnailUrl());
1085     }
1086     QDesktopServices::openUrl(url);
1087 }
1088
1089 void MediaView::shareViaEmail() {
1090     Video* video = playlistModel->activeVideo();
1091     if (!video) return;
1092     QUrl url("mailto:");
1093     {
1094         QUrlQueryHelper urlHelper(url);
1095         urlHelper.addQueryItem("subject", video->title());
1096         const QString body = video->title() + "\n" +
1097                 video->webpage() + "\n\n" +
1098                 tr("Sent from %1").arg(Constants::NAME) + "\n" +
1099                 Constants::WEBSITE;
1100         urlHelper.addQueryItem("body", body);
1101     }
1102     QDesktopServices::openUrl(url);
1103 }
1104
1105 void MediaView::authorPushed(QModelIndex index) {
1106     Video* video = playlistModel->videoAt(index.row());
1107     if (!video) return;
1108
1109     QString channelId = video->channelId();
1110     // if (channelId.isEmpty()) channelId = video->channelTitle();
1111     if (channelId.isEmpty()) return;
1112
1113     SearchParams *searchParams = new SearchParams();
1114     searchParams->setChannelId(channelId);
1115     searchParams->setSortBy(SearchParams::SortByNewest);
1116
1117     // go!
1118     search(searchParams);
1119 }
1120
1121 void MediaView::updateSubscriptionAction(Video *video, bool subscribed) {
1122     QAction *subscribeAction = The::globalActions()->value("subscribe-channel");
1123
1124     QString subscribeTip;
1125     QString subscribeText;
1126     if (!video) {
1127         subscribeText = subscribeAction->property("originalText").toString();
1128         subscribeAction->setEnabled(false);
1129     } else if (subscribed) {
1130         subscribeText = tr("Unsubscribe from %1").arg(video->channelTitle());
1131         subscribeTip = subscribeText;
1132         subscribeAction->setEnabled(true);
1133     } else {
1134         subscribeText = tr("Subscribe to %1").arg(video->channelTitle());
1135         subscribeTip = subscribeText;
1136         subscribeAction->setEnabled(true);
1137     }
1138     subscribeAction->setText(subscribeText);
1139     subscribeAction->setStatusTip(subscribeTip);
1140
1141     if (subscribed) {
1142 #ifdef APP_LINUX
1143         static QIcon tintedIcon;
1144         if (tintedIcon.isNull()) {
1145             QList<QSize> sizes;
1146             sizes << QSize(16, 16);
1147             tintedIcon = IconUtils::tintedIcon("bookmark-new", QColor(254, 240, 0), sizes);
1148         }
1149         subscribeAction->setIcon(tintedIcon);
1150 #else
1151         subscribeAction->setIcon(IconUtils::icon("bookmark-remove"));
1152 #endif
1153     } else {
1154         subscribeAction->setIcon(IconUtils::icon("bookmark-new"));
1155     }
1156
1157     IconUtils::setupAction(subscribeAction);
1158 }
1159
1160 void MediaView::toggleSubscription() {
1161     Video *video = playlistModel->activeVideo();
1162     if (!video) return;
1163     QString userId = video->channelId();
1164     if (userId.isEmpty()) return;
1165     bool subscribed = YTChannel::isSubscribed(userId);
1166     if (subscribed) {
1167         YTChannel::unsubscribe(userId);
1168         MainWindow::instance()->showMessage(tr("Unsubscribed from %1").arg(video->channelTitle()));
1169     } else {
1170         YTChannel::subscribe(userId);
1171         MainWindow::instance()->showMessage(tr("Subscribed to %1").arg(video->channelTitle()));
1172     }
1173     updateSubscriptionAction(video, !subscribed);
1174 }
1175
1176 void MediaView::adjustWindowSize() {
1177     if (!MainWindow::instance()->isMaximized() && !MainWindow::instance()->isFullScreen()) {
1178         const double ratio = 16. / 9.;
1179         const int w = videoAreaWidget->width();
1180         const int h = videoAreaWidget->height();
1181         const double currentVideoRatio = (double)w / (double)h;
1182         if (currentVideoRatio != ratio) {
1183             if (false && currentVideoRatio > ratio) {
1184                 // we have vertical black bars
1185                 int newWidth = (MainWindow::instance()->width() - w) + (h * ratio);
1186                 MainWindow::instance()->resize(newWidth, MainWindow::instance()->height());
1187             } else {
1188                 // horizontal black bars
1189                 int newHeight = (MainWindow::instance()->height() - h) + (w / ratio);
1190                 MainWindow::instance()->resize(MainWindow::instance()->width(), newHeight);
1191             }
1192         }
1193     }
1194 }