aboutsummaryrefslogtreecommitdiffstats
path: root/src/ivicore/qivisearchandbrowsemodel.cpp
blob: 637aecc1769c7ff7707f424559f993ea981c5302 (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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
/****************************************************************************
**
** 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 "qivisearchandbrowsemodel.h"
#include "qivisearchandbrowsemodel_p.h"

#include "qiviqmlconversion_helper.h"
#include "qivisearchandbrowsemodelinterface.h"
#include "queryparser/qiviqueryparser_p.h"

#include <QDebug>
#include <QMetaObject>

QT_BEGIN_NAMESPACE

QIviSearchAndBrowseModelPrivate::QIviSearchAndBrowseModelPrivate(const QString &interface, QIviSearchAndBrowseModel *model)
    : QIviAbstractFeatureListModelPrivate(interface, model)
    , q_ptr(model)
    , m_capabilities(QIviSearchAndBrowseModel::NoExtras)
    , m_chunkSize(30)
    , m_queryTerm(nullptr)
    , m_moreAvailable(false)
    , m_identifier(QUuid::createUuid())
    , m_fetchMoreThreshold(10)
    , m_fetchedDataCount(0)
    , m_canGoBack(false)
    , m_loadingType(QIviSearchAndBrowseModel::FetchMore)
{
    qRegisterMetaType<QIviSearchAndBrowseModel::LoadingType>();
    qRegisterMetaType<QIviSearchAndBrowseModelItem>();
}

QIviSearchAndBrowseModelPrivate::~QIviSearchAndBrowseModelPrivate()
{
    delete m_queryTerm;
}

void QIviSearchAndBrowseModelPrivate::initialize()
{
    QIviAbstractFeatureListModelPrivate::initialize();

    Q_Q(QIviSearchAndBrowseModel);
    q->setDiscoveryMode(QIviAbstractFeature::NoAutoDiscovery);

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

void QIviSearchAndBrowseModelPrivate::onCapabilitiesChanged(const QUuid &identifier, QIviSearchAndBrowseModel::Capabilities capabilities)
{
    if (identifier != m_identifier)
        return;

    if (m_capabilities == capabilities)
        return;

    Q_Q(QIviSearchAndBrowseModel);
    m_capabilities = capabilities;
    emit q->capabilitiesChanged(capabilities);
}

void QIviSearchAndBrowseModelPrivate::onDataFetched(const QUuid &identifer, const QList<QVariant> &items, int start, bool moreAvailable)
{
    if (!items.count() || identifer != m_identifier)
        return;

    Q_ASSERT(items.count() <= m_chunkSize);
    Q_ASSERT((start + items.count() - 1) / m_chunkSize == start / m_chunkSize);

    Q_Q(QIviSearchAndBrowseModel);
    m_moreAvailable = moreAvailable;

    if (m_loadingType == QIviSearchAndBrowseModel::FetchMore) {
        q->beginInsertRows(QModelIndex(), m_itemList.count(), m_itemList.count() + items.count() -1);
        m_itemList += items;
        m_fetchedDataCount = m_itemList.count();
        q->endInsertRows();
    } else {
        const int newSize = start + items.count();
        if (m_itemList.count() <  newSize || m_availableChunks.count() < newSize / m_chunkSize) {
            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));

        m_availableChunks.setBit(start / m_chunkSize);

        emit q->dataChanged(q->index(start), q->index(start + items.count() -1));
    }
}

void QIviSearchAndBrowseModelPrivate::onCountChanged(const QUuid &identifier, int new_length)
{
    if (identifier != m_identifier || m_loadingType != QIviSearchAndBrowseModel::DataChanged || m_itemList.count() == new_length)
        return;

    Q_Q(QIviSearchAndBrowseModel);
    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();

    m_availableChunks.resize(new_length / m_chunkSize + 1);
}

void QIviSearchAndBrowseModelPrivate::onDataChanged(const QUuid &identifier, const QList<QVariant> &data, int start, int count)
{
    if (identifier != m_identifier)
        return;

    if (start < 0 || start > m_itemList.count()) {
        qWarning("provided start argument is out of range");
        return;
    }

    if (count < 0 || count > m_itemList.count() - start) {
        qWarning("provided count argument is out of range");
        return;
    }

    Q_Q(QIviSearchAndBrowseModel);

    //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 QIviSearchAndBrowseModelPrivate::onFetchMoreThresholdReached()
{
    Q_Q(QIviSearchAndBrowseModel);
    q->fetchMore(QModelIndex());
}

void QIviSearchAndBrowseModelPrivate::resetModel()
{
    Q_Q(QIviSearchAndBrowseModel);

    q->beginResetModel();
    m_itemList.clear();
    m_availableChunks.clear();
    m_fetchedDataCount = 0;
    //Setting this to true to let fetchMore do one first fetchcall.
    m_moreAvailable = true;
    q->endResetModel();

    if (searchBackend())
        setAvailableContenTypes(searchBackend()->availableContentTypes().toList());

    checkType();
    parseQuery();

    q->fetchMore(QModelIndex());
}

void QIviSearchAndBrowseModelPrivate::parseQuery()
{
    if (!searchBackend())
        return;

    delete m_queryTerm;
    m_queryTerm = nullptr;
    m_orderTerms.clear();

    if (m_query.isEmpty())
        return;

    if (!m_capabilities.testFlag(QIviSearchAndBrowseModel::SupportsFiltering) && !m_capabilities.testFlag(QIviSearchAndBrowseModel::SupportsSorting)) {
        qtivi_qmlOrCppWarning(q_ptr, QStringLiteral("The backend doesn't support filtering or sorting. Changing the query will have no effect"));
        return;
    }

    QIviQueryParser parser;
    parser.setQuery(m_query);
    parser.setAllowedIdentifiers(searchBackend()->supportedIdentifiers(m_contentType));

    m_queryTerm = parser.parse();

    if (!m_queryTerm) {
        qtivi_qmlOrCppWarning(q_ptr, parser.lastError());
        return;
    }
    m_orderTerms = parser.orderTerms();
}

void QIviSearchAndBrowseModelPrivate::checkType()
{
    if (!searchBackend() || m_contentType.isEmpty())
        return;

    if (!m_availableContentTypes.contains(m_contentType)) {
        QString error = QString(QStringLiteral("Unsupported type: \"%1\" \n Supported types are: \n")).arg(m_contentType);
        for (const QString &type : qAsConst(m_availableContentTypes))
            error.append(type + QLatin1String("\n"));
        qtivi_qmlOrCppWarning(q_ptr, error);
    }
}

void QIviSearchAndBrowseModelPrivate::fetchData(int startIndex)
{
    if (!searchBackend() || m_contentType.isEmpty())
        return;

    m_moreAvailable = false;
    const int start = startIndex >= 0 ? startIndex : m_fetchedDataCount;
    const int chunkIndex = start / m_chunkSize;
    if (chunkIndex < m_availableChunks.size())
        m_availableChunks.setBit(chunkIndex);
    searchBackend()->fetchData(m_identifier, m_contentType, m_queryTerm, m_orderTerms, start, m_chunkSize);
}

void QIviSearchAndBrowseModelPrivate::clearToDefaults()
{
    m_chunkSize = 30;
    delete m_queryTerm;
    m_queryTerm = nullptr;
    m_moreAvailable = false;
    m_identifier = QUuid::createUuid();
    m_fetchMoreThreshold = 10;
    m_contentType = QString();
    m_fetchedDataCount = 0;
    m_canGoBack = false;
    m_loadingType = QIviSearchAndBrowseModel::FetchMore;
    m_availableContentTypes.clear();
    m_capabilities = QIviSearchAndBrowseModel::NoExtras;
    m_itemList.clear();
}

void QIviSearchAndBrowseModelPrivate::setCanGoBack(bool canGoBack)
{
    Q_Q(QIviSearchAndBrowseModel);
    if (m_canGoBack == canGoBack)
        return;

    m_canGoBack = canGoBack;
    emit q->canGoBackChanged(m_canGoBack);
}

void QIviSearchAndBrowseModelPrivate::setAvailableContenTypes(const QStringList &contentTypes)
{
    Q_Q(QIviSearchAndBrowseModel);
    if (m_availableContentTypes == contentTypes)
        return;

    m_availableContentTypes = contentTypes;
    emit q->availableContentTypesChanged(contentTypes);
}

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

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

QIviSearchAndBrowseModelInterface *QIviSearchAndBrowseModelPrivate::searchBackend() const
{
    Q_Q(const QIviSearchAndBrowseModel);
    QIviServiceObject *so = q->serviceObject();
    if (so)
        return qobject_cast<QIviSearchAndBrowseModelInterface*>(so->interfaceInstance(QStringLiteral(QIviSearchAndBrowseModel_iid)));

    return nullptr;
}

void QIviSearchAndBrowseModelPrivate::updateContentType(const QString &contentType)
{
    Q_Q(QIviSearchAndBrowseModel);
    m_query = QString();
    emit q->queryChanged(m_query);
    m_contentType = contentType;
    emit q->contentTypeChanged(m_contentType);

    if (searchBackend())
        setCanGoBack(searchBackend()->canGoBack(m_identifier, m_contentType));

    resetModel();
}

/*!
    \class QIviSearchAndBrowseModel
    \inmodule QtIviCore
    \brief The QIviSearchAndBrowseModel is a generic model which can be used to search, browse, filter and sort data.

    The QIviSearchAndBrowseModel should be used directly or as a base class whenever a lot of data needs to be
    presented in a ListView.

    The model is built upon the basic principle of filtering and sorting the data already where
    they are created instead of retrieving everything and sort or filter it locally. In addition the QIviSearchAndBrowseModel
    only fetches the data it really needs and can it can be configured how this can be done.

    The backend filling the model with data needs to implement the QIviSearchAndBrowseModelInterface class.

    \section1 Setting it up
    The QIviSearchAndBrowseModel is using QtIviCore's \l {Dynamic Backend System} and is derived from QIviAbstractFeatureListModel.
    Other than most "QtIvi Feature classes", the QIviSearchAndBrowseModel doesn't automatically connect to available backends.

    The easiest approach to set it up, is to connect to the same backend used by another feature. E.g. for connecting to the
    media backend, use the instance from the mediaplayer feature:
    \code
        QIviMediaPlayer *player = new QIviMediaPlayer();
        player->startAutoDiscovery();
        QIviSearchAndBrowseModel *model = new QIviSearchAndBrowseModel();
        model->setServiceObject(player->serviceObject());
    \endcode

    \section2 Content Types

    Once the model is connected to a backend, the contentType needs to be selected. All possible content types can be queried
    from the availableContentTypes property. As the name already suggests, this property selects what type of content
    should be shown in the model. For the mediaplayer example, the available content types could be "track", "album" and "artist".

    \section1 Filtering and Sorting
    \target FilteringAndSorting

    One of the main use case of the QIviSearchAndBrowseModel is to provide a powerful way of filtering and sorting the content
    of the underlying data model. As explained above, the filtering and sorting is supposed to happen where the data is produced.
    To make this work across multiple backends the \l {Qt IVI Query Language} was invented.

    The \l {QIviSearchAndBrowseModel::}{query} property is used to sort the content of the model: e.g. by setting the string "[/name]", the content
    will be sorted by name in ascending order.

    For filtering, the same property is used but without the brackets e.g. "name='Example Item'" for only showing items which
    have the 'name' property set to 'Example Item'.

    Filtering and sorting can also be combined in one string and the filter part can also be more complex. More on that
    can be found in the detailed \l {Qt IVI Query Language} Documentation.

    \section1 Browsing
    \target Browsing

    In addition to filtering and sorting, the QIviSearchAndBrowseModel also supports browsing through a hierarchy of different
    content types. The easiest way to explain this is to look at the existing media example.

    When implementing a library view of all available media files, you might want to provide a way for the user to browse
    through the media database and select a song. You might also want to provide several staring points and from there
    limit the results. E.g.

    \list
        \li Artist -> Album -> Track
        \li Album -> Track
        \li Track
    \endlist

    This can be achieved by defining a complex filter query which takes the previously selected item into account.
    That is the most powerful way of doing it, as the developer/designer can define the browsing order and it can easily
    be changed. The downside of this is that the backend needs to support this way of filtering and sorting as well, which
    is not always be the case. A good example here is a DLNA backend, where the server already defines a fixed  browsing order.

    The QIviSearchAndBrowseModel provides the following methods for browsing:
    \list
        \li canGoForward()
        \li goForward()
        \li canGoBack()
        \li goBack()
    \endlist

    \section2 Navigation Types

    The QIviSearchAndBrowseModel supports two navigation types when browsing through the available data: for most use cases
    the simple InModelNavigation type is sufficient. By using this, the content type of the current model instance changes
    when navigating and the model is reset to show the new data.
    The other navigation type is OutOfModelNavigation and leaves the current model instance as it is. Instead the goForward()
    method returns a new model instance which contains the new data. This is especially useful when several views need to
    be open at the same time. E.g. when used inside a QML StackView.

    \code
        QIviSearchAndBrowseModel *artistModel = new QIviSearchAndBrowseModel();
        model->setContentType("artist");
        //Returns a new instance of QIviSearchAndBrowseModel which contains all albums from the artist at index '0'
        QIviSearchAndBrowseModel *albumModel = artistModel->goForward(0, QIviSearchAndBrowseModel::OutOfModelNavigation);
    \endcode

    \section1 Loading Types

    Multiple loading types are supported, as the QIviSearchAndBrowseModel is made to work with asynchronous requests to
    fetch its data. The FetchMore loading type is the default and is using the \l{QAbstractItemModel::}{canFetchMore()}/\l{QAbstractItemModel::}{fetchMore()} functions of
    QAbstractItemModel to fetch new data once the view hits the end of the currently available data. As fetching can take
    some time, there is the fetchMoreThreshold property which controls how much in advance a new fetch should be started.

    The other loading type is DataChanged. In contrast to FetchMore, the complete model is pre-populated with empty rows
    and the actual data for a specific row is fetched the first time the data() function is called. Once the data is available,
    the dataChanged() signal will be triggered for this row and the view will start to render the new data.

    Please see the documentation of \l{QIviSearchAndBrowseModel::}{LoadingType} for more details on how the modes work and
    when they are suitable to use.
*/

/*!
    \enum QIviSearchAndBrowseModel::NavigationType
    \value InModelNavigation
           The new content will be loaded into this model and the existing model data will be reset
    \value OutOfModelNavigation
           A new model will be returned which loads the new content. The model data of this model will
           not be changed and can still be used.
*/

/*!
    \enum QIviSearchAndBrowseModel::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 you can't display a dynamic scroll-bar indicator which is resized depending on the content of the list,
           because the final size of the data is not known.
           The other problem could be fast scrolling, as the data might not arrive 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 content when it's first created.
*/

/*!
    \enum QIviSearchAndBrowseModel::Roles
    \value NameRole
          The name of the item. E.g. The name of a contact in a addressbook, or the artist-name in a list of artists.
    \value TypeRole
          The type of the item. E.g. "artist", "track", "contact".
    \value ItemRole
          The item itself. This provides access to the properties which are type specific. E.g. the address of a contact.
    \value CanGoForwardRole
          True if this item can be used to go one level forward and display the next set of items. \sa goForward()
*/

/*!
    \enum QIviSearchAndBrowseModel::Capability
    \value NoExtras
           The backend does only support the minimum feature set and is stateful.
    \value SupportsFiltering
           The backend supports filtering of the content. QIviSearchAndBrowseModelInterface::availableContentTypes() and QIviSearchAndBrowseModelInterface::supportedIdentifiers() will be used as input for the
           \l {Qt IVI Query Language}. \sa QIviSearchAndBrowseModelInterface::registerContentType
    \value SupportsSorting
           The backend supports sorting of the content. QIviSearchAndBrowseModelInterface::availableContentTypes() and QIviSearchAndBrowseModelInterface::supportedIdentifiers() will be used as input for the
           \l {Qt IVI Query Language}. \sa QIviSearchAndBrowseModelInterface::registerContentType
    \value SupportsAndConjunction
           The backend supports handling multiple filters at the same time and these filters can be combined by using the AND conjunction.
    \value SupportsOrConjunction
           The backend supports handling multiple filters at the same time and these filters can be combined by using the OR conjunction.
    \value SupportsStatelessNavigation
           The backend is stateless and supports handling multiple instances of a QIviSearchAndBrowseModel requesting different data at the same time.
           E.g. One request for artists, sorted by name and another request for tracks. The backend has to consider that both request come from models which are
           currently visible at the same time.
    \value SupportsGetSize
           The backend can return the final number of items for a specific request. This makes it possible to support the QIviSearchAndBrowseModel::DataChanged loading
           type.
    \value SupportsInsert
           The backend supports inserting new items at a given position.
    \value SupportsMove
           The backend supports moving items within the model.
    \value SupportsRemove
           The backend supports removing items from the model.
*/

/*!
    \qmltype SearchAndBrowseModel
    \instantiates QIviSearchAndBrowseModel
    \inqmlmodule QtIvi
    \inherits AbstractFeatureListModel
    \brief The SearchAndBrowseModel is a generic model which can be used to search, browse, filter and sort data.

    The SearchAndBrowseModel should be used directly or as a base class whenever a lot of data needs to be
    presented in a ListView.

    The model is built upon the basic principle of filtering and sorting the data already where
    they are created instead of retrieving everything and sort or filter it locally. In addition the SearchAndBrowseModel
    only fetches the data it really needs and can it can be configured how this can be done.

    All rows in the model need to be subclassed from SearchAndBrowseModelItem.

    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 item. E.g. The name of a contact in a addressbook, or the artist-name in a list of artists.
    \row
        \li \c type
        \li string
        \li The type of the item. E.g. "artist", "track", "contact".
    \row
        \li \c item
        \li object
        \li The item itself. This provides access to the properties which are type specific. E.g. the address of a contact.
    \row
        \li \c canGoForward
        \li bool
        \li True if this item can be used to go one level forward and display the next set of items. \sa goForward()
    \endtable

    \section1 Setting it up
    The SearchAndBrowseModel is using QtIviCore's \l {Dynamic Backend System} and is derived from QIviAbstractFeatureListModel.
    Other than most "QtIvi Feature classes", the SearchAndBrowseModel doesn't automatically connect to available backends.

    The easiest approach to set it up, is to connect to the same backend used by another feature. E.g. for connecting to the
    media backend, use the instance from the mediaplayer feature:
    \qml
        Item {
            MediaPlayer {
                id: player
            }

            SearchAndBrowseModel {
                serviceObject: player.serviceObject
            }
        }
    \endqml

    \section2 Content Types

    Once the model is connected to a backend, the contentType needs to be selected. All possible content types can be queried
    from the availableContentTypes property. As the name already suggests, this property selects what type of content
    should be shown in the model. For the mediaplayer example, the available content types could be "track", "album" and "artist".

    \section1 Filtering and Sorting
    \target FilteringAndSorting

    One of the main use case of the SearchAndBrowseModel is to provide a powerful way of filtering and sorting the content
    of the underlying data model. As explained above, the filtering and sorting is supposed to happen where the data is produced.
    To make this work across multiple backends the \l {Qt IVI Query Language} was invented.

    The \l {SearchAndBrowseModel::}{query} property is used to sort the content of the model: e.g. by setting the string "[/name]", the content
    will be sorted by name in ascending order.

    For filtering, the same property is used but without the brackets e.g. "name='Example Item'" for only showing items which
    have the 'name' property set to 'Example Item'.

    Filtering and sorting can also be combined in one string and the filter part can also be more complex. More on that
    can be found in the detailed \l {Qt IVI Query Language} Documentation.

    \section1 Browsing
    \target Browsing

    In addition to filtering and sorting, the SearchAndBrowseModel also supports browsing through a hierarchy of different
    content types. The easiest way to explain this is to look at the existing media example.

    When implementing a library view of all available media files, you might want to provide a way for the user to browse
    through the media database and select a song. You might also want to provide several staring points and from there
    limit the results. E.g.

    \list
        \li Artist -> Album -> Track
        \li Album -> Track
        \li Track
    \endlist

    This can be achieved by defining a complex filter query which takes the previously selected item into account.
    That is the most powerful way of doing it, as the developer/designer can define the browsing order and it can easily
    be changed. The downside of this is that the backend needs to support this way of filtering and sorting as well, which
    is not always be the case. A good example here is a DLNA backend, where the server already defines a fixed  browsing order.

    The SearchAndBrowseModel provides the following methods/properties for browsing:
    \list
        \li canGoForward()
        \li goForward()
        \li canGoBack
        \li goBack()
    \endlist

    \section2 Navigation Types

    The SearchAndBrowseModel supports two navigation types when browsing through the available data: for most use cases
    the simple InModelNavigation type is sufficient. By using this, the content type of the current model instance changes
    when navigating and the model is reset to show the new data.
    The other navigation type is OutOfModelNavigation and leaves the current model instance as it is. Instead the goForward()
    method returns a new model instance which contains the new data. This is especially useful when several views need to
    be open at the same time. E.g. when used inside a QML StackView.

    \qml
        StackView {
            id: stack
            initialItem: view

            Component {
                id: view
                ListView {
                    model: SearchAndBrowseModel {
                        contentType: "artist"
                    }
                    delegate: MouseArea {
                        onClicked: {
                            stack.push({ "item" : view,
                                        "properties:" {
                                            "model" : model->goForward(index, SearchAndBrowseModel.OutOfModelNavigation)
                                        }});
                        }
                    }
                }
            }
        }
    \endqml

    \section1 Loading Types

    Multiple loading types are supported, as the SearchAndBrowseModel is made to work with asynchronous requests to
    fetch its data. The FetchMore loading type is the default and is using the \l{QAbstractItemModel::}{canFetchMore()}/\l{QAbstractItemModel::}{fetchMore()} functions of
    QAbstractItemModel to fetch new data once the view hits the end of the currently available data. As fetching can take
    some time, there is the fetchMoreThreshold property which controls how much in advance a new fetch should be started.

    The other loading type is DataChanged. In contrast to FetchMore, the complete model is pre-populated with empty rows
    and the actual data for a specific row is fetched the first time the data() function is called. Once the data is available,
    the dataChanged() signal will be triggered for this row and the view will start to render the new data.

    Please see the documentation of loadingType for more details on how the modes work and
    when they are suitable to use.
*/

/*!
    Constructs a QIviSearchAndBrowseModel.

    The \a parent argument is passed on to the \l QIviAbstractFeatureListModel base class.
*/
QIviSearchAndBrowseModel::QIviSearchAndBrowseModel(QObject *parent)
    : QIviAbstractFeatureListModel(*new QIviSearchAndBrowseModelPrivate(QStringLiteral(QIviSearchAndBrowseModel_iid), this), parent)
{
}

/*!
    \qmlproperty enumeration SearchAndBrowseModel::capabilities
    \brief Holds the capabilities of the backend for the current content of the model.

    The capabilities controls what the current contentType supports. e.g. filtering or sorting.
    It can be a combination of the following values:

    \value NoExtras
           The backend does only support the minimum feature set and is stateful.
    \value SupportsFiltering
           The backend supports filtering of the content. QIviSearchAndBrowseModelInterface::availableContentTypes() and QIviSearchAndBrowseModelInterface::supportedIdentifiers() will be used as input for the
           \l {Qt IVI Query Language}. \sa QIviSearchAndBrowseModelInterface::registerContentType
    \value SupportsSorting
           The backend supports sorting of the content. QIviSearchAndBrowseModelInterface::availableContentTypes() and QIviSearchAndBrowseModelInterface::supportedIdentifiers() will be used as input for the
           \l {Qt IVI Query Language}. \sa QIviSearchAndBrowseModelInterface::registerContentType
    \value SupportsAndConjunction
           The backend supports handling multiple filters at the same time and these filters can be combined by using the AND conjunction.
    \value SupportsOrConjunction
           The backend supports handling multiple filters at the same time and these filters can be combined by using the OR conjunction.
    \value SupportsStatelessNavigation
           The backend is stateless and supports handling multiple instances of a QIviSearchAndBrowseModel requesting different data at the same time.
           E.g. One request for artists, sorted by name and another request for tracks. The backend has to consider that both request come from models which are
           currently visible at the same time.
    \value SupportsGetSize
           The backend can return the final number of items for a specific request. This makes it possible to support the QIviSearchAndBrowseModel::DataChanged loading
           type.
    \value SupportsInsert
           The backend supports inserting new items at a given position.
    \value SupportsMove
           The backend supports moving items within the model.
    \value SupportsRemove
           The backend supports removing items from the model.
*/

/*!
    \property QIviSearchAndBrowseModel::capabilities
    \brief Holds the capabilities of the backend for the current content of the model.

    The capabilities controls what the current contentType supports. e.g. filtering or sorting.
*/

QIviSearchAndBrowseModel::Capabilities QIviSearchAndBrowseModel::capabilities() const
{
    Q_D(const QIviSearchAndBrowseModel);
    return d->m_capabilities;
}

/*!
    \qmlproperty string SearchAndBrowseModel::query
    \brief Holds the current query used for filtering and sorting the current content of the model.

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

    See \l {Qt IVI Query Language} for more information.
    \sa FilteringAndSorting
*/

/*!
    \property QIviSearchAndBrowseModel::query
    \brief Holds the current query used for filtering and sorting the current content of the model.

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

    See \l {Qt IVI Query Language} for more information.
    \sa FilteringAndSorting
*/
QString QIviSearchAndBrowseModel::query() const
{
    Q_D(const QIviSearchAndBrowseModel);
    return d->m_query;
}

void QIviSearchAndBrowseModel::setQuery(const QString &query)
{
    Q_D(QIviSearchAndBrowseModel);
    if (d->m_query == query)
        return;

    //TODO If we use the stateless navigation this needs to be prevented on the second+ model

    d->m_query = query;
    emit queryChanged(d->m_query);

    //The query is checked in resetModel
    d->resetModel();
}

/*!
    \qmlproperty int SearchAndBrowseModel::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 QIviSearchAndBrowseModel::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 QIviSearchAndBrowseModel::chunkSize() const
{
    Q_D(const QIviSearchAndBrowseModel);
    return d->m_chunkSize;
}

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

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

/*!
    \qmlproperty int SearchAndBrowseModel::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 QIviSearchAndBrowseModel::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 QIviSearchAndBrowseModel::fetchMoreThreshold() const
{
    Q_D(const QIviSearchAndBrowseModel);
    return d->m_fetchMoreThreshold;
}

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

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

/*!
    \qmlproperty string SearchAndBrowseModel::contentType
    \brief Holds the current type of content displayed in this model.

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

    \sa SearchAndBrowseModel::availableContentTypes
*/

/*!
    \property QIviSearchAndBrowseModel::contentType
    \brief Holds the current type of content displayed in this model.

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

    \sa availableContentTypes
*/
QString QIviSearchAndBrowseModel::contentType() const
{
    Q_D(const QIviSearchAndBrowseModel);
    return d->m_contentType;
}

void QIviSearchAndBrowseModel::setContentType(const QString &contentType)
{
    Q_D(QIviSearchAndBrowseModel);
    if (d->m_contentType == contentType)
        return;

    d->updateContentType(contentType);
}

/*!
    \qmlproperty list<string> SearchAndBrowseModel::availableContentTypes
    \brief Holds all the available content types

    \sa contentType
*/

/*!
    \property QIviSearchAndBrowseModel::availableContentTypes
    \brief Holds all the available content types

    \sa contentType
*/
QStringList QIviSearchAndBrowseModel::availableContentTypes() const
{
    Q_D(const QIviSearchAndBrowseModel);
    return d->m_availableContentTypes;
}

/*!
    \qmlproperty bool SearchAndBrowseModel::canGoBack
    \brief Holds whether the goBack() function can be used to return to the previous content.

    See \l Browsing for more information.
*/

/*!
    \property QIviSearchAndBrowseModel::canGoBack
    \brief Holds whether the goBack() function can be used to return to the previous content.

    See \l Browsing for more information.
*/
bool QIviSearchAndBrowseModel::canGoBack() const
{
    Q_D(const QIviSearchAndBrowseModel);
    return d->m_canGoBack;
}

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

    It can be one of the following values:
    \target FetchMore
    \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 you can't display a dynamic scroll-bar indicator which is resized depending on the content of the list,
           because the final size of the data is not known.
           The other problem could be fast scrolling, as the data might not arrive in-time and scrolling stops. This can be tweaked by the fetchMoreThreshold property.

    \target DataChanged
    \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 content when it's first created.

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

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

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

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

    if (loadingType == QIviSearchAndBrowseModel::DataChanged && !d->m_capabilities.testFlag(QIviSearchAndBrowseModel::SupportsGetSize)) {
        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 SearchAndBrowseModel::count
    \brief Holds the current number of rows in this model.
*/
/*!
    \property QIviSearchAndBrowseModel::count
    \brief Holds the current number of rows in this model.
*/
int QIviSearchAndBrowseModel::rowCount(const QModelIndex &parent) const
{
    Q_D(const QIviSearchAndBrowseModel);
    if (parent.isValid())
        return 0;

    return d->m_itemList.count();
}

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

    int row = index.row();

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

    const int chunkIndex = row / d->m_chunkSize;
    if (d->m_loadingType == DataChanged && !d->m_availableChunks.at(chunkIndex)) {
        //qWarning() << "Cache miss: Fetching Data for index " << row << "and following";
        const_cast<QIviSearchAndBrowseModelPrivate*>(d)->fetchData(chunkIndex * d->m_chunkSize);
        return QVariant();
    }

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

    const QIviSearchAndBrowseModelItem *item = d->itemAt(row);
    if (!item) {
        //qWarning() << "Cache miss: Waiting for fetched Data";
        return QVariant();
    }

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

    return QVariant();
}

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

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

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

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

/*!
    \qmlmethod void SearchAndBrowseModel::goBack()
    Goes one level back in the navigation history.

    See also \l Browsing for more information.
*/
/*!
    Goes one level back in the navigation history.

    See also \l Browsing for more information.
*/
void QIviSearchAndBrowseModel::goBack()
{
    Q_D(QIviSearchAndBrowseModel);
    QIviSearchAndBrowseModelInterface *backend = d->searchBackend();

    if (!backend) {
        qtivi_qmlOrCppWarning(this, "No backend connected");
        return;
    }

    if (!backend->canGoBack(d->m_identifier, d->m_contentType)) {
        qtivi_qmlOrCppWarning(this, "Can't go backward anymore");
        return;
    }

    QString newContentType = backend->goBack(d->m_identifier, d->m_contentType);
    if (!newContentType.isEmpty())
        d->updateContentType(newContentType);
}

/*!
    \qmlmethod bool SearchAndBrowseModel::canGoForward(i)
    Returns true when the item at index \a i can be used to show the next set of elements.

    See also \l Browsing for more information.
*/
/*!
    Returns true when the item at index \a i can be used to show the next set of elements.

    See also \l Browsing for more information.
*/
bool QIviSearchAndBrowseModel::canGoForward(int i) const
{
    Q_D(const QIviSearchAndBrowseModel);
    QIviSearchAndBrowseModelInterface *backend = d->searchBackend();

    if (i >= d->m_itemList.count() || i < 0)
        return false;

    if (!backend) {
        qtivi_qmlOrCppWarning(this, "No backend connected");
        return false;
    }

    const QIviSearchAndBrowseModelItem *item = d->itemAt(i);
    if (!item)
        return false;

    return backend->canGoForward(d->m_identifier, d->m_contentType, item->id());
}

/*!
    \qmlmethod SearchAndBrowseModel SearchAndBrowseModel::goForward(i, navigationType)
    Uses the item at index \a i and shows the next set of items.

    \a navigationType can be one of the following values:
    \target InModelNavigation
    \value InModelNavigation
           The new content will be loaded into this model and the existing model data will be reset
    \target OutOfModelNavigation
    \value OutOfModelNavigation
           A new model will be returned which loads the new content. The model data of this model will
           not be changed and can still be used.

    \note Whether the OutOfModelNavigation navigation type is supported is decided by the backend.

    See also \l Browsing for more information.
*/
/*!
    Returns true when the item at index \a i can be used to show the next set of elements.

    Uses the item at index \a i and shows the next set of items. The \a navigationType can be used
    to control whether the new data should be shown in this model instance or whether a new instance
    should be created and returned. If a instance is returned, this instance is owned
    by the caller.

    \note Whether the OutOfModelNavigation navigation type is supported is decided by the backend.

    See also \l Browsing for more information.
*/
QIviSearchAndBrowseModel *QIviSearchAndBrowseModel::goForward(int i, NavigationType navigationType)
{
    Q_D(QIviSearchAndBrowseModel);
    QIviSearchAndBrowseModelInterface *backend = d->searchBackend();

    if (i >= d->m_itemList.count() || i < 0)
        return nullptr;

    if (!backend) {
        qtivi_qmlOrCppWarning(this, "No backend connected");
        return nullptr;
    }

    const QIviSearchAndBrowseModelItem *item = d->itemAt(i);
    if (!item)
        return nullptr;

    if (!backend->canGoForward(d->m_identifier, d->m_contentType, item->id())) {
        qtivi_qmlOrCppWarning(this, "Can't go forward anymore");
        return nullptr;
    }

    if (navigationType == OutOfModelNavigation) {
        if (d->m_capabilities.testFlag(QIviSearchAndBrowseModel::SupportsStatelessNavigation)) {
            QString newContentType = backend->goForward(d->m_identifier, d->m_contentType, item->id());
            auto newModel = new QIviSearchAndBrowseModel(serviceObject(), newContentType);
            return newModel;
        } else {
            qtivi_qmlOrCppWarning(this, "The backend doesn't support the OutOfModelNavigation");
            return nullptr;
        }
    } else {
        QString newContentType = backend->goForward(d->m_identifier, d->m_contentType, item->id());
        d->updateContentType(newContentType);
    }

    return nullptr;
}

/*!
    \qmlmethod SearchAndBrowseModel::insert(int index, SearchAndBrowseModelItem 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.

    The returned PendingReply notifies about when the action has been done or whether it failed.
*/

/*!
    \fn void QIviSearchAndBrowseModel::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.

    The returned QIviPendingReply notifies about when the action has been done or whether it failed.
*/
QIviPendingReply<void> QIviSearchAndBrowseModel::insert(int index, const QVariant &variant)
{
    Q_D(QIviSearchAndBrowseModel);
    const auto item = qtivi_gadgetFromVariant<QIviSearchAndBrowseModelItem>(this, variant);
    if (!item)
        return QIviPendingReply<void>::createFailedReply();

    QIviSearchAndBrowseModelInterface *backend = d->searchBackend();
    if (!backend) {
        qtivi_qmlOrCppWarning(this, "Can't insert itmes without a connected backend");
        return QIviPendingReply<void>::createFailedReply();
    }

    if (!d->m_capabilities.testFlag(SupportsInsert)) {
        qtivi_qmlOrCppWarning(this, "The backend doesn't support inserting items");
        return QIviPendingReply<void>::createFailedReply();
    }

    return backend->insert(d->m_identifier, d->m_contentType, index, item);
}

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

    Removes the item at position \a index.

    The returned PendingReply notifies about when the action has been done or whether it failed.
*/

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

    Removes the item at position \a index.

    The returned QIviPendingReply notifies about when the action has been done or whether it failed.
*/
QIviPendingReply<void> QIviSearchAndBrowseModel::remove(int index)
{
    Q_D(QIviSearchAndBrowseModel);
    QIviSearchAndBrowseModelInterface *backend = d->searchBackend();
    if (!backend) {
        qtivi_qmlOrCppWarning(this, "Can't remove items without a connected backend");
        return QIviPendingReply<void>::createFailedReply();
    }

    if (!d->m_capabilities.testFlag(SupportsRemove)) {
        qtivi_qmlOrCppWarning(this, "The backend doesn't support removing of items");
        return QIviPendingReply<void>::createFailedReply();
    }

    return backend->remove(d->m_identifier, d->m_contentType, index);
}

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

    Moves the item at position \a cur_index to the new position \a new_index.

    The returned PendingReply notifies about when the action has been done or whether it failed.
*/

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

    Moves the item at position \a cur_index to the new position \a new_index.

    The returned QIviPendingReply notifies about when the action has been done or whether it failed.
*/
QIviPendingReply<void> QIviSearchAndBrowseModel::move(int cur_index, int new_index)
{
    Q_D(QIviSearchAndBrowseModel);
    QIviSearchAndBrowseModelInterface *backend = d->searchBackend();
    if (!backend) {
        qtivi_qmlOrCppWarning(this, "Can't move items without a connected backend");
        return QIviPendingReply<void>::createFailedReply();
    }

    if (!d->m_capabilities.testFlag(SupportsMove)) {
        qtivi_qmlOrCppWarning(this, "The backend doesn't support moving of items");
        return QIviPendingReply<void>::createFailedReply();
    }

    return backend->move(d->m_identifier, d->m_contentType, cur_index, new_index);
}

/*!
    \qmlmethod SearchAndBrowseModel::indexOf(SearchAndBrowseModelItem item)

    Determines the index of \a item in this model.

    The result is returned as a PendingReply.
*/

/*!
    \fn void QIviSearchAndBrowseModel::indexOf(const QVariant &variant)

    Determines the index of \a item in this model.

    The result is returned as a QIviPendingReply.
*/
QIviPendingReply<int> QIviSearchAndBrowseModel::indexOf(const QVariant &variant)
{
    Q_D(QIviSearchAndBrowseModel);
    const auto *item = qtivi_gadgetFromVariant<QIviSearchAndBrowseModelItem>(this, variant);
    if (!item)
        return QIviPendingReply<int>::createFailedReply();

    QIviSearchAndBrowseModelInterface *backend = d->searchBackend();
    if (!backend) {
        qtivi_qmlOrCppWarning(this, "Can't get the index without a connected backend");
        return QIviPendingReply<int>::createFailedReply();
    }

    return backend->indexOf(d->m_identifier, d->m_contentType, item);
}

/*!
    \qmlmethod SearchAndBrowseModel::reload()

    Resets the model and starts fetching the content again.
*/
/*!
    Resets the model and starts fetching the content again.
*/
void QIviSearchAndBrowseModel::reload()
{
    Q_D(QIviSearchAndBrowseModel);
    d->resetModel();
}

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

    return d->m_moreAvailable;
}

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

    if (!d->searchBackend() || d->m_contentType.isEmpty())
        return;

    if (!d->m_moreAvailable)
        return;

    d->m_moreAvailable = false;
    d->fetchData(-1);
}

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

