qdom.cpp 214 KB
Newer Older
1
2
/****************************************************************************
**
Jani Heikkinen's avatar
Jani Heikkinen committed
3
4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5
6
7
**
** This file is part of the QtXml module of the Qt Toolkit.
**
Jani Heikkinen's avatar
Jani Heikkinen committed
8
** $QT_BEGIN_LICENSE:LGPL$
9
10
11
12
** Commercial License Usage
** Licensees holding valid commercial Qt 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
Jani Heikkinen's avatar
Jani Heikkinen committed
13
** a written agreement between you and The Qt Company. For licensing terms
Jani Heikkinen's avatar
Jani Heikkinen committed
14
15
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
16
**
17
** GNU Lesser General Public License Usage
18
** Alternatively, this file may be used under the terms of the GNU Lesser
Jani Heikkinen's avatar
Jani Heikkinen committed
19
20
21
22
23
** 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.
24
**
Jani Heikkinen's avatar
Jani Heikkinen committed
25
26
27
28
29
30
31
32
33
34
** 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.
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <qplatformdefs.h>
#include <qdom.h>
#include "private/qxmlutils_p.h"

#ifndef QT_NO_DOM

#include <qatomic.h>
#include <qbuffer.h>
#include <qhash.h>
#include <qiodevice.h>
#include <qlist.h>
#include <qregexp.h>
Liang Qi's avatar
Liang Qi committed
52
#if QT_CONFIG(textcodec)
53
#include <qtextcodec.h>
Liang Qi's avatar
Liang Qi committed
54
#endif
55
56
#include <qtextstream.h>
#include <qxml.h>
57
#include "private/qxml_p.h"
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
#include <qvariant.h>
#include <qmap.h>
#include <qshareddata.h>
#include <qdebug.h>
#include <stdio.h>

QT_BEGIN_NAMESPACE

/*
  ### old todo comments -- I don't know if they still apply...

  If the document dies, remove all pointers to it from children
  which can not be deleted at this time.

  If a node dies and has direct children which can not be deleted,
  then remove the pointer to the parent.

  createElement and friends create double reference counts.
*/

/* ##### new TODOs:

  Remove emtpy emthods in the *Private classes

  Make a lot of the (mostly empty) methods in the public classes inline.
  Specially constructors assignment operators and comparison operators are candidates.
*/

/*
  Reference counting:

  Some simple rules:
  1) If an intern object returns a pointer to another intern object
     then the reference count of the returned object is not increased.
  2) If an extern object is created and gets a pointer to some intern
     object, then the extern object increases the intern objects reference count.
  3) If an extern object is deleted, then it decreases the reference count
     on its associated intern object and deletes it if nobody else hold references
     on the intern object.
*/


/*
  Helper to split a qualified name in the prefix and local name.
*/
static void qt_split_namespace(QString& prefix, QString& name, const QString& qName, bool hasURI)
{
    int i = qName.indexOf(QLatin1Char(':'));
    if (i == -1) {
        if (hasURI)
            prefix = QLatin1String("");
        else
            prefix.clear();
        name = qName;
    } else {
        prefix = qName.left(i);
        name = qName.mid(i + 1);
    }
}

/**************************************************************
 *
 * Private class declerations
 *
 **************************************************************/

class QDomImplementationPrivate
{
public:
    inline QDomImplementationPrivate() {}

    QDomImplementationPrivate* clone();
    QAtomicInt ref;
    static QDomImplementation::InvalidDataPolicy invalidDataPolicy;
};

class QDomNodePrivate
{
public:
    QDomNodePrivate(QDomDocumentPrivate*, QDomNodePrivate* parent = 0);
    QDomNodePrivate(QDomNodePrivate* n, bool deep);
    virtual ~QDomNodePrivate();

    QString nodeName() const { return name; }
    QString nodeValue() const { return value; }
    virtual void setNodeValue(const QString& v) { value = v; }

    QDomDocumentPrivate* ownerDocument();
    void setOwnerDocument(QDomDocumentPrivate* doc);

    virtual QDomNodePrivate* insertBefore(QDomNodePrivate* newChild, QDomNodePrivate* refChild);
    virtual QDomNodePrivate* insertAfter(QDomNodePrivate* newChild, QDomNodePrivate* refChild);
    virtual QDomNodePrivate* replaceChild(QDomNodePrivate* newChild, QDomNodePrivate* oldChild);
    virtual QDomNodePrivate* removeChild(QDomNodePrivate* oldChild);
    virtual QDomNodePrivate* appendChild(QDomNodePrivate* newChild);

