aboutsummaryrefslogtreecommitdiffstats
path: root/src/ivicore/qivisearchandbrowsemodel.cpp
blob: 53b9a0f3f64e8a95846e94354fa0b4752f2d61ca (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
/****************************************************************************
**
** 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 "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)
    : QIviPagingModelPrivate(interface, model)
    , q_ptr(model)
    , m_queryTerm(nullptr)
    , m_canGoBack(false)
{
}

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

void QIviSearchAndBrowseModelPrivate::resetModel()
{
    QIviSearchAndBrowseModelInterface* backend = searchBackend();

    if (backend)
        backend->setContentType(m_identifier, m_contentTypeRequested);
}

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

    if (m_query.isEmpty()) {
        //The new query is empty, tell it to the backend and delete the old term
        setupFilter(nullptr, {});
        return;
    }

    if (!m_capabilities.testFlag(QtIviCoreModule::SupportsFiltering) && !m_capabilities.testFlag(QtIviCoreModule::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(m_queryIdentifiers);

    QIviAbstractQueryTerm* queryTerm = parser.parse();

    if (!queryTerm) {
        qtivi_qmlOrCppWarning(q_ptr, parser.lastError());
        return;
    }
    QList<QIviOrderTerm> orderTerms = parser.orderTerms();

    setupFilter(queryTerm, orderTerms);
}

void QIviSearchAndBrowseModelPrivate::setupFilter(QIviAbstractQueryTerm* queryTerm, const QList<QIviOrderTerm> &orderTerms)
{
    //1. Tell the backend about the new filter (or none)
    QIviSearchAndBrowseModelInterface* backend = searchBackend();
    if (backend)
        backend->setupFilter(m_identifier, queryTerm, orderTerms);

    //2. Now it's safe to delete the old filter
    delete m_queryTerm;
    m_queryTerm = nullptr;

    //3. Save the new filter
    m_queryTerm = queryTerm;
    m_orderTerms = orderTerms;
}

void QIviSearchAndBrowseModelPrivate::clearToDefaults()
{
    QIviPagingModelPrivate::clearToDefaults();

    Q_Q(QIviSearchAndBrowseModel);
    delete m_queryTerm;
    m_queryTerm = nullptr;
    m_query.clear();
    emit q->queryChanged(m_query);
    m_contentType = QString();
    emit q->contentTypeChanged(m_contentType);
    m_contentTypeRequested = QString();
    m_canGoBack = false;
    emit q->canGoBackChanged(m_canGoBack);
    m_availableContentTypes.clear();
    emit q->availableContentTypesChanged(m_availableContentTypes);
    m_canGoForward.clear();

    //Explicitly call the PagingModel resetModel to also reset the fetched data
    QIviPagingModelPrivate::resetModel();
}

void QIviSearchAndBrowseModelPrivate::onCanGoForwardChanged(const QUuid &identifier, const QVector<bool> &indexes, int start)
{
    if (m_identifier != identifier)
        return;

    //Always keep the list size in sync;
    m_canGoForward.resize(qMax(m_itemList.count(), indexes.count()));

    //Update the list
    for (int i = 0; i < indexes.count(); i++)
        m_canGoForward[start + i] = indexes.at(i);
}

void QIviSearchAndBrowseModelPrivate::onCanGoBackChanged(const QUuid &identifier, bool canGoBack)
{
    if (m_identifier != identifier)
        return;

    Q_Q(QIviSearchAndBrowseModel);
    if (m_canGoBack == canGoBack)
        return;

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

void QIviSearchAndBrowseModelPrivate::onContentTypeChanged(const QUuid &identifier, const QString &contentType)
{
    if (m_identifier != identifier)
        return;

    Q_Q(QIviSearchAndBrowseModel);
    // Don't return if the content type is already correct. We still need to continue to update the
    // query and start fetching again
    if (m_contentType != contentType) {
        m_contentType = contentType;
        emit q->contentTypeChanged(m_contentType);
    }
    parseQuery();

    QIviPagingModelPrivate::resetModel();
}

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

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

void QIviSearchAndBrowseModelPrivate::onQueryIdentifiersChanged(const QUuid &identifier, const QSet<QString> &queryIdentifiers)
{
    if (m_identifier != identifier)
        return;

    m_queryIdentifiers = queryIdentifiers;
}

QIviSearchAndBrowseModelInterface *QIviSearchAndBrowseModelPrivate::searchBackend() const
{
    return QIviAbstractFeatureListModelPrivate::backend<QIviSearchAndBrowseModelInterface*>();
}

void QIviSearchAndBrowseModelPrivate::updateContentType(const QString &contentType)
{
    Q_Q(QIviSearchAndBrowseModel);
    m_query = QString();
    m_queryIdentifiers.clear();
    emit q->queryChanged(m_query);
    m_contentTypeRequested = contentType;
    m_canGoForward.clear();
    m_canGoBack = false;

    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

    \note Please also see the \l{QIviPagingModel}{QIviPagingModel documentation} for how the data loading works and
          the \l{Models} section for more information about all models in QtIvi.
*/

/*!
    \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::Roles
    \value CanGoForwardRole
          True if this item can be used to go one level forward and display the next set of items. See also goForward()
    \omitvalue LastRole

    \sa QIviPagingModel::Roles
*/

/*!
    \qmltype SearchAndBrowseModel
    \instantiates QIviSearchAndBrowseModel
    \inqmlmodule QtIvi
    \inherits PagingModel
    \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 StandardItem.

    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

    \note Please also see the \l{PagingModel}{PagingModel documentation} for how the data loading works and
          the \l{Models} section for more information about all models in QtIvi.
*/

/*!
    Constructs a QIviSearchAndBrowseModel.

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

/*!
    \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 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_contentTypeRequested == 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;
}

/*!
    \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();

    if (role == CanGoForwardRole)
        return canGoForward(row);
    else
        return QIviPagingModel::data(index, role);
}

/*!
    \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 (!d->m_canGoBack) {
        qtivi_qmlOrCppWarning(this, "Can't go backward anymore");
        return;
    }

    QIviPendingReply<QString> reply = backend->goBack(d->m_identifier);
    reply.then([this, reply](const QString &value) {
        Q_D(QIviSearchAndBrowseModel);
        d->updateContentType(value);
    },
    [this]() {
        qtivi_qmlOrCppWarning(this, "Going backward failed");
    });
}

/*!
    \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_canGoForward.count() || i < 0)
        return false;

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

    return d->m_canGoForward[i];
}

/*!
    \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;
    }

    if (!d->m_canGoForward.value(i, false)) {
        qtivi_qmlOrCppWarning(this, "Can't go forward anymore");
        return nullptr;
    }

    if (navigationType == OutOfModelNavigation) {
        if (d->m_capabilities.testFlag(QtIviCoreModule::SupportsStatelessNavigation)) {
            QIviPendingReply<QString> reply = backend->goForward(d->m_identifier, i);
            auto newModel = new QIviSearchAndBrowseModel(serviceObject());
            reply.then([reply, newModel](const QString &value) {
                newModel->setContentType(value);
            },
            [this]() {
                qtivi_qmlOrCppWarning(this, "Going forward failed");
            });
            return newModel;

        } else {
            qtivi_qmlOrCppWarning(this, "The backend doesn't support the OutOfModelNavigation");
            return nullptr;
        }
    } else {
        QIviPendingReply<QString> reply = backend->goForward(d->m_identifier, i);
        reply.then([this, reply](const QString &value) {
            Q_D(QIviSearchAndBrowseModel);
            d->updateContentType(value);
        },
        [this]() {
            qtivi_qmlOrCppWarning(this, "Going forward failed");
        });
    }

    return nullptr;
}

/*!
    \qmlmethod SearchAndBrowseModel::insert(int index, StandardItem 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<QIviStandardItem>(this, variant);
    if (!item)
        return QIviPendingReply<void>::createFailedReply();

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

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

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

/*!
    \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(QtIviCoreModule::SupportsRemove)) {
        qtivi_qmlOrCppWarning(this, "The backend doesn't support removing of items");
        return QIviPendingReply<void>::createFailedReply();
    }

    return backend->remove(d->m_identifier, 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(QtIviCoreModule::SupportsMove)) {
        qtivi_qmlOrCppWarning(this, "The backend doesn't support moving of items");
        return QIviPendingReply<void>::createFailedReply();
    }

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

/*!
    \qmlmethod SearchAndBrowseModel::indexOf(StandardItem 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 variant 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<QIviStandardItem>(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, variant);
}

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

/*!
    \internal
*/
QIviSearchAndBrowseModel::QIviSearchAndBrowseModel(QIviServiceObject *serviceObject, QObject *parent)
    : QIviSearchAndBrowseModel(parent)
{
    setServiceObject(serviceObject);
}

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

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

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

    QObjectPrivate::connect(backend, &QIviSearchAndBrowseModelInterface::availableContentTypesChanged,
                            d, &QIviSearchAndBrowseModelPrivate::onAvailableContentTypesChanged);
    QObjectPrivate::connect(backend, &QIviSearchAndBrowseModelInterface::contentTypeChanged,
                            d, &QIviSearchAndBrowseModelPrivate::onContentTypeChanged);
    QObjectPrivate::connect(backend, &QIviSearchAndBrowseModelInterface::queryIdentifiersChanged,
                            d, &QIviSearchAndBrowseModelPrivate::onQueryIdentifiersChanged);
    QObjectPrivate::connect(backend, &QIviSearchAndBrowseModelInterface::canGoBackChanged,
                            d, &QIviSearchAndBrowseModelPrivate::onCanGoBackChanged);
    QObjectPrivate::connect(backend, &QIviSearchAndBrowseModelInterface::canGoForwardChanged,
                            d, &QIviSearchAndBrowseModelPrivate::onCanGoForwardChanged);

    QIviPagingModel::connectToServiceObject(serviceObject);

    //once the initialization is done QIviPagingModel will reset the model
}

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

QT_END_NAMESPACE

#include "moc_qivisearchandbrowsemodel.cpp"