aboutsummaryrefslogtreecommitdiffstats
path: root/src/ivimedia/qiviplayqueue.cpp
blob: 895f6dc3c84c020cbe6f418bc441450e9c281453 (plain)
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
/****************************************************************************
**
** Copyright (C) 2019 Luxoft Sweden AB
** Copyright (C) 2018 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtIVI module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite licenses may use
** this file in accordance with the commercial license agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and The Qt Company.  For
** licensing terms and conditions see https://www.qt.io/terms-conditions.
** For further information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
** SPDX-License-Identifier: LGPL-3.0
**
****************************************************************************/

#include "qiviplayqueue.h"
#include "qiviplayqueue_p.h"
#include "qivimediaplayer.h"
#include "qiviqmlconversion_helper.h"

#include <QtDebug>

QT_BEGIN_NAMESPACE

QIviPlayQueuePrivate::QIviPlayQueuePrivate(QIviMediaPlayer *player, QIviPlayQueue *model)
    : QAbstractItemModelPrivate()
    , q_ptr(model)
    , m_player(player)
    , m_identifier(QUuid::createUuid())
    , m_currentIndex(-1)
    , m_chunkSize(30)
    , m_moreAvailable(false)
    , m_fetchMoreThreshold(10)
    , m_fetchedDataCount(0)
    , m_canReportCount(false)
    , m_loadingType(QIviPlayQueue::FetchMore)
{
    qRegisterMetaType<QIviPlayableItem>();
}

QIviPlayQueuePrivate::~QIviPlayQueuePrivate()
{
}

void QIviPlayQueuePrivate::initialize()
{
    Q_Q(QIviPlayQueue);

    QObject::connect(q, &QAbstractListModel::rowsInserted,
                     q, &QIviPlayQueue::countChanged);
    QObject::connect(q, &QAbstractListModel::rowsRemoved,
                     q, &QIviPlayQueue::countChanged);
    QObject::connect(q, &QAbstractListModel::modelReset,
                     q, &QIviPlayQueue::countChanged);
    QObjectPrivate::connect(q, &QIviPlayQueue::fetchMoreThresholdReached,
                            this, &QIviPlayQueuePrivate::onFetchMoreThresholdReached);
}

void QIviPlayQueuePrivate::onInitializationDone()
{
    if (m_player->isInitialized())
        return;

    resetModel();
}

void QIviPlayQueuePrivate::onCurrentIndexChanged(int currentIndex)
{
    if (m_currentIndex == currentIndex)
        return;
    Q_Q(QIviPlayQueue);
    m_currentIndex = currentIndex;
    emit q->currentIndexChanged(currentIndex);
}

void QIviPlayQueuePrivate::onCanReportCountChanged(bool canReportCount)
{
    m_canReportCount = canReportCount;
}

void QIviPlayQueuePrivate::onDataFetched(const QUuid &identifier, const QList<QVariant> &items, int start, bool moreAvailable)
{
    if (m_identifier != identifier)
        return;

    if (!items.count())
        return;

    Q_Q(QIviPlayQueue);
    m_moreAvailable = moreAvailable;

    if (m_loadingType == QIviPlayQueue::FetchMore) {
        q->beginInsertRows(QModelIndex(), m_itemList.count(), m_itemList.count() + items.count() -1);
        m_itemList += items;
        m_fetchedDataCount = m_itemList.count();
        q->endInsertRows();
    } else {
        if (m_itemList.count() < start + items.count()) {
            qWarning() << "countChanged signal needs to be emitted before the dataFetched signal";
            return;
        }

        m_fetchedDataCount = start + items.count();

        for (int i = 0; i < items.count(); i++)
            m_itemList.replace(start + i, items.at(i));
        emit q->dataChanged(q->index(start), q->index(start + items.count() -1));
    }
}

