~ubuntu-branches/ubuntu/quantal/minitube/quantal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#include "ListModel.h"
#include "videomimedata.h"

#define MAX_ITEMS 10
static const QString recentKeywordsKey = "recentKeywords";
static const QString recentChannelsKey = "recentChannels";

ListModel::ListModel(QWidget *parent) : QAbstractListModel(parent) {
    youtubeSearch = 0;
    searching = false;
    canSearchMore = true;
    m_activeVideo = 0;
    m_activeRow = -1;
    skip = 1;
}

ListModel::~ListModel() {
    delete youtubeSearch;
}

int ListModel::rowCount(const QModelIndex &/*parent*/) const {
    int count = videos.size();
    
    // add the message item
    if (videos.isEmpty() || !searching)
        count++;
    
    return count;
}

QVariant ListModel::data(const QModelIndex &index, int role) const {
    
    int row = index.row();
    
    if (row == videos.size()) {
        
        QPalette palette;
        QFont boldFont;
        boldFont.setBold(true);
        
        switch (role) {
        case ItemTypeRole:
            return ItemTypeShowMore;
        case Qt::DisplayRole:
        case Qt::StatusTipRole:
            if (!errorMessage.isEmpty()) return errorMessage;
            if (searching) return tr("Searching...");
            if (canSearchMore) return tr("Show %1 More").arg(MAX_ITEMS);
            if (videos.isEmpty()) return tr("No videos");
            else return tr("No more videos");
        case Qt::TextAlignmentRole:
            return QVariant(int(Qt::AlignHCenter | Qt::AlignVCenter));
        case Qt::ForegroundRole:
            if (!errorMessage.isEmpty())
                return palette.color(QPalette::ToolTipText);
            else
                return palette.color(QPalette::Dark);
        case Qt::BackgroundColorRole:
            if (!errorMessage.isEmpty())
                return palette.color(QPalette::ToolTipBase);
            else
                return QVariant();
        case Qt::FontRole:
            return boldFont;
        default:
            return QVariant();
        }
        
    } else if (row < 0 || row >= videos.size())
        return QVariant();
    
    Video *video = videos.at(row);
    
    switch (role) {
    case ItemTypeRole:
        return ItemTypeVideo;
    case VideoRole:
        return QVariant::fromValue(QPointer<Video>(video));
    case ActiveTrackRole:
        return video == m_activeVideo;
    case Qt::DisplayRole:
        return video->title();
    }
    
    return QVariant();
}

void ListModel::setActiveRow( int row) {
    if ( rowExists( row ) ) {
        
        m_activeRow = row;
        m_activeVideo = videoAt(row);
        
        int oldactiverow = m_activeRow;
        
        if ( rowExists( oldactiverow ) )
            emit dataChanged( createIndex( oldactiverow, 0 ), createIndex( oldactiverow, columnCount() - 1 ) );
        
        emit dataChanged( createIndex( m_activeRow, 0 ), createIndex( m_activeRow, columnCount() - 1 ) );
        emit activeRowChanged(row);
        
    } else {
        m_activeRow = -1;
        m_activeVideo = 0;
    }

}

int ListModel::nextRow() const {
    int nextRow = m_activeRow + 1;
    if (rowExists(nextRow))
        return nextRow;
    return -1;
}

Video* ListModel::videoAt( int row ) const {
    if ( rowExists( row ) )
        return videos.at( row );
    return 0;
}

Video* ListModel::activeVideo() const {
    return m_activeVideo;
}

void ListModel::search(SearchParams *searchParams) {

    // delete current videos
    while (!videos.isEmpty())
        delete videos.takeFirst();
    m_activeVideo = 0;
    m_activeRow = -1;
    skip = 1;
    errorMessage.clear();
    reset();

    // (re)initialize the YouTubeSearch
    if (youtubeSearch) delete youtubeSearch;
    youtubeSearch = new YouTubeSearch();
    connect(youtubeSearch, SIGNAL(gotVideo(Video*)), this, SLOT(addVideo(Video*)));
    connect(youtubeSearch, SIGNAL(finished(int)), this, SLOT(searchFinished(int)));
    connect(youtubeSearch, SIGNAL(error(QString)), this, SLOT(searchError(QString)));

    this->searchParams = searchParams;
    searching = true;
    youtubeSearch->search(searchParams, MAX_ITEMS, skip);
    skip += MAX_ITEMS;
}

void ListModel::searchMore(int max) {
    if (searching) return;
    searching = true;
    errorMessage.clear();
    youtubeSearch->search(searchParams, max, skip);
    skip += max;
}

void ListModel::searchMore() {
    searchMore(MAX_ITEMS);
}

void ListModel::searchNeeded() {
    int remainingRows = videos.size() - m_activeRow;
    int rowsNeeded = MAX_ITEMS - remainingRows;
    if (rowsNeeded > 0)
        searchMore(rowsNeeded);
}

void ListModel::abortSearch() {
    while (!videos.isEmpty())
        delete videos.takeFirst();
    reset();
    youtubeSearch->abort();
    searching = false;
}

void ListModel::searchFinished(int total) {
    searching = false;
    canSearchMore = total > 0;

    // update the message item
    emit dataChanged( createIndex( MAX_ITEMS, 0 ), createIndex( MAX_ITEMS, columnCount() - 1 ) );
}

void ListModel::searchError(QString message) {
    errorMessage = message;
    // update the message item
    emit dataChanged( createIndex( MAX_ITEMS, 0 ), createIndex( MAX_ITEMS, columnCount() - 1 ) );
}

