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