void QIviPlayQueuePrivate::onCountChanged(int new_length)
{
    if (m_loadingType != QIviPlayQueue::DataChanged || m_itemList.count() == new_length)
        return;

    Q_Q(QIviPlayQueue);
    q->beginInsertRows(QModelIndex(), m_itemList.count(), m_itemList.count() + new_length -1);
    for (int i = 0; i < new_length; i++)
        m_itemList.append(QVariant());
    q->endInsertRows();
}

void QIviPlayQueuePrivate::onDataChanged(const QList<QVariant> &data, int start, int count)
{
    if (start < 0 || start > m_itemList.count()) {
        if (m_loadingType == QIviPlayQueue::DataChanged)
            qWarning("The provided start argument is out of range. Please make sure to emit the countChanged() before emitting dataChanged()");
        return;
    }

    if (count < 0 || count > m_itemList.count() - start) {
        if (m_loadingType == QIviPlayQueue::DataChanged)
            qWarning("The provided start argument is out of range. Please make sure to emit the countChanged() before emitting dataChanged()");
        return;
    }

    Q_Q(QIviPlayQueue);

    //delta > 0 insert rows
    //delta < 0 remove rows
    int delta = data.count() - count;
    //find data overlap for updates
    int updateCount = qMin(data.count(), count);
    int updateCountEnd = updateCount > 0 ? updateCount + 1 : 0;
    //range which is either added or removed
    int insertRemoveStart = start + updateCountEnd;
    int insertRemoveCount = qMax(data.count(), count) - updateCount;

    if (updateCount > 0) {
        for (int i = start, j=0; j < updateCount; i++, j++)
            m_itemList.replace(i, data.at(j));
        emit q->dataChanged(q->index(start), q->index(start + updateCount -1));
    }

    if (delta < 0) { //Remove
        q->beginRemoveRows(QModelIndex(), insertRemoveStart, insertRemoveStart + insertRemoveCount -1);
        for (int i = insertRemoveStart; i < insertRemoveStart + insertRemoveCount; i++)
            m_itemList.removeAt(i);
        q->endRemoveRows();
    } else if (delta > 0) { //Insert
        q->beginInsertRows(QModelIndex(), insertRemoveStart, insertRemoveStart + insertRemoveCount -1);
        for (int i = insertRemoveStart, j = updateCountEnd; i < insertRemoveStart + insertRemoveCount; i++, j++)
            m_itemList.insert(i, data.at(j));
        q->endInsertRows();
    }
}

void QIviPlayQueuePrivate::onFetchMoreThresholdReached()
{
    Q_Q(QIviPlayQueue);
    q->fetchMore(QModelIndex());
}

void QIviPlayQueuePrivate::resetModel()
{
    Q_Q(QIviPlayQueue);
    q->beginResetModel();
    m_itemList.clear();
    q->endResetModel();
    m_fetchedDataCount = 0;

    m_moreAvailable = false;
    q->fetchMore(QModelIndex());
}

void QIviPlayQueuePrivate::clearToDefaults()
{
    Q_Q(QIviPlayQueue);
    m_identifier = QUuid::createUuid();
    m_currentIndex = -1;
    emit q->currentIndexChanged(-1);
    m_chunkSize = 30;
    emit q->chunkSizeChanged(30);
    m_moreAvailable = false;
    m_fetchMoreThreshold = 10;
    emit q->fetchMoreThresholdChanged(m_fetchMoreThreshold);
    m_loadingType = QIviPlayQueue::FetchMore;
    emit q->loadingTypeChanged(m_loadingType);

    resetModel();
}

const QIviPlayableItem *QIviPlayQueuePrivate::itemAt(int i) const
{
    QVariant var = m_itemList.at(i);
    if (!var.isValid())
        return nullptr;

    return qtivi_gadgetFromVariant<QIviPlayableItem>(q_ptr, var);
}

QIviMediaPlayerBackendInterface *QIviPlayQueuePrivate::playerBackend() const
{
    return m_player->d_func()->playerBackend();
}