    QDomNodePrivate* namedItem(const QString& name);

    virtual QDomNodePrivate* cloneNode(bool deep = true);
    virtual void normalize();
    virtual void clear();

    inline QDomNodePrivate* parent() const { return hasParent ? ownerNode : 0; }
    inline void setParent(QDomNodePrivate *p) { ownerNode = p; hasParent = true; }

    void setNoParent() {
        ownerNode = hasParent ? (QDomNodePrivate*)ownerDocument() : 0;
        hasParent = false;
    }

    // Dynamic cast
Richard Moore's avatar
Richard Moore committed
169
170
171
172
173
174
175
    bool isAttr() const                     { return nodeType() == QDomNode::AttributeNode; }
    bool isCDATASection() const             { return nodeType() == QDomNode::CDATASectionNode; }
    bool isDocumentFragment() const         { return nodeType() == QDomNode::DocumentFragmentNode; }
    bool isDocument() const                 { return nodeType() == QDomNode::DocumentNode; }
    bool isDocumentType() const             { return nodeType() == QDomNode::DocumentTypeNode; }
    bool isElement() const                  { return nodeType() == QDomNode::ElementNode; }
    bool isEntityReference() const          { return nodeType() == QDomNode::EntityReferenceNode; }
176
177
178
    bool isText() const                     { const QDomNode::NodeType nt = nodeType();
                                              return (nt == QDomNode::TextNode)
                                                  || (nt == QDomNode::CDATASectionNode); }
Richard Moore's avatar
Richard Moore committed
179
180
181
    bool isEntity() const                   { return nodeType() == QDomNode::EntityNode; }
    bool isNotation() const                 { return nodeType() == QDomNode::NotationNode; }
    bool isProcessingInstruction() const    { return nodeType() == QDomNode::ProcessingInstructionNode; }
182
183
184
185
    bool isCharacterData() const            { const QDomNode::NodeType nt = nodeType();
                                              return (nt == QDomNode::CharacterDataNode)
                                                  || (nt == QDomNode::TextNode)
                                                  || (nt == QDomNode::CommentNode); }
Richard Moore's avatar
Richard Moore committed
186
    bool isComment() const                  { return nodeType() == QDomNode::CommentNode; }
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

    virtual QDomNode::NodeType nodeType() const { return QDomNode::BaseNode; }

    virtual void save(QTextStream&, int, int) const;

    void setLocation(int lineNumber, int columnNumber);

    // Variables
    QAtomicInt ref;
    QDomNodePrivate* prev;
    QDomNodePrivate* next;
    QDomNodePrivate* ownerNode; // either the node's parent or the node's owner document
    QDomNodePrivate* first;
    QDomNodePrivate* last;

    QString name; // this is the local name if prefix != null
    QString value;
    QString prefix; // set this only for ElementNode and AttributeNode
    QString namespaceURI; // set this only for ElementNode and AttributeNode
    bool createdWithDom1Interface : 1;
    bool hasParent                : 1;

    int lineNumber;
    int columnNumber;
};

class QDomNodeListPrivate
{
public:
    QDomNodeListPrivate(QDomNodePrivate*);
    QDomNodeListPrivate(QDomNodePrivate*, const QString& );
    QDomNodeListPrivate(QDomNodePrivate*, const QString&, const QString& );
    ~QDomNodeListPrivate();

    bool operator== (const QDomNodeListPrivate&) const;
    bool operator!= (const QDomNodeListPrivate&) const;

    void createList();
    QDomNodePrivate* item(int index);
226
    int length() const;
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250

    QAtomicInt ref;
    /*
      This list contains the children of this node.
     */
    QDomNodePrivate* node_impl;
    QString tagname;
    QString nsURI;
    QList<QDomNodePrivate*> list;
    long timestamp;
};

class QDomNamedNodeMapPrivate
{
public:
    QDomNamedNodeMapPrivate(QDomNodePrivate*);
    ~QDomNamedNodeMapPrivate();

