]> git.sur5r.net Git - minitube/blob - src/playlistmodel.cpp
Merge tag 'upstream/2.3'
[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 = 10;
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     skip = 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         QFont boldFont;
65         boldFont.setBold(true);
66         
67         switch (role) {
68         case ItemTypeRole:
69             return ItemTypeShowMore;
70         case Qt::DisplayRole:
71             if (!errorMessage.isEmpty()) return errorMessage;
72             if (searching) return tr("Searching...");
73             if (canSearchMore) return tr("Show %1 More").arg(maxItems);
74             if (videos.isEmpty()) return tr("No videos");
75             else return tr("No more videos");
76         case Qt::TextAlignmentRole:
77             return QVariant(int(Qt::AlignHCenter | Qt::AlignVCenter));
78         case Qt::ForegroundRole:
79             if (!errorMessage.isEmpty())
80                 return palette.color(QPalette::ToolTipText);
81             else
82                 return palette.color(QPalette::Dark);
83         case Qt::BackgroundColorRole:
84             if (!errorMessage.isEmpty())
85                 return palette.color(QPalette::ToolTipBase);
86             else
87                 return QVariant();
88         case Qt::FontRole:
89             return boldFont;
90         default:
91             return QVariant();
92         }
93         
94     } else if (row < 0 || row >= videos.size())
95         return QVariant();
96     
97     Video *video = videos.at(row);
98     
99     switch (role) {
100     case ItemTypeRole:
101         return ItemTypeVideo;
102     case VideoRole:
103         return QVariant::fromValue(QPointer<Video>(video));
104     case ActiveTrackRole:
105         return video == m_activeVideo;
106     case Qt::DisplayRole:
107         return video->title();
108     case HoveredItemRole:
109         return hoveredRow == index.row();
110     case AuthorHoveredRole:
111         return authorHovered;
112     case AuthorPressedRole:
113         return authorPressed;
114     case Qt::StatusTipRole:
115         return video->description();
116     }
117     
118     return QVariant();
119 }
120
121 void PlaylistModel::setActiveRow(int row, bool notify) {
122     if ( rowExists( row ) ) {
123         
124         m_activeRow = row;
125         m_activeVideo = videoAt(row);
126         
127         int oldactiverow = m_activeRow;
128         
129         if ( rowExists( oldactiverow ) )
130             emit dataChanged( createIndex( oldactiverow, 0 ), createIndex( oldactiverow, columnCount() - 1 ) );
131         
132         emit dataChanged( createIndex( m_activeRow, 0 ), createIndex( m_activeRow, columnCount() - 1 ) );
133         if (notify) emit activeRowChanged(row);
134         
135     } else {
136         m_activeRow = -1;
137         m_activeVideo = 0;
138     }
139
140 }
141
142 int PlaylistModel::nextRow() const {
143     int nextRow = m_activeRow + 1;
144     if (rowExists(nextRow))
145         return nextRow;
146     return -1;
147 }
148
149 int PlaylistModel::previousRow() const {
150     int prevRow = m_activeRow - 1;
151     if (rowExists(prevRow))
152         return prevRow;
153     return -1;
154 }
155
156 Video* PlaylistModel::videoAt( int row ) const {
157     if ( rowExists( row ) )
158         return videos.at( row );
159     return 0;
160 }
161
162 Video* PlaylistModel::activeVideo() const {
163     return m_activeVideo;
164 }
165
166 void PlaylistModel::setVideoSource(VideoSource *videoSource) {
167     beginResetModel();
168     while (!videos.isEmpty())
169         delete videos.takeFirst();
170     m_activeVideo = 0;
171     m_activeRow = -1;
172     skip = 1;
173     endResetModel();
174
175     this->videoSource = videoSource;
176     connect(videoSource, SIGNAL(gotVideos(QList<Video*>)),
177             SLOT(addVideos(QList<Video*>)), Qt::UniqueConnection);
178     connect(videoSource, SIGNAL(finished(int)),
179             SLOT(searchFinished(int)), Qt::UniqueConnection);
180     connect(videoSource, SIGNAL(error(QString)),
181             SLOT(searchError(QString)), Qt::UniqueConnection);
182
183     searchMore();
184 }
185
186 void PlaylistModel::searchMore(int max) {
187     if (searching) return;
188     searching = true;
189     firstSearch = skip == 1;
190     this->max = max;
191     errorMessage.clear();
192     videoSource->loadVideos(max, skip);
193     skip += max;
194 }
195
196 void PlaylistModel::searchMore() {
197     searchMore(maxItems);
198 }
199
200 void PlaylistModel::searchNeeded() {
201     int remainingRows = videos.size() - m_activeRow;
202     int rowsNeeded = maxItems - remainingRows;
203     if (rowsNeeded > 0)
204         searchMore(rowsNeeded);
205 }
206
207 void PlaylistModel::abortSearch() {
208     beginResetModel();
209     while (!videos.isEmpty())
210         delete videos.takeFirst();
211     // if (videoSource) videoSource->abort();
212     searching = false;
213     m_activeRow = -1;
214     m_activeVideo = 0;
215     skip = 1;
216     endResetModel();
217 }
218
219 void PlaylistModel::searchFinished(int total) {
220     searching = false;
221     canSearchMore = total >= max;
222
223     // update the message item
224     emit dataChanged( createIndex( maxItems, 0 ), createIndex( maxItems, columnCount() - 1 ) );
225
226     if (!videoSource->getSuggestions().isEmpty())
227         emit haveSuggestions(videoSource->getSuggestions());
228
229     if (firstSearch && !videos.isEmpty())
230         handleFirstVideo(videos.first());
231 }
232
233 void PlaylistModel::searchError(QString message) {
234     errorMessage = message;
235     // update the message item
236     emit dataChanged( createIndex( maxItems, 0 ), createIndex( maxItems, columnCount() - 1 ) );
237 }
238
239 void PlaylistModel::addVideos(QList<Video*> newVideos) {
240     if (newVideos.isEmpty()) return;
241     beginInsertRows(QModelIndex(), videos.size(), videos.size() + newVideos.size() - 2);
242     videos.append(newVideos);
243     endInsertRows();
244     foreach (Video* video, newVideos) {
245         connect(video, SIGNAL(gotThumbnail()),
246                 SLOT(updateThumbnail()), Qt::UniqueConnection);
247         video->loadThumbnail();
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 = dynamic_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 channel = searchParams->author();
292         if (!channel.isEmpty() && !searchParams->isTransient()) {
293             QString value;
294             if (!video->userId().isEmpty() && video->userId() != video->author())
295                 value = video->userId() + "|" + video->author();
296             else value = video->author();
297             QStringList channels = settings.value(recentChannelsKey).toStringList();
298             channels.removeAll(value);
299             channels.removeAll(channel);
300             channels.prepend(value);
301             while (channels.size() > maxRecentElements)
302                 channels.removeLast();
303             settings.setValue(recentChannelsKey, channels);
304         }
305     }
306 }
307
308 void PlaylistModel::updateThumbnail() {
309
310     Video *video = static_cast<Video *>(sender());
311     if (!video) {
312         qDebug() << "Cannot get sender";
313         return;
314     }
315
316     int row = rowForVideo(video);
317     emit dataChanged( createIndex( row, 0 ), createIndex( row, columnCount() - 1 ) );
318
319 }
320
321 // --- item removal
322
323 /**
324   * This function does not free memory
325   */
326 bool PlaylistModel::removeRows(int position, int rows, const QModelIndex & /*parent*/) {
327     beginRemoveRows(QModelIndex(), position, position+rows-1);
328     for (int row = 0; row < rows; ++row) {
329         videos.removeAt(position);
330     }
331     endRemoveRows();
332     return true;
333 }
334
335 void PlaylistModel::removeIndexes(QModelIndexList &indexes) {
336     QList<Video*> originalList(videos);
337     QList<Video*> delitems;
338     foreach (QModelIndex index, indexes) {
339         if (index.row() >= originalList.size()) continue;
340         Video* video = originalList.at(index.row());
341         int idx = videos.indexOf(video);
342         if (idx != -1) {
343             beginRemoveRows(QModelIndex(), idx, idx);
344             delitems.append(video);
345             videos.removeAll(video);
346             endRemoveRows();
347         }
348     }
349
350     qDeleteAll(delitems);
351
352 }
353
354 // --- Sturm und drang ---
355
356
357
358 Qt::DropActions PlaylistModel::supportedDropActions() const {
359     return Qt::CopyAction;
360 }
361
362 Qt::DropActions PlaylistModel::supportedDragActions() const {
363     return Qt::CopyAction;
364 }
365
366 Qt::ItemFlags PlaylistModel::flags(const QModelIndex &index) const {
367     if (index.isValid()) {
368         if (index.row() == videos.size()) {
369             // don't drag the "show 10 more" item
370             return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
371         } else return (Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled);
372     }
373     return Qt::ItemIsDropEnabled;
374 }
375
376 QStringList PlaylistModel::mimeTypes() const {
377     QStringList types;
378     types << "application/x-minitube-video";
379     return types;
380 }
381
382 QMimeData* PlaylistModel::mimeData( const QModelIndexList &indexes ) const {
383     VideoMimeData* mime = new VideoMimeData();
384
385     foreach( const QModelIndex &it, indexes ) {
386         int row = it.row();
387         if (row >= 0 && row < videos.size())
388             mime->addVideo( videos.at( it.row() ) );
389     }
390
391     return mime;
392 }
393
394 bool PlaylistModel::dropMimeData(const QMimeData *data,
395                                  Qt::DropAction action, int row, int column,
396                                  const QModelIndex &parent) {
397     if (action == Qt::IgnoreAction)
398         return true;
399
400     if (!data->hasFormat("application/x-minitube-video"))
401         return false;
402
403     if (column > 0)
404         return false;
405
406     int beginRow;
407     if (row != -1)
408         beginRow = row;
409     else if (parent.isValid())
410         beginRow = parent.row();
411     else
412         beginRow = rowCount(QModelIndex());
413
414     const VideoMimeData* videoMimeData = dynamic_cast<const VideoMimeData*>( data );
415     if(!videoMimeData ) return false;
416
417     QList<Video*> droppedVideos = videoMimeData->videos();
418     foreach( Video *video, droppedVideos) {
419         
420         // remove videos
421         int videoRow = videos.indexOf(video);
422         removeRows(videoRow, 1, QModelIndex());
423         
424         // and then add them again at the new position
425         beginInsertRows(QModelIndex(), beginRow, beginRow);
426         videos.insert(beginRow, video);
427         endInsertRows();
428
429     }
430
431     // fix m_activeRow after all this
432     m_activeRow = videos.indexOf(m_activeVideo);
433
434     // let the MediaView restore the selection
435     emit needSelectionFor(droppedVideos);
436
437     return true;
438
439 }
440
441 int PlaylistModel::rowForCloneVideo(const QString &videoId) const {
442     for (int i = 0; i < videos.size(); ++i) {
443         Video *v = videos.at(i);
444         if (v->id() == videoId) return i;
445     }
446     return -1;
447 }
448
449 int PlaylistModel::rowForVideo(Video* video) {
450     return videos.indexOf(video);
451 }
452
453 QModelIndex PlaylistModel::indexForVideo(Video* video) {
454     return createIndex(videos.indexOf(video), 0);
455 }
456
457 void PlaylistModel::move(QModelIndexList &indexes, bool up) {
458     QList<Video*> movedVideos;
459
460     foreach (QModelIndex index, indexes) {
461         int row = index.row();
462         if (row >= videos.size()) continue;
463         // qDebug() << "index row" << row;
464         Video *video = videoAt(row);
465         movedVideos << video;
466     }
467
468     int end=up ? -1 : rowCount()-1, mod=up ? -1 : 1;
469     foreach (Video *video, movedVideos) {
470
471         int row = rowForVideo(video);
472         if (row+mod==end) { end=row; continue; }
473         // qDebug() << "video row" << row;
474         removeRows(row, 1, QModelIndex());
475
476         if (up) row--;
477         else row++;
478
479         beginInsertRows(QModelIndex(), row, row);
480         videos.insert(row, video);
481         endInsertRows();
482
483     }
484
485     emit needSelectionFor(movedVideos);
486
487 }
488
489 /* row hovering */
490
491 void PlaylistModel::setHoveredRow(int row) {
492     int oldRow = hoveredRow;
493     hoveredRow = row;
494     emit dataChanged( createIndex( oldRow, 0 ), createIndex( oldRow, columnCount() - 1 ) );
495     emit dataChanged( createIndex( hoveredRow, 0 ), createIndex( hoveredRow, columnCount() - 1 ) );
496 }
497
498 void PlaylistModel::clearHover() {
499     emit dataChanged( createIndex( hoveredRow, 0 ), createIndex( hoveredRow, columnCount() - 1 ) );
500     hoveredRow = -1;
501 }
502
503 /* clickable author */
504
505 void PlaylistModel::enterAuthorHover() {
506     if (authorHovered) return;
507     authorHovered = true;
508     updateAuthor();
509 }
510
511 void PlaylistModel::exitAuthorHover() {
512     if (!authorHovered) return;
513     authorHovered = false;
514     updateAuthor();
515     setHoveredRow(hoveredRow);
516 }
517
518 void PlaylistModel::enterAuthorPressed() {
519     if (authorPressed) return;
520     authorPressed = true;
521     updateAuthor();
522 }
523
524 void PlaylistModel::exitAuthorPressed() {
525     if (!authorPressed) return;
526     authorPressed = false;
527     updateAuthor();
528 }
529
530 void PlaylistModel::updateAuthor() {
531     emit dataChanged( createIndex( hoveredRow, 0 ), createIndex( hoveredRow, columnCount() - 1 ) );
532 }