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