/*!
    \class QIviPlayQueue
    \inmodule QtIviMedia
    \brief Provides a play queue for the QIviMediaPlayer.

    The QIviPlayQueue is a model which is used by the QIviMediaPlayer to control the
    play order of QIviPlayableItems.

    It provides mechanisms for adding new items and managing the existing ones by removing
    or moving them around.

    The QIviPlayQueue can't be instantiated by its own and can only be retrieved through the QIviMediaPlayer.

    The following roles are available in this model:

    \table
    \header
        \li Role name
        \li Type
        \li Description
    \row
        \li \c name
        \li string
        \li The name of the playable item. E.g. The track name or the name of the web-stream.
    \row
        \li \c type
        \li string
        \li The type of the playable item. E.g. \e "track" or \e "web-stream"
    \row
        \li \c item
        \li QIviPlayableItem
        \li The playable item instance. This can be used to access type specific properties like the artist.
    \endtable

*/

/*!
    \enum QIviPlayQueue::Roles
    \value NameRole
          The name of the playable item. E.g. The track name or the name of the web-stream.
    \value TypeRole
          The type of the playable item. E.g. \e "track" or \e "web-stream"
    \value ItemRole
          The playable item instance. This can be used to access type specific properties like the artist.
*/

/*!
    \enum QIviPlayQueue::LoadingType
    \value FetchMore
           This is the default and can be used if you don't know the final size of the list (e.g. a infinite list).
           The list will detect that it is near the end (fetchMoreThreshold) and then fetch the next chunk of data using canFetchMore and fetchMore.
           The drawback of this method is that, because the final size of the data is not known, you can't display a dynamic scroll-bar indicator which is resized depending on the content of the list.
           The other problem could be fast scrolling, as the data might not come in-time and scrolling stops. This can be tweaked by the fetchMoreThreshold property.

    \value DataChanged
           For this loading type you need to know how many items are in the list, as dummy items are created and the user can already start scrolling even though the data is not yet ready to be displayed.
           Similar to FetchMore the data is also loaded in chunks. You can safely use a scroll indicator here.
           The delegate needs to support this approach, as it doesn't have a content when it's first created.
*/

/*!
    \qmltype PlayQueue
    \instantiates QIviPlayQueue
    \inqmlmodule QtIvi.Media
    \inherits QAbstractListModel
    \brief Provides a play queue for the MediaPlayer.

    The PlayQueue is a model which is used by the MediaPlayer to control the
    play order of PlayableItems.

    It provides mechanisms for adding new items and managing the existing ones by removing
    or moving them around.

    The PlayQueue can't be instantiated by its own and can only be retrieved through the MediaPlayer.
*/


QIviPlayQueue::~QIviPlayQueue()
{
}

/*!
    \qmlproperty int PlayQueue::currentIndex
    \brief Holds the index of the currently active track.

    Use the get() method to retrieve more information about the active track.
*/

/*!
    \property QIviPlayQueue::currentIndex
    \brief Holds the index of the currently active track.

    Use the get() method to retrieve more information about the active track.
*/
int QIviPlayQueue::currentIndex() const
{
    Q_D(const QIviPlayQueue);
    return d->m_currentIndex;
}

void QIviPlayQueue::setCurrentIndex(int currentIndex)
{
    Q_IVI_BACKEND(QIviPlayQueue, d->playerBackend(), "Can't set the current index without a connected backend");

    backend->setCurrentIndex(currentIndex);
}

/*!
    \qmlproperty int PlayQueue::chunkSize
    \brief Holds the number of rows which are requested from the backend interface.

    This property can be used to fine tune the loading performance.

    Bigger chunks means less calls to the backend and to a potential IPC underneath, but more data
    to be transferred and probably longer waiting time until the request was finished.
*/

/*!
    \property QIviPlayQueue::chunkSize
    \brief Holds the number of rows which are requested from the backend interface.

    This property can be used to fine tune the loading performance.

    Bigger chunks means less calls to the backend and to a potential IPC underneath, but more data
    to be transferred and probably longer waiting time until the request was finished.
*/
int QIviPlayQueue::chunkSize() const
{
    Q_D(const QIviPlayQueue);
    return d->m_chunkSize;
}