    QDomNodePrivate* namedItem(const QString& name) const;
    QDomNodePrivate* namedItemNS(const QString& nsURI, const QString& localName) const;
    QDomNodePrivate* setNamedItem(QDomNodePrivate* arg);
    QDomNodePrivate* setNamedItemNS(QDomNodePrivate* arg);
    QDomNodePrivate* removeNamedItem(const QString& name);
    QDomNodePrivate* item(int index) const;
251
    int length() const;
252
253
254
255
256
257
258
259
260
261
262
263
264
    bool contains(const QString& name) const;
    bool containsNS(const QString& nsURI, const QString & localName) const;

    /**
     * Remove all children from the map.
     */
    void clearMap();
    bool isReadOnly() { return readonly; }
    void setReadOnly(bool r) { readonly = r; }
    bool isAppendToParent() { return appendToParent; }
    /**
     * If true, then the node will redirect insert/remove calls
     * to its parent by calling QDomNodePrivate::appendChild or removeChild.
265
     * In addition the map won't increase or decrease the reference count
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
     * of the nodes it contains.
     *
     * By default this value is false and the map will handle reference counting
     * by itself.
     */
    void setAppendToParent(bool b) { appendToParent = b; }

    /**
     * Creates a copy of the map. It is a deep copy
     * that means that all children are cloned.
     */
    QDomNamedNodeMapPrivate* clone(QDomNodePrivate* parent);

    // Variables
    QAtomicInt ref;
    QHash<QString, QDomNodePrivate *> map;
    QDomNodePrivate* parent;
    bool readonly;
    bool appendToParent;
};

class QDomDocumentTypePrivate : public QDomNodePrivate
{
public:
    QDomDocumentTypePrivate(QDomDocumentPrivate*, QDomNodePrivate* parent = 0);
    QDomDocumentTypePrivate(QDomDocumentTypePrivate* n, bool deep);
    ~QDomDocumentTypePrivate();
    void init();

    // Reimplemented from QDomNodePrivate
296
297
298
299
300
301
    QDomNodePrivate* cloneNode(bool deep = true) override;
    QDomNodePrivate* insertBefore(QDomNodePrivate* newChild, QDomNodePrivate* refChild) override;
    QDomNodePrivate* insertAfter(QDomNodePrivate* newChild, QDomNodePrivate* refChild) override;
    QDomNodePrivate* replaceChild(QDomNodePrivate* newChild, QDomNodePrivate* oldChild) override;
    QDomNodePrivate* removeChild(QDomNodePrivate* oldChild) override;
    QDomNodePrivate* appendChild(QDomNodePrivate* newChild) override;
302

303
    QDomNode::NodeType nodeType() const override { return QDomNode::DocumentTypeNode; }
304

305
    void save(QTextStream& s, int, int) const override;
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321

    // Variables
    QDomNamedNodeMapPrivate* entities;
    QDomNamedNodeMapPrivate* notations;
    QString publicId;
    QString systemId;
    QString internalSubset;
};

class QDomDocumentFragmentPrivate : public QDomNodePrivate
{
public:
    QDomDocumentFragmentPrivate(QDomDocumentPrivate*, QDomNodePrivate* parent = 0);
    QDomDocumentFragmentPrivate(QDomNodePrivate* n, bool deep);

    // Reimplemented from QDomNodePrivate
322
323
    virtual QDomNodePrivate* cloneNode(bool deep = true) override;
    QDomNode::NodeType nodeType() const override { return QDomNode::DocumentFragmentNode; }
324
325
326
327
328
329
330
331
};

class QDomCharacterDataPrivate : public QDomNodePrivate
{
public:
    QDomCharacterDataPrivate(QDomDocumentPrivate*, QDomNodePrivate* parent, const QString& data);
    QDomCharacterDataPrivate(QDomCharacterDataPrivate* n, bool deep);

332
    int dataLength() const;
333
334
335
336
337
338
339
    QString substringData(unsigned long offset, unsigned long count) const;
    void appendData(const QString& arg);
    void insertData(unsigned long offset, const QString& arg);
    void deleteData(unsigned long offset, unsigned long count);
    void replaceData(unsigned long offset, unsigned long count, const QString& arg);

    // Reimplemented from QDomNodePrivate
340
341
    QDomNode::NodeType nodeType() const override { return QDomNode::CharacterDataNode; }
    QDomNodePrivate* cloneNode(bool deep = true) override;
342
343
344
345
346
347
348
349
350
351
352
};