/*!
    \internal
*/
QIviSearchAndBrowseModel::QIviSearchAndBrowseModel(QIviServiceObject *serviceObject, const QString &contentType, QObject *parent)
    : QIviSearchAndBrowseModel(parent)
{
    setServiceObject(serviceObject);
    setContentType(contentType);
}

/*!
    \internal
*/
QIviSearchAndBrowseModel::QIviSearchAndBrowseModel(QIviSearchAndBrowseModelPrivate &dd, QObject *parent)
    : QIviAbstractFeatureListModel(dd, parent)
{
}

/*!
    \reimp
*/
bool QIviSearchAndBrowseModel::acceptServiceObject(QIviServiceObject *serviceObject)
{
    if (serviceObject)
        return serviceObject->interfaces().contains(interfaceName());
    return false;
}

/*!
    \reimp
*/
void QIviSearchAndBrowseModel::connectToServiceObject(QIviServiceObject *serviceObject)
{
    Q_D(QIviSearchAndBrowseModel);

    QIviSearchAndBrowseModelInterface *backend = d->searchBackend();
    if (!backend)
        return;

    QObjectPrivate::connect(backend, &QIviSearchAndBrowseModelInterface::supportedCapabilitiesChanged,
                            d, &QIviSearchAndBrowseModelPrivate::onCapabilitiesChanged);
    QObjectPrivate::connect(backend, &QIviSearchAndBrowseModelInterface::dataFetched,
                            d, &QIviSearchAndBrowseModelPrivate::onDataFetched);
    QObjectPrivate::connect(backend, &QIviSearchAndBrowseModelInterface::countChanged,
                            d, &QIviSearchAndBrowseModelPrivate::onCountChanged);
    QObjectPrivate::connect(backend, &QIviSearchAndBrowseModelInterface::dataChanged,
                            d, &QIviSearchAndBrowseModelPrivate::onDataChanged);

    QIviAbstractFeatureListModel::connectToServiceObject(serviceObject);

    d->setCanGoBack(backend->canGoBack(d->m_identifier, d->m_contentType));

    d->resetModel();
}

/*!
    \reimp
*/
void QIviSearchAndBrowseModel::disconnectFromServiceObject(QIviServiceObject *serviceObject)
{
    auto backend = qobject_cast<QIviSearchAndBrowseModelInterface*>(serviceObject->interfaceInstance(QStringLiteral(QIviSearchAndBrowseModel_iid)));

    if (backend)
        disconnect(backend, nullptr, this, nullptr);
}

/*!
    \reimp
*/
void QIviSearchAndBrowseModel::clearServiceObject()
{
    Q_D(QIviSearchAndBrowseModel);
    d->clearToDefaults();
}

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

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

/*!
    \qmlsignal SearchAndBrowseModel::fetchMoreThresholdReached()

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

QT_END_NAMESPACE

#include "moc_qivisearchandbrowsemodel.cpp"