void QIviPlayQueue::setChunkSize(int chunkSize)
{
    Q_D(QIviPlayQueue);
    if (d->m_chunkSize == chunkSize)
        return;

    d->m_chunkSize = chunkSize;
    emit chunkSizeChanged(chunkSize);
}

/*!
    \qmlproperty int PlayQueue::fetchMoreThreshold
    \brief Holds the row delta to the end before the next chunk is loaded

    This property can be used to fine tune the loading performance. When the
    threshold is reached the next chunk of rows are requested from the backend. How many rows are fetched
    can be defined by using the chunkSize property.

    The threshold defines the number of rows before the cached rows ends.

    \note This property is only used when loadingType is set to FetchMore.
*/

/*!
    \property QIviPlayQueue::fetchMoreThreshold
    \brief Holds the row delta to the end before the next chunk is loaded

    This property can be used to fine tune the loading performance. When the
    threshold is reached the next chunk of rows are requested from the backend. How many rows are fetched
    can be defined by using the chunkSize property.

    The threshold defines the number of rows before the cached rows ends.

    \note This property is only used when loadingType is set to FetchMore.
*/
int QIviPlayQueue::fetchMoreThreshold() const
{
    Q_D(const QIviPlayQueue);
    return d->m_fetchMoreThreshold;
}

void QIviPlayQueue::setFetchMoreThreshold(int fetchMoreThreshold)
{
    Q_D(QIviPlayQueue);
    if (d->m_fetchMoreThreshold == fetchMoreThreshold)
        return;

    d->m_fetchMoreThreshold = fetchMoreThreshold;
    emit fetchMoreThresholdChanged(fetchMoreThreshold);
}

/*!
    \qmlproperty enumeration PlayQueue::loadingType
    \brief Holds the currently used loading type used for loading the data.

    \note When changing this property the content will be reset.
*/

/*!
    \property QIviPlayQueue::loadingType
    \brief Holds the currently used loading type used for loading the data.

    \note When changing this property the content will be reset.
*/
QIviPlayQueue::LoadingType QIviPlayQueue::loadingType() const
{
    Q_D(const QIviPlayQueue);
    return d->m_loadingType;
}

void QIviPlayQueue::setLoadingType(QIviPlayQueue::LoadingType loadingType)
{
    Q_D(QIviPlayQueue);
    if (d->m_loadingType == loadingType)
        return;

    if (loadingType == QIviPlayQueue::DataChanged && !d->m_canReportCount) {
        qtivi_qmlOrCppWarning(this, "The backend doesn't support the DataChanged loading type. This call will have no effect");
        return;
    }

    d->m_loadingType = loadingType;
    emit loadingTypeChanged(loadingType);

    d->resetModel();
}

/*!
    \qmlproperty int PlayQueue::count
    \brief Holds the current number of rows in this model.
*/
/*!
    \property QIviPlayQueue::count
    \brief Holds the current number of rows in this model.
*/
int QIviPlayQueue::rowCount(const QModelIndex &parent) const
{
    Q_D(const QIviPlayQueue);
    if (parent.isValid())
        return 0;

    return d->m_itemList.count();
}

/*!
    \reimp
*/
QVariant QIviPlayQueue::data(const QModelIndex &index, int role) const
{
    Q_D(const QIviPlayQueue);
    if (!index.isValid())
        return QVariant();

    int row = index.row();

    if (row >= d->m_itemList.count() || row < 0)
        return QVariant();

    if (row >= d->m_fetchedDataCount - d->m_fetchMoreThreshold && canFetchMore(QModelIndex()))
        emit fetchMoreThresholdReached();

    const QIviStandardItem *item = d->itemAt(row);
    if (!item)
        return QVariant();

    switch (role) {
        case NameRole: return item->name();
        case TypeRole: return item->type();
        case ItemRole: return d->m_itemList.at(row);
    }

    return QVariant();
}