class QDomTextPrivate : public QDomCharacterDataPrivate
{
public:
    QDomTextPrivate(QDomDocumentPrivate*, QDomNodePrivate* parent, const QString& val);
    QDomTextPrivate(QDomTextPrivate* n, bool deep);

    QDomTextPrivate* splitText(int offset);

    // Reimplemented from QDomNodePrivate
353
354
355
    QDomNodePrivate* cloneNode(bool deep = true) override;
    QDomNode::NodeType nodeType() const override { return QDomNode::TextNode; }
    virtual void save(QTextStream& s, int, int) const override;
356
357
358
359
360
361
362
363
364
365
366
367
};

class QDomAttrPrivate : public QDomNodePrivate
{
public:
    QDomAttrPrivate(QDomDocumentPrivate*, QDomNodePrivate*, const QString& name);
    QDomAttrPrivate(QDomDocumentPrivate*, QDomNodePrivate*, const QString& nsURI, const QString& qName);
    QDomAttrPrivate(QDomAttrPrivate* n, bool deep);

    bool specified() const;

    // Reimplemented from QDomNodePrivate
368
369
370
371
    void setNodeValue(const QString& v) override;
    QDomNodePrivate* cloneNode(bool deep = true) override;
    QDomNode::NodeType nodeType() const override { return QDomNode::AttributeNode; }
    virtual void save(QTextStream& s, int, int) const override;
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

    // Variables
    bool m_specified;
};

class QDomElementPrivate : public QDomNodePrivate
{
public:
    QDomElementPrivate(QDomDocumentPrivate*, QDomNodePrivate* parent, const QString& name);
    QDomElementPrivate(QDomDocumentPrivate*, QDomNodePrivate* parent, const QString& nsURI, const QString& qName);
    QDomElementPrivate(QDomElementPrivate* n, bool deep);
    ~QDomElementPrivate();

    QString attribute(const QString& name, const QString& defValue) const;
    QString attributeNS(const QString& nsURI, const QString& localName, const QString& defValue) const;
    void setAttribute(const QString& name, const QString& value);
    void setAttributeNS(const QString& nsURI, const QString& qName, const QString& newValue);
    void removeAttribute(const QString& name);
    QDomAttrPrivate* attributeNode(const QString& name);
    QDomAttrPrivate* attributeNodeNS(const QString& nsURI, const QString& localName);
    QDomAttrPrivate* setAttributeNode(QDomAttrPrivate* newAttr);
    QDomAttrPrivate* setAttributeNodeNS(QDomAttrPrivate* newAttr);
    QDomAttrPrivate* removeAttributeNode(QDomAttrPrivate* oldAttr);
    bool hasAttribute(const QString& name);
    bool hasAttributeNS(const QString& nsURI, const QString& localName);

    QString text();

    // Reimplemented from QDomNodePrivate
    QDomNamedNodeMapPrivate* attributes() { return m_attr; }
    bool hasAttributes() { return (m_attr->length() > 0); }
403
404
405
    QDomNode::NodeType nodeType() const override { return QDomNode::ElementNode; }
    QDomNodePrivate* cloneNode(bool deep = true) override;
    virtual void save(QTextStream& s, int, int) const override;
406
407
408
409
410
411
412
413
414
415
416
417
418

    // Variables
    QDomNamedNodeMapPrivate* m_attr;
};


class QDomCommentPrivate : public QDomCharacterDataPrivate
{
public:
    QDomCommentPrivate(QDomDocumentPrivate*, QDomNodePrivate* parent, const QString& val);
    QDomCommentPrivate(QDomCommentPrivate* n, bool deep);

    // Reimplemented from QDomNodePrivate
419
420
421
    QDomNodePrivate* cloneNode(bool deep = true) override;
    QDomNode::NodeType nodeType() const override { return QDomNode::CommentNode; }
    virtual void save(QTextStream& s, int, int) const override;
422
423
424
425
426
427
428
429
430
};

class QDomCDATASectionPrivate : public QDomTextPrivate
{
public:
    QDomCDATASectionPrivate(QDomDocumentPrivate*, QDomNodePrivate* parent, const QString& val);
    QDomCDATASectionPrivate(QDomCDATASectionPrivate* n, bool deep);

    // Reimplemented from QDomNodePrivate
431
432
433
    QDomNodePrivate* cloneNode(bool deep = true) override;
    QDomNode::NodeType nodeType() const override { return QDomNode::CDATASectionNode; }
    virtual void save(QTextStream& s, int, int) const override;
434
435
436
437
438
439
440
441
442
443
};

