This repository has been archived by the owner on Aug 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
XMLNode.cpp
1628 lines (1475 loc) · 53.5 KB
/
XMLNode.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
//
// Copyright 2006 The Android Open Source Project
//
// Build resource files from raw assets.
//
#include "XMLNode.h"
#include "ResourceTable.h"
#include "pseudolocalize.h"
#include <utils/ByteOrder.h>
#include <errno.h>
#include <string.h>
#ifndef _WIN32
#define O_BINARY 0
#endif
// SSIZE: mingw does not have signed size_t == ssize_t.
// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
#if !defined(_WIN32)
# define SSIZE(x) x
# define STATUST(x) x
#else
# define SSIZE(x) (signed size_t)x
# define STATUST(x) (status_t)x
#endif
// Set to true for noisy debug output.
static const bool kIsDebug = false;
// Set to true for noisy debug output of parsing.
static const bool kIsDebugParse = false;
#if PRINT_STRING_METRICS
static const bool kPrintStringMetrics = true;
#else
static const bool kPrintStringMetrics = false;
#endif
const char* const RESOURCES_ROOT_NAMESPACE = "http://schemas.android.com/apk/res/";
const char* const RESOURCES_ANDROID_NAMESPACE = "http://schemas.android.com/apk/res/android";
const char* const RESOURCES_AUTO_PACKAGE_NAMESPACE = "http://schemas.android.com/apk/res-auto";
const char* const RESOURCES_ROOT_PRV_NAMESPACE = "http://schemas.android.com/apk/prv/res/";
const char* const XLIFF_XMLNS = "urn:oasis:names:tc:xliff:document:1.2";
const char* const ALLOWED_XLIFF_ELEMENTS[] = {
"bpt",
"ept",
"it",
"ph",
"g",
"bx",
"ex",
"x"
};
bool isWhitespace(const char16_t* str)
{
while (*str != 0 && *str < 128 && isspace(*str)) {
str++;
}
return *str == 0;
}
static const String16 RESOURCES_PREFIX(RESOURCES_ROOT_NAMESPACE);
static const String16 RESOURCES_PREFIX_AUTO_PACKAGE(RESOURCES_AUTO_PACKAGE_NAMESPACE);
static const String16 RESOURCES_PRV_PREFIX(RESOURCES_ROOT_PRV_NAMESPACE);
static const String16 RESOURCES_TOOLS_NAMESPACE("http://schemas.android.com/tools");
String16 getNamespaceResourcePackage(String16 appPackage, String16 namespaceUri, bool* outIsPublic)
{
//printf("%s starts with %s?\n", String8(namespaceUri).string(),
// String8(RESOURCES_PREFIX).string());
size_t prefixSize;
bool isPublic = true;
if(namespaceUri.startsWith(RESOURCES_PREFIX_AUTO_PACKAGE)) {
if (kIsDebug) {
printf("Using default application package: %s -> %s\n", String8(namespaceUri).string(),
String8(appPackage).string());
}
isPublic = true;
return appPackage;
} else if (namespaceUri.startsWith(RESOURCES_PREFIX)) {
prefixSize = RESOURCES_PREFIX.size();
} else if (namespaceUri.startsWith(RESOURCES_PRV_PREFIX)) {
isPublic = false;
prefixSize = RESOURCES_PRV_PREFIX.size();
} else {
if (outIsPublic) *outIsPublic = isPublic; // = true
return String16();
}
//printf("YES!\n");
//printf("namespace: %s\n", String8(String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize)).string());
if (outIsPublic) *outIsPublic = isPublic;
return String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize);
}
status_t hasSubstitutionErrors(const char* fileName,
ResXMLTree* inXml,
String16 str16)
{
const char16_t* str = str16.string();
const char16_t* p = str;
const char16_t* end = str + str16.size();
bool nonpositional = false;
int argCount = 0;
while (p < end) {
/*
* Look for the start of a Java-style substitution sequence.
*/
if (*p == '%' && p + 1 < end) {
p++;
// A literal percent sign represented by %%
if (*p == '%') {
p++;
continue;
}
argCount++;
if (*p >= '0' && *p <= '9') {
do {
p++;
} while (*p >= '0' && *p <= '9');
if (*p != '$') {
// This must be a size specification instead of position.
nonpositional = true;
}
} else if (*p == '<') {
// Reusing last argument; bad idea since it can be re-arranged.
nonpositional = true;
p++;
// Optionally '$' can be specified at the end.
if (p < end && *p == '$') {
p++;
}
} else {
nonpositional = true;
}
// Ignore flags and widths
while (p < end && (*p == '-' ||
*p == '#' ||
*p == '+' ||
*p == ' ' ||
*p == ',' ||
*p == '(' ||
(*p >= '0' && *p <= '9'))) {
p++;
}
/*
* This is a shortcut to detect strings that are going to Time.format()
* instead of String.format()
*
* Comparison of String.format() and Time.format() args:
*
* String: ABC E GH ST X abcdefgh nost x
* Time: DEFGHKMS W Za d hkm s w yz
*
* Therefore we know it's definitely Time if we have:
* DFKMWZkmwyz
*/
if (p < end) {
switch (*p) {
case 'D':
case 'F':
case 'K':
case 'M':
case 'W':
case 'Z':
case 'k':
case 'm':
case 'w':
case 'y':
case 'z':
return NO_ERROR;
}
}
}
p++;
}
/*
* If we have more than one substitution in this string and any of them
* are not in positional form, give the user an error.
*/
if (argCount > 1 && nonpositional) {
SourcePos(String8(fileName), inXml->getLineNumber()).error(
"Multiple substitutions specified in non-positional format; "
"did you mean to add the formatted=\"false\" attribute?\n");
return NOT_ENOUGH_DATA;
}
return NO_ERROR;
}
status_t parseStyledString(Bundle* /* bundle */,
const char* fileName,
ResXMLTree* inXml,
const String16& endTag,
String16* outString,
Vector<StringPool::entry_style_span>* outSpans,
bool isFormatted,
PseudolocalizationMethod pseudolocalize)
{
Vector<StringPool::entry_style_span> spanStack;
String16 curString;
String16 rawString;
Pseudolocalizer pseudo(pseudolocalize);
const char* errorMsg;
int xliffDepth = 0;
bool firstTime = true;
size_t len;
ResXMLTree::event_code_t code;
curString.append(pseudo.start());
while ((code=inXml->next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
if (code == ResXMLTree::TEXT) {
String16 text(inXml->getText(&len));
if (firstTime && text.size() > 0) {
firstTime = false;
if (text.string()[0] == '@') {
// If this is a resource reference, don't do the pseudoloc.
pseudolocalize = NO_PSEUDOLOCALIZATION;
pseudo.setMethod(pseudolocalize);
curString = String16();
}
}
if (xliffDepth == 0 && pseudolocalize > 0) {
curString.append(pseudo.text(text));
} else {
if (isFormatted && hasSubstitutionErrors(fileName, inXml, text) != NO_ERROR) {
return UNKNOWN_ERROR;
} else {
curString.append(text);
}
}
} else if (code == ResXMLTree::START_TAG) {
const String16 element16(inXml->getElementName(&len));
const String8 element8(element16);
size_t nslen;
const char16_t* ns = inXml->getElementNamespace(&nslen);
if (ns == NULL) {
ns = (const char16_t*)"\0\0";
nslen = 0;
}
const String8 nspace(String16(ns, nslen));
if (nspace == XLIFF_XMLNS) {
const int N = sizeof(ALLOWED_XLIFF_ELEMENTS)/sizeof(ALLOWED_XLIFF_ELEMENTS[0]);
for (int i=0; i<N; i++) {
if (element8 == ALLOWED_XLIFF_ELEMENTS[i]) {
xliffDepth++;
// in this case, treat it like it was just text, in other words, do nothing
// here and silently drop this element
goto moveon;
}
}
{
SourcePos(String8(fileName), inXml->getLineNumber()).error(
"Found unsupported XLIFF tag <%s>\n",
element8.string());
return UNKNOWN_ERROR;
}
moveon:
continue;
}
if (outSpans == NULL) {
SourcePos(String8(fileName), inXml->getLineNumber()).error(
"Found style tag <%s> where styles are not allowed\n", element8.string());
return UNKNOWN_ERROR;
}
if (!ResTable::collectString(outString, curString.string(),
curString.size(), false, &errorMsg, true)) {
SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
errorMsg, String8(curString).string());
return UNKNOWN_ERROR;
}
rawString.append(curString);
curString = String16();
StringPool::entry_style_span span;
span.name = element16;
for (size_t ai=0; ai<inXml->getAttributeCount(); ai++) {
span.name.append(String16(";"));
const char16_t* str = inXml->getAttributeName(ai, &len);
span.name.append(str, len);
span.name.append(String16("="));
str = inXml->getAttributeStringValue(ai, &len);
span.name.append(str, len);
}
//printf("Span: %s\n", String8(span.name).string());
span.span.firstChar = span.span.lastChar = outString->size();
spanStack.push(span);
} else if (code == ResXMLTree::END_TAG) {
size_t nslen;
const char16_t* ns = inXml->getElementNamespace(&nslen);
if (ns == NULL) {
ns = (const char16_t*)"\0\0";
nslen = 0;
}
const String8 nspace(String16(ns, nslen));
if (nspace == XLIFF_XMLNS) {
xliffDepth--;
continue;
}
if (!ResTable::collectString(outString, curString.string(),
curString.size(), false, &errorMsg, true)) {
SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
errorMsg, String8(curString).string());
return UNKNOWN_ERROR;
}
rawString.append(curString);
curString = String16();
if (spanStack.size() == 0) {
if (strcmp16(inXml->getElementName(&len), endTag.string()) != 0) {
SourcePos(String8(fileName), inXml->getLineNumber()).error(
"Found tag %s where <%s> close is expected\n",
String8(inXml->getElementName(&len)).string(),
String8(endTag).string());
return UNKNOWN_ERROR;
}
break;
}
StringPool::entry_style_span span = spanStack.top();
String16 spanTag;
ssize_t semi = span.name.findFirst(';');
if (semi >= 0) {
spanTag.setTo(span.name.string(), semi);
} else {
spanTag.setTo(span.name);
}
if (strcmp16(inXml->getElementName(&len), spanTag.string()) != 0) {
SourcePos(String8(fileName), inXml->getLineNumber()).error(
"Found close tag %s where close tag %s is expected\n",
String8(inXml->getElementName(&len)).string(),
String8(spanTag).string());
return UNKNOWN_ERROR;
}
bool empty = true;
if (outString->size() > 0) {
span.span.lastChar = outString->size()-1;
if (span.span.lastChar >= span.span.firstChar) {
empty = false;
outSpans->add(span);
}
}
spanStack.pop();
/*
* This warning seems to be just an irritation to most people,
* since it is typically introduced by translators who then never
* see the warning.
*/
if (0 && empty) {
fprintf(stderr, "%s:%d: warning: empty '%s' span found in text '%s'\n",
fileName, inXml->getLineNumber(),
String8(spanTag).string(), String8(*outString).string());
}
} else if (code == ResXMLTree::START_NAMESPACE) {
// nothing
}
}
curString.append(pseudo.end());
if (code == ResXMLTree::BAD_DOCUMENT) {
SourcePos(String8(fileName), inXml->getLineNumber()).error(
"Error parsing XML\n");
}
if (outSpans != NULL && outSpans->size() > 0) {
if (curString.size() > 0) {
if (!ResTable::collectString(outString, curString.string(),
curString.size(), false, &errorMsg, true)) {
SourcePos(String8(fileName), inXml->getLineNumber()).error(
"%s (in %s)\n",
errorMsg, String8(curString).string());
return UNKNOWN_ERROR;
}
}
} else {
// There is no style information, so string processing will happen
// later as part of the overall type conversion. Return to the
// client the raw unprocessed text.
rawString.append(curString);
outString->setTo(rawString);
}
return NO_ERROR;
}
struct namespace_entry {
String8 prefix;
String8 uri;
};
static String8 make_prefix(int depth)
{
String8 prefix;
int i;
for (i=0; i<depth; i++) {
prefix.append(" ");
}
return prefix;
}
static String8 build_namespace(const Vector<namespace_entry>& namespaces,
const char16_t* ns)
{
String8 str;
if (ns != NULL) {
str = String8(ns);
const size_t N = namespaces.size();
for (size_t i=0; i<N; i++) {
const namespace_entry& ne = namespaces.itemAt(i);
if (ne.uri == str) {
str = ne.prefix;
break;
}
}
str.append(":");
}
return str;
}
void printXMLBlock(ResXMLTree* block)
{
block->restart();
Vector<namespace_entry> namespaces;
ResXMLTree::event_code_t code;
int depth = 0;
while ((code=block->next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
String8 prefix = make_prefix(depth);
int i;
if (code == ResXMLTree::START_TAG) {
size_t len;
const char16_t* ns16 = block->getElementNamespace(&len);
String8 elemNs = build_namespace(namespaces, ns16);
const char16_t* com16 = block->getComment(&len);
if (com16) {
printf("%s <!-- %s -->\n", prefix.string(), String8(com16).string());
}
printf("%sE: %s%s (line=%d)\n", prefix.string(), elemNs.string(),
String8(block->getElementName(&len)).string(),
block->getLineNumber());
int N = block->getAttributeCount();
depth++;
prefix = make_prefix(depth);
for (i=0; i<N; i++) {
uint32_t res = block->getAttributeNameResID(i);
ns16 = block->getAttributeNamespace(i, &len);
String8 ns = build_namespace(namespaces, ns16);
String8 name(block->getAttributeName(i, &len));
printf("%sA: ", prefix.string());
if (res) {
printf("%s%s(0x%08x)", ns.string(), name.string(), res);
} else {
printf("%s%s", ns.string(), name.string());
}
Res_value value;
block->getAttributeValue(i, &value);
if (value.dataType == Res_value::TYPE_NULL) {
printf("=(null)");
} else if (value.dataType == Res_value::TYPE_REFERENCE) {
printf("=@0x%x", (int)value.data);
} else if (value.dataType == Res_value::TYPE_ATTRIBUTE) {
printf("=?0x%x", (int)value.data);
} else if (value.dataType == Res_value::TYPE_STRING) {
printf("=\"%s\"",
ResTable::normalizeForOutput(String8(block->getAttributeStringValue(i,
&len)).string()).string());
} else {
printf("=(type 0x%x)0x%x", (int)value.dataType, (int)value.data);
}
const char16_t* val = block->getAttributeStringValue(i, &len);
if (val != NULL) {
printf(" (Raw: \"%s\")", ResTable::normalizeForOutput(String8(val).string()).
string());
}
printf("\n");
}
} else if (code == ResXMLTree::END_TAG) {
// Invalid tag nesting can be misused to break the parsing
// code below. Break if detected.
if (--depth < 0) {
printf("***BAD DEPTH in XMLBlock: %d\n", depth);
break;
}
} else if (code == ResXMLTree::START_NAMESPACE) {
namespace_entry ns;
size_t len;
const char16_t* prefix16 = block->getNamespacePrefix(&len);
if (prefix16) {
ns.prefix = String8(prefix16);
} else {
ns.prefix = "<DEF>";
}
ns.uri = String8(block->getNamespaceUri(&len));
namespaces.push(ns);
printf("%sN: %s=%s\n", prefix.string(), ns.prefix.string(),
ns.uri.string());
depth++;
} else if (code == ResXMLTree::END_NAMESPACE) {
if (--depth < 0) {
printf("***BAD DEPTH in XMLBlock: %d\n", depth);
break;
}
const namespace_entry& ns = namespaces.top();
size_t len;
const char16_t* prefix16 = block->getNamespacePrefix(&len);
String8 pr;
if (prefix16) {
pr = String8(prefix16);
} else {
pr = "<DEF>";
}
if (ns.prefix != pr) {
prefix = make_prefix(depth);
printf("%s*** BAD END NS PREFIX: found=%s, expected=%s\n",
prefix.string(), pr.string(), ns.prefix.string());
}
String8 uri = String8(block->getNamespaceUri(&len));
if (ns.uri != uri) {
prefix = make_prefix(depth);
printf("%s *** BAD END NS URI: found=%s, expected=%s\n",
prefix.string(), uri.string(), ns.uri.string());
}
namespaces.pop();
} else if (code == ResXMLTree::TEXT) {
size_t len;
printf("%sC: \"%s\"\n", prefix.string(),
ResTable::normalizeForOutput(String8(block->getText(&len)).string()).string());
}
}
block->restart();
}
status_t parseXMLResource(const sp<AaptFile>& file, ResXMLTree* outTree,
bool stripAll, bool keepComments,
const char** cDataTags)
{
sp<XMLNode> root = XMLNode::parse(file);
if (root == NULL) {
return UNKNOWN_ERROR;
}
root->removeWhitespace(stripAll, cDataTags);
if (kIsDebug) {
printf("Input XML from %s:\n", (const char*)file->getPrintableSource());
root->print();
}
sp<AaptFile> rsc = new AaptFile(String8(), AaptGroupEntry(), String8());
status_t err = root->flatten(rsc, !keepComments, false);
if (err != NO_ERROR) {
return err;
}
err = outTree->setTo(rsc->getData(), rsc->getSize(), true);
if (err != NO_ERROR) {
return err;
}
if (kIsDebug) {
printf("Output XML:\n");
printXMLBlock(outTree);
}
return NO_ERROR;
}
sp<XMLNode> XMLNode::parse(const sp<AaptFile>& file)
{
char buf[16384];
int fd = open(file->getSourceFile().string(), O_RDONLY | O_BINARY);
if (fd < 0) {
SourcePos(file->getSourceFile(), -1).error("Unable to open file for read: %s",
strerror(errno));
return NULL;
}
XML_Parser parser = XML_ParserCreateNS(NULL, 1);
ParseState state;
state.filename = file->getPrintableSource();
state.parser = parser;
XML_SetUserData(parser, &state);
XML_SetElementHandler(parser, startElement, endElement);
XML_SetNamespaceDeclHandler(parser, startNamespace, endNamespace);
XML_SetCharacterDataHandler(parser, characterData);
XML_SetCommentHandler(parser, commentData);
ssize_t len;
bool done;
do {
len = read(fd, buf, sizeof(buf));
done = len < (ssize_t)sizeof(buf);
if (len < 0) {
SourcePos(file->getSourceFile(), -1).error("Error reading file: %s\n", strerror(errno));
close(fd);
return NULL;
}
if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
SourcePos(file->getSourceFile(), (int)XML_GetCurrentLineNumber(parser)).error(
"Error parsing XML: %s\n", XML_ErrorString(XML_GetErrorCode(parser)));
close(fd);
return NULL;
}
} while (!done);
XML_ParserFree(parser);
if (state.root == NULL) {
SourcePos(file->getSourceFile(), -1).error("No XML data generated when parsing");
}
close(fd);
return state.root;
}
XMLNode::XMLNode()
: mNextAttributeIndex(0x80000000)
, mStartLineNumber(0)
, mEndLineNumber(0)
, mUTF8(false) {}
XMLNode::XMLNode(const String8& filename, const String16& s1, const String16& s2, bool isNamespace)
: mNextAttributeIndex(0x80000000)
, mFilename(filename)
, mStartLineNumber(0)
, mEndLineNumber(0)
, mUTF8(false)
{
if (isNamespace) {
mNamespacePrefix = s1;
mNamespaceUri = s2;
} else {
mNamespaceUri = s1;
mElementName = s2;
}
}
XMLNode::XMLNode(const String8& filename)
: mFilename(filename)
{
memset(&mCharsValue, 0, sizeof(mCharsValue));
}
XMLNode::type XMLNode::getType() const
{
if (mElementName.size() != 0) {
return TYPE_ELEMENT;
}
if (mNamespaceUri.size() != 0) {
return TYPE_NAMESPACE;
}
return TYPE_CDATA;
}
const String16& XMLNode::getNamespacePrefix() const
{
return mNamespacePrefix;
}
const String16& XMLNode::getNamespaceUri() const
{
return mNamespaceUri;
}
const String16& XMLNode::getElementNamespace() const
{
return mNamespaceUri;
}
const String16& XMLNode::getElementName() const
{
return mElementName;
}
const Vector<sp<XMLNode> >& XMLNode::getChildren() const
{
return mChildren;
}
Vector<sp<XMLNode> >& XMLNode::getChildren()
{
return mChildren;
}
const String8& XMLNode::getFilename() const
{
return mFilename;
}
const Vector<XMLNode::attribute_entry>&
XMLNode::getAttributes() const
{
return mAttributes;
}
const XMLNode::attribute_entry* XMLNode::getAttribute(const String16& ns,
const String16& name) const
{
for (size_t i=0; i<mAttributes.size(); i++) {
const attribute_entry& ae(mAttributes.itemAt(i));
if (ae.ns == ns && ae.name == name) {
return &ae;
}
}
return NULL;
}
bool XMLNode::removeAttribute(const String16& ns, const String16& name)
{
for (size_t i = 0; i < mAttributes.size(); i++) {
const attribute_entry& ae(mAttributes.itemAt(i));
if (ae.ns == ns && ae.name == name) {
removeAttribute(i);
return true;
}
}
return false;
}
XMLNode::attribute_entry* XMLNode::editAttribute(const String16& ns,
const String16& name)
{
for (size_t i=0; i<mAttributes.size(); i++) {
attribute_entry * ae = &mAttributes.editItemAt(i);
if (ae->ns == ns && ae->name == name) {
return ae;
}
}
return NULL;
}
const String16& XMLNode::getCData() const
{
return mChars;
}
const String16& XMLNode::getComment() const
{
return mComment;
}
int32_t XMLNode::getStartLineNumber() const
{
return mStartLineNumber;
}
int32_t XMLNode::getEndLineNumber() const
{
return mEndLineNumber;
}
sp<XMLNode> XMLNode::searchElement(const String16& tagNamespace, const String16& tagName)
{
if (getType() == XMLNode::TYPE_ELEMENT
&& mNamespaceUri == tagNamespace
&& mElementName == tagName) {
return this;
}
for (size_t i=0; i<mChildren.size(); i++) {
sp<XMLNode> found = mChildren.itemAt(i)->searchElement(tagNamespace, tagName);
if (found != NULL) {
return found;
}
}
return NULL;
}
sp<XMLNode> XMLNode::getChildElement(const String16& tagNamespace, const String16& tagName)
{
for (size_t i=0; i<mChildren.size(); i++) {
sp<XMLNode> child = mChildren.itemAt(i);
if (child->getType() == XMLNode::TYPE_ELEMENT
&& child->mNamespaceUri == tagNamespace
&& child->mElementName == tagName) {
return child;
}
}
return NULL;
}
status_t XMLNode::addChild(const sp<XMLNode>& child)
{
if (getType() == TYPE_CDATA) {
SourcePos(mFilename, child->getStartLineNumber()).error("Child to CDATA node.");
return UNKNOWN_ERROR;
}
//printf("Adding child %p to parent %p\n", child.get(), this);
mChildren.add(child);
return NO_ERROR;
}
status_t XMLNode::insertChildAt(const sp<XMLNode>& child, size_t index)
{
if (getType() == TYPE_CDATA) {
SourcePos(mFilename, child->getStartLineNumber()).error("Child to CDATA node.");
return UNKNOWN_ERROR;
}
//printf("Adding child %p to parent %p\n", child.get(), this);
mChildren.insertAt(child, index);
return NO_ERROR;
}
status_t XMLNode::addAttribute(const String16& ns, const String16& name,
const String16& value)
{
if (getType() == TYPE_CDATA) {
SourcePos(mFilename, getStartLineNumber()).error("Child to CDATA node.");
return UNKNOWN_ERROR;
}
if (ns != RESOURCES_TOOLS_NAMESPACE) {
attribute_entry e;
e.index = mNextAttributeIndex++;
e.ns = ns;
e.name = name;
e.string = value;
mAttributes.add(e);
mAttributeOrder.add(e.index, mAttributes.size()-1);
}
return NO_ERROR;
}
status_t XMLNode::removeAttribute(size_t index)
{
if (getType() == TYPE_CDATA) {
return UNKNOWN_ERROR;
}
if (index >= mAttributes.size()) {
return UNKNOWN_ERROR;
}
const attribute_entry& e = mAttributes[index];
const uint32_t key = e.nameResId ? e.nameResId : e.index;
mAttributeOrder.removeItem(key);
mAttributes.removeAt(index);
// Shift all the indices.
const size_t attrCount = mAttributeOrder.size();
for (size_t i = 0; i < attrCount; i++) {
size_t attrIdx = mAttributeOrder[i];
if (attrIdx > index) {
mAttributeOrder.replaceValueAt(i, attrIdx - 1);
}
}
return NO_ERROR;
}
void XMLNode::setAttributeResID(size_t attrIdx, uint32_t resId)
{
attribute_entry& e = mAttributes.editItemAt(attrIdx);
if (e.nameResId) {
mAttributeOrder.removeItem(e.nameResId);
} else {
mAttributeOrder.removeItem(e.index);
}
if (kIsDebug) {
printf("Elem %s %s=\"%s\": set res id = 0x%08x\n",
String8(getElementName()).string(),
String8(mAttributes.itemAt(attrIdx).name).string(),
String8(mAttributes.itemAt(attrIdx).string).string(),
resId);
}
mAttributes.editItemAt(attrIdx).nameResId = resId;
mAttributeOrder.add(resId, attrIdx);
}
status_t XMLNode::appendChars(const String16& chars)
{
if (getType() != TYPE_CDATA) {
SourcePos(mFilename, getStartLineNumber()).error("Adding characters to element node.");
return UNKNOWN_ERROR;
}
mChars.append(chars);
return NO_ERROR;
}
status_t XMLNode::appendComment(const String16& comment)
{
if (mComment.size() > 0) {
mComment.append(String16("\n"));
}
mComment.append(comment);
return NO_ERROR;
}
void XMLNode::setStartLineNumber(int32_t line)
{
mStartLineNumber = line;
}
void XMLNode::setEndLineNumber(int32_t line)
{
mEndLineNumber = line;
}
void XMLNode::removeWhitespace(bool stripAll, const char** cDataTags)
{
//printf("Removing whitespace in %s\n", String8(mElementName).string());
size_t N = mChildren.size();
if (cDataTags) {
String8 tag(mElementName);
const char** p = cDataTags;
while (*p) {
if (tag == *p) {
stripAll = false;
break;
}
}
}
for (size_t i=0; i<N; i++) {
sp<XMLNode> node = mChildren.itemAt(i);
if (node->getType() == TYPE_CDATA) {
// This is a CDATA node...
const char16_t* p = node->mChars.string();
while (*p != 0 && *p < 128 && isspace(*p)) {
p++;
}
//printf("Space ends at %d in \"%s\"\n",
// (int)(p-node->mChars.string()),
// String8(node->mChars).string());
if (*p == 0) {
if (stripAll) {
// Remove this node!
mChildren.removeAt(i);
N--;
i--;
} else {
node->mChars = String16(" ");
}
} else {
// Compact leading/trailing whitespace.
const char16_t* e = node->mChars.string()+node->mChars.size()-1;
while (e > p && *e < 128 && isspace(*e)) {
e--;
}
if (p > node->mChars.string()) {
p--;
}
if (e < (node->mChars.string()+node->mChars.size()-1)) {
e++;
}
if (p > node->mChars.string() ||
e < (node->mChars.string()+node->mChars.size()-1)) {
String16 tmp(p, e-p+1);
node->mChars = tmp;
}
}
} else {
node->removeWhitespace(stripAll, cDataTags);
}
}
}
status_t XMLNode::parseValues(const sp<AaptAssets>& assets,
ResourceTable* table)
{
bool hasErrors = false;
if (getType() == TYPE_ELEMENT) {
const size_t N = mAttributes.size();
String16 defPackage(assets->getPackage());
for (size_t i=0; i<N; i++) {
attribute_entry& e = mAttributes.editItemAt(i);
AccessorCookie ac(SourcePos(mFilename, getStartLineNumber()), String8(e.name),
String8(e.string));
table->setCurrentXmlPos(SourcePos(mFilename, getStartLineNumber()));
if (!assets->getIncludedResources()
.stringToValue(&e.value, &e.string,
e.string.string(), e.string.size(), true, true,
e.nameResId, NULL, &defPackage, table, &ac)) {
hasErrors = true;
}
if (kIsDebug) {
printf("Attr %s: type=0x%x, str=%s\n",
String8(e.name).string(), e.value.dataType,
String8(e.string).string());
}