aboutsummaryrefslogtreecommitdiffstats
path: root/src/quick3d/qquick3drepeater.cpp
blob: 1dd45af3b30e196b2fcb432cca94d484d624001f (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
// Copyright (C) 2019 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#include "qquick3drepeater_p.h"

#include <private/qqmlglobal_p.h>
#include <private/qqmllistaccessor_p.h>
#include <private/qqmlchangeset_p.h>

#include <QtQml/QQmlInfo>

QT_BEGIN_NAMESPACE


/*!
    \qmltype Repeater3D
    \inqmlmodule QtQuick3D
    \inherits Node
    \brief Instantiates a number of Node-based components using a provided model.

    The Repeater3D type is used to create a large number of
    similar items. Like other view types, a Repeater3D has a \l model and a \l delegate:
    for each entry in the model, the delegate is instantiated
    in a context seeded with data from the model.

    A Repeater's \l model can be any of the supported \l {qml-data-models}{data models}.
    Additionally, like delegates for other views, a Repeater delegate can access
    its index within the repeater, as well as the model data relevant to the
    delegate. See the \l delegate property documentation for details.

    \note A Repeater3D item owns all items it instantiates. Removing or dynamically destroying
    an item created by a Repeater3D results in unpredictable behavior.

    \note Repeater3D is \l {Node}-based, and can only repeat \l {Node}-derived objects.
 */

/*!
    \qmlsignal QtQuick3D::Repeater3D::objectAdded(int index, Object3D object)

    This signal is emitted when an object is added to the repeater. The \a index
    parameter holds the index at which object has been inserted within the
    repeater, and the \a object parameter holds the \l Object3D that has been added.

    The corresponding handler is \c onObjectAdded.
*/

/*!
    \qmlsignal QtQuick3D::Repeater3D::objectRemoved(int index, Object3D object)

    This signal is emitted when an object is removed from the repeater. The \a index
    parameter holds the index at which the item was removed from the repeater,
    and the \a object parameter holds the \l Object3D that was removed.

    Do not keep a reference to \a object if it was created by this repeater, as
    in these cases it will be deleted shortly after the signal is handled.

    The corresponding handler is \c onObjectRemoved.
*/

QQuick3DRepeater::QQuick3DRepeater(QQuick3DNode *parent)
    : QQuick3DNode(parent)
    , m_model(nullptr)
    , m_itemCount(0)
    , m_ownModel(false)
    , m_dataSourceIsObject(false)
    , m_delegateValidated(false)
    , m_explicitDelegate(false)
    , m_explicitDelegateModelAccess(false)
{
}

QQuick3DRepeater::~QQuick3DRepeater()
{
    if (m_ownModel) {
        delete m_model;
    } else {
        QQmlDelegateModelPointer model(m_model);
        disconnectModel(&model);
    }
}

void QQuick3DRepeater::connectModel(QQmlDelegateModelPointer *model)
{
    QQmlInstanceModel *instanceModel = model->instanceModel();
    if (!instanceModel)
        return;

    connect(instanceModel, &QQmlInstanceModel::modelUpdated,
            this, &QQuick3DRepeater::modelUpdated);
    connect(instanceModel, &QQmlInstanceModel::createdItem,
            this, &QQuick3DRepeater::createdObject);
    connect(instanceModel, &QQmlInstanceModel::initItem,
            this, &QQuick3DRepeater::initObject);
    if (QQmlDelegateModel *dataModel = model->delegateModel()) {
        QObject::connect(
                dataModel, &QQmlDelegateModel::delegateChanged,
                this, &QQuick3DRepeater::applyDelegateChange);
    }
    regenerate();
}

void QQuick3DRepeater::disconnectModel(QQmlDelegateModelPointer *model)
{
    QQmlInstanceModel *instanceModel = model->instanceModel();
    if (!instanceModel)
        return;

    disconnect(instanceModel, &QQmlInstanceModel::modelUpdated,
               this, &QQuick3DRepeater::modelUpdated);
    disconnect(instanceModel, &QQmlInstanceModel::createdItem,
               this, &QQuick3DRepeater::createdObject);
    disconnect(instanceModel, &QQmlInstanceModel::initItem,
               this, &QQuick3DRepeater::initObject);
    if (QQmlDelegateModel *delegateModel = model->delegateModel()) {
        QObject::disconnect(
                delegateModel, &QQmlDelegateModel::delegateChanged,
                this, &QQuick3DRepeater::applyDelegateChange);
    }
}

/*!
    \qmlproperty any QtQuick3D::Repeater3D::model

    The model providing data for the repeater.

    This property can be set to any of the supported \l {qml-data-models}{data models}:

    \list
    \li A number that indicates the number of delegates to be created by the repeater
    \li A model (e.g. a ListModel item, or a QAbstractItemModel subclass)
    \li A string list
    \li An object list
    \endlist

    The type of model affects the properties that are exposed to the \l delegate.

    \sa {qml-data-models}{Data Models}
*/

QVariant QQuick3DRepeater::model() const
{
    if (m_dataSourceIsObject) {
        QObject *o = m_dataSourceAsObject;
        return QVariant::fromValue(o);
    }

    return m_dataSource;

}

void QQuick3DRepeater::applyDelegateChange()
{
    if (m_explicitDelegate) {
        qmlWarning(this) << "Explicitly set delegate is externally overridden";
        m_explicitDelegate = false;
    }

    emit delegateChanged();
}

QQmlDelegateModel *QQuick3DRepeater::createDelegateModel()
{
    Q_ASSERT(m_model.isNull());
    QQmlDelegateModel *delegateModel = new QQmlDelegateModel(qmlContext(this), this);
    m_model = delegateModel;
    m_ownModel = true;
    if (isComponentComplete())
        delegateModel->componentComplete();
    return delegateModel;
}

void QQuick3DRepeater::setModel(const QVariant &m)
{
    QVariant model = m;
    if (model.userType() == qMetaTypeId<QJSValue>())
        model = model.value<QJSValue>().toVariant();

    if (m_dataSource == model)
        return;

    clear();

    QQmlDelegateModelPointer oldModel(m_model);
    disconnectModel(&oldModel);

    m_model = nullptr;
    m_dataSource = model;

    QObject *object = qvariant_cast<QObject *>(model);
    m_dataSourceAsObject = object;
    m_dataSourceIsObject = object != nullptr;

    QQmlDelegateModelPointer newModel(qobject_cast<QQmlInstanceModel *>(object));
    if (newModel) {
        if (m_explicitDelegate) {
            QQmlComponent *delegate = nullptr;
            if (QQmlDelegateModel *old = oldModel.delegateModel())
                delegate = old->delegate();
            if (QQmlDelegateModel *delegateModel = newModel.delegateModel()) {
                delegateModel->setDelegate(delegate);
            } else if (delegate) {
                qmlWarning(this) << "Cannot retain explicitly set delegate on non-DelegateModel";
                m_explicitDelegate = false;
            }
        }
        if (m_ownModel) {
            delete oldModel.instanceModel();
            m_ownModel = false;
        }
        m_model = newModel.instanceModel();
    } else if (m_ownModel) {
        newModel = oldModel;
        m_model = newModel.instanceModel();
        if (QQmlDelegateModel *delegateModel = newModel.delegateModel())
            delegateModel->setModel(model);
    } else {
        newModel = createDelegateModel();
        if (m_explicitDelegate) {
            QQmlComponent *delegate = nullptr;
            if (QQmlDelegateModel *old = oldModel.delegateModel())
                delegate = old->delegate();
            newModel.delegateModel()->setDelegate(delegate);
        }

        newModel.delegateModel()->setModel(model);
    }

    connectModel(&newModel);

    emit modelChanged();
    emit countChanged();
}

/*!
    \qmlproperty Component QtQuick3D::Repeater3D::delegate
    \qmldefault

    The delegate provides a template defining each object instantiated by the repeater.

    Delegates are exposed to a read-only \c index property that indicates the index
    of the delegate within the repeater.

    If the \l model is a model object (such as a \l ListModel) the delegate
    can access all model roles as named properties, in the same way that delegates
    do for view classes like ListView.

    \sa {QML Data Models}
 */

QQmlComponent *QQuick3DRepeater::delegate() const
{
    if (m_model) {
        if (QQmlDelegateModel *dataModel = qobject_cast<QQmlDelegateModel*>(m_model))
            return dataModel->delegate();
    }

    return nullptr;
}

void QQuick3DRepeater::setDelegate(QQmlComponent *delegate)
{
    const auto setExplicitDelegate = [&](QQmlDelegateModel *delegateModel) {
        if (delegateModel->delegate() == delegate) {
            m_explicitDelegate = true;
            return;
        }

        const int oldCount = delegateModel->count();
        delegateModel->setDelegate(delegate);
        regenerate();
        if (oldCount != delegateModel->count())
            emit countChanged();
        m_explicitDelegate = true;
        m_delegateValidated = false;
    };

    if (!m_model) {
        if (!delegate) {
            // Explicitly set a null delegate. We can do this without model.
            m_explicitDelegate = true;
            return;
        }

        setExplicitDelegate(createDelegateModel());
        // The new model is not connected to applyDelegateChange, yet. We only do this once
        // there is actual data, via an explicit setModel(). So we have to manually emit the
        // delegateChanged() here.
        emit delegateChanged();
        return;
    }

    if (QQmlDelegateModel *delegateModel = qobject_cast<QQmlDelegateModel *>(m_model)) {
        // Disable the warning in applyDelegateChange since the new delegate is also explicit.
        m_explicitDelegate = false;
        setExplicitDelegate(delegateModel);
        return;
    }

    if (delegate)
        qmlWarning(this) << "Cannot set a delegate on an explicitly provided non-DelegateModel";
    else
        m_explicitDelegate = true; // Explicitly set null delegate always works
}

/*!
    \qmlproperty int QtQuick3D::Repeater3D::count
    \readonly

    This property holds the number of items in the model.

    \note The number of items in the model as reported by count may differ from
    the number of created delegates if the Repeater3D is in the process of
    instantiating delegates or is incorrectly set up.
*/

int QQuick3DRepeater::count() const
{
    if (m_model)
        return m_model->count();
    return 0;
}

/*!
    \qmlmethod Object3D QtQuick3D::Repeater3D::objectAt(index)

    Returns the \l Object3D that has been created at the given \a index, or \c null
    if no item exists at \a index.
*/

QQuick3DObject *QQuick3DRepeater::objectAt(int index) const
{
    if (index >= 0 && index < m_deletables.size())
        return m_deletables[index];
    return nullptr;
}

/*!
    \qmlproperty enumeration QtQuick3D::Repeater3D::delegateModelAccess
    \since 6.10

    This property determines how delegates can access the model.

    \value DelegateModel.ReadOnly
        Prohibit delegates from writing the model via either context properties,
        the \c model object, or required properties.

    \value DelegateModel.ReadWrite
        Allow delegates to write the model via either context properties,
        the \c model object, or required properties.

    \value DelegateModel.Qt5ReadWrite
        Allow delegates to write the model via the \c model object and context
        properties but \e not via required properties.

    The default is \c DelegateModel.Qt5ReadWrite.

    \sa {Models and Views in Qt Quick#Changing Model Data}
*/
QQmlDelegateModel::DelegateModelAccess QQuick3DRepeater::delegateModelAccess() const
{
    if (QQmlDelegateModel *dataModel = qobject_cast<QQmlDelegateModel *>(m_model))
        return dataModel->delegateModelAccess();
    return QQmlDelegateModel::Qt5ReadWrite;
}

void QQuick3DRepeater::setDelegateModelAccess(QQmlDelegateModel::DelegateModelAccess delegateModelAccess)
{
    const auto setExplicitDelegateModelAccess = [&](QQmlDelegateModel *delegateModel) {
        delegateModel->setDelegateModelAccess(delegateModelAccess);
        m_explicitDelegateModelAccess = true;
    };

    if (!m_model) {
        if (delegateModelAccess == QQmlDelegateModel::Qt5ReadWrite) {
            // Explicitly set delegateModelAccess to Legacy. We can do this without model.
            m_explicitDelegateModelAccess = true;
            return;
        }

        QQmlDelegateModel *delegateModel = new QQmlDelegateModel(qmlContext(this), this);
        m_model = delegateModel;
        m_ownModel = true;
        if (isComponentComplete())
            delegateModel->componentComplete();

        setExplicitDelegateModelAccess(delegateModel);

        // The new model is not connected to applyDelegateModelAccessChange, yet. We only do this
        // once there is actual data, via an explicit setModel(). So we have to manually emit the
        // delegateModelAccessChanged() here.
        emit delegateModelAccessChanged();
        return;
    }

    if (QQmlDelegateModel *delegateModel = qobject_cast<QQmlDelegateModel *>(m_model)) {
        // Disable the warning in applyDelegateModelAccessChange since the new delegate model
        // access is also explicit.
        m_explicitDelegateModelAccess = false;
        setExplicitDelegateModelAccess(delegateModel);
        return;
    }

    if (delegateModelAccess == QQmlDelegateModel::Qt5ReadWrite) {
        m_explicitDelegateModelAccess = true; // Explicitly set null delegate always works
    } else {
        qmlWarning(this) << "Cannot set a delegateModelAccess on an explicitly provided "
                            "non-DelegateModel";
    }
}

void QQuick3DRepeater::clear()
{
    bool complete = isComponentComplete();

    if (m_model) {
        // We remove in reverse order deliberately; so that signals are emitted
        // with sensible indices.
        for (int i = m_deletables.size() - 1; i >= 0; --i) {
            if (QQuick3DObject *item = m_deletables.at(i)) {
                if (complete)
                    emit objectRemoved(i, item);
                m_model->release(item);
            }
        }
        for (QQuick3DObject *item : std::as_const(m_deletables)) {
            if (item)
                item->setParentItem(nullptr);
        }
    }
    m_deletables.clear();
    m_itemCount = 0;
}

void QQuick3DRepeater::regenerate()
{
    if (!isComponentComplete())
        return;

    clear();

    if (!m_model || !m_model->count() || !m_model->isValid() || !parentItem() || !isComponentComplete())
        return;

    m_itemCount = count();
    m_deletables.resize(m_itemCount);
    requestItems();
}

void QQuick3DRepeater::componentComplete()
{
    if (m_model && m_ownModel)
        static_cast<QQmlDelegateModel *>(m_model.data())->componentComplete();
    QQuick3DNode::componentComplete();
    regenerate();
    if (m_model && m_model->count())
        emit countChanged();
}

void QQuick3DRepeater::itemChange(QQuick3DObject::ItemChange change, const QQuick3DObject::ItemChangeData &value)
{
    QQuick3DObject::itemChange(change, value);
    if (change == ItemParentHasChanged) {
        regenerate();
    }
}

void QQuick3DRepeater::createdObject(int index, QObject *)
{
    QObject *object = m_model->object(index, QQmlIncubator::AsynchronousIfNested);
    QQuick3DObject *item = qmlobject_cast<QQuick3DObject*>(object);
    emit objectAdded(index, item);
}

void QQuick3DRepeater::initObject(int index, QObject *object)
{
    QQuick3DNode *item = qmlobject_cast<QQuick3DNode*>(object);

    if (!m_deletables.at(index)) {
        if (!item) {
            if (object) {
                m_model->release(object);
                if (!m_delegateValidated) {
                    m_delegateValidated = true;
                    QObject* delegate = this->delegate();
                    qmlWarning(delegate ? delegate : this) << QQuick3DRepeater::tr("Delegate must be of Node type");
                }
            }
            return;
        }
        m_deletables[index] = item;
        item->setParent(this);
        item->setParentItem(static_cast<QQuick3DNode*>(this));
        initDelegate(index, item);
    }
}

void QQuick3DRepeater::modelUpdated(const QQmlChangeSet &changeSet, bool reset)
{
    if (!isComponentComplete())
        return;

    if (reset) {
        regenerate();
        if (changeSet.difference() != 0)
            emit countChanged();
        return;
    }

    int difference = 0;
    QHash<int, QVector<QPointer<QQuick3DNode> > > moved;
    for (const QQmlChangeSet::Change &remove : changeSet.removes()) {
        int index = qMin(remove.index, m_deletables.size());
        int count = qMin(remove.index + remove.count, m_deletables.size()) - index;
        if (remove.isMove()) {
            moved.insert(remove.moveId, m_deletables.mid(index, count));
            m_deletables.erase(
                    m_deletables.begin() + index,
                    m_deletables.begin() + index + count);
        } else while (count--) {
            QQuick3DNode *item = m_deletables.at(index);
            m_deletables.remove(index);
            emit objectRemoved(index, item);
            if (item) {
                m_model->release(item);
                item->setParentItem(nullptr);
            }
            --m_itemCount;
        }

        difference -= remove.count;
    }

    for (const QQmlChangeSet::Change &insert : changeSet.inserts()) {
        int index = qMin(insert.index, m_deletables.size());
        if (insert.isMove()) {
            QVector<QPointer<QQuick3DNode> > items = moved.value(insert.moveId);
            m_deletables = m_deletables.mid(0, index) + items + m_deletables.mid(index);
        } else for (int i = 0; i < insert.count; ++i) {
            int modelIndex = index + i;
            ++m_itemCount;
            m_deletables.insert(modelIndex, nullptr);
            QObject *object = m_model->object(modelIndex, QQmlIncubator::AsynchronousIfNested);
            if (object)
                m_model->release(object);
        }
        difference += insert.count;
    }

    if (difference != 0)
        emit countChanged();
}

void QQuick3DRepeater::requestItems()
{
    for (int i = 0; i < m_itemCount; i++) {
        QObject *object = m_model->object(i, QQmlIncubator::AsynchronousIfNested);
        if (object)
            m_model->release(object);
    }
}

QT_END_NAMESPACE

#include "moc_qquick3drepeater_p.cpp"