class QDomNotationPrivate : public QDomNodePrivate
{
public:
    QDomNotationPrivate(QDomDocumentPrivate*, QDomNodePrivate* parent, const QString& name,
                          const QString& pub, const QString& sys);
    QDomNotationPrivate(QDomNotationPrivate* n, bool deep);

    // Reimplemented from QDomNodePrivate
444
445
446
    QDomNodePrivate* cloneNode(bool deep = true) override;
    QDomNode::NodeType nodeType() const override { return QDomNode::NotationNode; }
    virtual void save(QTextStream& s, int, int) const override;
447
448
449
450
451
452
453
454
455
456
457
458
459
460

    // Variables
    QString m_sys;
    QString m_pub;
};

class QDomEntityPrivate : public QDomNodePrivate
{
public:
    QDomEntityPrivate(QDomDocumentPrivate*, QDomNodePrivate* parent, const QString& name,
                        const QString& pub, const QString& sys, const QString& notation);
    QDomEntityPrivate(QDomEntityPrivate* n, bool deep);

    // Reimplemented from QDomNodePrivate
461
462
463
    QDomNodePrivate* cloneNode(bool deep = true) override;
    QDomNode::NodeType nodeType() const override { return QDomNode::EntityNode; }
    virtual void save(QTextStream& s, int, int) const override;
464
465
466
467
468
469
470
471
472
473
474
475
476
477

    // Variables
    QString m_sys;
    QString m_pub;
    QString m_notationName;
};

class QDomEntityReferencePrivate : public QDomNodePrivate
{
public:
    QDomEntityReferencePrivate(QDomDocumentPrivate*, QDomNodePrivate* parent, const QString& name);
    QDomEntityReferencePrivate(QDomNodePrivate* n, bool deep);

    // Reimplemented from QDomNodePrivate
478
479
480
    QDomNodePrivate* cloneNode(bool deep = true) override;
    QDomNode::NodeType nodeType() const override { return QDomNode::EntityReferenceNode; }
    virtual void save(QTextStream& s, int, int) const override;
481
482
483
484
485
486
487
488
489
490
};

class QDomProcessingInstructionPrivate : public QDomNodePrivate
{
public:
    QDomProcessingInstructionPrivate(QDomDocumentPrivate*, QDomNodePrivate* parent, const QString& target,
                                       const QString& data);
    QDomProcessingInstructionPrivate(QDomProcessingInstructionPrivate* n, bool deep);

    // Reimplemented from QDomNodePrivate
491
492
493
    QDomNodePrivate* cloneNode(bool deep = true) override;
    QDomNode::NodeType nodeType() const override { return QDomNode::ProcessingInstructionNode; }
    virtual void save(QTextStream& s, int, int) const override;
494
495
496
497
498
499
500
501
502
503
504
505
};

class QDomDocumentPrivate : public QDomNodePrivate
{
public:
    QDomDocumentPrivate();
    QDomDocumentPrivate(const QString& name);
    QDomDocumentPrivate(QDomDocumentTypePrivate* dt);
    QDomDocumentPrivate(QDomDocumentPrivate* n, bool deep);
    ~QDomDocumentPrivate();

    bool setContent(QXmlInputSource *source, bool namespaceProcessing, QString *errorMsg, int *errorLine, int *errorColumn);
506
    bool setContent(QXmlInputSource *source, QXmlReader *reader, QXmlSimpleReader *simpleReader, QString *errorMsg, int *errorLine, int *errorColumn);
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524

    // Attributes
    QDomDocumentTypePrivate* doctype() { return type.data(); }
    QDomImplementationPrivate* implementation() { return impl.data(); }
    QDomElementPrivate* documentElement();

    // Factories
    QDomElementPrivate* createElement(const QString& tagName);
    QDomElementPrivate*        createElementNS(const QString& nsURI, const QString& qName);
    QDomDocumentFragmentPrivate* createDocumentFragment();
    QDomTextPrivate* createTextNode(const QString& data);
    QDomCommentPrivate* createComment(const QString& data);
    QDomCDATASectionPrivate* createCDATASection(const QString& data);
    QDomProcessingInstructionPrivate* createProcessingInstruction(const QString& target, const QString& data);
    QDomAttrPrivate* createAttribute(const QString& name);
    QDomAttrPrivate* createAttributeNS(const QString& nsURI, const QString& qName);
    QDomEntityReferencePrivate* createEntityReference(const QString& name);

525
    QDomNodePrivate* importNode(QDomNodePrivate* importedNode, bool deep);
526
527

