3 This file is part of Minitube.
4 Copyright 2009, Flavio Tordini <flavio.tordini@gmail.com>
6 Minitube is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Minitube is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Minitube. If not, see <http://www.gnu.org/licenses/>.
21 #include "playlistmodel.h"
22 #include "videomimedata.h"
23 #include "videosource.h"
26 #include "searchparams.h"
27 #include "mediaview.h"
29 static const int maxItems = 50;
30 static const QString recentKeywordsKey = "recentKeywords";
31 static const QString recentChannelsKey = "recentChannels";
33 PlaylistModel::PlaylistModel(QWidget *parent) : QAbstractListModel(parent) {
43 authorHovered = false;
44 authorPressed = false;
47 int PlaylistModel::rowCount(const QModelIndex &/*parent*/) const {
48 int count = videos.size();
50 // add the message item
51 if (videos.isEmpty() || !searching)
57 QVariant PlaylistModel::data(const QModelIndex &index, int role) const {
59 int row = index.row();
61 if (row == videos.size()) {
67 return ItemTypeShowMore;
69 if (!errorMessage.isEmpty()) return errorMessage;
70 if (searching) return tr("Searching...");
71 if (canSearchMore) return tr("Show %1 More").arg("").simplified();
72 if (videos.isEmpty()) return tr("No videos");
73 else return tr("No more videos");
74 case Qt::TextAlignmentRole:
75 return QVariant(int(Qt::AlignHCenter | Qt::AlignVCenter));
76 case Qt::ForegroundRole:
77 if (!errorMessage.isEmpty())
78 return palette.color(QPalette::ToolTipText);
80 return palette.color(QPalette::Dark);
81 case Qt::BackgroundColorRole:
82 if (!errorMessage.isEmpty())
83 return palette.color(QPalette::ToolTipBase);
90 } else if (row < 0 || row >= videos.size())
93 Video *video = videos.at(row);
99 return QVariant::fromValue(QPointer<Video>(video));
100 case ActiveTrackRole:
101 return video == m_activeVideo;
102 case Qt::DisplayRole:
103 return video->title();
104 case HoveredItemRole:
105 return hoveredRow == index.row();
106 case AuthorHoveredRole:
107 return authorHovered;
108 case AuthorPressedRole:
109 return authorPressed;
111 case Qt::StatusTipRole:
112 return video->description();
119 void PlaylistModel::setActiveRow(int row, bool notify) {
120 if ( rowExists( row ) ) {
123 m_activeVideo = videoAt(row);
125 int oldactiverow = m_activeRow;
127 if ( rowExists( oldactiverow ) )
128 emit dataChanged( createIndex( oldactiverow, 0 ), createIndex( oldactiverow, columnCount() - 1 ) );
130 emit dataChanged( createIndex( m_activeRow, 0 ), createIndex( m_activeRow, columnCount() - 1 ) );
131 if (notify) emit activeRowChanged(row);
140 int PlaylistModel::nextRow() const {
141 int nextRow = m_activeRow + 1;
142 if (rowExists(nextRow))
147 int PlaylistModel::previousRow() const {
148 int prevRow = m_activeRow - 1;
149 if (rowExists(prevRow))
154 Video* PlaylistModel::videoAt( int row ) const {
155 if ( rowExists( row ) )
156 return videos.at( row );
160 Video* PlaylistModel::activeVideo() const {
161 return m_activeVideo;
164 void PlaylistModel::setVideoSource(VideoSource *videoSource) {
166 while (!videos.isEmpty()) delete videos.takeFirst();
173 this->videoSource = videoSource;
174 connect(videoSource, SIGNAL(gotVideos(QList<Video*>)),
175 SLOT(addVideos(QList<Video*>)), Qt::UniqueConnection);
176 connect(videoSource, SIGNAL(finished(int)),
177 SLOT(searchFinished(int)), Qt::UniqueConnection);
178 connect(videoSource, SIGNAL(error(QString)),
179 SLOT(searchError(QString)), Qt::UniqueConnection);
184 void PlaylistModel::searchMore(int max) {
185 if (searching) return;
187 firstSearch = startIndex == 1;
189 errorMessage.clear();
190 videoSource->loadVideos(max, startIndex);
194 void PlaylistModel::searchMore() {
195 searchMore(maxItems);
198 void PlaylistModel::searchNeeded() {
199 const int desiredRowsAhead = 10;
200 int remainingRows = videos.size() - m_activeRow;
201 if (remainingRows < desiredRowsAhead)
202 searchMore(maxItems);
205 void PlaylistModel::abortSearch() {
206 QMutexLocker locker(&mutex);
208 // while (!videos.isEmpty()) delete videos.takeFirst();
209 // if (videoSource) videoSource->abort();
218 void PlaylistModel::searchFinished(int total) {
220 canSearchMore = videoSource->hasMoreVideos();
222 // update the message item
223 emit dataChanged( createIndex( maxItems, 0 ), createIndex( maxItems, columnCount() - 1 ) );
225 if (!videoSource->getSuggestions().isEmpty())
226 emit haveSuggestions(videoSource->getSuggestions());
228 if (firstSearch && !videos.isEmpty())
229 handleFirstVideo(videos.first());
232 void PlaylistModel::searchError(const QString &message) {
233 errorMessage = message;
234 // update the message item
235 emit dataChanged( createIndex( maxItems, 0 ), createIndex( maxItems, columnCount() - 1 ) );
238 void PlaylistModel::addVideos(QList<Video*> newVideos) {
239 if (newVideos.isEmpty()) return;
240 beginInsertRows(QModelIndex(), videos.size(), videos.size() + newVideos.size() - 2);
241 videos.append(newVideos);
243 foreach (Video* video, newVideos) {
244 connect(video, SIGNAL(gotThumbnail()),
245 SLOT(updateVideoSender()), Qt::UniqueConnection);
246 video->loadThumbnail();
247 qApp->processEvents();
251 void PlaylistModel::handleFirstVideo(Video *video) {
253 int currentVideoRow = rowForCloneVideo(MediaView::instance()->getCurrentVideoId());
254 if (currentVideoRow != -1) setActiveRow(currentVideoRow, false);
257 if (!settings.value("manualplay", false).toBool())
262 if (!settings.value("manualplay", false).toBool()) {
263 int newActiveRow = rowForCloneVideo(MediaView::instance()->getCurrentVideoId());
264 if (newActiveRow != -1) setActiveRow(newActiveRow, false);
265 else setActiveRow(0);
268 if (videoSource->metaObject()->className() == QLatin1String("YTSearch")) {
270 static const int maxRecentElements = 10;
272 YTSearch *search = qobject_cast<YTSearch *>(videoSource);
273 SearchParams *searchParams = search->getSearchParams();
276 QString query = searchParams->keywords();
277 if (!query.isEmpty() && !searchParams->isTransient()) {
278 if (query.startsWith("http://")) {
279 // Save the video title
280 query += "|" + videos.first()->title();
282 QStringList keywords = settings.value(recentKeywordsKey).toStringList();
283 keywords.removeAll(query);
284 keywords.prepend(query);
285 while (keywords.size() > maxRecentElements)
286 keywords.removeLast();
287 settings.setValue(recentKeywordsKey, keywords);
291 QString channelId = searchParams->channelId();
292 if (!channelId.isEmpty() && !searchParams->isTransient()) {
294 if (!video->channelId().isEmpty() && video->channelId() != video->channelTitle())
295 value = video->channelId() + "|" + video->channelTitle();
296 else value = video->channelTitle();
297 QStringList channels = settings.value(recentChannelsKey).toStringList();
298 channels.removeAll(value);
299 channels.removeAll(channelId);
300 channels.prepend(value);
301 while (channels.size() > maxRecentElements)
302 channels.removeLast();
303 settings.setValue(recentChannelsKey, channels);
308 void PlaylistModel::updateVideoSender() {
309 Video *video = static_cast<Video *>(sender());
311 qDebug() << "Cannot get sender";
314 int row = rowForVideo(video);
315 emit dataChanged( createIndex( row, 0 ), createIndex( row, columnCount() - 1 ) );
318 void PlaylistModel::emitDataChanged() {
319 QModelIndex index = createIndex(rowCount()-1, 0);
320 emit dataChanged(index, index);
326 * This function does not free memory
328 bool PlaylistModel::removeRows(int position, int rows, const QModelIndex & /*parent*/) {
329 beginRemoveRows(QModelIndex(), position, position+rows-1);
330 for (int row = 0; row < rows; ++row) {
331 videos.removeAt(position);
337 void PlaylistModel::removeIndexes(QModelIndexList &indexes) {
338 QList<Video*> originalList(videos);
339 QList<Video*> delitems;
340 foreach (const QModelIndex &index, indexes) {
341 if (index.row() >= originalList.size()) continue;
342 Video* video = originalList.at(index.row());
343 int idx = videos.indexOf(video);
345 beginRemoveRows(QModelIndex(), idx, idx);
346 delitems.append(video);
347 videos.removeAll(video);
352 qDeleteAll(delitems);
356 // --- Sturm und drang ---
360 Qt::DropActions PlaylistModel::supportedDropActions() const {
361 return Qt::CopyAction;
364 Qt::DropActions PlaylistModel::supportedDragActions() const {
365 return Qt::CopyAction;
368 Qt::ItemFlags PlaylistModel::flags(const QModelIndex &index) const {
369 if (index.isValid()) {
370 if (index.row() == videos.size()) {
371 // don't drag the "show more" item
372 return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
373 } else return (Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled);
375 return Qt::ItemIsDropEnabled;
378 QStringList PlaylistModel::mimeTypes() const {
380 types << "application/x-minitube-video";
384 QMimeData* PlaylistModel::mimeData( const QModelIndexList &indexes ) const {
385 VideoMimeData* mime = new VideoMimeData();
387 foreach( const QModelIndex &it, indexes ) {
389 if (row >= 0 && row < videos.size())
390 mime->addVideo( videos.at( it.row() ) );
396 bool PlaylistModel::dropMimeData(const QMimeData *data,
397 Qt::DropAction action, int row, int column,
398 const QModelIndex &parent) {
399 if (action == Qt::IgnoreAction)
402 if (!data->hasFormat("application/x-minitube-video"))
411 else if (parent.isValid())
412 beginRow = parent.row();
414 beginRow = rowCount(QModelIndex());
416 const VideoMimeData* videoMimeData = qobject_cast<const VideoMimeData*>( data );
417 if(!videoMimeData ) return false;
419 QList<Video*> droppedVideos = videoMimeData->videos();
420 foreach( Video *video, droppedVideos) {
423 int videoRow = videos.indexOf(video);
424 removeRows(videoRow, 1, QModelIndex());
426 // and then add them again at the new position
427 beginInsertRows(QModelIndex(), beginRow, beginRow);
428 videos.insert(beginRow, video);
433 // fix m_activeRow after all this
434 m_activeRow = videos.indexOf(m_activeVideo);
436 // let the MediaView restore the selection
437 emit needSelectionFor(droppedVideos);
443 int PlaylistModel::rowForCloneVideo(const QString &videoId) const {
444 if (videoId.isEmpty()) return -1;
445 for (int i = 0; i < videos.size(); ++i) {
446 Video *v = videos.at(i);
447 // qDebug() << "Comparing" << v->id() << videoId;
448 if (v->id() == videoId) return i;
453 int PlaylistModel::rowForVideo(Video* video) {
454 return videos.indexOf(video);
457 QModelIndex PlaylistModel::indexForVideo(Video* video) {
458 return createIndex(videos.indexOf(video), 0);
461 void PlaylistModel::move(QModelIndexList &indexes, bool up) {
462 QList<Video*> movedVideos;
464 foreach (const QModelIndex &index, indexes) {
465 int row = index.row();
466 if (row >= videos.size()) continue;
467 // qDebug() << "index row" << row;
468 Video *video = videoAt(row);
469 movedVideos << video;
472 int end=up ? -1 : rowCount()-1, mod=up ? -1 : 1;
473 foreach (Video *video, movedVideos) {
475 int row = rowForVideo(video);
476 if (row+mod==end) { end=row; continue; }
477 // qDebug() << "video row" << row;
478 removeRows(row, 1, QModelIndex());
483 beginInsertRows(QModelIndex(), row, row);
484 videos.insert(row, video);
489 emit needSelectionFor(movedVideos);
495 void PlaylistModel::setHoveredRow(int row) {
496 int oldRow = hoveredRow;
498 emit dataChanged( createIndex( oldRow, 0 ), createIndex( oldRow, columnCount() - 1 ) );
499 emit dataChanged( createIndex( hoveredRow, 0 ), createIndex( hoveredRow, columnCount() - 1 ) );
502 void PlaylistModel::clearHover() {
503 int oldRow = hoveredRow;
505 emit dataChanged( createIndex( oldRow, 0 ), createIndex( oldRow, columnCount() - 1) );
508 void PlaylistModel::updateHoveredRow() {
509 emit dataChanged( createIndex( hoveredRow, 0 ), createIndex( hoveredRow, columnCount() - 1 ) );
512 /* clickable author */
514 void PlaylistModel::enterAuthorHover() {
515 if (authorHovered) return;
516 authorHovered = true;
520 void PlaylistModel::exitAuthorHover() {
521 if (!authorHovered) return;
522 authorHovered = false;
524 setHoveredRow(hoveredRow);
527 void PlaylistModel::enterAuthorPressed() {
528 if (authorPressed) return;
529 authorPressed = true;
533 void PlaylistModel::exitAuthorPressed() {
534 if (!authorPressed) return;
535 authorPressed = false;