/*!
    \fn T QIviPlayQueue::at(int i) const

    Returns the item at index \a i converted to the template type T.
*/
/*!
    \qmlmethod object PlayQueue::get(i)

    Returns the item at index \a i.
*/
/*!
    Returns the item at index \a i.

    This function is intended to be used from QML. For C++
    please use the at() instead.
*/
QVariant QIviPlayQueue::get(int i) const
{
    return data(index(i,0), ItemRole);
}

/*!
    \qmlmethod PlayQueue::insert(int index, PlayableItem item)

    Insert the \a item at the position \a index.

    If the backend doesn't accept the provided item, this operation will end in a no op.
*/

/*!
    \fn void QIviPlayQueue::insert(int index, const QVariant &variant)

    Insert the \a variant at the position \a index.

    If the backend doesn't accept the provided item, this operation will end in a no op.
*/
void QIviPlayQueue::insert(int index, const QVariant &variant)
{
    const QIviPlayableItem *item = qtivi_gadgetFromVariant<QIviPlayableItem>(this, variant);
    if (!item)
        return;

    Q_IVI_BACKEND(QIviPlayQueue, d->playerBackend(), "Can't insert items without a connected backend");

    backend->insert(index, variant);
}

/*!
    \qmlmethod PlayQueue::remove(int index)

    Removes the item at position \a index from the play queue.
*/

/*!
    \fn void QIviPlayQueue::remove(int index)

    Removes the item at position \a index from the play queue.
*/
void QIviPlayQueue::remove(int index)
{
    Q_IVI_BACKEND(QIviPlayQueue, d->playerBackend(), "Can't remove items without a connected backend");

    backend->remove(index);
}

/*!
    \qmlmethod PlayQueue::move(int cur_index, int new_index)

    Moves the item at position \a cur_index to the new position \a new_index the play queue.
*/

/*!
    \fn void QIviPlayQueue::move(int cur_index, int new_index)

    Moves the item at position \a cur_index to the new position \a new_index the play queue.
*/
void QIviPlayQueue::move(int cur_index, int new_index)
{
    Q_IVI_BACKEND(QIviPlayQueue, d->playerBackend(), "Can't move items without a connected backend");

    backend->move(cur_index, new_index);
}

/*!
    \reimp
*/
bool QIviPlayQueue::canFetchMore(const QModelIndex &parent) const
{
    Q_D(const QIviPlayQueue);
    if (parent.isValid())
        return false;

    return d->m_moreAvailable;
}

/*!
    \reimp
*/
void QIviPlayQueue::fetchMore(const QModelIndex &parent)
{
    Q_D(QIviPlayQueue);
    if (parent.isValid())
        return;

    if (!d->playerBackend())
        return;

    d->m_moreAvailable = false;
    d->playerBackend()->fetchData(d->m_identifier, d->m_fetchedDataCount, d->m_chunkSize);
}

/*!
    \reimp
*/
QHash<int, QByteArray> QIviPlayQueue::roleNames() const
{
    static QHash<int, QByteArray> roles;
    if (roles.isEmpty()) {
        roles[NameRole] = "name";
        roles[TypeRole] = "type";
        roles[ItemRole] = "item";
    }
    return roles;
}

/*!
    Creates a play queue for the QIviMediaPlayer instance \a parent.
*/
QIviPlayQueue::QIviPlayQueue(QIviMediaPlayer *parent)
    : QAbstractListModel(*new QIviPlayQueuePrivate(parent, this), parent)
{
    Q_D(QIviPlayQueue);
    d->initialize();
}

/*!
    \fn void QIviPlayQueue::fetchMoreThresholdReached() const

    This signal is emitted whenever the fetchMoreThreshold is reached and new data is requested from the backend.
*/

/*!
    \qmlsignal PlayQueue::fetchMoreThresholdReached()

    This signal is emitted whenever the fetchMoreThreshold is reached and new data is requested from the backend.
*/

QT_END_NAMESPACE

#include "moc_qiviplayqueue.cpp"