    // Reimplemented from QDomNodePrivate
528
529
530
    QDomNodePrivate* cloneNode(bool deep = true) override;
    QDomNode::NodeType nodeType() const override { return QDomNode::DocumentNode; }
    void clear() override;
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

    // Variables
    QExplicitlySharedDataPointer<QDomImplementationPrivate> impl;
    QExplicitlySharedDataPointer<QDomDocumentTypePrivate> type;

    void saveDocument(QTextStream& stream, const int indent, QDomNode::EncodingPolicy encUsed) const;

    /* \internal
       Counter for the QDomNodeListPrivate timestamps.

       This is a cache optimization, that might in some cases be effective. The
       dilemma is that QDomNode::childNodes() returns a list, but the
       implementation stores the children in a linked list. Hence, in order to
       get the children out through childNodes(), a list must be populated each
       time, which is O(N).

       DOM has the requirement of node references being live, see DOM Core
       Level 3, 1.1.1 The DOM Structure Model, which means that changes to the
       underlying documents must be reflected in node lists.

       This mechanism, nodeListTime, is a caching optimization that reduces the
       amount of times the node list is rebuilt, by only doing so when the
       document actually changes. However, a change to anywhere in any document
       invalidate all lists, since no dependency tracking is done.

       It functions by that all modifying functions(insertBefore() and so on)
       increment the count; each QDomNodeListPrivate copies nodeListTime on
       construction, and compares its own value to nodeListTime in order to
       determine whether it needs to rebuild.

       This is reentrant. The nodeListTime may overflow, but that's ok since we
       check for equalness, not whether nodeListTime is smaller than the list's
       stored timestamp.
    */
    long nodeListTime;
};

/**************************************************************
 *
 * QDomHandler
 *
 **************************************************************/

class QDomHandler : public QXmlDefaultHandler
{
public:
577
    QDomHandler(QDomDocumentPrivate* d, QXmlSimpleReader *reader, bool namespaceProcessing);
578
579
580
    ~QDomHandler();

    // content handler
581
582
583
584
585
586
    bool endDocument() override;
    bool startElement(const QString& nsURI, const QString& localName, const QString& qName, const QXmlAttributes& atts) override;
    bool endElement(const QString& nsURI, const QString& localName, const QString& qName) override;
    bool characters(const QString& ch) override;
    bool processingInstruction(const QString& target, const QString& data) override;
    bool skippedEntity(const QString& name) override;
587
588

    // error handler
589
    bool fatalError(const QXmlParseException& exception) override;
590
591

    // lexical handler
592
593
594
595
596
597
    bool startCDATA() override;
    bool endCDATA() override;
    bool startEntity(const QString &) override;
    bool endEntity(const QString &) override;
    bool startDTD(const QString& name, const QString& publicId, const QString& systemId) override;
    bool comment(const QString& ch) override;
598
599

    // decl handler
600
    bool externalEntityDecl(const QString &name, const QString &publicId, const QString &systemId) override ;
601
602

    // DTD handler
603
604
    bool notationDecl(const QString & name, const QString & publicId, const QString & systemId) override;
    bool unparsedEntityDecl(const QString &name, const QString &publicId, const QString &systemId, const QString &notationName) override ;
605

606
    void setDocumentLocator(QXmlLocator *locator) override;
607
608
609
610
611
612
613
614
615
616
617
618

    QString errorMsg;
    int errorLine;
    int errorColumn;

private:
    QDomDocumentPrivate *doc;
    QDomNodePrivate *node;
    QString entityName;
    bool cdata;
    bool nsProcessing;
    QXmlLocator *locator;
619
    QXmlSimpleReader *reader;
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
};

/**************************************************************
 *
 * Functions for verifying legal data
 *
 **************************************************************/
QDomImplementation::InvalidDataPolicy QDomImplementationPrivate::invalidDataPolicy
    = QDomImplementation::AcceptInvalidChars;

// [5] Name ::= (Letter | '_' | ':') (NameChar)*

