summaryrefslogtreecommitdiffstats
path: root/src/declarative/util/qmllistmodel.cpp
blob: 48371808ae22aeac50a37917f1244ece7e0b9a0f (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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/qdebug.h>
#include <QtCore/qstack.h>
#include <QXmlStreamReader>
#include <private/qmlcustomparser_p.h>
#include "qmlopenmetaobject.h"
#include <qmlcontext.h>
#include <qmlbindablevalue.h>
#include "qmllistmodel.h"

QT_BEGIN_NAMESPACE

#define DATA_ROLE_ID 1
#define DATA_ROLE_NAME "data"

struct ListInstruction
{
    enum { Push, Pop, Value, Set } type;
    int dataIdx;
};

struct ListModelData
{
    int dataOffset;
    int instrCount;
    ListInstruction *instructions() const { return (ListInstruction *)((char *)this + sizeof(ListModelData)); }
};

Q_DECLARE_METATYPE(QListModelInterface *);

/*!
    \qmlclass ListModel 
    \brief The ListModel element defines a free-form list data source.

    The ListModel is a simple XML heirarchy of items containing data roles.
    For example:

    \code
    <ListModel id="FruitModel">
        <Fruit>
            <name>Apple</name>
            <cost>2.45</cost>
        <Fruit>
        <Fruit>
            <name>Orange</name>
            <cost>3.25</cost>
        </Fruit>
        <Fruit>
            <name>Banana</name>
            <cost>1.95</cost>
        </Fruit>
    </ListModel>
    \endcode

    Elements beginning with a capital are items.  Elements beginning
    with lower-case are the data roles.  The above example defines a
    ListModel containing three items, with the roles "name" and "cost".

    The defined model can be used in views such as ListView:
    \code
    <Component id="FruitDelegate">
        <Item width="200" height="50">
            <Text text="{name}"/>
            <Text text="{'$'+cost}" anchors.right="{parent.right}"/>
        </Item>
    </Component>

    <ListView model="{FruitModel}" delegate="{FruitDelegate}" anchors.fill="{parent}"/>
    \endcode
*/

struct ModelNode;
class ListModel : public QListModelInterface
{
    Q_OBJECT
public:
    ListModel(QObject *parent=0);

    virtual QList<int> roles() const;
    virtual QString toString(int role) const;
    Q_PROPERTY(int count READ count);
    virtual int count() const;
    virtual QHash<int,QVariant> data(int index, const QList<int> &roles = (QList<int>())) const;

private:
    QVariant valueForNode(ModelNode *) const;
    mutable QStringList roleStrings;
    friend class ListModelParser;
    friend struct ModelNode;

    void checkRoles() const;
    void addRole(const QString &) const;
    mutable bool _rolesOk;
    ModelNode *_root;
};

class ModelObject : public QObject
{
    Q_OBJECT
public:
    ModelObject(ModelNode *);

    void setValue(const QByteArray &name, const QVariant &val)
    {
        _mo->setValue(name, val);
    }

private:
    ModelNode *_node;
    bool _haveProperties;
    QmlOpenMetaObject *_mo;
};

struct ModelNode
{
    ModelNode();
    ~ModelNode();
    QString className;

    QList<QVariant> values;
    QHash<QString, ModelNode *> properties;

    ListModel *model() {
        if (!modelCache) { 
            modelCache = new ListModel;
            modelCache->_root = this; 
        }
        return modelCache;
    }

    ModelObject *object() {
        if (!objectCache) {
            objectCache = new ModelObject(this);
            QHash<QString, ModelNode *>::iterator it;
            for (it = properties.begin(); it != properties.end(); ++it) {
                if (!(*it)->values.isEmpty())
                    objectCache->setValue(it.key().toLatin1(), (*it)->values.first());
            }
        }
        return objectCache;
    }

    ListModel *modelCache;
    ModelObject *objectCache;
};
Q_DECLARE_METATYPE(ModelNode *);

ModelObject::ModelObject(ModelNode *node)
: _node(node), _haveProperties(false), _mo(new QmlOpenMetaObject(this))
{
}

QML_DECLARE_TYPE(ListModel);
QML_DEFINE_TYPE(ListModel,ListModel);
ListModel::ListModel(QObject *parent)
: QListModelInterface(parent), _rolesOk(false), _root(0)
{
}

void ListModel::checkRoles() const
{
    if (_rolesOk)
        return;

    for (int ii = 0; ii < _root->values.count(); ++ii) {
        ModelNode *node = qvariant_cast<ModelNode *>(_root->values.at(ii));
        if (node) {
            foreach (const QString &role, node->properties.keys())
                addRole(role);
        } 
    }

    _rolesOk = true;
}

void ListModel::addRole(const QString &role) const
{
    if (!roleStrings.contains(role))
        roleStrings << role;
}

QList<int> ListModel::roles() const
{
    checkRoles();
    QList<int> rv;
    for (int ii = 0; ii < roleStrings.count(); ++ii)
        rv << ii;
    return rv;
}

QString ListModel::toString(int role) const
{
    checkRoles();
    if (role < roleStrings.count())
        return roleStrings.at(role);
    else
        return QString();
}

QVariant ListModel::valueForNode(ModelNode *node) const
{
    QObject *rv = 0;

    if (!node->properties.isEmpty()) {
        // Object
        rv = node->object();
    } else if (node->values.count() == 0) {
        // Invalid
        return QVariant();
    } else if (node->values.count() == 1) {
        // Value
        QVariant &var = node->values[0];
        ModelNode *valueNode = qvariant_cast<ModelNode *>(var);
        if (valueNode) {
            if (!valueNode->properties.isEmpty())
                rv = valueNode->object();
            else
                rv = valueNode->model();
        } else {
            return var;
        }
    } else if (node->values.count() > 1) {
        // List
        rv = node->model();
    }

    if (rv)
        return QVariant::fromValue(rv);
    else
        return QVariant();
}

QHash<int,QVariant> ListModel::data(int index, const QList<int> &roles) const
{
    checkRoles();
    QHash<int, QVariant> rv;
    if (index >= count())
        return rv;

    ModelNode *node = qvariant_cast<ModelNode *>(_root->values.at(index));
    if (!node) 
        return rv;

    for (int ii = 0; ii < roles.count(); ++ii) {
        const QString &roleString = roleStrings.at(roles.at(ii));

        QHash<QString, ModelNode *>::ConstIterator iter = 
            node->properties.find(roleString);
        if (iter != node->properties.end()) {
            ModelNode *row = *iter;
            rv.insert(roles.at(ii), valueForNode(row));
        }
    }

    return rv;
}

int ListModel::count() const
{
    if (!_root) return 0;
    return _root->values.count();
}

class ListModelParser : public QmlCustomParser
{
public:
    virtual QByteArray compile(QXmlStreamReader& reader, bool *);
    QByteArray compile(const QList<QmlCustomParserProperty> &, bool *ok);
    virtual QVariant create(const QByteArray &);

    bool compileProperty(const QmlCustomParserProperty &prop, QList<ListInstruction> &instr, QByteArray &data);
    void setCustomData(QObject *, const QByteArray &);
};
QML_DEFINE_CUSTOM_PARSER(ListModel, ListModelParser);

bool ListModelParser::compileProperty(const QmlCustomParserProperty &prop, QList<ListInstruction> &instr, QByteArray &data)
{
    QList<QVariant> values = prop.assignedValues();
    for(int ii = 0; ii < values.count(); ++ii) {
        const QVariant &value = values.at(ii);

        if(value.userType() == qMetaTypeId<QmlCustomParserNode>()) {
            QmlCustomParserNode node = 
                qvariant_cast<QmlCustomParserNode>(value);

            {
            ListInstruction li;
            li.type = ListInstruction::Push;
            li.dataIdx = -1;
            instr << li;
            }

            QList<QmlCustomParserProperty> props = node.properties();
            for(int jj = 0; jj < props.count(); ++jj) {
                const QmlCustomParserProperty &nodeProp = props.at(jj);
                if(nodeProp.name() == "")
                    return false;

                ListInstruction li;
                int ref = data.count();
                data.append(nodeProp.name());
                data.append('\0');
                li.type = ListInstruction::Set;
                li.dataIdx = ref;
                instr << li;

                if(!compileProperty(nodeProp, instr, data))
                    return false;

                li.type = ListInstruction::Pop;
                li.dataIdx = -1;
                instr << li;
            }

            {
            ListInstruction li;
            li.type = ListInstruction::Pop;
            li.dataIdx = -1;
            instr << li;
            }

        } else {

            int ref = data.count();
            QByteArray d = value.toString().toLatin1();
            d.append('\0');
            data.append(d);

            ListInstruction li;
            li.type = ListInstruction::Value;
            li.dataIdx = ref;
            instr << li;

        }
    }

    return true;
}

QByteArray ListModelParser::compile(const QList<QmlCustomParserProperty> &customProps, bool *ok)
{
    *ok = true;
    QList<ListInstruction> instr;
    QByteArray data;

    for(int ii = 0; ii < customProps.count(); ++ii) {
        const QmlCustomParserProperty &prop = customProps.at(ii);
        if(prop.name() != "") { // isn't default property
            *ok = false;
            return QByteArray();
        }

        if(!compileProperty(prop, instr, data)) {
            *ok = false;
            return QByteArray();
        }
    }

    int size = sizeof(ListModelData) + 
               instr.count() * sizeof(ListInstruction) + 
               data.count();

    QByteArray rv;
    rv.resize(size);

    ListModelData *lmd = (ListModelData *)rv.data();
    lmd->dataOffset = sizeof(ListModelData) + 
                     instr.count() * sizeof(ListInstruction);
    lmd->instrCount = instr.count();
    for (int ii = 0; ii < instr.count(); ++ii)
        lmd->instructions()[ii] = instr.at(ii);
    ::memcpy(rv.data() + lmd->dataOffset, data.constData(), data.count());

    return rv;
}

void ListModelParser::setCustomData(QObject *obj, const QByteArray &d)
{
    ListModel *rv = static_cast<ListModel *>(obj);

    ModelNode *root = new ModelNode;
    rv->_root = root;
    QStack<ModelNode *> nodes;
    nodes << root;

    const ListModelData *lmd = (const ListModelData *)d.constData();
    const char *data = ((const char *)lmd) + lmd->dataOffset;

    for (int ii = 0; ii < lmd->instrCount; ++ii) {
        const ListInstruction &instr = lmd->instructions()[ii];

        switch(instr.type) {
        case ListInstruction::Push:
            {
                ModelNode *n = nodes.top();
                ModelNode *n2 = new ModelNode;
                n->values << qVariantFromValue(n2);
                nodes.push(n2);
            }
            break;

        case ListInstruction::Pop:
            nodes.pop();
            break;

        case ListInstruction::Value:
            {
                ModelNode *n = nodes.top();
                n->values.append(QByteArray(data + instr.dataIdx));
            }
            break;

        case ListInstruction::Set:
            {
                ModelNode *n = nodes.top();
                ModelNode *n2 = new ModelNode;
                n->properties.insert(QLatin1String(data + instr.dataIdx), n2);
                nodes.push(n2);
            }
            break;
        }
    }
}

class ListModel2 : public ListModel
{
Q_OBJECT
};
QML_DECLARE_TYPE(ListModel2);
QML_DEFINE_CUSTOM_TYPE(ListModel2, ListModel2, ListModelParser);

class ListElement : public QObject
{
Q_OBJECT
};
QML_DECLARE_TYPE(ListElement);
QML_DEFINE_TYPE(ListElement,ListElement);

static void dump(ModelNode *node, int ind)
{
    QByteArray indentBa(ind * 4, ' ');
    const char *indent = indentBa.constData();

    for (int ii = 0; ii < node->values.count(); ++ii) {
        ModelNode *subNode = qvariant_cast<ModelNode *>(node->values.at(ii));
        if (subNode) {
            qWarning().nospace() << indent << "Sub-node " << ii << ": class " << subNode->className;
            dump(subNode, ind + 1);
        } else {
            qWarning().nospace() << indent << "Sub-node " << ii << ": " << node->values.at(ii).toString();
        }
    }

    for (QHash<QString, ModelNode *>::ConstIterator iter = node->properties.begin(); iter != node->properties.end(); ++iter) {
        qWarning().nospace() << indent << "Property " << iter.key() << ":";
        dump(iter.value(), ind + 1);
    }
}

ModelNode::ModelNode()
: modelCache(0), objectCache(0)
{
}

ModelNode::~ModelNode()
{
    qDeleteAll(properties);
    for (int ii = 0; ii < values.count(); ++ii) {
        ModelNode *node = qvariant_cast<ModelNode *>(values.at(ii));
        if (node) { delete node; node = 0; }
    }
    if (modelCache) { delete modelCache; modelCache = 0; }
}

QByteArray ListModelParser::compile(QXmlStreamReader& reader, bool *ok)
{
    *ok = true;

    QByteArray data;
    QList<ListInstruction> instr;
    int depth=0;

    while(!reader.atEnd() && depth >= 0) {
        switch(reader.readNext()) {
            case QXmlStreamReader::StartElement:
                {
                    QStringRef name = reader.name();
                    bool isType = name.at(0).isUpper();

                    if (isType) {
                        ListInstruction li;
                        li.type = ListInstruction::Push;
                        li.dataIdx = -1;
                        instr << li;

                        for (int i = 0; i < reader.attributes().count(); ++i) {
                            const QXmlStreamAttribute &attr = reader.attributes().at(i);
                            QStringRef attrName = attr.name();
                            QStringRef attrValue = attr.value();

                            ListInstruction li;
                            int ref = data.count();
                            data.append(attrName.toString().toLatin1());
                            data.append('\0');
                            li.type = ListInstruction::Set;
                            li.dataIdx = ref;
                            instr << li;

                            ref = data.count();
                            data.append(attrValue.toString().toLatin1());
                            data.append('\0');
                            li.type = ListInstruction::Value;
                            li.dataIdx = ref;
                            instr << li;

                            li.type = ListInstruction::Pop;
                            li.dataIdx = -1;
                            instr << li;
                        }
                    } else {
                        ListInstruction li;
                        int ref = data.count();
                        data.append(name.toString().toLatin1());
                        data.append('\0');
                        li.type = ListInstruction::Set;
                        li.dataIdx = ref;
                        instr << li;
                    }
                }
                ++depth;
                break;
            case QXmlStreamReader::EndElement:
                {
                    ListInstruction li;
                    li.type = ListInstruction::Pop;
                    li.dataIdx = -1;
                    instr << li;
                    --depth;
                }
                break;
            case QXmlStreamReader::Characters:
                if (!reader.isWhitespace()) {
                    int ref = data.count();
                    QByteArray d = reader.text().toString().toLatin1();
                    d.append('\0');
                    data.append(d);

                    ListInstruction li;
                    li.type = ListInstruction::Value;
                    li.dataIdx = ref;
                    instr << li;
                }
                break;

            case QXmlStreamReader::Invalid:
            case QXmlStreamReader::NoToken:
            case QXmlStreamReader::StartDocument:
            case QXmlStreamReader::EndDocument:
            case QXmlStreamReader::Comment:
            case QXmlStreamReader::DTD:
            case QXmlStreamReader::EntityReference:
            case QXmlStreamReader::ProcessingInstruction:
                break;
        }
    }

    if (reader.hasError())
        *ok = true;

    if (!*ok)
        return QByteArray();

    int size = sizeof(ListModelData) + 
               instr.count() * sizeof(ListInstruction) + 
               data.count();

    QByteArray rv;
    rv.resize(size);

    ListModelData *lmd = (ListModelData *)rv.data();
    lmd->dataOffset = sizeof(ListModelData) + 
                     instr.count() * sizeof(ListInstruction);
    lmd->instrCount = instr.count();
    for (int ii = 0; ii < instr.count(); ++ii)
        lmd->instructions()[ii] = instr.at(ii);
    ::memcpy(rv.data() + lmd->dataOffset, data.constData(), data.count());

    return rv;
}

QVariant ListModelParser::create(const QByteArray &d)
{
    ListModel *rv = new ListModel;
    ModelNode *root = new ModelNode;
    rv->_root = root;
    QStack<ModelNode *> nodes;
    nodes << root;

    const ListModelData *lmd = (const ListModelData *)d.constData();
    const char *data = ((const char *)lmd) + lmd->dataOffset;

    for (int ii = 0; ii < lmd->instrCount; ++ii) {
        const ListInstruction &instr = lmd->instructions()[ii];

        switch(instr.type) {
        case ListInstruction::Push:
            {
                ModelNode *n = nodes.top();
                ModelNode *n2 = new ModelNode;
                n->values << qVariantFromValue(n2);
                nodes.push(n2);
            }
            break;

        case ListInstruction::Pop:
            nodes.pop();
            break;

        case ListInstruction::Value:
            {
                ModelNode *n = nodes.top();
                n->values.append(QByteArray(data + instr.dataIdx));
            }
            break;

        case ListInstruction::Set:
            {
                ModelNode *n = nodes.top();
                ModelNode *n2 = new ModelNode;
                n->properties.insert(QLatin1String(data + instr.dataIdx), n2);
                nodes.push(n2);
            }
            break;
        }
    }

    return QVariant::fromValue(rv);
}

QT_END_NAMESPACE
#include "qmllistmodel.moc"