forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsXMLContentSerializer.cpp
1722 lines (1483 loc) · 51.2 KB
/
nsXMLContentSerializer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* nsIContentSerializer implementation that can be used with an
* nsIDocumentEncoder to convert an XML DOM to an XML string that
* could be parsed into more or less the original DOM.
*/
#include "nsXMLContentSerializer.h"
#include "nsGkAtoms.h"
#include "nsIDOMProcessingInstruction.h"
#include "nsIDOMComment.h"
#include "nsIDOMDocumentType.h"
#include "nsIContent.h"
#include "nsIDocument.h"
#include "nsIDocumentEncoder.h"
#include "nsNameSpaceManager.h"
#include "nsTextFragment.h"
#include "nsString.h"
#include "prprf.h"
#include "nsUnicharUtils.h"
#include "nsCRT.h"
#include "nsContentUtils.h"
#include "nsAttrName.h"
#include "nsILineBreaker.h"
#include "mozilla/dom/Element.h"
#include "nsParserConstants.h"
using namespace mozilla::dom;
#define kXMLNS "xmlns"
// to be readable, we assume that an indented line contains
// at least this number of characters (arbitrary value here).
// This is a limit for the indentation.
#define MIN_INDENTED_LINE_LENGTH 15
// the string used to indent.
#define INDENT_STRING " "
#define INDENT_STRING_LENGTH 2
nsresult NS_NewXMLContentSerializer(nsIContentSerializer** aSerializer)
{
nsXMLContentSerializer* it = new nsXMLContentSerializer();
if (!it) {
return NS_ERROR_OUT_OF_MEMORY;
}
return CallQueryInterface(it, aSerializer);
}
nsXMLContentSerializer::nsXMLContentSerializer()
: mPrefixIndex(0),
mColPos(0),
mIndentOverflow(0),
mIsIndentationAddedOnCurrentLine(false),
mInAttribute(false),
mAddNewlineForRootNode(false),
mAddSpace(false),
mMayIgnoreLineBreakSequence(false),
mBodyOnly(false),
mInBody(0)
{
}
nsXMLContentSerializer::~nsXMLContentSerializer()
{
}
NS_IMPL_ISUPPORTS(nsXMLContentSerializer, nsIContentSerializer)
NS_IMETHODIMP
nsXMLContentSerializer::Init(uint32_t aFlags, uint32_t aWrapColumn,
const char* aCharSet, bool aIsCopying,
bool aRewriteEncodingDeclaration)
{
mPrefixIndex = 0;
mColPos = 0;
mIndentOverflow = 0;
mIsIndentationAddedOnCurrentLine = false;
mInAttribute = false;
mAddNewlineForRootNode = false;
mAddSpace = false;
mMayIgnoreLineBreakSequence = false;
mBodyOnly = false;
mInBody = 0;
mCharset = aCharSet;
mFlags = aFlags;
// Set the line break character:
if ((mFlags & nsIDocumentEncoder::OutputCRLineBreak)
&& (mFlags & nsIDocumentEncoder::OutputLFLineBreak)) { // Windows
mLineBreak.AssignLiteral("\r\n");
}
else if (mFlags & nsIDocumentEncoder::OutputCRLineBreak) { // Mac
mLineBreak.Assign('\r');
}
else if (mFlags & nsIDocumentEncoder::OutputLFLineBreak) { // Unix/DOM
mLineBreak.Assign('\n');
}
else {
mLineBreak.AssignLiteral(NS_LINEBREAK); // Platform/default
}
mDoRaw = !!(mFlags & nsIDocumentEncoder::OutputRaw);
mDoFormat = (mFlags & nsIDocumentEncoder::OutputFormatted && !mDoRaw);
mDoWrap = (mFlags & nsIDocumentEncoder::OutputWrap && !mDoRaw);
if (!aWrapColumn) {
mMaxColumn = 72;
}
else {
mMaxColumn = aWrapColumn;
}
mPreLevel = 0;
mIsIndentationAddedOnCurrentLine = false;
return NS_OK;
}
nsresult
nsXMLContentSerializer::AppendTextData(nsIContent* aNode,
int32_t aStartOffset,
int32_t aEndOffset,
nsAString& aStr,
bool aTranslateEntities)
{
nsIContent* content = aNode;
const nsTextFragment* frag;
if (!content || !(frag = content->GetText())) {
return NS_ERROR_FAILURE;
}
int32_t fragLength = frag->GetLength();
int32_t endoffset = (aEndOffset == -1) ? fragLength : std::min(aEndOffset, fragLength);
int32_t length = endoffset - aStartOffset;
NS_ASSERTION(aStartOffset >= 0, "Negative start offset for text fragment!");
NS_ASSERTION(aStartOffset <= endoffset, "A start offset is beyond the end of the text fragment!");
if (length <= 0) {
// XXX Zero is a legal value, maybe non-zero values should be an
// error.
return NS_OK;
}
if (frag->Is2b()) {
const char16_t *strStart = frag->Get2b() + aStartOffset;
if (aTranslateEntities) {
AppendAndTranslateEntities(Substring(strStart, strStart + length), aStr);
}
else {
aStr.Append(Substring(strStart, strStart + length));
}
}
else {
if (aTranslateEntities) {
AppendAndTranslateEntities(NS_ConvertASCIItoUTF16(frag->Get1b()+aStartOffset, length), aStr);
}
else {
aStr.Append(NS_ConvertASCIItoUTF16(frag->Get1b()+aStartOffset, length));
}
}
return NS_OK;
}
NS_IMETHODIMP
nsXMLContentSerializer::AppendText(nsIContent* aText,
int32_t aStartOffset,
int32_t aEndOffset,
nsAString& aStr)
{
NS_ENSURE_ARG(aText);
nsAutoString data;
nsresult rv;
rv = AppendTextData(aText, aStartOffset, aEndOffset, data, true);
if (NS_FAILED(rv))
return NS_ERROR_FAILURE;
if (mDoRaw || PreLevel() > 0) {
AppendToStringConvertLF(data, aStr);
}
else if (mDoFormat) {
AppendToStringFormatedWrapped(data, aStr);
}
else if (mDoWrap) {
AppendToStringWrapped(data, aStr);
}
else {
AppendToStringConvertLF(data, aStr);
}
return NS_OK;
}
NS_IMETHODIMP
nsXMLContentSerializer::AppendCDATASection(nsIContent* aCDATASection,
int32_t aStartOffset,
int32_t aEndOffset,
nsAString& aStr)
{
NS_ENSURE_ARG(aCDATASection);
nsresult rv;
NS_NAMED_LITERAL_STRING(cdata , "<![CDATA[");
if (mDoRaw || PreLevel() > 0) {
AppendToString(cdata, aStr);
}
else if (mDoFormat) {
AppendToStringFormatedWrapped(cdata, aStr);
}
else if (mDoWrap) {
AppendToStringWrapped(cdata, aStr);
}
else {
AppendToString(cdata, aStr);
}
nsAutoString data;
rv = AppendTextData(aCDATASection, aStartOffset, aEndOffset, data, false);
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
AppendToStringConvertLF(data, aStr);
AppendToString(NS_LITERAL_STRING("]]>"), aStr);
return NS_OK;
}
NS_IMETHODIMP
nsXMLContentSerializer::AppendProcessingInstruction(nsIContent* aPI,
int32_t aStartOffset,
int32_t aEndOffset,
nsAString& aStr)
{
nsCOMPtr<nsIDOMProcessingInstruction> pi = do_QueryInterface(aPI);
NS_ENSURE_ARG(pi);
nsresult rv;
nsAutoString target, data, start;
MaybeAddNewlineForRootNode(aStr);
rv = pi->GetTarget(target);
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
rv = pi->GetData(data);
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
start.AppendLiteral("<?");
start.Append(target);
if (mDoRaw || PreLevel() > 0) {
AppendToString(start, aStr);
}
else if (mDoFormat) {
if (mAddSpace) {
AppendNewLineToString(aStr);
}
AppendToStringFormatedWrapped(start, aStr);
}
else if (mDoWrap) {
AppendToStringWrapped(start, aStr);
}
else {
AppendToString(start, aStr);
}
if (!data.IsEmpty()) {
AppendToString(char16_t(' '), aStr);
AppendToStringConvertLF(data, aStr);
}
AppendToString(NS_LITERAL_STRING("?>"), aStr);
MaybeFlagNewlineForRootNode(aPI);
return NS_OK;
}
NS_IMETHODIMP
nsXMLContentSerializer::AppendComment(nsIContent* aComment,
int32_t aStartOffset,
int32_t aEndOffset,
nsAString& aStr)
{
nsCOMPtr<nsIDOMComment> comment = do_QueryInterface(aComment);
NS_ENSURE_ARG(comment);
nsresult rv;
nsAutoString data;
rv = comment->GetData(data);
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
int32_t dataLength = data.Length();
if (aStartOffset || (aEndOffset != -1 && aEndOffset < dataLength)) {
int32_t length =
(aEndOffset == -1) ? dataLength : std::min(aEndOffset, dataLength);
length -= aStartOffset;
nsAutoString frag;
if (length > 0) {
data.Mid(frag, aStartOffset, length);
}
data.Assign(frag);
}
MaybeAddNewlineForRootNode(aStr);
NS_NAMED_LITERAL_STRING(startComment, "<!--");
if (mDoRaw || PreLevel() > 0) {
AppendToString(startComment, aStr);
}
else if (mDoFormat) {
if (mAddSpace) {
AppendNewLineToString(aStr);
}
AppendToStringFormatedWrapped(startComment, aStr);
}
else if (mDoWrap) {
AppendToStringWrapped(startComment, aStr);
}
else {
AppendToString(startComment, aStr);
}
// Even if mDoformat, we don't format the content because it
// could have been preformated by the author
AppendToStringConvertLF(data, aStr);
AppendToString(NS_LITERAL_STRING("-->"), aStr);
MaybeFlagNewlineForRootNode(aComment);
return NS_OK;
}
NS_IMETHODIMP
nsXMLContentSerializer::AppendDoctype(nsIContent* aDocType,
nsAString& aStr)
{
nsCOMPtr<nsIDOMDocumentType> docType = do_QueryInterface(aDocType);
NS_ENSURE_ARG(docType);
nsresult rv;
nsAutoString name, publicId, systemId, internalSubset;
rv = docType->GetName(name);
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
rv = docType->GetPublicId(publicId);
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
rv = docType->GetSystemId(systemId);
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
rv = docType->GetInternalSubset(internalSubset);
if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
MaybeAddNewlineForRootNode(aStr);
AppendToString(NS_LITERAL_STRING("<!DOCTYPE "), aStr);
AppendToString(name, aStr);
char16_t quote;
if (!publicId.IsEmpty()) {
AppendToString(NS_LITERAL_STRING(" PUBLIC "), aStr);
if (publicId.FindChar(char16_t('"')) == -1) {
quote = char16_t('"');
}
else {
quote = char16_t('\'');
}
AppendToString(quote, aStr);
AppendToString(publicId, aStr);
AppendToString(quote, aStr);
if (!systemId.IsEmpty()) {
AppendToString(char16_t(' '), aStr);
if (systemId.FindChar(char16_t('"')) == -1) {
quote = char16_t('"');
}
else {
quote = char16_t('\'');
}
AppendToString(quote, aStr);
AppendToString(systemId, aStr);
AppendToString(quote, aStr);
}
}
else if (!systemId.IsEmpty()) {
if (systemId.FindChar(char16_t('"')) == -1) {
quote = char16_t('"');
}
else {
quote = char16_t('\'');
}
AppendToString(NS_LITERAL_STRING(" SYSTEM "), aStr);
AppendToString(quote, aStr);
AppendToString(systemId, aStr);
AppendToString(quote, aStr);
}
if (!internalSubset.IsEmpty()) {
AppendToString(NS_LITERAL_STRING(" ["), aStr);
AppendToString(internalSubset, aStr);
AppendToString(char16_t(']'), aStr);
}
AppendToString(kGreaterThan, aStr);
MaybeFlagNewlineForRootNode(aDocType);
return NS_OK;
}
nsresult
nsXMLContentSerializer::PushNameSpaceDecl(const nsAString& aPrefix,
const nsAString& aURI,
nsIContent* aOwner)
{
NameSpaceDecl* decl = mNameSpaceStack.AppendElement();
if (!decl) return NS_ERROR_OUT_OF_MEMORY;
decl->mPrefix.Assign(aPrefix);
decl->mURI.Assign(aURI);
// Don't addref - this weak reference will be removed when
// we pop the stack
decl->mOwner = aOwner;
return NS_OK;
}
void
nsXMLContentSerializer::PopNameSpaceDeclsFor(nsIContent* aOwner)
{
int32_t index, count;
count = mNameSpaceStack.Length();
for (index = count - 1; index >= 0; index--) {
if (mNameSpaceStack[index].mOwner != aOwner) {
break;
}
mNameSpaceStack.RemoveElementAt(index);
}
}
bool
nsXMLContentSerializer::ConfirmPrefix(nsAString& aPrefix,
const nsAString& aURI,
nsIContent* aElement,
bool aIsAttribute)
{
if (aPrefix.EqualsLiteral(kXMLNS)) {
return false;
}
if (aURI.EqualsLiteral("http://www.w3.org/XML/1998/namespace")) {
// The prefix must be xml for this namespace. We don't need to declare it,
// so always just set the prefix to xml.
aPrefix.AssignLiteral("xml");
return false;
}
bool mustHavePrefix;
if (aIsAttribute) {
if (aURI.IsEmpty()) {
// Attribute in the null namespace. This just shouldn't have a prefix.
// And there's no need to push any namespace decls
aPrefix.Truncate();
return false;
}
// Attribute not in the null namespace -- must have a prefix
mustHavePrefix = true;
} else {
// Not an attribute, so doesn't _have_ to have a prefix
mustHavePrefix = false;
}
// Keep track of the closest prefix that's bound to aURI and whether we've
// found such a thing. closestURIMatch holds the prefix, and uriMatch
// indicates whether we actually have one.
nsAutoString closestURIMatch;
bool uriMatch = false;
// Also keep track of whether we've seen aPrefix already. If we have, that
// means that it's already bound to a URI different from aURI, so even if we
// later (so in a more outer scope) see it bound to aURI we can't reuse it.
bool haveSeenOurPrefix = false;
int32_t count = mNameSpaceStack.Length();
int32_t index = count - 1;
while (index >= 0) {
NameSpaceDecl& decl = mNameSpaceStack.ElementAt(index);
// Check if we've found a prefix match
if (aPrefix.Equals(decl.mPrefix)) {
// If the URIs match and aPrefix is not bound to any other URI, we can
// use aPrefix
if (!haveSeenOurPrefix && aURI.Equals(decl.mURI)) {
// Just use our uriMatch stuff. That will deal with an empty aPrefix
// the right way. We can break out of the loop now, though.
uriMatch = true;
closestURIMatch = aPrefix;
break;
}
haveSeenOurPrefix = true;
// If they don't, and either:
// 1) We have a prefix (so we'd be redeclaring this prefix to point to a
// different namespace) or
// 2) We're looking at an existing default namespace decl on aElement (so
// we can't create a new default namespace decl for this URI)
// then generate a new prefix. Note that we do NOT generate new prefixes
// if we happen to have aPrefix == decl->mPrefix == "" and mismatching
// URIs when |decl| doesn't have aElement as its owner. In that case we
// can simply push the new namespace URI as the default namespace for
// aElement.
if (!aPrefix.IsEmpty() || decl.mOwner == aElement) {
NS_ASSERTION(!aURI.IsEmpty(),
"Not allowed to add a xmlns attribute with an empty "
"namespace name unless it declares the default "
"namespace.");
GenerateNewPrefix(aPrefix);
// Now we need to validate our new prefix/uri combination; check it
// against the full namespace stack again. Note that just restarting
// the while loop is ok, since we haven't changed aURI, so the
// closestURIMatch and uriMatch state is not affected.
index = count - 1;
haveSeenOurPrefix = false;
continue;
}
}
// If we've found a URI match, then record the first one
if (!uriMatch && aURI.Equals(decl.mURI)) {
// Need to check that decl->mPrefix is not declared anywhere closer to
// us. If it is, we can't use it.
bool prefixOK = true;
int32_t index2;
for (index2 = count-1; index2 > index && prefixOK; --index2) {
prefixOK = (mNameSpaceStack[index2].mPrefix != decl.mPrefix);
}
if (prefixOK) {
uriMatch = true;
closestURIMatch.Assign(decl.mPrefix);
}
}
--index;
}
// At this point the following invariants hold:
// 1) The prefix in closestURIMatch is mapped to aURI in our scope if
// uriMatch is set.
// 2) There is nothing on the namespace stack that has aPrefix as the prefix
// and a _different_ URI, except for the case aPrefix.IsEmpty (and
// possible default namespaces on ancestors)
// So if uriMatch is set it's OK to use the closestURIMatch prefix. The one
// exception is when closestURIMatch is actually empty (default namespace
// decl) and we must have a prefix.
if (uriMatch && (!mustHavePrefix || !closestURIMatch.IsEmpty())) {
aPrefix.Assign(closestURIMatch);
return false;
}
if (aPrefix.IsEmpty()) {
// At this point, aPrefix is empty (which means we never had a prefix to
// start with). If we must have a prefix, just generate a new prefix and
// then send it back through the namespace stack checks to make sure it's
// OK.
if (mustHavePrefix) {
GenerateNewPrefix(aPrefix);
return ConfirmPrefix(aPrefix, aURI, aElement, aIsAttribute);
}
// One final special case. If aPrefix is empty and we never saw an empty
// prefix (default namespace decl) on the namespace stack and we're in the
// null namespace there is no reason to output an |xmlns=""| here. It just
// makes the output less readable.
if (!haveSeenOurPrefix && aURI.IsEmpty()) {
return false;
}
}
// Now just set aURI as the new default namespace URI. Indicate that we need
// to create a namespace decl for the final prefix
return true;
}
void
nsXMLContentSerializer::GenerateNewPrefix(nsAString& aPrefix)
{
aPrefix.Assign('a');
char buf[128];
PR_snprintf(buf, sizeof(buf), "%d", mPrefixIndex++);
AppendASCIItoUTF16(buf, aPrefix);
}
void
nsXMLContentSerializer::SerializeAttr(const nsAString& aPrefix,
const nsAString& aName,
const nsAString& aValue,
nsAString& aStr,
bool aDoEscapeEntities)
{
nsAutoString attrString_;
// For innerHTML we can do faster appending without
// temporary strings.
bool rawAppend = mDoRaw && aDoEscapeEntities;
nsAString& attrString = (rawAppend) ? aStr : attrString_;
attrString.Append(char16_t(' '));
if (!aPrefix.IsEmpty()) {
attrString.Append(aPrefix);
attrString.Append(char16_t(':'));
}
attrString.Append(aName);
if (aDoEscapeEntities) {
// if problem characters are turned into character entity references
// then there will be no problem with the value delimiter characters
attrString.AppendLiteral("=\"");
mInAttribute = true;
AppendAndTranslateEntities(aValue, attrString);
mInAttribute = false;
attrString.Append(char16_t('"'));
if (rawAppend) {
return;
}
}
else {
// Depending on whether the attribute value contains quotes or apostrophes we
// need to select the delimiter character and escape characters using
// character entity references, ignoring the value of aDoEscapeEntities.
// See http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.3.2.2 for
// the standard on character entity references in values. We also have to
// make sure to escape any '&' characters.
bool bIncludesSingle = false;
bool bIncludesDouble = false;
nsAString::const_iterator iCurr, iEnd;
uint32_t uiSize, i;
aValue.BeginReading(iCurr);
aValue.EndReading(iEnd);
for ( ; iCurr != iEnd; iCurr.advance(uiSize) ) {
const char16_t * buf = iCurr.get();
uiSize = iCurr.size_forward();
for ( i = 0; i < uiSize; i++, buf++ ) {
if ( *buf == char16_t('\'') )
{
bIncludesSingle = true;
if ( bIncludesDouble ) break;
}
else if ( *buf == char16_t('"') )
{
bIncludesDouble = true;
if ( bIncludesSingle ) break;
}
}
// if both have been found we don't need to search further
if ( bIncludesDouble && bIncludesSingle ) break;
}
// Delimiter and escaping is according to the following table
// bIncludesDouble bIncludesSingle Delimiter Escape Double Quote
// FALSE FALSE " FALSE
// FALSE TRUE " FALSE
// TRUE FALSE ' FALSE
// TRUE TRUE " TRUE
char16_t cDelimiter =
(bIncludesDouble && !bIncludesSingle) ? char16_t('\'') : char16_t('"');
attrString.Append(char16_t('='));
attrString.Append(cDelimiter);
nsAutoString sValue(aValue);
sValue.ReplaceSubstring(NS_LITERAL_STRING("&"),
NS_LITERAL_STRING("&"));
if (bIncludesDouble && bIncludesSingle) {
sValue.ReplaceSubstring(NS_LITERAL_STRING("\""),
NS_LITERAL_STRING("""));
}
attrString.Append(sValue);
attrString.Append(cDelimiter);
}
if (mDoRaw || PreLevel() > 0) {
AppendToStringConvertLF(attrString, aStr);
}
else if (mDoFormat) {
AppendToStringFormatedWrapped(attrString, aStr);
}
else if (mDoWrap) {
AppendToStringWrapped(attrString, aStr);
}
else {
AppendToStringConvertLF(attrString, aStr);
}
}
uint32_t
nsXMLContentSerializer::ScanNamespaceDeclarations(nsIContent* aContent,
nsIContent *aOriginalElement,
const nsAString& aTagNamespaceURI)
{
uint32_t index, count;
nsAutoString uriStr, valueStr;
count = aContent->GetAttrCount();
// First scan for namespace declarations, pushing each on the stack
uint32_t skipAttr = count;
for (index = 0; index < count; index++) {
const nsAttrName* name = aContent->GetAttrNameAt(index);
int32_t namespaceID = name->NamespaceID();
nsIAtom *attrName = name->LocalName();
if (namespaceID == kNameSpaceID_XMLNS ||
// Also push on the stack attrs named "xmlns" in the null
// namespace... because once we serialize those out they'll look like
// namespace decls. :(
// XXXbz what if we have both "xmlns" in the null namespace and "xmlns"
// in the xmlns namespace?
(namespaceID == kNameSpaceID_None &&
attrName == nsGkAtoms::xmlns)) {
aContent->GetAttr(namespaceID, attrName, uriStr);
if (!name->GetPrefix()) {
if (aTagNamespaceURI.IsEmpty() && !uriStr.IsEmpty()) {
// If the element is in no namespace we need to add a xmlns
// attribute to declare that. That xmlns attribute must not have a
// prefix (see http://www.w3.org/TR/REC-xml-names/#dt-prefix), ie it
// must declare the default namespace. We just found an xmlns
// attribute that declares the default namespace to something
// non-empty. We're going to ignore this attribute, for children we
// will detect that we need to add it again and attributes aren't
// affected by the default namespace.
skipAttr = index;
}
else {
// Default NS attribute does not have prefix (and the name is "xmlns")
PushNameSpaceDecl(EmptyString(), uriStr, aOriginalElement);
}
}
else {
PushNameSpaceDecl(nsDependentAtomString(attrName), uriStr,
aOriginalElement);
}
}
}
return skipAttr;
}
bool
nsXMLContentSerializer::IsJavaScript(nsIContent * aContent, nsIAtom* aAttrNameAtom,
int32_t aAttrNamespaceID, const nsAString& aValueString)
{
bool isHtml = aContent->IsHTML();
bool isXul = aContent->IsXUL();
bool isSvg = aContent->IsSVG();
if (aAttrNamespaceID == kNameSpaceID_None &&
(isHtml || isXul || isSvg) &&
(aAttrNameAtom == nsGkAtoms::href ||
aAttrNameAtom == nsGkAtoms::src)) {
static const char kJavaScript[] = "javascript";
int32_t pos = aValueString.FindChar(':');
if (pos < (int32_t)(sizeof kJavaScript - 1))
return false;
nsAutoString scheme(Substring(aValueString, 0, pos));
scheme.StripWhitespace();
if ((scheme.Length() == (sizeof kJavaScript - 1)) &&
scheme.EqualsIgnoreCase(kJavaScript))
return true;
else
return false;
}
return aContent->IsEventAttributeName(aAttrNameAtom);
}
void
nsXMLContentSerializer::SerializeAttributes(nsIContent* aContent,
nsIContent *aOriginalElement,
nsAString& aTagPrefix,
const nsAString& aTagNamespaceURI,
nsIAtom* aTagName,
nsAString& aStr,
uint32_t aSkipAttr,
bool aAddNSAttr)
{
nsAutoString prefixStr, uriStr, valueStr;
nsAutoString xmlnsStr;
xmlnsStr.AssignLiteral(kXMLNS);
uint32_t index, count;
// If we had to add a new namespace declaration, serialize
// and push it on the namespace stack
if (aAddNSAttr) {
if (aTagPrefix.IsEmpty()) {
// Serialize default namespace decl
SerializeAttr(EmptyString(), xmlnsStr, aTagNamespaceURI, aStr, true);
}
else {
// Serialize namespace decl
SerializeAttr(xmlnsStr, aTagPrefix, aTagNamespaceURI, aStr, true);
}
PushNameSpaceDecl(aTagPrefix, aTagNamespaceURI, aOriginalElement);
}
count = aContent->GetAttrCount();
// Now serialize each of the attributes
// XXX Unfortunately we need a namespace manager to get
// attribute URIs.
for (index = 0; index < count; index++) {
if (aSkipAttr == index) {
continue;
}
const nsAttrName* name = aContent->GetAttrNameAt(index);
int32_t namespaceID = name->NamespaceID();
nsIAtom* attrName = name->LocalName();
nsIAtom* attrPrefix = name->GetPrefix();
// Filter out any attribute starting with [-|_]moz
nsDependentAtomString attrNameStr(attrName);
if (StringBeginsWith(attrNameStr, NS_LITERAL_STRING("_moz")) ||
StringBeginsWith(attrNameStr, NS_LITERAL_STRING("-moz"))) {
continue;
}
if (attrPrefix) {
attrPrefix->ToString(prefixStr);
}
else {
prefixStr.Truncate();
}
bool addNSAttr = false;
if (kNameSpaceID_XMLNS != namespaceID) {
nsContentUtils::NameSpaceManager()->GetNameSpaceURI(namespaceID, uriStr);
addNSAttr = ConfirmPrefix(prefixStr, uriStr, aOriginalElement, true);
}
aContent->GetAttr(namespaceID, attrName, valueStr);
nsDependentAtomString nameStr(attrName);
bool isJS = IsJavaScript(aContent, attrName, namespaceID, valueStr);
SerializeAttr(prefixStr, nameStr, valueStr, aStr, !isJS);
if (addNSAttr) {
NS_ASSERTION(!prefixStr.IsEmpty(),
"Namespaced attributes must have a prefix");
SerializeAttr(xmlnsStr, prefixStr, uriStr, aStr, true);
PushNameSpaceDecl(prefixStr, uriStr, aOriginalElement);
}
}
}
NS_IMETHODIMP
nsXMLContentSerializer::AppendElementStart(Element* aElement,
Element* aOriginalElement,
nsAString& aStr)
{
NS_ENSURE_ARG(aElement);
nsIContent* content = aElement;
bool forceFormat = false;
if (!CheckElementStart(content, forceFormat, aStr)) {
return NS_OK;
}
nsAutoString tagPrefix, tagLocalName, tagNamespaceURI;
aElement->NodeInfo()->GetPrefix(tagPrefix);
aElement->NodeInfo()->GetName(tagLocalName);
aElement->NodeInfo()->GetNamespaceURI(tagNamespaceURI);
uint32_t skipAttr = ScanNamespaceDeclarations(content,
aOriginalElement, tagNamespaceURI);
nsIAtom *name = content->Tag();
bool lineBreakBeforeOpen = LineBreakBeforeOpen(content->GetNameSpaceID(), name);
if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel()) {
if (mColPos && lineBreakBeforeOpen) {
AppendNewLineToString(aStr);
}
else {
MaybeAddNewlineForRootNode(aStr);
}
if (!mColPos) {
AppendIndentation(aStr);
}
else if (mAddSpace) {
AppendToString(char16_t(' '), aStr);
mAddSpace = false;
}
}
else if (mAddSpace) {
AppendToString(char16_t(' '), aStr);
mAddSpace = false;
}
else {
MaybeAddNewlineForRootNode(aStr);
}
// Always reset to avoid false newlines in case MaybeAddNewlineForRootNode wasn't
// called
mAddNewlineForRootNode = false;
bool addNSAttr;
addNSAttr = ConfirmPrefix(tagPrefix, tagNamespaceURI, aOriginalElement,
false);
// Serialize the qualified name of the element
AppendToString(kLessThan, aStr);
if (!tagPrefix.IsEmpty()) {
AppendToString(tagPrefix, aStr);
AppendToString(NS_LITERAL_STRING(":"), aStr);
}
AppendToString(tagLocalName, aStr);
MaybeEnterInPreContent(content);
if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel()) {
IncrIndentation(name);
}
SerializeAttributes(content, aOriginalElement, tagPrefix, tagNamespaceURI,
name, aStr, skipAttr, addNSAttr);
AppendEndOfElementStart(aOriginalElement, name, content->GetNameSpaceID(),
aStr);
if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel()
&& LineBreakAfterOpen(content->GetNameSpaceID(), name)) {
AppendNewLineToString(aStr);
}
AfterElementStart(content, aOriginalElement, aStr);
return NS_OK;
}
void
nsXMLContentSerializer::AppendEndOfElementStart(nsIContent *aOriginalElement,
nsIAtom * aName,
int32_t aNamespaceID,
nsAString& aStr)
{
// We don't output a separate end tag for empty elements
if (!aOriginalElement->GetChildCount()) {
AppendToString(NS_LITERAL_STRING("/>"), aStr);
}
else {
AppendToString(kGreaterThan, aStr);
}
}
NS_IMETHODIMP
nsXMLContentSerializer::AppendElementEnd(Element* aElement,
nsAString& aStr)
{
NS_ENSURE_ARG(aElement);
nsIContent* content = aElement;
bool forceFormat = false, outputElementEnd;
outputElementEnd = CheckElementEnd(content, forceFormat, aStr);
nsIAtom *name = content->Tag();
if ((mDoFormat || forceFormat) && !mDoRaw && !PreLevel()) {
DecrIndentation(name);
}
if (!outputElementEnd) {
PopNameSpaceDeclsFor(aElement);
MaybeFlagNewlineForRootNode(aElement);
return NS_OK;
}
nsAutoString tagPrefix, tagLocalName, tagNamespaceURI;