]> git.sur5r.net Git - minitube/blob - src/playlistmodel.cpp
Imported Upstream version 2.5.1
[minitube] / src / playlistmodel.cpp
1 /* $BEGIN_LICENSE
2
3 This file is part of Minitube.
4 Copyright 2009, Flavio Tordini <flavio.tordini@gmail.com>
5
6 Minitube is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 Minitube is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Minitube.  If not, see <http://www.gnu.org/licenses/>.
18
19 $END_LICENSE */
20
21 #include "playlistmodel.h"
22 #include "videomimedata.h"
23 #include "videosource.h"
24 #include "ytsearch.h"
25 #include "video.h"
26 #include "searchparams.h"
27 #include "mediaview.h"
28
29 static const int maxItems = 50;
30 static const QString recentKeywordsKey = "recentKeywords";
31 static const QString recentChannelsKey = "recentChannels";
32
33 PlaylistModel::PlaylistModel(QWidget *parent) : QAbstractListModel(parent) {
34     videoSource = 0;
35     searching = false;
36     canSearchMore = true;
37     firstSearch = false;
38     m_activeVideo = 0;
39     m_activeRow = -1;
40     startIndex = 1;
41     max = 0;
42     hoveredRow = -1;
43     authorHovered = false;
44     authorPressed = false;
45 }
46
47 int PlaylistModel::rowCount(const QModelIndex &/*parent*/) const {
48     int count = videos.size();
49     
50     // add the message item
51     if (videos.isEmpty() || !searching)
52         count++;
53     
54     return count;
55 }
56
57 QVariant PlaylistModel::data(const QModelIndex &index, int role) const {
58     
59     int row = index.row();
60     
61     if (row == videos.size()) {
62         
63         QPalette palette;
64         
65         switch (role) {
66         case ItemTypeRole:
67             return ItemTypeShowMore;
68         case Qt::DisplayRole:
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);
79             else
80                 return palette.color(QPalette::Dark);
81         case Qt::BackgroundColorRole:
82             if (!errorMessage.isEmpty())
83                 return palette.color(QPalette::ToolTipBase);
84             else
85                 return QVariant();
86         default:
87             return QVariant();
88         }
89         
90     } else if (row < 0 || row >= videos.size())
91         return QVariant();
92     
93     Video *video = videos.at(row);
94     
95     switch (role) {
96     case ItemTypeRole:
97         return ItemTypeVideo;
98     case VideoRole:
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;
110         /*
111     case Qt::StatusTipRole:
112         return video->description();
113         */
114     }
115     
116     return QVariant();
117 }
118
119 void PlaylistModel::setActiveRow(int row, bool notify) {
120     if ( rowExists( row ) ) {
121         
122         m_activeRow = row;
123         m_activeVideo = videoAt(row);
124         
125         int oldactiverow = m_activeRow;
126         
127         if ( rowExists( oldactiverow ) )
128             emit dataChanged( createIndex( oldactiverow, 0 ), createIndex( oldactiverow, columnCount() - 1 ) );
129         
130         emit dataChanged( createIndex( m_activeRow, 0 ), createIndex( m_activeRow, columnCount() - 1 ) );
131         if (notify) emit activeRowChanged(row);
132         
133     } else {
134         m_activeRow = -1;
135         m_activeVideo = 0;
136     }
137
138 }
139
140 int PlaylistModel::nextRow() const {
141     int nextRow = m_activeRow + 1;
142     if (rowExists(nextRow))
143         return nextRow;
144     return -1;
145 }
146
147 int PlaylistModel::previousRow() const {
148     int prevRow = m_activeRow - 1;
149     if (rowExists(prevRow))
150         return prevRow;
151     return -1;
152 }
153
154 Video* PlaylistModel::videoAt( int row ) const {
155     if ( rowExists( row ) )
156         return videos.at( row );
157     return 0;
158 }
159
160 Video* PlaylistModel::activeVideo() const {
161     return m_activeVideo;
162 }
163
164 void PlaylistModel::setVideoSource(VideoSource *videoSource) {
165     beginResetModel();
166     while (!videos.isEmpty()) delete videos.takeFirst();
167     videos.clear();
168     m_activeVideo = 0;
169     m_activeRow = -1;
170     startIndex = 1;
171     endResetModel();
172
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);
180
181     searchMore();
182 }
183
184 void PlaylistModel::searchMore(int max) {
185     if (searching) return;
186     searching = true;
187     firstSearch = startIndex == 1;
188     this->max = max;
189     errorMessage.clear();
190     videoSource->loadVideos(max, startIndex);
191     startIndex += max;
192 }
193
194 void PlaylistModel::searchMore() {
195     searchMore(maxItems);
196 }
197
198 void PlaylistModel::searchNeeded() {
199     const int desiredRowsAhead = 10;
200     int remainingRows = videos.size() - m_activeRow;
201     if (remainingRows < desiredRowsAhead)
202         searchMore(maxItems);
203 }
204
205 void PlaylistModel::abortSearch() {
206     QMutexLocker locker(&mutex);
207     beginResetModel();
208     // while (!videos.isEmpty()) delete videos.takeFirst();
209     // if (videoSource) videoSource->abort();
210     videos.clear();
211     searching = false;
212     m_activeRow = -1;
213     m_activeVideo = 0;
214     startIndex = 1;
215     endResetModel();
216 }
217
218 void PlaylistModel::searchFinished(int total) {
219     searching = false;
220     canSearchMore = videoSource->hasMoreVideos();
221
222     // update the message item
223     emit dataChanged( createIndex( maxItems, 0 ), createIndex( maxItems, columnCount() - 1 ) );
224
225     if (!videoSource->getSuggestions().isEmpty())
226         emit haveSuggestions(videoSource->getSuggestions());
227
228     if (firstSearch && !videos.isEmpty())
229         handleFirstVideo(videos.first());
230 }
231
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 ) );
236 }
237
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);
242     endInsertRows();
243     foreach (Video* video, newVideos) {
244         connect(video, SIGNAL(gotThumbnail()),
245                 SLOT(updateVideoSender()), Qt::UniqueConnection);
246         video->loadThumbnail();
247         qApp->processEvents();
248     }
249 }
250
251 void PlaylistModel::handleFirstVideo(Video *video) {
252
253     int currentVideoRow = rowForCloneVideo(MediaView::instance()->getCurrentVideoId());
254     if (currentVideoRow != -1) setActiveRow(currentVideoRow, false);
255     else {
256         QSettings settings;
257         if (!settings.value("manualplay", false).toBool())
258             setActiveRow(0);
259     }
260
261     QSettings settings;
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);
266     }
267
268     if (videoSource->metaObject()->className() == QLatin1String("YTSearch")) {
269
270         static const int maxRecentElements = 10;
271
272         YTSearch *search = qobject_cast<YTSearch *>(videoSource);
273         SearchParams *searchParams = search->getSearchParams();
274
275         // save keyword
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();
281             }
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);
288         }
289
290         // save channel
291         QString channelId = searchParams->channelId();
292         if (!channelId.isEmpty() && !searchParams->isTransient()) {
293             QString value;
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);
304         }
305     }
306 }
307
308 void PlaylistModel::updateVideoSender() {
309     Video *video = static_cast<Video *>(sender());
310     if (!video) {
311         qDebug() << "Cannot get sender";
312         return;
313     }
314     int row = rowForVideo(video);
315     emit dataChanged( createIndex( row, 0 ), createIndex( row, columnCount() - 1 ) );
316 }
317
318 void PlaylistModel::emitDataChanged() {
319     QModelIndex index = createIndex(rowCount()-1, 0);
320     emit dataChanged(index, index);
321 }
322
323 // --- item removal
324
325 /**
326   * This function does not free memory
327   */
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);
332     }
333     endRemoveRows();
334     return true;
335 }
336
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);
344         if (idx != -1) {
345             beginRemoveRows(QModelIndex(), idx, idx);
346             delitems.append(video);
347             videos.removeAll(video);
348             endRemoveRows();
349         }
350     }
351
352     qDeleteAll(delitems);
353
354 }
355
356 // --- Sturm und drang ---
357
358
359
360 Qt::DropActions PlaylistModel::supportedDropActions() const {
361     return Qt::CopyAction;
362 }
363
364 Qt::DropActions PlaylistModel::supportedDragActions() const {
365     return Qt::CopyAction;
366 }
367
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);
374     }
375     return Qt::ItemIsDropEnabled;
376 }
377
378 QStringList PlaylistModel::mimeTypes() const {
379     QStringList types;
380     types << "application/x-minitube-video";
381     return types;
382 }
383
384 QMimeData* PlaylistModel::mimeData( const QModelIndexList &indexes ) const {
385     VideoMimeData* mime = new VideoMimeData();
386
387     foreach( const QModelIndex &it, indexes ) {
388         int row = it.row();
389         if (row >= 0 && row < videos.size())
390             mime->addVideo( videos.at( it.row() ) );
391     }
392
393     return mime;
394 }
395
396 bool PlaylistModel::dropMimeData(const QMimeData *data,
397                                  Qt::DropAction action, int row, int column,
398                                  const QModelIndex &parent) {
399     if (action == Qt::IgnoreAction)
400         return true;
401
402     if (!data->hasFormat("application/x-minitube-video"))
403         return false;
404
405     if (column > 0)
406         return false;
407
408     int beginRow;
409     if (row != -1)
410         beginRow = row;
411     else if (parent.isValid())
412         beginRow = parent.row();
413     else
414         beginRow = rowCount(QModelIndex());
415
416     const VideoMimeData* videoMimeData = qobject_cast<const VideoMimeData*>( data );
417     if(!videoMimeData ) return false;
418
419     QList<Video*> droppedVideos = videoMimeData->videos();
420     foreach( Video *video, droppedVideos) {
421         
422         // remove videos
423         int videoRow = videos.indexOf(video);
424         removeRows(videoRow, 1, QModelIndex());
425         
426         // and then add them again at the new position
427         beginInsertRows(QModelIndex(), beginRow, beginRow);
428         videos.insert(beginRow, video);
429         endInsertRows();
430
431     }
432
433     // fix m_activeRow after all this
434     m_activeRow = videos.indexOf(m_activeVideo);
435
436     // let the MediaView restore the selection
437     emit needSelectionFor(droppedVideos);
438
439     return true;
440
441 }
442
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;
449     }
450     return -1;
451 }
452
453 int PlaylistModel::rowForVideo(Video* video) {
454     return videos.indexOf(video);
455 }
456
457 QModelIndex PlaylistModel::indexForVideo(Video* video) {
458     return createIndex(videos.indexOf(video), 0);
459 }
460
461 void PlaylistModel::move(QModelIndexList &indexes, bool up) {
462     QList<Video*> movedVideos;
463
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;
470     }
471
472     int end=up ? -1 : rowCount()-1, mod=up ? -1 : 1;
473     foreach (Video *video, movedVideos) {
474
475         int row = rowForVideo(video);
476         if (row+mod==end) { end=row; continue; }
477         // qDebug() << "video row" << row;
478         removeRows(row, 1, QModelIndex());
479
480         if (up) row--;
481         else row++;
482
483         beginInsertRows(QModelIndex(), row, row);
484         videos.insert(row, video);
485         endInsertRows();
486
487     }
488
489     emit needSelectionFor(movedVideos);
490
491 }
492
493 /* row hovering */
494
495 void PlaylistModel::setHoveredRow(int row) {
496     int oldRow = hoveredRow;
497     hoveredRow = row;
498     emit dataChanged( createIndex( oldRow, 0 ), createIndex( oldRow, columnCount() - 1 ) );
499     emit dataChanged( createIndex( hoveredRow, 0 ), createIndex( hoveredRow, columnCount() - 1 ) );
500 }
501
502 void PlaylistModel::clearHover() {
503     int oldRow = hoveredRow;
504     hoveredRow = -1;
505     emit dataChanged( createIndex( oldRow, 0 ), createIndex( oldRow, columnCount() - 1) );
506 }
507
508 void PlaylistModel::updateHoveredRow() {
509     emit dataChanged( createIndex( hoveredRow, 0 ), createIndex( hoveredRow, columnCount() - 1 ) );
510 }
511
512 /* clickable author */
513
514 void PlaylistModel::enterAuthorHover() {
515     if (authorHovered) return;
516     authorHovered = true;
517     updateHoveredRow();
518 }
519
520 void PlaylistModel::exitAuthorHover() {
521     if (!authorHovered) return;
522     authorHovered = false;
523     updateHoveredRow();
524     setHoveredRow(hoveredRow);
525 }
526
527 void PlaylistModel::enterAuthorPressed() {
528     if (authorPressed) return;
529     authorPressed = true;
530     updateHoveredRow();
531 }
532
533 void PlaylistModel::exitAuthorPressed() {
534     if (!authorPressed) return;
535     authorPressed = false;
536     updateHoveredRow();
537 }