void ListModel::addVideo(Video* video) {
    
    connect(video, SIGNAL(gotThumbnail()), this, SLOT(updateThumbnail()));

    beginInsertRows(QModelIndex(), videos.size(), videos.size());
    videos << video;
    endInsertRows();
    
    // first result!
    if (videos.size() == 1) {
        // autoplay
        setActiveRow(0);

        // save keyword
        QString query = searchParams->keywords();
        if (!query.isEmpty() && !searchParams->isTransient()) {
            if (query.startsWith("http://")) {
                // Save the video title
                query += "|" + videos.first()->title();
            }
            QSettings settings;
            QStringList keywords = settings.value(recentKeywordsKey).toStringList();
            keywords.removeAll(query);
            keywords.prepend(query);
            while (keywords.size() > 10)
                keywords.removeLast();
            settings.setValue(recentKeywordsKey, keywords);
        }

        // save channel
        QString channel = searchParams->author();
        if (!channel.isEmpty() && !searchParams->isTransient()) {
            QSettings settings;
            QStringList channels = settings.value(recentChannelsKey).toStringList();
            channels.removeAll(channel);
            channels.prepend(channel);
            while (channels.size() > 10)
                channels.removeLast();
            settings.setValue(recentChannelsKey, channels);
        }

    }

}

void ListModel::updateThumbnail() {

    Video *video = static_cast<Video *>(sender());
    if (!video) {
        qDebug() << "Cannot get sender";
        return;
    }

    int row = rowForVideo(video);
    emit dataChanged( createIndex( row, 0 ), createIndex( row, columnCount() - 1 ) );

}

// --- item removal

/**
  * This function does not free memory
  */
bool ListModel::removeRows(int position, int rows, const QModelIndex & /*parent*/) {
    beginRemoveRows(QModelIndex(), position, position+rows-1);
    for (int row = 0; row < rows; ++row) {
        videos.removeAt(position);
    }
    endRemoveRows();
    return true;
}

void ListModel::removeIndexes(QModelIndexList &indexes) {
    QList<Video*> originalList(videos);
    QList<Video*> delitems;
    foreach (QModelIndex index, indexes) {
        if (index.row() >= originalList.size()) continue;
        Video* video = originalList.at(index.row());
        int idx = videos.indexOf(video);
        if (idx != -1) {
            beginRemoveRows(QModelIndex(), idx, idx);
            delitems.append(video);
            videos.removeAll(video);
            endRemoveRows();
        }
    }

    qDeleteAll(delitems);

}

// --- Sturm und drang ---



Qt::DropActions ListModel::supportedDropActions() const {
    return Qt::MoveAction;
}

Qt::ItemFlags ListModel::flags(const QModelIndex &index) const {
    Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index);

    if (index.isValid()) {
        if (index.row() == videos.size()) {
            // don't drag the "show 10 more" item
            return defaultFlags;
        } else
            return ( defaultFlags | Qt::ItemIsDropEnabled | Qt::ItemIsDragEnabled );
    } else
        return Qt::ItemIsDropEnabled | defaultFlags;
}

QStringList ListModel::mimeTypes() const {
    QStringList types;
    types << "application/x-minitube-video";
    return types;
}

QMimeData* ListModel::mimeData( const QModelIndexList &indexes ) const {
    VideoMimeData* mime = new VideoMimeData();

    foreach( const QModelIndex &it, indexes ) {
        int row = it.row();
        if (row >= 0 && row < videos.size())
            mime->addVideo( videos.at( it.row() ) );
    }

    return mime;
}

bool ListModel::dropMimeData(const QMimeData *data,
                             Qt::DropAction action, int row, int column,
                             const QModelIndex &parent) {
    if (action == Qt::IgnoreAction)
        return true;

    if (!data->hasFormat("application/x-minitube-video"))
        return false;

    if (column > 0)
        return false;

    int beginRow;
    if (row != -1)
        beginRow = row;
    else if (parent.isValid())
        beginRow = parent.row();
    else
        beginRow = rowCount(QModelIndex());

    const VideoMimeData* videoMimeData = dynamic_cast<const VideoMimeData*>( data );
    if(!videoMimeData ) return false;

    QList<Video*> droppedVideos = videoMimeData->videos();
    foreach( Video *video, droppedVideos) {
        
        // remove videos
        int videoRow = videos.indexOf(video);
        removeRows(videoRow, 1, QModelIndex());
        
        // and then add them again at the new position
        beginInsertRows(QModelIndex(), beginRow, beginRow);
        videos.insert(beginRow, video);
        endInsertRows();

    }

    // fix m_activeRow after all this
    m_activeRow = videos.indexOf(m_activeVideo);

    // let the MediaView restore the selection
    emit needSelectionFor(droppedVideos);

    return true;

}

int ListModel::rowForVideo(Video* video) {
    return videos.indexOf(video);
}

QModelIndex ListModel::indexForVideo(Video* video) {
    return createIndex(videos.indexOf(video), 0);
}

void ListModel::move(QModelIndexList &indexes, bool up) {
    QList<Video*> movedVideos;

    foreach (QModelIndex index, indexes) {
        int row = index.row();
        if (row >= videos.size()) continue;
        // qDebug() << "index row" << row;
        Video *video = videoAt(row);
        movedVideos << video;
    }

    int end=up ? -1 : rowCount()-1, mod=up ? -1 : 1;
    foreach (Video *video, movedVideos) {

        int row = rowForVideo(video);
        if (row+mod==end) { end=row; continue; }
        // qDebug() << "video row" << row;
        removeRows(row, 1, QModelIndex());

        if (up) row--;
        else row++;

        beginInsertRows(QModelIndex(), row, row);
        videos.insert(row, video);
        endInsertRows();

    }

    emit needSelectionFor(movedVideos);

}