]> git.sur5r.net Git - minitube/blob - src/mediaview.cpp
Imported Upstream version 2.0
[minitube] / src / mediaview.cpp
1 #include "mediaview.h"
2 #include "playlistmodel.h"
3 #include "playlistview.h"
4 #include "loadingwidget.h"
5 #include "videoareawidget.h"
6 #include "networkaccess.h"
7 #include "videowidget.h"
8 #include "minisplitter.h"
9 #include "constants.h"
10 #include "downloadmanager.h"
11 #include "downloaditem.h"
12 #include "mainwindow.h"
13 #include "temporary.h"
14 #include "refinesearchwidget.h"
15 #include "sidebarwidget.h"
16 #include "sidebarheader.h"
17 #ifdef APP_MAC
18 #include "macfullscreen.h"
19 #include "macutils.h"
20 #endif
21 #ifdef APP_ACTIVATION
22 #include "activation.h"
23 #endif
24 #include "videosource.h"
25 #include "ytsearch.h"
26 #include "searchparams.h"
27 #include "ytsinglevideosource.h"
28
29 namespace The {
30 NetworkAccess* http();
31 QHash<QString, QAction*>* globalActions();
32 QMap<QString, QMenu*>* globalMenus();
33 QNetworkAccessManager* networkAccessManager();
34 }
35
36 MediaView* MediaView::instance() {
37     static MediaView *i = new MediaView();
38     return i;
39 }
40
41 MediaView::MediaView(QWidget *parent) : QWidget(parent) {
42     reallyStopped = false;
43     downloadItem = 0;
44
45     QBoxLayout *layout = new QVBoxLayout(this);
46     layout->setMargin(0);
47
48     splitter = new MiniSplitter();
49     splitter->setChildrenCollapsible(false);
50
51     playlistView = new PlaylistView(this);
52     // respond to the user doubleclicking a playlist item
53     connect(playlistView, SIGNAL(activated(const QModelIndex &)),
54             SLOT(itemActivated(const QModelIndex &)));
55
56     playlistModel = new PlaylistModel();
57     connect(playlistModel, SIGNAL(activeRowChanged(int)),
58             SLOT(activeRowChanged(int)));
59     // needed to restore the selection after dragndrop
60     connect(playlistModel, SIGNAL(needSelectionFor(QList<Video*>)),
61             SLOT(selectVideos(QList<Video*>)));
62     playlistView->setModel(playlistModel);
63
64     connect(playlistView->selectionModel(),
65             SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
66             SLOT(selectionChanged(const QItemSelection &, const QItemSelection &)));
67
68     connect(playlistView, SIGNAL(authorPushed(QModelIndex)), SLOT(authorPushed(QModelIndex)));
69
70     sidebar = new SidebarWidget(this);
71     sidebar->setPlaylist(playlistView);
72     connect(sidebar->getRefineSearchWidget(), SIGNAL(searchRefined()),
73             SLOT(searchAgain()));
74     connect(playlistModel, SIGNAL(haveSuggestions(const QStringList &)),
75             sidebar, SLOT(showSuggestions(const QStringList &)));
76     connect(sidebar, SIGNAL(suggestionAccepted(QString)),
77             MainWindow::instance(), SLOT(startToolbarSearch(QString)));
78     splitter->addWidget(sidebar);
79
80     videoAreaWidget = new VideoAreaWidget(this);
81     videoAreaWidget->setMinimumSize(320,240);
82     videoWidget = new Phonon::VideoWidget(this);
83     videoAreaWidget->setVideoWidget(videoWidget);
84     videoAreaWidget->setListModel(playlistModel);
85
86     loadingWidget = new LoadingWidget(this);
87     videoAreaWidget->setLoadingWidget(loadingWidget);
88
89     splitter->addWidget(videoAreaWidget);
90
91     layout->addWidget(splitter);
92
93     splitter->setStretchFactor(0, 1);
94     splitter->setStretchFactor(1, 5);
95
96     // restore splitter state
97     QSettings settings;
98     splitter->restoreState(settings.value("splitter").toByteArray());
99
100     errorTimer = new QTimer(this);
101     errorTimer->setSingleShot(true);
102     errorTimer->setInterval(3000);
103     connect(errorTimer, SIGNAL(timeout()), SLOT(skipVideo()));
104
105 #ifdef APP_ACTIVATION
106     demoTimer = new QTimer(this);
107     demoTimer->setSingleShot(true);
108     connect(demoTimer, SIGNAL(timeout()), SLOT(demoMessage()));
109 #endif
110
111 }
112
113 void MediaView::initialize() {
114     connect(videoAreaWidget, SIGNAL(doubleClicked()),
115             The::globalActions()->value("fullscreen"), SLOT(trigger()));
116
117     QAction* refineSearchAction = The::globalActions()->value("refine-search");
118     connect(refineSearchAction, SIGNAL(toggled(bool)),
119             sidebar, SLOT(toggleRefineSearch(bool)));
120 }
121
122 void MediaView::setMediaObject(Phonon::MediaObject *mediaObject) {
123     this->mediaObject = mediaObject;
124     Phonon::createPath(mediaObject, videoWidget);
125     connect(mediaObject, SIGNAL(finished()), SLOT(playbackFinished()));
126     connect(mediaObject, SIGNAL(stateChanged(Phonon::State, Phonon::State)),
127             SLOT(stateChanged(Phonon::State, Phonon::State)));
128     connect(mediaObject, SIGNAL(currentSourceChanged(Phonon::MediaSource)),
129             SLOT(currentSourceChanged(Phonon::MediaSource)));
130     connect(mediaObject, SIGNAL(aboutToFinish()), SLOT(aboutToFinish()));
131 }
132
133 SearchParams* MediaView::getSearchParams() {
134     VideoSource *videoSource = playlistModel->getVideoSource();
135     if (videoSource && videoSource->metaObject()->className() == QLatin1String("YTSearch")) {
136         YTSearch *search = dynamic_cast<YTSearch *>(videoSource);
137         return search->getSearchParams();
138     }
139     return 0;
140 }
141
142 void MediaView::search(SearchParams *searchParams) {
143     if (!searchParams->keywords().isEmpty()) {
144         if (searchParams->keywords().startsWith("http://") ||
145                 searchParams->keywords().startsWith("https://")) {
146             QString videoId = YTSearch::videoIdFromUrl(searchParams->keywords());
147             if (!videoId.isEmpty()) {
148                 YTSingleVideoSource *singleVideoSource = new YTSingleVideoSource(this);
149                 singleVideoSource->setVideoId(videoId);
150                 setVideoSource(singleVideoSource);
151                 return;
152             }
153         }
154     }
155     setVideoSource(new YTSearch(searchParams, this));
156 }
157
158 void MediaView::setVideoSource(VideoSource *videoSource, bool addToHistory) {
159     reallyStopped = false;
160
161 #ifdef APP_ACTIVATION
162     demoTimer->stop();
163 #endif
164     errorTimer->stop();
165
166     if (addToHistory) {
167         int currentIndex = getHistoryIndex();
168         if (currentIndex >= 0 && currentIndex < history.size() - 1) {
169             while (history.size() > currentIndex + 1) {
170                 VideoSource *vs = history.takeLast();
171                 if (!vs->parent()) delete vs;
172             }
173         }
174         history.append(videoSource);
175     }
176
177     playlistModel->setVideoSource(videoSource);
178
179     sidebar->showPlaylist();
180     sidebar->getRefineSearchWidget()->setSearchParams(getSearchParams());
181     sidebar->hideSuggestions();
182     sidebar->getHeader()->updateInfo();
183
184     SearchParams *searchParams = getSearchParams();
185     bool isChannel = searchParams && !searchParams->author().isEmpty();
186     playlistView->setClickableAuthors(!isChannel);
187
188     The::globalActions()->value("related-videos")->setEnabled(true);
189 }
190
191 void MediaView::searchAgain() {
192     VideoSource *currentVideoSource = playlistModel->getVideoSource();
193     setVideoSource(currentVideoSource, false);
194 }
195
196 bool MediaView::canGoBack() {
197     return getHistoryIndex() > 0;
198 }
199
200 void MediaView::goBack() {
201     if (history.size() > 1) {
202         int currentIndex = getHistoryIndex();
203         if (currentIndex > 0) {
204             VideoSource *previousVideoSource = history.at(currentIndex - 1);
205             setVideoSource(previousVideoSource, false);
206         }
207     }
208 }
209
210 bool MediaView::canGoForward() {
211     int currentIndex = getHistoryIndex();
212     return currentIndex >= 0 && currentIndex < history.size() - 1;
213 }
214
215 void MediaView::goForward() {
216     if (canGoForward()) {
217         int currentIndex = getHistoryIndex();
218         VideoSource *nextVideoSource = history.at(currentIndex + 1);
219         setVideoSource(nextVideoSource, false);
220     }
221 }
222
223 int MediaView::getHistoryIndex() {
224     return history.lastIndexOf(playlistModel->getVideoSource());
225 }
226
227 void MediaView::appear() {
228     playlistView->setFocus();
229 }
230
231 void MediaView::disappear() {
232
233 }
234
235 void MediaView::handleError(QString /* message */) {
236     QTimer::singleShot(500, this, SLOT(startPlaying()));
237 }
238
239 void MediaView::stateChanged(Phonon::State newState, Phonon::State /*oldState*/) {
240     if (newState == Phonon::PlayingState)
241         videoAreaWidget->showVideo();
242     else if (newState == Phonon::ErrorState) {
243         qDebug() << "Phonon error:" << mediaObject->errorString() << mediaObject->errorType();
244         if (mediaObject->errorType() == Phonon::FatalError)
245             handleError(mediaObject->errorString());
246     }
247 }
248
249 void MediaView::pause() {
250     switch( mediaObject->state() ) {
251     case Phonon::PlayingState:
252         mediaObject->pause();
253         break;
254     default:
255         mediaObject->play();
256         break;
257     }
258 }
259
260 QRegExp MediaView::wordRE(QString s) {
261     return QRegExp("\\W" + s + "\\W?", Qt::CaseInsensitive);
262 }
263
264 void MediaView::stop() {
265     playlistModel->abortSearch();
266     reallyStopped = true;
267     mediaObject->stop();
268     videoAreaWidget->clear();
269     errorTimer->stop();
270     playlistView->selectionModel()->clearSelection();
271     if (downloadItem) {
272         downloadItem->stop();
273         delete downloadItem;
274         downloadItem = 0;
275     }
276     The::globalActions()->value("refine-search")->setChecked(false);
277
278     while (!history.isEmpty()) {
279         VideoSource *videoSource = history.takeFirst();
280         if (!videoSource->parent()) delete videoSource;
281     }
282 }
283
284 Video* MediaView::getCurrentVideo() {
285     Video *currentVideo = 0;
286     if (downloadItem)
287         currentVideo = downloadItem->getVideo();
288     return currentVideo;
289 }
290
291 void MediaView::activeRowChanged(int row) {
292     if (reallyStopped) return;
293
294     Video *video = playlistModel->videoAt(row);
295     if (!video) return;
296
297     errorTimer->stop();
298
299     videoAreaWidget->showLoading(video);
300
301     mediaObject->stop();
302     if (downloadItem) {
303         downloadItem->stop();
304         delete downloadItem;
305         downloadItem = 0;
306     }
307
308     connect(video, SIGNAL(gotStreamUrl(QUrl)),
309             SLOT(gotStreamUrl(QUrl)), Qt::UniqueConnection);
310     connect(video, SIGNAL(errorStreamUrl(QString)),
311             SLOT(handleError(QString)), Qt::UniqueConnection);
312
313     video->loadStreamUrl();
314
315     // video title in the statusbar
316     MainWindow::instance()->showMessage(video->title());
317
318     // ensure active item is visible
319     if (row != -1) {
320         QModelIndex index = playlistModel->index(row, 0, QModelIndex());
321         playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
322     }
323
324     // enable/disable actions
325     The::globalActions()->value("download")->setEnabled(
326                 DownloadManager::instance()->itemForVideo(video) == 0);
327     The::globalActions()->value("skip")->setEnabled(true);
328     The::globalActions()->value("previous")->setEnabled(row > 0);
329     The::globalActions()->value("stopafterthis")->setEnabled(true);
330     The::globalActions()->value("related-videos")->setEnabled(true);
331
332     // see you in gotStreamUrl...
333 }
334
335 void MediaView::gotStreamUrl(QUrl streamUrl) {
336     if (reallyStopped) return;
337
338     Video *video = static_cast<Video *>(sender());
339     if (!video) {
340         qDebug() << "Cannot get sender in" << __PRETTY_FUNCTION__;
341         return;
342     }
343     video->disconnect(this);
344
345     QString tempFile = Temporary::filename();
346
347     Video *videoCopy = video->clone();
348     if (downloadItem) {
349         downloadItem->stop();
350         delete downloadItem;
351     }
352     downloadItem = new DownloadItem(videoCopy, streamUrl, tempFile, this);
353     connect(downloadItem, SIGNAL(statusChanged()),
354             SLOT(downloadStatusChanged()), Qt::UniqueConnection);
355     // connect(downloadItem, SIGNAL(progress(int)), SLOT(downloadProgress(int)));
356     connect(downloadItem, SIGNAL(bufferProgress(int)),
357             loadingWidget, SLOT(bufferStatus(int)), Qt::UniqueConnection);
358     // connect(downloadItem, SIGNAL(finished()), SLOT(itemFinished()));
359     connect(video, SIGNAL(errorStreamUrl(QString)),
360             SLOT(handleError(QString)), Qt::UniqueConnection);
361     connect(downloadItem, SIGNAL(error(QString)),
362             SLOT(handleError(QString)), Qt::UniqueConnection);
363     downloadItem->start();
364
365 #ifdef Q_WS_MAC
366     if (mac::canNotify())
367         mac::notify(video->title(), video->author(), video->formattedDuration());
368 #endif
369 }
370
371 /*
372 void MediaView::downloadProgress(int percent) {
373     MainWindow* mainWindow = dynamic_cast<MainWindow*>(window());
374
375     mainWindow->getSeekSlider()->setStyleSheet(" QSlider::groove:horizontal {"
376         "border: 1px solid #999999;"
377         // "border-left: 50px solid rgba(255, 0, 0, 128);"
378         "height: 8px;"
379         "background: qlineargradient(x1:0, y1:0, x2:.5, y2:0, stop:0 rgba(255, 0, 0, 92), stop:"
380         + QString::number(percent/100.0) +
381
382         " rgba(255, 0, 0, 92), stop:" + QString::number((percent+1)/100.0) + " transparent, stop:1 transparent);"
383         "margin: 2px 0;"
384     "}"
385     "QSlider::handle:horizontal {"
386         "background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f);"
387         "border: 1px solid #5c5c5c;"
388         "width: 16px;"
389         "height: 16px;"
390         "margin: -2px 0;"
391         "border-radius: 8px;"
392     "}"
393
394     );
395 }
396
397 */
398
399 void MediaView::downloadStatusChanged() {
400     switch(downloadItem->status()) {
401     case Downloading:
402         startPlaying();
403         break;
404     case Starting:
405         // qDebug() << "Starting";
406         break;
407     case Finished:
408         // qDebug() << "Finished" << mediaObject->state();
409         // if (mediaObject->state() == Phonon::StoppedState) startPlaying();
410 #ifdef Q_WS_X11
411         MainWindow::instance()->getSeekSlider()->setEnabled(mediaObject->isSeekable());
412 #endif
413         break;
414     case Failed:
415         // qDebug() << "Failed";
416     case Idle:
417         // qDebug() << "Idle";
418         break;
419     }
420 }
421
422 void MediaView::startPlaying() {
423     if (reallyStopped) return;
424     if (!downloadItem) {
425         skip();
426         return;
427     }
428
429     // go!
430     QString source = downloadItem->currentFilename();
431     qDebug() << "Playing" << source;
432     mediaObject->setCurrentSource(source);
433     mediaObject->play();
434 #ifdef Q_WS_X11
435     MainWindow::instance()->getSeekSlider()->setEnabled(false);
436 #endif
437
438     // ensure we always have 10 videos ahead
439     playlistModel->searchNeeded();
440
441     // ensure active item is visible
442     int row = playlistModel->activeRow();
443     if (row != -1) {
444         QModelIndex index = playlistModel->index(row, 0, QModelIndex());
445         playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
446     }
447
448 #ifdef APP_ACTIVATION
449     if (!Activation::instance().isActivated())
450         demoTimer->start(180000);
451 #endif
452
453 }
454
455 void MediaView::itemActivated(const QModelIndex &index) {
456     if (playlistModel->rowExists(index.row())) {
457
458         // if it's the current video, just rewind and play
459         Video *activeVideo = playlistModel->activeVideo();
460         Video *video = playlistModel->videoAt(index.row());
461         if (activeVideo && video && activeVideo == video) {
462             mediaObject->seek(0);
463             mediaObject->play();
464         } else playlistModel->setActiveRow(index.row());
465
466         // the user doubleclicked on the "Search More" item
467     } else {
468         playlistModel->searchMore();
469         playlistView->selectionModel()->clearSelection();
470     }
471 }
472
473 void MediaView::currentSourceChanged(const Phonon::MediaSource /* source */ ) {
474
475 }
476
477 void MediaView::skipVideo() {
478     // skippedVideo is useful for DELAYED skip operations
479     // in order to be sure that we're skipping the video we wanted
480     // and not another one
481     if (skippedVideo) {
482         if (playlistModel->activeVideo() != skippedVideo) {
483             qDebug() << "Skip of video canceled";
484             return;
485         }
486         int nextRow = playlistModel->rowForVideo(skippedVideo);
487         nextRow++;
488         if (nextRow == -1) return;
489         playlistModel->setActiveRow(nextRow);
490     }
491 }
492
493 void MediaView::skip() {
494     int nextRow = playlistModel->nextRow();
495     if (nextRow == -1) return;
496     playlistModel->setActiveRow(nextRow);
497 }
498
499 void MediaView::skipBackward() {
500     int prevRow = playlistModel->previousRow();
501     if (prevRow == -1) return;
502     playlistModel->setActiveRow(prevRow);
503 }
504
505 void MediaView::aboutToFinish() {
506     qint64 currentTime = mediaObject->currentTime();
507     qDebug() << __PRETTY_FUNCTION__ << currentTime;
508     if (currentTime + 10000 < mediaObject->totalTime()) {
509         // mediaObject->seek(mediaObject->currentTime());
510         // QTimer::singleShot(500, this, SLOT(playbackResume()));
511         mediaObject->seek(currentTime);
512         mediaObject->play();
513     }
514 }
515
516 void MediaView::playbackFinished() {
517     const int totalTime = mediaObject->totalTime();
518     const int currentTime = mediaObject->currentTime();
519     qDebug() << __PRETTY_FUNCTION__ << mediaObject->currentTime() << totalTime;
520     // add 10 secs for imprecise Phonon backends (VLC, Xine)
521     if (currentTime > 0 && currentTime + 10000 < totalTime) {
522         // mediaObject->seek(currentTime);
523         QTimer::singleShot(500, this, SLOT(playbackResume()));
524     } else {
525         QAction* stopAfterThisAction = The::globalActions()->value("stopafterthis");
526         if (stopAfterThisAction->isChecked()) {
527             stopAfterThisAction->setChecked(false);
528         } else skip();
529     }
530 }
531
532 void MediaView::playbackResume() {
533     qDebug() << __PRETTY_FUNCTION__ << mediaObject->currentTime();
534     mediaObject->seek(mediaObject->currentTime());
535     mediaObject->play();
536 }
537
538 void MediaView::openWebPage() {
539     Video* video = playlistModel->activeVideo();
540     if (!video) return;
541     mediaObject->pause();
542     QDesktopServices::openUrl(video->webpage());
543 }
544
545 void MediaView::copyWebPage() {
546     Video* video = playlistModel->activeVideo();
547     if (!video) return;
548     QString address = video->webpage().toString();
549     QApplication::clipboard()->setText(address);
550     QString message = tr("You can now paste the YouTube link into another application");
551     MainWindow::instance()->showMessage(message);
552 }
553
554 void MediaView::copyVideoLink() {
555     Video* video = playlistModel->activeVideo();
556     if (!video) return;
557     QApplication::clipboard()->setText(video->getStreamUrl().toEncoded());
558     QString message = tr("You can now paste the video stream URL into another application")
559             + ". " + tr("The link will be valid only for a limited time.");
560     MainWindow::instance()->showMessage(message);
561 }
562
563 void MediaView::removeSelected() {
564     if (!playlistView->selectionModel()->hasSelection()) return;
565     QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
566     playlistModel->removeIndexes(indexes);
567 }
568
569 void MediaView::selectVideos(QList<Video*> videos) {
570     foreach (Video *video, videos) {
571         QModelIndex index = playlistModel->indexForVideo(video);
572         playlistView->selectionModel()->select(index, QItemSelectionModel::Select);
573         playlistView->scrollTo(index, QAbstractItemView::EnsureVisible);
574     }
575 }
576
577 void MediaView::selectionChanged(const QItemSelection & /*selected*/, const QItemSelection & /*deselected*/) {
578     const bool gotSelection = playlistView->selectionModel()->hasSelection();
579     The::globalActions()->value("remove")->setEnabled(gotSelection);
580     The::globalActions()->value("moveUp")->setEnabled(gotSelection);
581     The::globalActions()->value("moveDown")->setEnabled(gotSelection);
582 }
583
584 void MediaView::moveUpSelected() {
585     if (!playlistView->selectionModel()->hasSelection()) return;
586
587     QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
588     qStableSort(indexes.begin(), indexes.end());
589     playlistModel->move(indexes, true);
590
591     // set current index after row moves to something more intuitive
592     int row = indexes.first().row();
593     playlistView->selectionModel()->setCurrentIndex(playlistModel->index(row>1?row:1), QItemSelectionModel::NoUpdate);
594 }
595
596 void MediaView::moveDownSelected() {
597     if (!playlistView->selectionModel()->hasSelection()) return;
598
599     QModelIndexList indexes = playlistView->selectionModel()->selectedIndexes();
600     qStableSort(indexes.begin(), indexes.end(), qGreater<QModelIndex>());
601     playlistModel->move(indexes, false);
602
603     // set current index after row moves to something more intuitive (respect 1 static item on bottom)
604     int row = indexes.first().row()+1, max = playlistModel->rowCount() - 2;
605     playlistView->selectionModel()->setCurrentIndex(playlistModel->index(row>max?max:row), QItemSelectionModel::NoUpdate);
606 }
607
608 void MediaView::setPlaylistVisible(bool visible) {
609     if (splitter->widget(0)->isVisible() == visible) return;
610     splitter->widget(0)->setVisible(visible);
611     playlistView->setFocus();
612 }
613
614 bool MediaView::isPlaylistVisible() {
615     return splitter->widget(0)->isVisible();
616 }
617
618 void MediaView::saveSplitterState() {
619     QSettings settings;
620     settings.setValue("splitter", splitter->saveState());
621 }
622
623 #ifdef APP_ACTIVATION
624
625 static QPushButton *continueButton;
626
627 void MediaView::demoMessage() {
628     if (mediaObject->state() != Phonon::PlayingState) return;
629     mediaObject->pause();
630
631     QMessageBox msgBox(this);
632     msgBox.setIconPixmap(QPixmap(":/images/app.png").scaled(64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation));
633     msgBox.setText(tr("This is just the demo version of %1.").arg(Constants::NAME));
634     msgBox.setInformativeText(tr("It allows you to test the application and see if it works for you."));
635     msgBox.setModal(true);
636     // make it a "sheet" on the Mac
637     msgBox.setWindowModality(Qt::WindowModal);
638
639     continueButton = msgBox.addButton("5", QMessageBox::RejectRole);
640     continueButton->setEnabled(false);
641     QPushButton *buyButton = msgBox.addButton(tr("Get the full version"), QMessageBox::ActionRole);
642
643     QTimeLine *timeLine = new QTimeLine(6000, this);
644     timeLine->setCurveShape(QTimeLine::LinearCurve);
645     timeLine->setFrameRange(5, 0);
646     connect(timeLine, SIGNAL(frameChanged(int)), SLOT(updateContinueButton(int)));
647     timeLine->start();
648
649     msgBox.exec();
650
651     if (msgBox.clickedButton() == buyButton) {
652         MainWindow::instance()->showActivationView();
653     } else {
654         mediaObject->play();
655         demoTimer->start(600000);
656     }
657
658     delete timeLine;
659
660 }
661
662 void MediaView::updateContinueButton(int value) {
663     if (value == 0) {
664         continueButton->setText(tr("Continue"));
665         continueButton->setEnabled(true);
666     } else {
667         continueButton->setText(QString::number(value));
668     }
669 }
670
671 #endif
672
673 void MediaView::downloadVideo() {
674     Video* video = playlistModel->activeVideo();
675     if (!video) return;
676     DownloadManager::instance()->addItem(video);
677     The::globalActions()->value("downloads")->setVisible(true);
678     QString message = tr("Downloading %1").arg(video->title());
679     MainWindow::instance()->showMessage(message);
680 }
681
682 void MediaView::snapshot() {
683     QImage image = videoWidget->snapshot();
684     qDebug() << image.size();
685
686     const QPixmap& pixmap = QPixmap::grabWindow(videoWidget->winId());
687     // qDebug() << pixmap.size();
688     videoAreaWidget->showSnapshotPreview(pixmap);
689 }
690
691 void MediaView::fullscreen() {
692     videoAreaWidget->setParent(0);
693     videoAreaWidget->showFullScreen();
694 }
695
696 /*
697 void MediaView::setSlider(QSlider *slider) {
698     this->slider = slider;
699     // slider->setEnabled(false);
700     slider->setTracking(false);
701     // connect(slider, SIGNAL(valueChanged(int)), SLOT(sliderMoved(int)));
702 }
703
704 void MediaView::sliderMoved(int value) {
705     qDebug() << __func__;
706     int sliderPercent = (value * 100) / (slider->maximum() - slider->minimum());
707     qDebug() << slider->minimum() << value << slider->maximum();
708     if (sliderPercent <= downloadItem->currentPercent()) {
709         qDebug() << sliderPercent << downloadItem->currentPercent();
710         mediaObject->seek(value);
711     } else {
712         seekTo(value);
713     }
714 }
715
716 void MediaView::seekTo(int value) {
717     qDebug() << __func__;
718     mediaObject->pause();
719     errorTimer->stop();
720     // mediaObject->clear();
721
722     QString tempDir = QDesktopServices::storageLocation(QDesktopServices::TempLocation);
723     QString tempFile = tempDir + "/minitube" + QString::number(value) + ".mp4";
724     if (!QFile::remove(tempFile)) {
725         qDebug() << "Cannot remove temp file";
726     }
727     Video *videoCopy = downloadItem->getVideo()->clone();
728     QUrl streamUrl = videoCopy->getStreamUrl();
729     streamUrl.addQueryItem("begin", QString::number(value));
730     if (downloadItem) delete downloadItem;
731     downloadItem = new DownloadItem(videoCopy, streamUrl, tempFile, this);
732     connect(downloadItem, SIGNAL(statusChanged()), SLOT(downloadStatusChanged()));
733     // connect(downloadItem, SIGNAL(finished()), SLOT(itemFinished()));
734     downloadItem->start();
735
736     // slider->setMinimum(value);
737
738 }
739
740 */
741
742 void MediaView::findVideoParts() {
743
744     // parts
745     Video* video = playlistModel->activeVideo();
746     if (!video) return;
747
748     QString query = video->title();
749
750     static QString optionalSpace = "\\s*";
751     static QString staticCounterSeparators = "[\\/\\-]";
752     QString counterSeparators = "( of | " +
753             tr("of", "Used in video parts, as in '2 of 3'") +
754             " |" + staticCounterSeparators + ")";
755
756     // numbers from 1 to 15
757     static QString counterNumber = "([1-9]|1[0-5])";
758
759     // query.remove(QRegExp(counterSeparators + optionalSpace + counterNumber));
760     query.remove(QRegExp(counterNumber + optionalSpace + counterSeparators + optionalSpace + counterNumber));
761     query.remove(wordRE("pr?t\\.?" + optionalSpace + counterNumber));
762     query.remove(wordRE("ep\\.?" + optionalSpace + counterNumber));
763     query.remove(wordRE("part" + optionalSpace + counterNumber));
764     query.remove(wordRE("episode" + optionalSpace + counterNumber));
765     query.remove(wordRE(tr("part", "This is for video parts, as in 'Cool video - part 1'") +
766                         optionalSpace + counterNumber));
767     query.remove(wordRE(tr("episode", "This is for video parts, as in 'Cool series - episode 1'") +
768                         optionalSpace + counterNumber));
769     query.remove(QRegExp("[\\(\\)\\[\\]]"));
770
771 #define NUMBERS "one|two|three|four|five|six|seven|eight|nine|ten"
772
773     QRegExp englishNumberRE = QRegExp(QLatin1String(".*(") + NUMBERS + ").*", Qt::CaseInsensitive);
774     // bool numberAsWords = englishNumberRE.exactMatch(query);
775     query.remove(englishNumberRE);
776
777     QRegExp localizedNumberRE = QRegExp(QLatin1String(".*(") + tr(NUMBERS) + ").*", Qt::CaseInsensitive);
778     // if (!numberAsWords) numberAsWords = localizedNumberRE.exactMatch(query);
779     query.remove(localizedNumberRE);
780
781     SearchParams *searchParams = new SearchParams();
782     searchParams->setTransient(true);
783     searchParams->setKeywords(query);
784     searchParams->setAuthor(video->author());
785
786     /*
787     if (!numberAsWords) {
788         qDebug() << "We don't have number as words";
789         // searchParams->setSortBy(SearchParams::SortByNewest);
790         // TODO searchParams->setReverseOrder(true);
791         // TODO searchParams->setMax(50);
792     }
793     */
794
795     search(searchParams);
796
797 }
798
799 void MediaView::relatedVideos() {
800     Video* video = playlistModel->activeVideo();
801     if (!video) return;
802     YTSingleVideoSource *singleVideoSource = new YTSingleVideoSource();
803     singleVideoSource->setVideoId(video->id());
804     setVideoSource(singleVideoSource);
805     The::globalActions()->value("related-videos")->setEnabled(false);
806 }
807
808 void MediaView::shareViaTwitter() {
809     Video* video = playlistModel->activeVideo();
810     if (!video) return;
811     QUrl url("https://twitter.com/intent/tweet");
812     url.addQueryItem("via", "minitubeapp");
813     url.addQueryItem("text", video->title());
814     url.addQueryItem("url", video->webpage().toString());
815     QDesktopServices::openUrl(url);
816 }
817
818 void MediaView::shareViaFacebook() {
819     Video* video = playlistModel->activeVideo();
820     if (!video) return;
821     QUrl url("https://www.facebook.com/sharer.php");
822     url.addQueryItem("t", video->title());
823     url.addQueryItem("u", video->webpage().toString());
824     QDesktopServices::openUrl(url);
825 }
826
827 void MediaView::shareViaBuffer() {
828     Video* video = playlistModel->activeVideo();
829     if (!video) return;
830     QUrl url("http://bufferapp.com/add");
831     url.addQueryItem("via", "minitubeapp");
832     url.addQueryItem("text", video->title());
833     url.addQueryItem("url", video->webpage().toString());
834     url.addQueryItem("picture", video->thumbnailUrl());
835     QDesktopServices::openUrl(url);
836 }
837
838 void MediaView::shareViaEmail() {
839     Video* video = playlistModel->activeVideo();
840     if (!video) return;
841     QUrl url("mailto:");
842     url.addQueryItem("subject", video->title());
843     QString body = video->title() + "\n" +
844             video->webpage().toString() + "\n\n" +
845             tr("Sent from %1").arg(Constants::NAME) + "\n" +
846             Constants::WEBSITE;
847     url.addQueryItem("body", body);
848     QDesktopServices::openUrl(url);
849 }
850
851 void MediaView::authorPushed(QModelIndex index) {
852     Video* video = playlistModel->videoAt(index.row());
853     if (!video) return;
854
855     QString channel = video->authorUri();
856     if (channel.isEmpty()) channel = video->author();
857     if (channel.isEmpty()) return;
858
859     SearchParams *searchParams = new SearchParams();
860     searchParams->setAuthor(channel);
861     searchParams->setSortBy(SearchParams::SortByNewest);
862
863     // go!
864     search(searchParams);
865 }