static QString fixedXmlName(const QString &_name, bool *ok, bool namespaces = false)
{
    QString name, prefix;
    if (namespaces)
        qt_split_namespace(prefix, name, _name, true);
    else
        name = _name;

    if (name.isEmpty()) {
        *ok = false;
        return QString();
    }

    if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::AcceptInvalidChars) {
        *ok = true;
        return _name;
    }

    QString result;
    bool firstChar = true;
    for (int i = 0; i < name.size(); ++i) {
        QChar c = name.at(i);
        if (firstChar) {
            if (QXmlUtils::isLetter(c) || c.unicode() == '_' || c.unicode() == ':') {
                result.append(c);
                firstChar = false;
            } else if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::ReturnNullNode) {
                *ok = false;
                return QString();
            }
        } else {
            if (QXmlUtils::isNameChar(c))
                result.append(c);
            else if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::ReturnNullNode) {
                *ok = false;
                return QString();
            }
        }
    }

    if (result.isEmpty()) {
        *ok = false;
        return QString();
    }

    *ok = true;
    if (namespaces && !prefix.isEmpty())
        return prefix + QLatin1Char(':') + result;
    return result;
}

// [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
// '<', '&' and "]]>" will be escaped when writing

static QString fixedCharData(const QString &data, bool *ok)
{
    if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::AcceptInvalidChars) {
        *ok = true;
        return data;
    }

    QString result;
    for (int i = 0; i < data.size(); ++i) {
        QChar c = data.at(i);
        if (QXmlUtils::isChar(c)) {
            result.append(c);
        } else if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::ReturnNullNode) {
            *ok = false;
            return QString();
        }
    }

    *ok = true;
    return result;
}

// [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
// can't escape "--", since entities are not recognised within comments

static QString fixedComment(const QString &data, bool *ok)
{
    if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::AcceptInvalidChars) {
        *ok = true;
        return data;
    }

    QString fixedData = fixedCharData(data, ok);
    if (!*ok)
        return QString();

    for (;;) {
        int idx = fixedData.indexOf(QLatin1String("--"));
        if (idx == -1)
            break;
        if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::ReturnNullNode) {
            *ok = false;
            return QString();
        }
        fixedData.remove(idx, 2);
    }

    *ok = true;
    return fixedData;
}

// [20] CData ::= (Char* - (Char* ']]>' Char*))
// can't escape "]]>", since entities are not recognised within comments

static QString fixedCDataSection(const QString &data, bool *ok)
{
    if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::AcceptInvalidChars) {
        *ok = true;
        return data;
    }

    QString fixedData = fixedCharData(data, ok);
    if (!*ok)
        return QString();

    for (;;) {
        int idx = fixedData.indexOf(QLatin1String("]]>"));
        if (idx == -1)
            break;
        if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::ReturnNullNode) {
            *ok = false;
            return QString();
        }
        fixedData.remove(idx, 3);
    }

    *ok = true;
    return fixedData;
}

// [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'

static QString fixedPIData(const QString &data, bool *ok)
{
    if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::AcceptInvalidChars) {
        *ok = true;
        return data;
    }

    QString fixedData = fixedCharData(data, ok);
    if (!*ok)
        return QString();

    for (;;) {
        int idx = fixedData.indexOf(QLatin1String("?>"));
        if (idx == -1)
            break;
        if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::ReturnNullNode) {
            *ok = false;
            return QString();
        }
        fixedData.remove(idx, 2);
    }

    *ok = true;
    return fixedData;
}

// [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
// The correct quote will be chosen when writing

static QString fixedPubidLiteral(const QString &data, bool *ok)
{
    if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::AcceptInvalidChars) {
        *ok = true;
        return data;
    }

    QString result;

    if(QXmlUtils::isPublicID(data))
        result = data;
    else if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::ReturnNullNode) {
        *ok = false;
        return QString();
    }

    if (result.indexOf(QLatin1Char('\'')) != -1
        && result.indexOf(QLatin1Char('"')) != -1) {
        if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::ReturnNullNode) {
            *ok = false;
            return QString();
        } else {
            result.remove(QLatin1Char('\''));
        }
    }

    *ok = true;
    return result;
}

// [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
// The correct quote will be chosen when writing

