summaryrefslogtreecommitdiffstats
path: root/tests/auto/xmlpatternsxqts/lib/XMLWriter.cpp
blob: 8f495a4aefffeb37e1f59b0853e811033d8c5a06 (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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite 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 http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Patternist project on Qt Labs.
**
** $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 http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
***************************************************************************
*/

#include <QCoreApplication>
#include <QDateTime>
#include <QIODevice>
#include <QList>
#include <QPair>
#include <QStack>
#include <QtDebug>

#include "XMLWriter.h"

/* Issues:
 * - Switch to Qt's d-pointer semantics, if in Qt.
 * - Remove namespace(PatternistSDK), and change name, if in Qt.
 * - Is it really necessary to pass the tag name to endElement()?
 * - Could it be of interest to let the user control the encoding? Are those cases common
 *   enough to justify support in Qt? Using anything but UTF-8 or UTF-16
 *   means asking for trouble, from an interoperability perspective.
 */

/* Design rationalis, comments:
 *
 * - The class is called XMLWriter to harvest familarity by being consistent with
 *   Java's XMLWriter class. If XMLWriter is moved to Qt, the name QXmlWriter is perhaps suitable.
 * - The class does not handle indentation because the "do one thing well"-principle is
 *   in use. XMLWriter should be fast and not assume a certain idea of indentation. Indentation
 *   should be implemented in a standalone QXmlContentHandler that performs the indentation and
 *   "has a" QXmlContentHandler which it in addition calls, and by that proxying/piping another
 *   QXmlContentHandler(which most likely is an XMLWriter). Thus, achieving a modularized,
 *   flexibly approach to indentation. A reason is also that indentation is very subjective.
 *   The indenter class should probably be called XMLIndenter/QXmlIndenter.
 * - It could be of interest to implement QXmlDTDHandler such that it would be possible to serialize
 *   DTDs. Must be done before BC becomes significant.
 * - I think the most valuable of this class is its Q_ASSERT tests. Many programmers have severe problems
 *   producing XML, and the tests helps them catching their mistakes. They therefore promote
 *   interoperability. Do not remove them. If any are wrong, fix them instead.
 */

using namespace QPatternistSDK;

/**
 * A namespace binding, prefix/namespace URI.
 */
typedef QPair<QString, QString> NSBinding;
typedef QList<NSBinding> NSBindingList;

#ifdef QT_NO_DEBUG
#   define DEBUG_CODE(code)
#else
#   define DEBUG_CODE(code) code
#endif

class XMLWriter::Private
{
public:
    inline Private(QIODevice *devP) : insideCDATA(false),
                                     addModificationNote(false),
                                     dev(devP)
    {
        hasContentStack.push(true);
    }

#ifdef QT_NO_DEBUG
    inline void validateQName(const QString &) const
    {
    }

    inline void verifyNS(const QString &) const
    {
    }
#else
    /**
     * Simple test of that @p name is an acceptable QName.
     */
    inline void validateQName(const QString &name)
    {
        Q_ASSERT_X(!name.isEmpty(), Q_FUNC_INFO,
                   "An XML name cannot be empty.");
        Q_ASSERT_X(!name.endsWith(QLatin1Char(':')), Q_FUNC_INFO,
                   "An XML name cannot end with a colon(QLatin1Char(':')).");
        Q_ASSERT_X(!name.contains(QRegExp(QLatin1String("[ \t\n]"))), Q_FUNC_INFO,
                   "An XML name cannot contain whitespace.");
    }

    /**
     * Ensures that the prefix of @p qName is declared.
     */
    inline void verifyNS(const QString &qName) const
    {
        const QString prefix(qName.left(qName.indexOf(QLatin1Char(':'))));

        if(qName.contains(QLatin1Char(':')) && prefix != QLatin1String("xml"))
        {
            bool foundPrefix = false;
            const QStack<NSBindingList>::const_iterator end(namespaceTracker.constEnd());
            QStack<NSBindingList>::const_iterator it(namespaceTracker.constBegin());

            for(; it != end; ++it)
            {
                const NSBindingList::const_iterator lend((*it).constEnd());
                NSBindingList::const_iterator lit((*it).constBegin());

                for(; lit != lend; ++it)
                {
                    if((*lit).first == prefix)
                    {
                        foundPrefix = true;
                        break;
                    }
                }
                if(foundPrefix)
                    break;
            }

            Q_ASSERT_X(foundPrefix, "XMLWriter::startElement()",
                       qPrintable(QString::fromLatin1("The prefix %1 is not declared. All prefixes "
                                          "except 'xml' must be declared.").arg(prefix)));
        }
    }
#endif

    inline QString escapeElementContent(const QString &ch)
    {
        const int l = ch.length();
        QString retval;

        for(int i = 0; i != l; ++i)
        {
            const QChar c(ch.at(i));

            if(c == QLatin1Char(QLatin1Char('&')))
                retval += QLatin1String("&amp;");
            else if(c == QLatin1Char(QLatin1Char('<')))
                retval += QLatin1String("&lt;");
            else
                retval += c;
        }

        return retval;
    }

    inline QString escapeAttributeContent(const QString &ch)
    {
        const int l = ch.length();
        QString retval;

        for(int i = 0; i != l; ++i)
        {
            const QChar c(ch.at(i));

            /* We don't have to escape '\'' because we use '\"' as attribute delimiter. */
            if(c == QLatin1Char('&'))
                retval += QLatin1String("&amp;");
            else if(c == QLatin1Char('<'))
                retval += QLatin1String("&lt;");
            else if(c == QLatin1Char('"'))
                retval += QLatin1String("&quot;");
            else
                retval += c;
        }

        return retval;
    }

    inline QString escapeCDATAContent(const QString &ch)
    {
        const int l = ch.length();
        QString retval;
        qint8 atEnd = 0;

        for(int i = 0; i != l; ++i)
        {
            const QChar c(ch.at(i));

            /* Escape '>' if in "]]>" */
            if(c == QLatin1Char(']'))
            {
                if(atEnd == 0 || atEnd == 1)
                    ++atEnd;
                else
                    atEnd = 0;

                retval += QLatin1Char(']');
            }
            else if(c == QLatin1Char('>'))
            {
                if(atEnd == 2)
                    retval += QLatin1String("&gt;");
                else
                {
                    atEnd = 0;
                    retval += QLatin1Char('>');
                }
            }
            else
                retval += c;
        }

        return retval;
    }

    /**
     * We wrap dev in this function such that we can deploy the Q_ASSERT_X
     * macro in each place it's used.
     */
    inline QIODevice *device() const
    {
        Q_ASSERT_X(dev, Q_FUNC_INFO,
                   "No device specified for XMLWriter; one must be specified with "
                   "setDevice() or via the constructor before XMLWriter can be used.");
        return dev;
    }

    /**
     * @returns true on success, otherwise false
     */
    inline bool serialize(const QString &data)
    {
        const QByteArray utf8(data.toUtf8());

        return device()->write(utf8) == utf8.size();
    }

    /**
     * @returns true on success, otherwise false
     */
    inline bool serialize(const char data)
    {
        return device()->putChar(data);
    }

    /**
     * @returns true on success, otherwise false
     */
    inline bool serialize(const char *data)
    {
        return device()->write(data) == qstrlen(data);
    }

    inline bool hasElementContent() const
    {
        return hasContentStack.top();
    }

    inline void handleElement()
    {
        if(!hasElementContent())
            serialize('>');

        /* This element is content for the parent. */
        hasContentStack.top() = true;
    }

    NSBindingList namespaces;
    bool insideCDATA;
    bool addModificationNote;
    QString msg;
    QIODevice *dev;
    QStack<bool> hasContentStack;
    QString errorString;
    DEBUG_CODE(QStack<QString> tags;)
    DEBUG_CODE(QStack<NSBindingList> namespaceTracker;)
};

/**
 * Reduces complexity. The empty else clause is for avoiding mess when macro
 * is used in the 'then' branch of an if clause, which is followed by an else clause.
 */
#define serialize(string) if(!d->serialize(string)) \
                          { \
                              d->errorString = d->device()->errorString(); \
                              return false; \
                          } \
                          else

XMLWriter::XMLWriter(QIODevice *outStream) : d(new Private(outStream))
{
}

XMLWriter::~XMLWriter()
{
    delete d;
}

bool XMLWriter::startDocument()
{
    if(!device()->isOpen() && !device()->open(QIODevice::WriteOnly))
        return false;

    if(d->addModificationNote)
    {
        if(d->msg.isNull())
        {
            d->msg = QString::fromLatin1("NOTE: This file was automatically generated "
                                         "by %1 at %2. All changes to this file will be lost.")
                                         .arg(QCoreApplication::instance()->applicationName(),
                                              QDateTime::currentDateTime().toString());
        }
        if(!comment(d->msg))
            return false;

        serialize('\n');
    }

    serialize(QLatin1String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"));

    return true;
}

bool XMLWriter::startElement(const QString &/*namespaceURI*/,
                             const QString &/*localName*/,
                             const QString &qName,
                             const QXmlAttributes &atts)
{
    return startElement(qName, atts);
}

bool XMLWriter::startElement(const QString &qName,
                             const QXmlAttributes &atts)
{
    Q_ASSERT_X(!d->insideCDATA, Q_FUNC_INFO,
               "Only characters() can be received when inside CDATA.");
    Q_ASSERT_X(!qName.startsWith(QLatin1String("xmlns")), Q_FUNC_INFO,
               "startElement should not be used for declaring prefixes, "
               "use startPrefixMapping() for that.");

    d->validateQName(qName);
    d->verifyNS(qName);

    d->handleElement();

    serialize('<');
    serialize(qName);

    DEBUG_CODE(d->tags.push(qName));
    DEBUG_CODE(d->namespaceTracker.push(d->namespaces));

    /* Add namespace declarations. */
    const NSBindingList::const_iterator end(d->namespaces.constEnd());
    NSBindingList::const_iterator it(d->namespaces.constBegin());

    for(; it != end; ++it)
    {
        if((*it).first.isEmpty())
            serialize(" xmlns=");
        else
        {
            serialize(" xmlns:");
            serialize((*it).first);
            serialize('=');
        }

        serialize('"');
        serialize(d->escapeElementContent((*it).second));
        serialize('"');
    }
    d->namespaces.clear();

    const int c = atts.count();

    /* Serialize attributes. */
    for(int i = 0; i != c; ++i)
    {
        d->validateQName(atts.qName(i));
        d->verifyNS(atts.qName(i));

        serialize(' ');
        serialize(atts.qName(i));
        serialize("=\"");
        serialize(d->escapeAttributeContent(atts.value(i)));
        serialize('"');
    }

    d->hasContentStack.push(false);
    return true;
}

bool XMLWriter::endElement(const QString &/*namespaceURI*/,
                           const QString &/*localName*/,
                           const QString &qName)
{
    return endElement(qName);
}

bool XMLWriter::endElement(const QString &qName)
{
    Q_ASSERT_X(!d->insideCDATA, Q_FUNC_INFO,
               "Only characters() can be received when inside CDATA.");
    Q_ASSERT_X(d->tags.pop() == qName, Q_FUNC_INFO,
               "The element tags are not balanced, the produced XML is invalid.");

    DEBUG_CODE(d->namespaceTracker.pop());

    /* "this" element is content for our parent, so ensure hasElementContent is true. */

    if(d->hasElementContent())
    {
        serialize(QLatin1String("</"));
        serialize(qName);
        serialize('>');
    }
    else
        serialize(QLatin1String("/>"));

    d->hasContentStack.pop();

    return true;
}

bool XMLWriter::startPrefixMapping(const QString &prefix, const QString &uri)
{
    Q_ASSERT_X(!d->insideCDATA, Q_FUNC_INFO,
               "Only characters() can be received when inside CDATA.");
    Q_ASSERT_X(prefix.toLower() != QLatin1String("xml") ||
               (prefix.toLower() == QLatin1String("xml") &&
               (uri == QLatin1String("http://www.w3.org/TR/REC-xml-names/") ||
                                              uri.isEmpty())),
               Q_FUNC_INFO,
               "The prefix 'xml' can only be bound to the namespace "
               "\"http://www.w3.org/TR/REC-xml-names/\".");
    Q_ASSERT_X(prefix.toLower() != QLatin1String("xml") &&
                uri != QLatin1String("http://www.w3.org/TR/REC-xml-names/"),
               Q_FUNC_INFO,
               "The namespace \"http://www.w3.org/TR/REC-xml-names/\" can only be bound to the "
               "\"xml\" prefix.");

    d->namespaces.append(qMakePair(prefix, uri));
    return true;
}

bool XMLWriter::processingInstruction(const QString &target,
                                      const QString &data)
{
    Q_ASSERT_X(target.toLower() != QLatin1String("xml"), Q_FUNC_INFO,
               "A processing instruction cannot have the name xml in any "
               "capitalization, because it is reserved.");
    Q_ASSERT_X(!data.contains(QLatin1String("?>")), Q_FUNC_INFO,
               "The content of a processing instruction cannot contain the string \"?>\".");
    Q_ASSERT_X(!d->insideCDATA, "XMLWriter::processingInstruction()",
               "Only characters() can be received when inside CDATA.");

    d->handleElement();

    serialize(QLatin1String("<?"));
    serialize(target);
    serialize(' ');
    serialize(data);
    serialize(QLatin1String("?>"));
    return true;
}

bool XMLWriter::characters(const QString &ch)
{
    Q_ASSERT_X(d->tags.count() >= 1, Q_FUNC_INFO,
               "Text nodes can only appear inside elements(no elements sent).");
    d->handleElement();

    if(d->insideCDATA)
        serialize(d->escapeCDATAContent(ch));
    else
        serialize(d->escapeElementContent(ch));

    return true;
}

bool XMLWriter::comment(const QString &ch)
{
    Q_ASSERT_X(!d->insideCDATA, Q_FUNC_INFO,
               "Only characters() can be received when inside CDATA.");
    Q_ASSERT_X(!ch.contains(QLatin1String("--")), Q_FUNC_INFO,
               "XML comments may not contain double-hyphens(\"--\").");
    Q_ASSERT_X(!ch.endsWith(QLatin1Char('-')), Q_FUNC_INFO,
               "XML comments cannot end with a hyphen, \"-\"(add a space, for example).");
    /* A comment starting with "<!---" is ok. */

    d->handleElement();

    serialize(QLatin1String("<!--"));
    serialize(ch);
    serialize(QLatin1String("-->"));

    return true;
}

bool XMLWriter::startCDATA()
{
    Q_ASSERT_X(d->insideCDATA, Q_FUNC_INFO,
               "startCDATA() has already been called.");
    Q_ASSERT_X(d->tags.count() >= 1, Q_FUNC_INFO,
               "CDATA sections can only appear inside elements(no elements sent).");
    d->insideCDATA = true;
    serialize(QLatin1String("<![CDATA["));
    return true;
}

bool XMLWriter::endCDATA()
{
    d->insideCDATA = false;
    serialize("]]>");
    return true;
}

bool XMLWriter::startDTD(const QString &name,
                         const QString &publicId,
                         const QString &systemId)
{
    Q_ASSERT_X(!d->insideCDATA, Q_FUNC_INFO,
               "Only characters() can be received when inside CDATA.");
    Q_ASSERT_X(!name.isEmpty(), Q_FUNC_INFO,
               "The DOCTYPE name cannot be empty.");
    Q_ASSERT_X(d->tags.isEmpty() && d->namespaces.isEmpty(), Q_FUNC_INFO,
               "No content such as namespace declarations or elements can be serialized "
               "before the DOCTYPE declaration, the XML is invalid.");
    Q_ASSERT_X(!publicId.contains(QLatin1Char('"')), Q_FUNC_INFO,
               "The PUBLIC ID cannot contain quotes('\"').");
    Q_ASSERT_X(!systemId.contains(QLatin1Char('"')), Q_FUNC_INFO,
               "The SYSTEM ID cannot contain quotes('\"').");

    serialize(QLatin1String("<!DOCTYPE "));
    serialize(name);

    if(!publicId.isEmpty())
    {
        Q_ASSERT_X(!systemId.isEmpty(), Q_FUNC_INFO,
                   "When a public identifier is specified, a system identifier "
                   "must also be specified in order to produce valid XML.");
        serialize(" PUBLIC \"");
        serialize(publicId);
        serialize('"');
    }

    if(!systemId.isEmpty())
    {
        if(publicId.isEmpty())
            serialize(" SYSTEM");

        serialize(" \"");
        serialize(systemId);
        serialize('"');
    }

    return true;
}

bool XMLWriter::endDTD()
{
    Q_ASSERT_X(d->tags.isEmpty() && d->namespaces.isEmpty(), Q_FUNC_INFO,
               "Content such as namespace declarations or elements cannot occur inside "
               "the DOCTYPE declaration, the XML is invalid.");
    serialize(QLatin1String(">\n"));
    return true;
}

bool XMLWriter::startEntity(const QString &)
{
    return true;
}

bool XMLWriter::endEntity(const QString &)
{
    return true;
}

void XMLWriter::setMessage(const QString &msg)
{
    d->msg = msg;
}

QString XMLWriter::modificationMessage() const
{
    return d->msg;
}

bool XMLWriter::endDocument()
{
    Q_ASSERT_X(d->tags.isEmpty(), Q_FUNC_INFO,
               "endDocument() called before all elements were closed with endElement().");
    d->device()->close();
    return true;
}

QString XMLWriter::errorString() const
{
    return d->errorString;
}

bool XMLWriter::ignorableWhitespace(const QString &ch)
{
    return characters(ch);
}

bool XMLWriter::endPrefixMapping(const QString &)
{
    /* Again, should we do something with this? */
    return true;
}

bool XMLWriter::skippedEntity(const QString &)
{
    return true;
}

void XMLWriter::setDocumentLocator(QXmlLocator *)
{
}

QIODevice *XMLWriter::device() const
{
    return d->dev;
}

void XMLWriter::setDevice(QIODevice *dev)
{
    d->dev = dev;
}

void XMLWriter::setAddMessage(const bool toggle)
{
    d->addModificationNote = toggle;
}

bool XMLWriter::addModificationMessage() const
{
    return d->addModificationNote;
}

#undef serialize
// vim: et:ts=4:sw=4:sts=4