static QString fixedSystemLiteral(const QString &data, bool *ok)
{
    if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::AcceptInvalidChars) {
        *ok = true;
        return data;
    }

    QString result = data;

    if (result.indexOf(QLatin1Char('\'')) != -1
        && result.indexOf(QLatin1Char('"')) != -1) {
        if (QDomImplementationPrivate::invalidDataPolicy == QDomImplementation::ReturnNullNode) {
            *ok = false;
            return QString();
        } else {
            result.remove(QLatin1Char('\''));
        }
    }

    *ok = true;
    return result;
}

/**************************************************************
 *
 * QDomImplementationPrivate
 *
 **************************************************************/

QDomImplementationPrivate* QDomImplementationPrivate::clone()
{
    return new QDomImplementationPrivate;
}

/**************************************************************
 *
 * QDomImplementation
 *
 **************************************************************/

/*!
    \class QDomImplementation
    \reentrant
    \brief The QDomImplementation class provides information about the
    features of the DOM implementation.

    \inmodule QtXml
    \ingroup xml-tools

    This class describes the features that are supported by the DOM
    implementation. Currently the XML subset of DOM Level 1 and DOM
    Level 2 Core are supported.

    Normally you will use the function QDomDocument::implementation()
    to get the implementation object.

    You can create a new document type with createDocumentType() and a
    new document with createDocument().

Jani Heikkinen's avatar
Jani Heikkinen committed
889
   For further information about the Document Object Model see
890
891
892
893
894
895
896
    \l{http://www.w3.org/TR/REC-DOM-Level-1/}{Level 1} and
    \l{http://www.w3.org/TR/DOM-Level-2-Core/}{Level 2 Core}. For a more
    general introduction of the DOM implementation see the QDomDocument
    documentation.

    The QDom classes have a few issues of nonconformance with the XML
    specifications that cannot be fixed in Qt 4 without breaking backward
897
    compatibility. The Qt XML Patterns module and the QXmlStreamReader and
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
    QXmlStreamWriter classes have a higher degree of a conformance.

    \sa hasFeature()
*/

/*!
    Constructs a QDomImplementation object.
*/
QDomImplementation::QDomImplementation()
{
    impl = 0;
}

/*!
    Constructs a copy of \a x.
*/
QDomImplementation::QDomImplementation(const QDomImplementation &x)
{
    impl = x.impl;
    if (impl)
        impl->ref.ref();
}

QDomImplementation::QDomImplementation(QDomImplementationPrivate *p)
{
    // We want to be co-owners, so increase the reference count
    impl = p;
    if (impl)
        impl->ref.ref();
}

/*!
    Assigns \a x to this DOM implementation.
*/
QDomImplementation& QDomImplementation::operator=(const QDomImplementation &x)
{
    if (x.impl)
        x.impl->ref.ref();
    if (impl && !impl->ref.deref())
        delete impl;
    impl = x.impl;
    return *this;
}

/*!
943
944
    Returns \c true if \a x and this DOM implementation object were
    created from the same QDomDocument; otherwise returns \c false.
945
946
947
948
949
950
951
*/
bool QDomImplementation::operator==(const QDomImplementation &x) const
{
    return (impl == x.impl);
}

/*!
952
953
    Returns \c true if \a x and this DOM implementation object were
    created from different QDomDocuments; otherwise returns \c false.
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
*/
bool QDomImplementation::operator!=(const QDomImplementation &x) const
{
    return (impl != x.impl);
}

/*!
    Destroys the object and frees its resources.
*/
QDomImplementation::~QDomImplementation()
{
    if (impl && !impl->ref.deref())
        delete impl;
}

/*!
970
971
    The function returns \c true if QDom implements the requested \a
    version of a \a feature; otherwise returns \c false.
972
973
974

    The currently supported features and their versions:
    \table
975
976
    \header \li Feature \li Version
    \row \li XML \li 1.0
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    \endtable
*/
bool QDomImplementation::hasFeature(const QString& feature, const QString& version) const
{
    if (feature == QLatin1String("XML")) {
        if (version.isEmpty() || version == QLatin1String("1.0")) {
            return true;
        }
    }
    // ### add DOM level 2 features
    return false;
}

/*!
    Creates a document type node for the name \a qName.

    \a publicId specifies the public identifier of the external
    subset. If you specify an empty string (QString()) as the \a
    publicId, this means that the document type has no public
    identifier.

    \a systemId specifies the system identifier of the external
    subset. If you specify an empty string as the \a systemId, this
    means that the document type has no system identifier.
For faster browsing, not all history is shown. View entire blame