]> git.saurik.com Git - android/aapt.git/blame - ResourceTable.cpp
am d3f14a62: reconcile donut snapshot
[android/aapt.git] / ResourceTable.cpp
CommitLineData
a534180c
TAOSP
1//
2// Copyright 2006 The Android Open Source Project
3//
4// Build resource files from raw assets.
5//
6
7#include "ResourceTable.h"
8
9#include "XMLNode.h"
10
11#include <utils/ByteOrder.h>
12#include <utils/ResourceTypes.h>
13#include <stdarg.h>
14
15#define NOISY(x) //x
16
17status_t compileXmlFile(const sp<AaptAssets>& assets,
18 const sp<AaptFile>& target,
19 ResourceTable* table,
20 int options)
21{
22 sp<XMLNode> root = XMLNode::parse(target);
23 if (root == NULL) {
24 return UNKNOWN_ERROR;
25 }
e942a5c2
DH
26
27 return compileXmlFile(assets, root, target, table, options);
28}
29
30status_t compileXmlFile(const sp<AaptAssets>& assets,
31 const sp<XMLNode>& root,
32 const sp<AaptFile>& target,
33 ResourceTable* table,
34 int options)
35{
a534180c
TAOSP
36 if ((options&XML_COMPILE_STRIP_WHITESPACE) != 0) {
37 root->removeWhitespace(true, NULL);
38 } else if ((options&XML_COMPILE_COMPACT_WHITESPACE) != 0) {
39 root->removeWhitespace(false, NULL);
40 }
41
42 bool hasErrors = false;
43
44 if ((options&XML_COMPILE_ASSIGN_ATTRIBUTE_IDS) != 0) {
45 status_t err = root->assignResourceIds(assets, table);
46 if (err != NO_ERROR) {
47 hasErrors = true;
48 }
49 }
50
51 status_t err = root->parseValues(assets, table);
52 if (err != NO_ERROR) {
53 hasErrors = true;
54 }
55
56 if (hasErrors) {
57 return UNKNOWN_ERROR;
58 }
59
60 NOISY(printf("Input XML Resource:\n"));
61 NOISY(root->print());
62 err = root->flatten(target,
63 (options&XML_COMPILE_STRIP_COMMENTS) != 0,
64 (options&XML_COMPILE_STRIP_RAW_VALUES) != 0);
65 if (err != NO_ERROR) {
66 return err;
67 }
68
69 NOISY(printf("Output XML Resource:\n"));
70 NOISY(ResXMLTree tree;
71 tree.setTo(target->getData(), target->getSize());
72 printXMLBlock(&tree));
73
74 target->setCompressionMethod(ZipEntry::kCompressDeflated);
75
76 return err;
77}
78
79#undef NOISY
80#define NOISY(x) //x
81
82struct flag_entry
83{
84 const char16_t* name;
85 size_t nameLen;
86 uint32_t value;
87 const char* description;
88};
89
90static const char16_t referenceArray[] =
91 { 'r', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e' };
92static const char16_t stringArray[] =
93 { 's', 't', 'r', 'i', 'n', 'g' };
94static const char16_t integerArray[] =
95 { 'i', 'n', 't', 'e', 'g', 'e', 'r' };
96static const char16_t booleanArray[] =
97 { 'b', 'o', 'o', 'l', 'e', 'a', 'n' };
98static const char16_t colorArray[] =
99 { 'c', 'o', 'l', 'o', 'r' };
100static const char16_t floatArray[] =
101 { 'f', 'l', 'o', 'a', 't' };
102static const char16_t dimensionArray[] =
103 { 'd', 'i', 'm', 'e', 'n', 's', 'i', 'o', 'n' };
104static const char16_t fractionArray[] =
105 { 'f', 'r', 'a', 'c', 't', 'i', 'o', 'n' };
106static const char16_t enumArray[] =
107 { 'e', 'n', 'u', 'm' };
108static const char16_t flagsArray[] =
109 { 'f', 'l', 'a', 'g', 's' };
110
111static const flag_entry gFormatFlags[] = {
112 { referenceArray, sizeof(referenceArray)/2, ResTable_map::TYPE_REFERENCE,
113 "a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\n"
114 "or to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\"."},
115 { stringArray, sizeof(stringArray)/2, ResTable_map::TYPE_STRING,
116 "a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character." },
117 { integerArray, sizeof(integerArray)/2, ResTable_map::TYPE_INTEGER,
118 "an integer value, such as \"<code>100</code>\"." },
119 { booleanArray, sizeof(booleanArray)/2, ResTable_map::TYPE_BOOLEAN,
120 "a boolean value, either \"<code>true</code>\" or \"<code>false</code>\"." },
121 { colorArray, sizeof(colorArray)/2, ResTable_map::TYPE_COLOR,
122 "a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n"
123 "\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\"." },
124 { floatArray, sizeof(floatArray)/2, ResTable_map::TYPE_FLOAT,
125 "a floating point value, such as \"<code>1.2</code>\"."},
126 { dimensionArray, sizeof(dimensionArray)/2, ResTable_map::TYPE_DIMENSION,
127 "a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\n"
128 "Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\n"
129 "in (inches), mm (millimeters)." },
130 { fractionArray, sizeof(fractionArray)/2, ResTable_map::TYPE_FRACTION,
131 "a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\n"
132 "The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\n"
133 "some parent container." },
134 { enumArray, sizeof(enumArray)/2, ResTable_map::TYPE_ENUM, NULL },
135 { flagsArray, sizeof(flagsArray)/2, ResTable_map::TYPE_FLAGS, NULL },
136 { NULL, 0, 0, NULL }
137};
138
139static const char16_t suggestedArray[] = { 's', 'u', 'g', 'g', 'e', 's', 't', 'e', 'd' };
140
141static const flag_entry l10nRequiredFlags[] = {
142 { suggestedArray, sizeof(suggestedArray)/2, ResTable_map::L10N_SUGGESTED, NULL },
143 { NULL, 0, 0, NULL }
144};
145
146static const char16_t nulStr[] = { 0 };
147
148static uint32_t parse_flags(const char16_t* str, size_t len,
149 const flag_entry* flags, bool* outError = NULL)
150{
151 while (len > 0 && isspace(*str)) {
152 str++;
153 len--;
154 }
155 while (len > 0 && isspace(str[len-1])) {
156 len--;
157 }
158
159 const char16_t* const end = str + len;
160 uint32_t value = 0;
161
162 while (str < end) {
163 const char16_t* div = str;
164 while (div < end && *div != '|') {
165 div++;
166 }
167
168 const flag_entry* cur = flags;
169 while (cur->name) {
170 if (strzcmp16(cur->name, cur->nameLen, str, div-str) == 0) {
171 value |= cur->value;
172 break;
173 }
174 cur++;
175 }
176
177 if (!cur->name) {
178 if (outError) *outError = true;
179 return 0;
180 }
181
182 str = div < end ? div+1 : div;
183 }
184
185 if (outError) *outError = false;
186 return value;
187}
188
189static String16 mayOrMust(int type, int flags)
190{
191 if ((type&(~flags)) == 0) {
192 return String16("<p>Must");
193 }
194
195 return String16("<p>May");
196}
197
198static void appendTypeInfo(ResourceTable* outTable, const String16& pkg,
199 const String16& typeName, const String16& ident, int type,
200 const flag_entry* flags)
201{
202 bool hadType = false;
203 while (flags->name) {
204 if ((type&flags->value) != 0 && flags->description != NULL) {
205 String16 fullMsg(mayOrMust(type, flags->value));
206 fullMsg.append(String16(" be "));
207 fullMsg.append(String16(flags->description));
208 outTable->appendTypeComment(pkg, typeName, ident, fullMsg);
209 hadType = true;
210 }
211 flags++;
212 }
213 if (hadType && (type&ResTable_map::TYPE_REFERENCE) == 0) {
214 outTable->appendTypeComment(pkg, typeName, ident,
215 String16("<p>This may also be a reference to a resource (in the form\n"
216 "\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\n"
217 "theme attribute (in the form\n"
218 "\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\n"
219 "containing a value of this type."));
220 }
221}
222
223struct PendingAttribute
224{
225 const String16 myPackage;
226 const SourcePos sourcePos;
227 const bool appendComment;
228 int32_t type;
229 String16 ident;
230 String16 comment;
231 bool hasErrors;
232 bool added;
233
234 PendingAttribute(String16 _package, const sp<AaptFile>& in,
235 ResXMLTree& block, bool _appendComment)
236 : myPackage(_package)
237 , sourcePos(in->getPrintableSource(), block.getLineNumber())
238 , appendComment(_appendComment)
239 , type(ResTable_map::TYPE_ANY)
240 , hasErrors(false)
241 , added(false)
242 {
243 }
244
245 status_t createIfNeeded(ResourceTable* outTable)
246 {
247 if (added || hasErrors) {
248 return NO_ERROR;
249 }
250 added = true;
251
252 String16 attr16("attr");
253
254 if (outTable->hasBagOrEntry(myPackage, attr16, ident)) {
255 sourcePos.error("Attribute \"%s\" has already been defined\n",
256 String8(ident).string());
257 hasErrors = true;
258 return UNKNOWN_ERROR;
259 }
260
261 char numberStr[16];
262 sprintf(numberStr, "%d", type);
263 status_t err = outTable->addBag(sourcePos, myPackage,
264 attr16, ident, String16(""),
265 String16("^type"),
266 String16(numberStr), NULL, NULL);
267 if (err != NO_ERROR) {
268 hasErrors = true;
269 return err;
270 }
271 outTable->appendComment(myPackage, attr16, ident, comment, appendComment);
272 //printf("Attribute %s comment: %s\n", String8(ident).string(),
273 // String8(comment).string());
274 return err;
275 }
276};
277
278static status_t compileAttribute(const sp<AaptFile>& in,
279 ResXMLTree& block,
280 const String16& myPackage,
281 ResourceTable* outTable,
282 String16* outIdent = NULL,
283 bool inStyleable = false)
284{
285 PendingAttribute attr(myPackage, in, block, inStyleable);
286
287 const String16 attr16("attr");
288 const String16 id16("id");
289
290 // Attribute type constants.
291 const String16 enum16("enum");
292 const String16 flag16("flag");
293
294 ResXMLTree::event_code_t code;
295 size_t len;
296 status_t err;
297
298 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
299 if (identIdx >= 0) {
300 attr.ident = String16(block.getAttributeStringValue(identIdx, &len));
301 if (outIdent) {
302 *outIdent = attr.ident;
303 }
304 } else {
305 attr.sourcePos.error("A 'name' attribute is required for <attr>\n");
306 attr.hasErrors = true;
307 }
308
309 attr.comment = String16(
310 block.getComment(&len) ? block.getComment(&len) : nulStr);
311
312 ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
313 if (typeIdx >= 0) {
314 String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
315 attr.type = parse_flags(typeStr.string(), typeStr.size(), gFormatFlags);
316 if (attr.type == 0) {
317 attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
318 String8(typeStr).string());
319 attr.hasErrors = true;
320 }
321 attr.createIfNeeded(outTable);
322 } else if (!inStyleable) {
323 // Attribute definitions outside of styleables always define the
324 // attribute as a generic value.
325 attr.createIfNeeded(outTable);
326 }
327
328 //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).string(), attr.type);
329
330 ssize_t minIdx = block.indexOfAttribute(NULL, "min");
331 if (minIdx >= 0) {
332 String16 val = String16(block.getAttributeStringValue(minIdx, &len));
333 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
334 attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
335 String8(val).string());
336 attr.hasErrors = true;
337 }
338 attr.createIfNeeded(outTable);
339 if (!attr.hasErrors) {
340 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
341 String16(""), String16("^min"), String16(val), NULL, NULL);
342 if (err != NO_ERROR) {
343 attr.hasErrors = true;
344 }
345 }
346 }
347
348 ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
349 if (maxIdx >= 0) {
350 String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
351 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
352 attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
353 String8(val).string());
354 attr.hasErrors = true;
355 }
356 attr.createIfNeeded(outTable);
357 if (!attr.hasErrors) {
358 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
359 String16(""), String16("^max"), String16(val), NULL, NULL);
360 attr.hasErrors = true;
361 }
362 }
363
364 if ((minIdx >= 0 || maxIdx >= 0) && (attr.type&ResTable_map::TYPE_INTEGER) == 0) {
365 attr.sourcePos.error("Tag <attr> must have format=integer attribute if using max or min\n");
366 attr.hasErrors = true;
367 }
368
369 ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization");
370 if (l10nIdx >= 0) {
371 const uint16_t* str = block.getAttributeStringValue(l10nIdx, &len);
372 bool error;
373 uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
374 if (error) {
375 attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
376 String8(str).string());
377 attr.hasErrors = true;
378 }
379 attr.createIfNeeded(outTable);
380 if (!attr.hasErrors) {
381 char buf[10];
382 sprintf(buf, "%d", l10n_required);
383 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
384 String16(""), String16("^l10n"), String16(buf), NULL, NULL);
385 if (err != NO_ERROR) {
386 attr.hasErrors = true;
387 }
388 }
389 }
390
391 String16 enumOrFlagsComment;
392
393 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
394 if (code == ResXMLTree::START_TAG) {
395 uint32_t localType = 0;
396 if (strcmp16(block.getElementName(&len), enum16.string()) == 0) {
397 localType = ResTable_map::TYPE_ENUM;
398 } else if (strcmp16(block.getElementName(&len), flag16.string()) == 0) {
399 localType = ResTable_map::TYPE_FLAGS;
400 } else {
401 SourcePos(in->getPrintableSource(), block.getLineNumber())
402 .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
403 String8(block.getElementName(&len)).string());
404 return UNKNOWN_ERROR;
405 }
406
407 attr.createIfNeeded(outTable);
408
409 if (attr.type == ResTable_map::TYPE_ANY) {
410 // No type was explicitly stated, so supplying enum tags
411 // implicitly creates an enum or flag.
412 attr.type = 0;
413 }
414
415 if ((attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) == 0) {
416 // Wasn't originally specified as an enum, so update its type.
417 attr.type |= localType;
418 if (!attr.hasErrors) {
419 char numberStr[16];
420 sprintf(numberStr, "%d", attr.type);
421 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
422 myPackage, attr16, attr.ident, String16(""),
423 String16("^type"), String16(numberStr), NULL, NULL, true);
424 if (err != NO_ERROR) {
425 attr.hasErrors = true;
426 }
427 }
428 } else if ((uint32_t)(attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) != localType) {
429 if (localType == ResTable_map::TYPE_ENUM) {
430 SourcePos(in->getPrintableSource(), block.getLineNumber())
431 .error("<enum> attribute can not be used inside a flags format\n");
432 attr.hasErrors = true;
433 } else {
434 SourcePos(in->getPrintableSource(), block.getLineNumber())
435 .error("<flag> attribute can not be used inside a enum format\n");
436 attr.hasErrors = true;
437 }
438 }
439
440 String16 itemIdent;
441 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
442 if (itemIdentIdx >= 0) {
443 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
444 } else {
445 SourcePos(in->getPrintableSource(), block.getLineNumber())
446 .error("A 'name' attribute is required for <enum> or <flag>\n");
447 attr.hasErrors = true;
448 }
449
450 String16 value;
451 ssize_t valueIdx = block.indexOfAttribute(NULL, "value");
452 if (valueIdx >= 0) {
453 value = String16(block.getAttributeStringValue(valueIdx, &len));
454 } else {
455 SourcePos(in->getPrintableSource(), block.getLineNumber())
456 .error("A 'value' attribute is required for <enum> or <flag>\n");
457 attr.hasErrors = true;
458 }
459 if (!attr.hasErrors && !ResTable::stringToInt(value.string(), value.size(), NULL)) {
460 SourcePos(in->getPrintableSource(), block.getLineNumber())
461 .error("Tag <enum> or <flag> 'value' attribute must be a number,"
462 " not \"%s\"\n",
463 String8(value).string());
464 attr.hasErrors = true;
465 }
466
467 // Make sure an id is defined for this enum/flag identifier...
468 if (!attr.hasErrors && !outTable->hasBagOrEntry(itemIdent, &id16, &myPackage)) {
469 err = outTable->startBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
470 myPackage, id16, itemIdent, String16(), NULL);
471 if (err != NO_ERROR) {
472 attr.hasErrors = true;
473 }
474 }
475
476 if (!attr.hasErrors) {
477 if (enumOrFlagsComment.size() == 0) {
478 enumOrFlagsComment.append(mayOrMust(attr.type,
479 ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS));
480 enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM)
481 ? String16(" be one of the following constant values.")
482 : String16(" be one or more (separated by '|') of the following constant values."));
483 enumOrFlagsComment.append(String16("</p>\n<table border=\"2\" width=\"85%\" align=\"center\" frame=\"hsides\" rules=\"all\" cellpadding=\"5\">\n"
484 "<colgroup align=\"left\" />\n"
485 "<colgroup align=\"left\" />\n"
486 "<colgroup align=\"left\" />\n"
487 "<tr><th>Constant<th>Value<th>Description</tr>"));
488 }
489
490 enumOrFlagsComment.append(String16("\n<tr><th><code>"));
491 enumOrFlagsComment.append(itemIdent);
492 enumOrFlagsComment.append(String16("</code><td>"));
493 enumOrFlagsComment.append(value);
494 enumOrFlagsComment.append(String16("<td>"));
495 if (block.getComment(&len)) {
496 enumOrFlagsComment.append(String16(block.getComment(&len)));
497 }
498 enumOrFlagsComment.append(String16("</tr>"));
499
500 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
501 myPackage,
502 attr16, attr.ident, String16(""),
503 itemIdent, value, NULL, NULL, false, true);
504 if (err != NO_ERROR) {
505 attr.hasErrors = true;
506 }
507 }
508 } else if (code == ResXMLTree::END_TAG) {
509 if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
510 break;
511 }
512 if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
513 if (strcmp16(block.getElementName(&len), enum16.string()) != 0) {
514 SourcePos(in->getPrintableSource(), block.getLineNumber())
515 .error("Found tag </%s> where </enum> is expected\n",
516 String8(block.getElementName(&len)).string());
517 return UNKNOWN_ERROR;
518 }
519 } else {
520 if (strcmp16(block.getElementName(&len), flag16.string()) != 0) {
521 SourcePos(in->getPrintableSource(), block.getLineNumber())
522 .error("Found tag </%s> where </flag> is expected\n",
523 String8(block.getElementName(&len)).string());
524 return UNKNOWN_ERROR;
525 }
526 }
527 }
528 }
529
530 if (!attr.hasErrors && attr.added) {
531 appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags);
532 }
533
534 if (!attr.hasErrors && enumOrFlagsComment.size() > 0) {
535 enumOrFlagsComment.append(String16("\n</table>"));
536 outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment);
537 }
538
539
540 return NO_ERROR;
541}
542
543bool localeIsDefined(const ResTable_config& config)
544{
545 return config.locale == 0;
546}
547
548status_t parseAndAddBag(Bundle* bundle,
549 const sp<AaptFile>& in,
550 ResXMLTree* block,
551 const ResTable_config& config,
552 const String16& myPackage,
553 const String16& curType,
554 const String16& ident,
555 const String16& parentIdent,
556 const String16& itemIdent,
557 int32_t curFormat,
558 bool pseudolocalize,
559 const bool overwrite,
560 ResourceTable* outTable)
561{
562 status_t err;
563 const String16 item16("item");
564
565 String16 str;
566 Vector<StringPool::entry_style_span> spans;
567 err = parseStyledString(bundle, in->getPrintableSource().string(),
568 block, item16, &str, &spans,
569 pseudolocalize);
570 if (err != NO_ERROR) {
571 return err;
572 }
573
574 NOISY(printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
575 " pid=%s, bag=%s, id=%s: %s\n",
576 config.language[0], config.language[1],
577 config.country[0], config.country[1],
578 config.orientation, config.density,
579 String8(parentIdent).string(),
580 String8(ident).string(),
581 String8(itemIdent).string(),
582 String8(str).string()));
583
584 err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
585 myPackage, curType, ident, parentIdent, itemIdent, str,
586 &spans, &config, overwrite, false, curFormat);
587 return err;
588}
589
590
591status_t parseAndAddEntry(Bundle* bundle,
592 const sp<AaptFile>& in,
593 ResXMLTree* block,
594 const ResTable_config& config,
595 const String16& myPackage,
596 const String16& curType,
597 const String16& ident,
598 const String16& curTag,
599 bool curIsStyled,
600 int32_t curFormat,
601 bool pseudolocalize,
602 const bool overwrite,
603 ResourceTable* outTable)
604{
605 status_t err;
606
607 String16 str;
608 Vector<StringPool::entry_style_span> spans;
609 err = parseStyledString(bundle, in->getPrintableSource().string(), block,
610 curTag, &str, curIsStyled ? &spans : NULL,
611 pseudolocalize);
612
613 if (err < NO_ERROR) {
614 return err;
615 }
616
617 NOISY(printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
618 config.language[0], config.language[1],
619 config.country[0], config.country[1],
620 config.orientation, config.density,
621 String8(ident).string(), String8(str).string()));
622
623 err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
624 myPackage, curType, ident, str, &spans, &config,
625 false, curFormat, overwrite);
626
627 return err;
628}
629
630status_t compileResourceFile(Bundle* bundle,
631 const sp<AaptAssets>& assets,
632 const sp<AaptFile>& in,
633 const ResTable_config& defParams,
634 const bool overwrite,
635 ResourceTable* outTable)
636{
637 ResXMLTree block;
638 status_t err = parseXMLResource(in, &block, false, true);
639 if (err != NO_ERROR) {
640 return err;
641 }
642
643 // Top-level tag.
644 const String16 resources16("resources");
645
646 // Identifier declaration tags.
647 const String16 declare_styleable16("declare-styleable");
648 const String16 attr16("attr");
649
650 // Data creation organizational tags.
651 const String16 string16("string");
652 const String16 drawable16("drawable");
653 const String16 color16("color");
654 const String16 bool16("bool");
655 const String16 integer16("integer");
656 const String16 dimen16("dimen");
657 const String16 fraction16("fraction");
658 const String16 style16("style");
659 const String16 plurals16("plurals");
660 const String16 array16("array");
661 const String16 string_array16("string-array");
662 const String16 integer_array16("integer-array");
663 const String16 public16("public");
664 const String16 private_symbols16("private-symbols");
665 const String16 skip16("skip");
666 const String16 eat_comment16("eat-comment");
667
668 // Data creation tags.
669 const String16 bag16("bag");
670 const String16 item16("item");
671
672 // Attribute type constants.
673 const String16 enum16("enum");
674
675 // plural values
676 const String16 other16("other");
677 const String16 quantityOther16("^other");
678 const String16 zero16("zero");
679 const String16 quantityZero16("^zero");
680 const String16 one16("one");
681 const String16 quantityOne16("^one");
682 const String16 two16("two");
683 const String16 quantityTwo16("^two");
684 const String16 few16("few");
685 const String16 quantityFew16("^few");
686 const String16 many16("many");
687 const String16 quantityMany16("^many");
688
689 // useful attribute names and special values
690 const String16 name16("name");
691 const String16 translatable16("translatable");
692 const String16 false16("false");
693
694 const String16 myPackage(assets->getPackage());
695
696 bool hasErrors = false;
697
698 uint32_t nextPublicId = 0;
699
700 ResXMLTree::event_code_t code;
701 do {
702 code = block.next();
703 } while (code == ResXMLTree::START_NAMESPACE);
704
705 size_t len;
706 if (code != ResXMLTree::START_TAG) {
707 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
708 "No start tag found\n");
709 return UNKNOWN_ERROR;
710 }
711 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
712 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
713 "Invalid start tag %s\n", String8(block.getElementName(&len)).string());
714 return UNKNOWN_ERROR;
715 }
716
717 ResTable_config curParams(defParams);
718
719 ResTable_config pseudoParams(curParams);
720 pseudoParams.language[0] = 'z';
721 pseudoParams.language[1] = 'z';
722 pseudoParams.country[0] = 'Z';
723 pseudoParams.country[1] = 'Z';
724
725 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
726 if (code == ResXMLTree::START_TAG) {
727 const String16* curTag = NULL;
728 String16 curType;
729 int32_t curFormat = ResTable_map::TYPE_ANY;
730 bool curIsBag = false;
731 bool curIsStyled = false;
732 bool curIsPseudolocalizable = false;
733 bool localHasErrors = false;
734
735 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
736 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
737 && code != ResXMLTree::BAD_DOCUMENT) {
738 if (code == ResXMLTree::END_TAG) {
739 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
740 break;
741 }
742 }
743 }
744 continue;
745
746 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
747 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
748 && code != ResXMLTree::BAD_DOCUMENT) {
749 if (code == ResXMLTree::END_TAG) {
750 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
751 break;
752 }
753 }
754 }
755 continue;
756
757 } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
758 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
759
760 String16 type;
761 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
762 if (typeIdx < 0) {
763 srcPos.error("A 'type' attribute is required for <public>\n");
764 hasErrors = localHasErrors = true;
765 }
766 type = String16(block.getAttributeStringValue(typeIdx, &len));
767
768 String16 name;
769 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
770 if (nameIdx < 0) {
771 srcPos.error("A 'name' attribute is required for <public>\n");
772 hasErrors = localHasErrors = true;
773 }
774 name = String16(block.getAttributeStringValue(nameIdx, &len));
775
776 uint32_t ident = 0;
777 ssize_t identIdx = block.indexOfAttribute(NULL, "id");
778 if (identIdx >= 0) {
779 const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
780 Res_value identValue;
781 if (!ResTable::stringToInt(identStr, len, &identValue)) {
782 srcPos.error("Given 'id' attribute is not an integer: %s\n",
783 String8(block.getAttributeStringValue(identIdx, &len)).string());
784 hasErrors = localHasErrors = true;
785 } else {
786 ident = identValue.data;
787 nextPublicId = ident+1;
788 }
789 } else if (nextPublicId == 0) {
790 srcPos.error("No 'id' attribute supplied <public>,"
791 " and no previous id defined in this file.\n");
792 hasErrors = localHasErrors = true;
793 } else if (!localHasErrors) {
794 ident = nextPublicId;
795 nextPublicId++;
796 }
797
798 if (!localHasErrors) {
799 err = outTable->addPublic(srcPos, myPackage, type, name, ident);
800 if (err < NO_ERROR) {
801 hasErrors = localHasErrors = true;
802 }
803 }
804 if (!localHasErrors) {
805 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
806 if (symbols != NULL) {
807 symbols = symbols->addNestedSymbol(String8(type), srcPos);
808 }
809 if (symbols != NULL) {
810 symbols->makeSymbolPublic(String8(name), srcPos);
811 String16 comment(
812 block.getComment(&len) ? block.getComment(&len) : nulStr);
813 symbols->appendComment(String8(name), comment, srcPos);
814 } else {
815 srcPos.error("Unable to create symbols!\n");
816 hasErrors = localHasErrors = true;
817 }
818 }
819
820 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
821 if (code == ResXMLTree::END_TAG) {
822 if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
823 break;
824 }
825 }
826 }
827 continue;
828
829 } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
830 String16 pkg;
831 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
832 if (pkgIdx < 0) {
833 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
834 "A 'package' attribute is required for <private-symbols>\n");
835 hasErrors = localHasErrors = true;
836 }
837 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
838 if (!localHasErrors) {
839 assets->setSymbolsPrivatePackage(String8(pkg));
840 }
841
842 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
843 if (code == ResXMLTree::END_TAG) {
844 if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
845 break;
846 }
847 }
848 }
849 continue;
850
851 } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
852 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
853
854 String16 ident;
855 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
856 if (identIdx < 0) {
857 srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
858 hasErrors = localHasErrors = true;
859 }
860 ident = String16(block.getAttributeStringValue(identIdx, &len));
861
862 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
863 if (!localHasErrors) {
864 if (symbols != NULL) {
865 symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
866 }
867 sp<AaptSymbols> styleSymbols = symbols;
868 if (symbols != NULL) {
869 symbols = symbols->addNestedSymbol(String8(ident), srcPos);
870 }
871 if (symbols == NULL) {
872 srcPos.error("Unable to create symbols!\n");
873 return UNKNOWN_ERROR;
874 }
875
876 String16 comment(
877 block.getComment(&len) ? block.getComment(&len) : nulStr);
878 styleSymbols->appendComment(String8(ident), comment, srcPos);
879 } else {
880 symbols = NULL;
881 }
882
883 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
884 if (code == ResXMLTree::START_TAG) {
885 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
886 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
887 && code != ResXMLTree::BAD_DOCUMENT) {
888 if (code == ResXMLTree::END_TAG) {
889 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
890 break;
891 }
892 }
893 }
894 continue;
895 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
896 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
897 && code != ResXMLTree::BAD_DOCUMENT) {
898 if (code == ResXMLTree::END_TAG) {
899 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
900 break;
901 }
902 }
903 }
904 continue;
905 } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
906 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
907 "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
908 String8(block.getElementName(&len)).string());
909 return UNKNOWN_ERROR;
910 }
911
912 String16 comment(
913 block.getComment(&len) ? block.getComment(&len) : nulStr);
914 String16 itemIdent;
915 err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
916 if (err != NO_ERROR) {
917 hasErrors = localHasErrors = true;
918 }
919
920 if (symbols != NULL) {
921 SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
922 symbols->addSymbol(String8(itemIdent), 0, srcPos);
923 symbols->appendComment(String8(itemIdent), comment, srcPos);
924 //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
925 // String8(comment).string());
926 }
927 } else if (code == ResXMLTree::END_TAG) {
928 if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
929 break;
930 }
931
932 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
933 "Found tag </%s> where </attr> is expected\n",
934 String8(block.getElementName(&len)).string());
935 return UNKNOWN_ERROR;
936 }
937 }
938 continue;
939
940 } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
941 err = compileAttribute(in, block, myPackage, outTable, NULL);
942 if (err != NO_ERROR) {
943 hasErrors = true;
944 }
945 continue;
946
947 } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
948 curTag = &item16;
949 ssize_t attri = block.indexOfAttribute(NULL, "type");
950 if (attri >= 0) {
951 curType = String16(block.getAttributeStringValue(attri, &len));
952 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
953 if (formatIdx >= 0) {
954 String16 formatStr = String16(block.getAttributeStringValue(
955 formatIdx, &len));
956 curFormat = parse_flags(formatStr.string(), formatStr.size(),
957 gFormatFlags);
958 if (curFormat == 0) {
959 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
960 "Tag <item> 'format' attribute value \"%s\" not valid\n",
961 String8(formatStr).string());
962 hasErrors = localHasErrors = true;
963 }
964 }
965 } else {
966 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
967 "A 'type' attribute is required for <item>\n");
968 hasErrors = localHasErrors = true;
969 }
970 curIsStyled = true;
971 } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
972 // Note the existence and locale of every string we process
973 char rawLocale[16];
974 curParams.getLocale(rawLocale);
975 String8 locale(rawLocale);
976 String16 name;
977 String16 translatable;
978
979 size_t n = block.getAttributeCount();
980 for (size_t i = 0; i < n; i++) {
981 size_t length;
982 const uint16_t* attr = block.getAttributeName(i, &length);
983 if (strcmp16(attr, name16.string()) == 0) {
984 name.setTo(block.getAttributeStringValue(i, &length));
985 } else if (strcmp16(attr, translatable16.string()) == 0) {
986 translatable.setTo(block.getAttributeStringValue(i, &length));
987 }
988 }
989
990 if (name.size() > 0) {
991 if (translatable == false16) {
992 // Untranslatable strings must only exist in the default [empty] locale
993 if (locale.size() > 0) {
994 fprintf(stderr, "aapt: warning: string '%s' in %s marked untranslatable but exists"
995 " in locale '%s'\n", String8(name).string(),
996 bundle->getResourceSourceDirs()[0],
997 locale.string());
998 // hasErrors = localHasErrors = true;
999 } else {
1000 // Intentionally empty block:
1001 //
1002 // Don't add untranslatable strings to the localization table; that
1003 // way if we later see localizations of them, they'll be flagged as
1004 // having no default translation.
1005 }
1006 } else {
1007 outTable->addLocalization(name, locale);
1008 }
1009 }
1010
1011 curTag = &string16;
1012 curType = string16;
1013 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1014 curIsStyled = true;
1015 curIsPseudolocalizable = true;
1016 } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
1017 curTag = &drawable16;
1018 curType = drawable16;
1019 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1020 } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
1021 curTag = &color16;
1022 curType = color16;
1023 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1024 } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
1025 curTag = &bool16;
1026 curType = bool16;
1027 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
1028 } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
1029 curTag = &integer16;
1030 curType = integer16;
1031 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1032 } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
1033 curTag = &dimen16;
1034 curType = dimen16;
1035 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
1036 } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) {
1037 curTag = &fraction16;
1038 curType = fraction16;
1039 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
1040 } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
1041 curTag = &bag16;
1042 curIsBag = true;
1043 ssize_t attri = block.indexOfAttribute(NULL, "type");
1044 if (attri >= 0) {
1045 curType = String16(block.getAttributeStringValue(attri, &len));
1046 } else {
1047 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1048 "A 'type' attribute is required for <bag>\n");
1049 hasErrors = localHasErrors = true;
1050 }
1051 } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
1052 curTag = &style16;
1053 curType = style16;
1054 curIsBag = true;
1055 } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
1056 curTag = &plurals16;
1057 curType = plurals16;
1058 curIsBag = true;
1059 } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
1060 curTag = &array16;
1061 curType = array16;
1062 curIsBag = true;
1063 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1064 if (formatIdx >= 0) {
1065 String16 formatStr = String16(block.getAttributeStringValue(
1066 formatIdx, &len));
1067 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1068 gFormatFlags);
1069 if (curFormat == 0) {
1070 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1071 "Tag <array> 'format' attribute value \"%s\" not valid\n",
1072 String8(formatStr).string());
1073 hasErrors = localHasErrors = true;
1074 }
1075 }
1076 } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
1077 curTag = &string_array16;
1078 curType = array16;
1079 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1080 curIsBag = true;
1081 curIsPseudolocalizable = true;
1082 } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
1083 curTag = &integer_array16;
1084 curType = array16;
1085 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1086 curIsBag = true;
1087 } else {
1088 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1089 "Found tag %s where item is expected\n",
1090 String8(block.getElementName(&len)).string());
1091 return UNKNOWN_ERROR;
1092 }
1093
1094 String16 ident;
1095 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1096 if (identIdx >= 0) {
1097 ident = String16(block.getAttributeStringValue(identIdx, &len));
1098 } else {
1099 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1100 "A 'name' attribute is required for <%s>\n",
1101 String8(*curTag).string());
1102 hasErrors = localHasErrors = true;
1103 }
1104
1105 String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1106
1107 if (curIsBag) {
1108 // Figure out the parent of this bag...
1109 String16 parentIdent;
1110 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1111 if (parentIdentIdx >= 0) {
1112 parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1113 } else {
1114 ssize_t sep = ident.findLast('.');
1115 if (sep >= 0) {
1116 parentIdent.setTo(ident, sep);
1117 }
1118 }
1119
1120 if (!localHasErrors) {
1121 err = outTable->startBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
76486813
RG
1122 myPackage, curType, ident, parentIdent, &curParams,
1123 overwrite);
a534180c
TAOSP
1124 if (err != NO_ERROR) {
1125 hasErrors = localHasErrors = true;
1126 }
1127 }
1128
1129 ssize_t elmIndex = 0;
1130 char elmIndexStr[14];
1131 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1132 && code != ResXMLTree::BAD_DOCUMENT) {
1133
1134 if (code == ResXMLTree::START_TAG) {
1135 if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
1136 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1137 "Tag <%s> can not appear inside <%s>, only <item>\n",
1138 String8(block.getElementName(&len)).string(),
1139 String8(*curTag).string());
1140 return UNKNOWN_ERROR;
1141 }
1142
1143 String16 itemIdent;
1144 if (curType == array16) {
1145 sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1146 itemIdent = String16(elmIndexStr);
1147 } else if (curType == plurals16) {
1148 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1149 if (itemIdentIdx >= 0) {
1150 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1151 if (quantity16 == other16) {
1152 itemIdent = quantityOther16;
1153 }
1154 else if (quantity16 == zero16) {
1155 itemIdent = quantityZero16;
1156 }
1157 else if (quantity16 == one16) {
1158 itemIdent = quantityOne16;
1159 }
1160 else if (quantity16 == two16) {
1161 itemIdent = quantityTwo16;
1162 }
1163 else if (quantity16 == few16) {
1164 itemIdent = quantityFew16;
1165 }
1166 else if (quantity16 == many16) {
1167 itemIdent = quantityMany16;
1168 }
1169 else {
1170 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1171 "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1172 hasErrors = localHasErrors = true;
1173 }
1174 } else {
1175 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1176 "A 'quantity' attribute is required for <item> inside <plurals>\n");
1177 hasErrors = localHasErrors = true;
1178 }
1179 } else {
1180 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1181 if (itemIdentIdx >= 0) {
1182 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1183 } else {
1184 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1185 "A 'name' attribute is required for <item>\n");
1186 hasErrors = localHasErrors = true;
1187 }
1188 }
1189
1190 ResXMLParser::ResXMLPosition parserPosition;
1191 block.getPosition(&parserPosition);
1192
1193 err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1194 ident, parentIdent, itemIdent, curFormat,
1195 false, overwrite, outTable);
1196 if (err == NO_ERROR) {
1197 if (curIsPseudolocalizable && localeIsDefined(curParams)
1198 && bundle->getPseudolocalize()) {
1199 // pseudolocalize here
1200#if 1
1201 block.setPosition(parserPosition);
1202 err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1203 curType, ident, parentIdent, itemIdent, curFormat, true,
1204 overwrite, outTable);
1205#endif
1206 }
1207 }
1208 if (err != NO_ERROR) {
1209 hasErrors = localHasErrors = true;
1210 }
1211 } else if (code == ResXMLTree::END_TAG) {
1212 if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
1213 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1214 "Found tag </%s> where </%s> is expected\n",
1215 String8(block.getElementName(&len)).string(),
1216 String8(*curTag).string());
1217 return UNKNOWN_ERROR;
1218 }
1219 break;
1220 }
1221 }
1222 } else {
1223 ResXMLParser::ResXMLPosition parserPosition;
1224 block.getPosition(&parserPosition);
1225
1226 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1227 *curTag, curIsStyled, curFormat, false, overwrite, outTable);
1228
1229 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1230 hasErrors = localHasErrors = true;
1231 }
1232 else if (err == NO_ERROR) {
1233 if (curIsPseudolocalizable && localeIsDefined(curParams)
1234 && bundle->getPseudolocalize()) {
1235 // pseudolocalize here
1236 block.setPosition(parserPosition);
1237 err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
03938ad3 1238 ident, *curTag, curIsStyled, curFormat, true, overwrite, outTable);
a534180c
TAOSP
1239 if (err != NO_ERROR) {
1240 hasErrors = localHasErrors = true;
1241 }
1242 }
1243 }
1244 }
1245
1246#if 0
1247 if (comment.size() > 0) {
1248 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
1249 String8(curType).string(), String8(ident).string(),
1250 String8(comment).string());
1251 }
1252#endif
1253 if (!localHasErrors) {
1254 outTable->appendComment(myPackage, curType, ident, comment, false);
1255 }
1256 }
1257 else if (code == ResXMLTree::END_TAG) {
1258 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
1259 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1260 "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
1261 return UNKNOWN_ERROR;
1262 }
1263 }
1264 else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1265 }
1266 else if (code == ResXMLTree::TEXT) {
1267 if (isWhitespace(block.getText(&len))) {
1268 continue;
1269 }
1270 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1271 "Found text \"%s\" where item tag is expected\n",
1272 String8(block.getText(&len)).string());
1273 return UNKNOWN_ERROR;
1274 }
1275 }
1276
1277 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1278}
1279
1280ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage)
1281 : mAssetsPackage(assetsPackage), mNextPackageId(1), mHaveAppPackage(false),
1282 mIsAppPackage(!bundle->getExtending()),
1283 mNumLocal(0),
1284 mBundle(bundle)
1285{
1286}
1287
1288status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1289{
1290 status_t err = assets->buildIncludedResources(bundle);
1291 if (err != NO_ERROR) {
1292 return err;
1293 }
1294
1295 // For future reference to included resources.
1296 mAssets = assets;
1297
1298 const ResTable& incl = assets->getIncludedResources();
1299
1300 // Retrieve all the packages.
1301 const size_t N = incl.getBasePackageCount();
1302 for (size_t phase=0; phase<2; phase++) {
1303 for (size_t i=0; i<N; i++) {
1304 String16 name(incl.getBasePackageName(i));
1305 uint32_t id = incl.getBasePackageId(i);
1306 // First time through: only add base packages (id
1307 // is not 0); second time through add the other
1308 // packages.
1309 if (phase != 0) {
1310 if (id != 0) {
1311 // Skip base packages -- already one.
1312 id = 0;
1313 } else {
1314 // Assign a dynamic id.
1315 id = mNextPackageId;
1316 }
1317 } else if (id != 0) {
1318 if (id == 127) {
1319 if (mHaveAppPackage) {
e942a5c2 1320 fprintf(stderr, "Included resources have two application packages!\n");
a534180c
TAOSP
1321 return UNKNOWN_ERROR;
1322 }
1323 mHaveAppPackage = true;
1324 }
1325 if (mNextPackageId > id) {
1326 fprintf(stderr, "Included base package ID %d already in use!\n", id);
1327 return UNKNOWN_ERROR;
1328 }
1329 }
1330 if (id != 0) {
1331 NOISY(printf("Including package %s with ID=%d\n",
1332 String8(name).string(), id));
1333 sp<Package> p = new Package(name, id);
1334 mPackages.add(name, p);
1335 mOrderedPackages.add(p);
1336
1337 if (id >= mNextPackageId) {
1338 mNextPackageId = id+1;
1339 }
1340 }
1341 }
1342 }
1343
1344 // Every resource table always has one first entry, the bag attributes.
1345 const SourcePos unknown(String8("????"), 0);
1346 sp<Type> attr = getType(mAssetsPackage, String16("attr"), unknown);
1347
1348 return NO_ERROR;
1349}
1350
1351status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1352 const String16& package,
1353 const String16& type,
1354 const String16& name,
1355 const uint32_t ident)
1356{
1357 uint32_t rid = mAssets->getIncludedResources()
1358 .identifierForName(name.string(), name.size(),
1359 type.string(), type.size(),
1360 package.string(), package.size());
1361 if (rid != 0) {
1362 sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
1363 String8(type).string(), String8(name).string(),
1364 String8(package).string());
1365 return UNKNOWN_ERROR;
1366 }
1367
1368 sp<Type> t = getType(package, type, sourcePos);
1369 if (t == NULL) {
1370 return UNKNOWN_ERROR;
1371 }
1372 return t->addPublic(sourcePos, name, ident);
1373}
1374
1375status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1376 const String16& package,
1377 const String16& type,
1378 const String16& name,
1379 const String16& value,
1380 const Vector<StringPool::entry_style_span>* style,
1381 const ResTable_config* params,
1382 const bool doSetIndex,
1383 const int32_t format,
1384 const bool overwrite)
1385{
1386 // Check for adding entries in other packages... for now we do
1387 // nothing. We need to do the right thing here to support skinning.
1388 uint32_t rid = mAssets->getIncludedResources()
1389 .identifierForName(name.string(), name.size(),
1390 type.string(), type.size(),
1391 package.string(), package.size());
1392 if (rid != 0) {
1393 return NO_ERROR;
1394 }
1395
1396#if 0
1397 if (name == String16("left")) {
1398 printf("Adding entry left: file=%s, line=%d, type=%s, value=%s\n",
1399 sourcePos.file.string(), sourcePos.line, String8(type).string(),
1400 String8(value).string());
1401 }
1402#endif
1403
1404 sp<Entry> e = getEntry(package, type, name, sourcePos, params, doSetIndex);
1405 if (e == NULL) {
1406 return UNKNOWN_ERROR;
1407 }
1408 status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1409 if (err == NO_ERROR) {
1410 mNumLocal++;
1411 }
1412 return err;
1413}
1414
1415status_t ResourceTable::startBag(const SourcePos& sourcePos,
1416 const String16& package,
1417 const String16& type,
1418 const String16& name,
1419 const String16& bagParent,
1420 const ResTable_config* params,
1421 bool replace, bool isId)
1422{
76486813
RG
1423 status_t result = NO_ERROR;
1424
a534180c
TAOSP
1425 // Check for adding entries in other packages... for now we do
1426 // nothing. We need to do the right thing here to support skinning.
1427 uint32_t rid = mAssets->getIncludedResources()
1428 .identifierForName(name.string(), name.size(),
1429 type.string(), type.size(),
1430 package.string(), package.size());
1431 if (rid != 0) {
1432 return NO_ERROR;
1433 }
1434
1435#if 0
1436 if (name == String16("left")) {
1437 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1438 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1439 }
1440#endif
1441
1442 sp<Entry> e = getEntry(package, type, name, sourcePos, params);
1443 if (e == NULL) {
1444 return UNKNOWN_ERROR;
1445 }
1446
1447 // If a parent is explicitly specified, set it.
1448 if (bagParent.size() > 0) {
1449 String16 curPar = e->getParent();
1450 if (curPar.size() > 0 && curPar != bagParent) {
1451 sourcePos.error("Conflicting parents specified, was '%s', now '%s'\n",
1452 String8(e->getParent()).string(),
1453 String8(bagParent).string());
1454 return UNKNOWN_ERROR;
1455 }
1456 e->setParent(bagParent);
1457 }
76486813
RG
1458
1459 if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1460 return result;
1461 }
9d911eb6
RG
1462
1463 if (replace) {
1464 return e->emptyBag(sourcePos);
1465 }
1466 return result;
a534180c
TAOSP
1467}
1468
1469status_t ResourceTable::addBag(const SourcePos& sourcePos,
1470 const String16& package,
1471 const String16& type,
1472 const String16& name,
1473 const String16& bagParent,
1474 const String16& bagKey,
1475 const String16& value,
1476 const Vector<StringPool::entry_style_span>* style,
1477 const ResTable_config* params,
1478 bool replace, bool isId, const int32_t format)
1479{
1480 // Check for adding entries in other packages... for now we do
1481 // nothing. We need to do the right thing here to support skinning.
1482 uint32_t rid = mAssets->getIncludedResources()
1483 .identifierForName(name.string(), name.size(),
1484 type.string(), type.size(),
1485 package.string(), package.size());
1486 if (rid != 0) {
1487 return NO_ERROR;
1488 }
1489
1490#if 0
1491 if (name == String16("left")) {
1492 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1493 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1494 }
1495#endif
1496
1497 sp<Entry> e = getEntry(package, type, name, sourcePos, params);
1498 if (e == NULL) {
1499 return UNKNOWN_ERROR;
1500 }
1501
1502 // If a parent is explicitly specified, set it.
1503 if (bagParent.size() > 0) {
1504 String16 curPar = e->getParent();
1505 if (curPar.size() > 0 && curPar != bagParent) {
1506 sourcePos.error("Conflicting parents specified, was '%s', now '%s'\n",
1507 String8(e->getParent()).string(),
1508 String8(bagParent).string());
1509 return UNKNOWN_ERROR;
1510 }
1511 e->setParent(bagParent);
1512 }
1513
1514 const bool first = e->getBag().indexOfKey(bagKey) < 0;
1515 status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1516 if (err == NO_ERROR && first) {
1517 mNumLocal++;
1518 }
1519 return err;
1520}
1521
1522bool ResourceTable::hasBagOrEntry(const String16& package,
1523 const String16& type,
1524 const String16& name) const
1525{
1526 // First look for this in the included resources...
1527 uint32_t rid = mAssets->getIncludedResources()
1528 .identifierForName(name.string(), name.size(),
1529 type.string(), type.size(),
1530 package.string(), package.size());
1531 if (rid != 0) {
1532 return true;
1533 }
1534
1535 sp<Package> p = mPackages.valueFor(package);
1536 if (p != NULL) {
1537 sp<Type> t = p->getTypes().valueFor(type);
1538 if (t != NULL) {
1539 sp<ConfigList> c = t->getConfigs().valueFor(name);
1540 if (c != NULL) return true;
1541 }
1542 }
1543
1544 return false;
1545}
1546
1547bool ResourceTable::hasBagOrEntry(const String16& ref,
1548 const String16* defType,
1549 const String16* defPackage)
1550{
1551 String16 package, type, name;
1552 if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
1553 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
1554 return false;
1555 }
1556 return hasBagOrEntry(package, type, name);
1557}
1558
1559bool ResourceTable::appendComment(const String16& package,
1560 const String16& type,
1561 const String16& name,
1562 const String16& comment,
1563 bool onlyIfEmpty)
1564{
1565 if (comment.size() <= 0) {
1566 return true;
1567 }
1568
1569 sp<Package> p = mPackages.valueFor(package);
1570 if (p != NULL) {
1571 sp<Type> t = p->getTypes().valueFor(type);
1572 if (t != NULL) {
1573 sp<ConfigList> c = t->getConfigs().valueFor(name);
1574 if (c != NULL) {
1575 c->appendComment(comment, onlyIfEmpty);
1576 return true;
1577 }
1578 }
1579 }
1580 return false;
1581}
1582
1583bool ResourceTable::appendTypeComment(const String16& package,
1584 const String16& type,
1585 const String16& name,
1586 const String16& comment)
1587{
1588 if (comment.size() <= 0) {
1589 return true;
1590 }
1591
1592 sp<Package> p = mPackages.valueFor(package);
1593 if (p != NULL) {
1594 sp<Type> t = p->getTypes().valueFor(type);
1595 if (t != NULL) {
1596 sp<ConfigList> c = t->getConfigs().valueFor(name);
1597 if (c != NULL) {
1598 c->appendTypeComment(comment);
1599 return true;
1600 }
1601 }
1602 }
1603 return false;
1604}
1605
1606size_t ResourceTable::size() const {
1607 return mPackages.size();
1608}
1609
1610size_t ResourceTable::numLocalResources() const {
1611 return mNumLocal;
1612}
1613
1614bool ResourceTable::hasResources() const {
1615 return mNumLocal > 0;
1616}
1617
1618sp<AaptFile> ResourceTable::flatten(Bundle* bundle)
1619{
1620 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
1621 status_t err = flatten(bundle, data);
1622 return err == NO_ERROR ? data : NULL;
1623}
1624
1625inline uint32_t ResourceTable::getResId(const sp<Package>& p,
1626 const sp<Type>& t,
1627 uint32_t nameId)
1628{
1629 return makeResId(p->getAssignedId(), t->getIndex(), nameId);
1630}
1631
1632uint32_t ResourceTable::getResId(const String16& package,
1633 const String16& type,
1634 const String16& name,
1635 bool onlyPublic) const
1636{
1637 sp<Package> p = mPackages.valueFor(package);
1638 if (p == NULL) return 0;
1639
1640 // First look for this in the included resources...
1641 uint32_t specFlags = 0;
1642 uint32_t rid = mAssets->getIncludedResources()
1643 .identifierForName(name.string(), name.size(),
1644 type.string(), type.size(),
1645 package.string(), package.size(),
1646 &specFlags);
1647 if (rid != 0) {
1648 if (onlyPublic) {
1649 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
1650 return 0;
1651 }
1652 }
1653
1654 if (Res_INTERNALID(rid)) {
1655 return rid;
1656 }
1657 return Res_MAKEID(p->getAssignedId()-1,
1658 Res_GETTYPE(rid),
1659 Res_GETENTRY(rid));
1660 }
1661
1662 sp<Type> t = p->getTypes().valueFor(type);
1663 if (t == NULL) return 0;
1664 sp<ConfigList> c = t->getConfigs().valueFor(name);
1665 if (c == NULL) return 0;
1666 int32_t ei = c->getEntryIndex();
1667 if (ei < 0) return 0;
1668 return getResId(p, t, ei);
1669}
1670
1671uint32_t ResourceTable::getResId(const String16& ref,
1672 const String16* defType,
1673 const String16* defPackage,
1674 const char** outErrorMsg,
1675 bool onlyPublic) const
1676{
1677 String16 package, type, name;
1678 if (!ResTable::expandResourceRef(
1679 ref.string(), ref.size(), &package, &type, &name,
1680 defType, defPackage ? defPackage:&mAssetsPackage,
1681 outErrorMsg)) {
1682 NOISY(printf("Expanding resource: ref=%s\n",
1683 String8(ref).string()));
1684 NOISY(printf("Expanding resource: defType=%s\n",
1685 defType ? String8(*defType).string() : "NULL"));
1686 NOISY(printf("Expanding resource: defPackage=%s\n",
1687 defPackage ? String8(*defPackage).string() : "NULL"));
1688 NOISY(printf("Expanding resource: ref=%s\n", String8(ref).string()));
1689 NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
1690 String8(package).string(), String8(type).string(),
1691 String8(name).string()));
1692 return 0;
1693 }
1694 uint32_t res = getResId(package, type, name, onlyPublic);
1695 NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
1696 String8(package).string(), String8(type).string(),
1697 String8(name).string(), res));
1698 if (res == 0) {
1699 if (outErrorMsg)
1700 *outErrorMsg = "No resource found that matches the given name";
1701 }
1702 return res;
1703}
1704
1705bool ResourceTable::isValidResourceName(const String16& s)
1706{
1707 const char16_t* p = s.string();
1708 bool first = true;
1709 while (*p) {
1710 if ((*p >= 'a' && *p <= 'z')
1711 || (*p >= 'A' && *p <= 'Z')
1712 || *p == '_'
1713 || (!first && *p >= '0' && *p <= '9')) {
1714 first = false;
1715 p++;
1716 continue;
1717 }
1718 return false;
1719 }
1720 return true;
1721}
1722
1723bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
1724 const String16& str,
1725 bool preserveSpaces, bool coerceType,
1726 uint32_t attrID,
1727 const Vector<StringPool::entry_style_span>* style,
1728 String16* outStr, void* accessorCookie,
1729 uint32_t attrType)
1730{
1731 String16 finalStr;
1732
1733 bool res = true;
1734 if (style == NULL || style->size() == 0) {
1735 // Text is not styled so it can be any type... let's figure it out.
1736 res = mAssets->getIncludedResources()
1737 .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
1738 coerceType, attrID, NULL, &mAssetsPackage, this,
1739 accessorCookie, attrType);
1740 } else {
1741 // Styled text can only be a string, and while collecting the style
1742 // information we have already processed that string!
1743 outValue->size = sizeof(Res_value);
1744 outValue->res0 = 0;
1745 outValue->dataType = outValue->TYPE_STRING;
1746 outValue->data = 0;
1747 finalStr = str;
1748 }
1749
1750 if (!res) {
1751 return false;
1752 }
1753
1754 if (outValue->dataType == outValue->TYPE_STRING) {
1755 // Should do better merging styles.
1756 if (pool) {
1757 if (style != NULL && style->size() > 0) {
1758 outValue->data = pool->add(finalStr, *style);
1759 } else {
1760 outValue->data = pool->add(finalStr, true);
1761 }
1762 } else {
1763 // Caller will fill this in later.
1764 outValue->data = 0;
1765 }
1766
1767 if (outStr) {
1768 *outStr = finalStr;
1769 }
1770
1771 }
1772
1773 return true;
1774}
1775
1776uint32_t ResourceTable::getCustomResource(
1777 const String16& package, const String16& type, const String16& name) const
1778{
1779 //printf("getCustomResource: %s %s %s\n", String8(package).string(),
1780 // String8(type).string(), String8(name).string());
1781 sp<Package> p = mPackages.valueFor(package);
1782 if (p == NULL) return 0;
1783 sp<Type> t = p->getTypes().valueFor(type);
1784 if (t == NULL) return 0;
1785 sp<ConfigList> c = t->getConfigs().valueFor(name);
1786 if (c == NULL) return 0;
1787 int32_t ei = c->getEntryIndex();
1788 if (ei < 0) return 0;
1789 return getResId(p, t, ei);
1790}
1791
1792uint32_t ResourceTable::getCustomResourceWithCreation(
1793 const String16& package, const String16& type, const String16& name,
1794 const bool createIfNotFound)
1795{
1796 uint32_t resId = getCustomResource(package, type, name);
1797 if (resId != 0 || !createIfNotFound) {
1798 return resId;
1799 }
1800 String16 value("false");
1801
1802 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
1803 if (status == NO_ERROR) {
1804 resId = getResId(package, type, name);
1805 return resId;
1806 }
1807 return 0;
1808}
1809
1810uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
1811{
1812 return origPackage;
1813}
1814
1815bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
1816{
1817 //printf("getAttributeType #%08x\n", attrID);
1818 Res_value value;
1819 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
1820 //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
1821 // String8(getEntry(attrID)->getName()).string(), value.data);
1822 *outType = value.data;
1823 return true;
1824 }
1825 return false;
1826}
1827
1828bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
1829{
1830 //printf("getAttributeMin #%08x\n", attrID);
1831 Res_value value;
1832 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
1833 *outMin = value.data;
1834 return true;
1835 }
1836 return false;
1837}
1838
1839bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
1840{
1841 //printf("getAttributeMax #%08x\n", attrID);
1842 Res_value value;
1843 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
1844 *outMax = value.data;
1845 return true;
1846 }
1847 return false;
1848}
1849
1850uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
1851{
1852 //printf("getAttributeL10N #%08x\n", attrID);
1853 Res_value value;
1854 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
1855 return value.data;
1856 }
1857 return ResTable_map::L10N_NOT_REQUIRED;
1858}
1859
1860bool ResourceTable::getLocalizationSetting()
1861{
1862 return mBundle->getRequireLocalization();
1863}
1864
1865void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
1866{
1867 if (accessorCookie != NULL && fmt != NULL) {
1868 AccessorCookie* ac = (AccessorCookie*)accessorCookie;
1869 int retval=0;
1870 char buf[1024];
1871 va_list ap;
1872 va_start(ap, fmt);
1873 retval = vsnprintf(buf, sizeof(buf), fmt, ap);
1874 va_end(ap);
1875 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
1876 buf, ac->attr.string(), ac->value.string());
1877 }
1878}
1879
1880bool ResourceTable::getAttributeKeys(
1881 uint32_t attrID, Vector<String16>* outKeys)
1882{
1883 sp<const Entry> e = getEntry(attrID);
1884 if (e != NULL) {
1885 const size_t N = e->getBag().size();
1886 for (size_t i=0; i<N; i++) {
1887 const String16& key = e->getBag().keyAt(i);
1888 if (key.size() > 0 && key.string()[0] != '^') {
1889 outKeys->add(key);
1890 }
1891 }
1892 return true;
1893 }
1894 return false;
1895}
1896
1897bool ResourceTable::getAttributeEnum(
1898 uint32_t attrID, const char16_t* name, size_t nameLen,
1899 Res_value* outValue)
1900{
1901 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
1902 String16 nameStr(name, nameLen);
1903 sp<const Entry> e = getEntry(attrID);
1904 if (e != NULL) {
1905 const size_t N = e->getBag().size();
1906 for (size_t i=0; i<N; i++) {
1907 //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
1908 // String8(e->getBag().keyAt(i)).string());
1909 if (e->getBag().keyAt(i) == nameStr) {
1910 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
1911 }
1912 }
1913 }
1914 return false;
1915}
1916
1917bool ResourceTable::getAttributeFlags(
1918 uint32_t attrID, const char16_t* name, size_t nameLen,
1919 Res_value* outValue)
1920{
1921 outValue->dataType = Res_value::TYPE_INT_HEX;
1922 outValue->data = 0;
1923
1924 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
1925 String16 nameStr(name, nameLen);
1926 sp<const Entry> e = getEntry(attrID);
1927 if (e != NULL) {
1928 const size_t N = e->getBag().size();
1929
1930 const char16_t* end = name + nameLen;
1931 const char16_t* pos = name;
1932 bool failed = false;
1933 while (pos < end && !failed) {
1934 const char16_t* start = pos;
1935 end++;
1936 while (pos < end && *pos != '|') {
1937 pos++;
1938 }
1939
1940 String16 nameStr(start, pos-start);
1941 size_t i;
1942 for (i=0; i<N; i++) {
1943 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
1944 // String8(e->getBag().keyAt(i)).string());
1945 if (e->getBag().keyAt(i) == nameStr) {
1946 Res_value val;
1947 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
1948 if (!got) {
1949 return false;
1950 }
1951 //printf("Got value: 0x%08x\n", val.data);
1952 outValue->data |= val.data;
1953 break;
1954 }
1955 }
1956
1957 if (i >= N) {
1958 // Didn't find this flag identifier.
1959 return false;
1960 }
1961 if (pos < end) {
1962 pos++;
1963 }
1964 }
1965
1966 return true;
1967 }
1968 return false;
1969}
1970
1971status_t ResourceTable::assignResourceIds()
1972{
1973 const size_t N = mOrderedPackages.size();
1974 size_t pi;
1975 status_t firstError = NO_ERROR;
1976
1977 // First generate all bag attributes and assign indices.
1978 for (pi=0; pi<N; pi++) {
1979 sp<Package> p = mOrderedPackages.itemAt(pi);
1980 if (p == NULL || p->getTypes().size() == 0) {
1981 // Empty, skip!
1982 continue;
1983 }
1984
1985 status_t err = p->applyPublicTypeOrder();
1986 if (err != NO_ERROR && firstError == NO_ERROR) {
1987 firstError = err;
1988 }
1989
1990 // Generate attributes...
1991 const size_t N = p->getOrderedTypes().size();
1992 size_t ti;
1993 for (ti=0; ti<N; ti++) {
1994 sp<Type> t = p->getOrderedTypes().itemAt(ti);
1995 if (t == NULL) {
1996 continue;
1997 }
1998 const size_t N = t->getOrderedConfigs().size();
1999 for (size_t ci=0; ci<N; ci++) {
2000 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2001 if (c == NULL) {
2002 continue;
2003 }
2004 const size_t N = c->getEntries().size();
2005 for (size_t ei=0; ei<N; ei++) {
2006 sp<Entry> e = c->getEntries().valueAt(ei);
2007 if (e == NULL) {
2008 continue;
2009 }
2010 status_t err = e->generateAttributes(this, p->getName());
2011 if (err != NO_ERROR && firstError == NO_ERROR) {
2012 firstError = err;
2013 }
2014 }
2015 }
2016 }
2017
2018 const SourcePos unknown(String8("????"), 0);
2019 sp<Type> attr = p->getType(String16("attr"), unknown);
2020
2021 // Assign indices...
2022 for (ti=0; ti<N; ti++) {
2023 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2024 if (t == NULL) {
2025 continue;
2026 }
2027 err = t->applyPublicEntryOrder();
2028 if (err != NO_ERROR && firstError == NO_ERROR) {
2029 firstError = err;
2030 }
2031
2032 const size_t N = t->getOrderedConfigs().size();
2033 t->setIndex(ti+1);
2034
2035 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2036 "First type is not attr!");
2037
2038 for (size_t ei=0; ei<N; ei++) {
2039 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2040 if (c == NULL) {
2041 continue;
2042 }
2043 c->setEntryIndex(ei);
2044 }
2045 }
2046
2047 // Assign resource IDs to keys in bags...
2048 for (ti=0; ti<N; ti++) {
2049 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2050 if (t == NULL) {
2051 continue;
2052 }
2053 const size_t N = t->getOrderedConfigs().size();
2054 for (size_t ci=0; ci<N; ci++) {
2055 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2056 //printf("Ordered config #%d: %p\n", ci, c.get());
2057 const size_t N = c->getEntries().size();
2058 for (size_t ei=0; ei<N; ei++) {
2059 sp<Entry> e = c->getEntries().valueAt(ei);
2060 if (e == NULL) {
2061 continue;
2062 }
2063 status_t err = e->assignResourceIds(this, p->getName());
2064 if (err != NO_ERROR && firstError == NO_ERROR) {
2065 firstError = err;
2066 }
2067 }
2068 }
2069 }
2070 }
2071 return firstError;
2072}
2073
2074status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols) {
2075 const size_t N = mOrderedPackages.size();
2076 size_t pi;
2077
2078 for (pi=0; pi<N; pi++) {
2079 sp<Package> p = mOrderedPackages.itemAt(pi);
2080 if (p->getTypes().size() == 0) {
2081 // Empty, skip!
2082 continue;
2083 }
2084
2085 const size_t N = p->getOrderedTypes().size();
2086 size_t ti;
2087
2088 for (ti=0; ti<N; ti++) {
2089 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2090 if (t == NULL) {
2091 continue;
2092 }
2093 const size_t N = t->getOrderedConfigs().size();
2094 sp<AaptSymbols> typeSymbols;
2095 typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2096 for (size_t ci=0; ci<N; ci++) {
2097 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2098 if (c == NULL) {
2099 continue;
2100 }
2101 uint32_t rid = getResId(p, t, ci);
2102 if (rid == 0) {
2103 return UNKNOWN_ERROR;
2104 }
2105 if (Res_GETPACKAGE(rid) == (size_t)(p->getAssignedId()-1)) {
2106 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2107
2108 String16 comment(c->getComment());
2109 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
2110 //printf("Type symbol %s comment: %s\n", String8(e->getName()).string(),
2111 // String8(comment).string());
2112 comment = c->getTypeComment();
2113 typeSymbols->appendTypeComment(String8(c->getName()), comment);
2114 } else {
2115#if 0
2116 printf("**** NO MATCH: 0x%08x vs 0x%08x\n",
2117 Res_GETPACKAGE(rid), p->getAssignedId());
2118#endif
2119 }
2120 }
2121 }
2122 }
2123 return NO_ERROR;
2124}
2125
2126
2127void
2128ResourceTable::addLocalization(const String16& name, const String8& locale)
2129{
2130 mLocalizations[name].insert(locale);
2131}
2132
2133
2134/*!
2135 * Flag various sorts of localization problems. '+' indicates checks already implemented;
2136 * '-' indicates checks that will be implemented in the future.
2137 *
2138 * + A localized string for which no default-locale version exists => warning
2139 * + A string for which no version in an explicitly-requested locale exists => warning
2140 * + A localized translation of an translateable="false" string => warning
2141 * - A localized string not provided in every locale used by the table
2142 */
2143status_t
2144ResourceTable::validateLocalizations(void)
2145{
2146 status_t err = NO_ERROR;
2147 const String8 defaultLocale;
2148
2149 // For all strings...
2150 for (map<String16, set<String8> >::iterator nameIter = mLocalizations.begin();
2151 nameIter != mLocalizations.end();
2152 nameIter++) {
2153 const set<String8>& configSet = nameIter->second; // naming convenience
2154
2155 // Look for strings with no default localization
2156 if (configSet.count(defaultLocale) == 0) {
2157 fprintf(stdout, "aapt: warning: string '%s' has no default translation in %s; found:",
2158 String8(nameIter->first).string(), mBundle->getResourceSourceDirs()[0]);
2159 for (set<String8>::iterator locales = configSet.begin();
2160 locales != configSet.end();
2161 locales++) {
2162 fprintf(stdout, " %s", (*locales).string());
2163 }
2164 fprintf(stdout, "\n");
2165 // !!! TODO: throw an error here in some circumstances
2166 }
2167
2168 // Check that all requested localizations are present for this string
2169 if (mBundle->getConfigurations() != NULL && mBundle->getRequireLocalization()) {
2170 const char* allConfigs = mBundle->getConfigurations();
2171 const char* start = allConfigs;
2172 const char* comma;
2173
2174 do {
2175 String8 config;
2176 comma = strchr(start, ',');
2177 if (comma != NULL) {
2178 config.setTo(start, comma - start);
2179 start = comma + 1;
2180 } else {
2181 config.setTo(start);
2182 }
2183
2184 // don't bother with the pseudolocale "zz_ZZ"
2185 if (config != "zz_ZZ") {
2186 if (configSet.find(config) == configSet.end()) {
2187 // okay, no specific localization found. it's possible that we are
2188 // requiring a specific regional localization [e.g. de_DE] but there is an
2189 // available string in the generic language localization [e.g. de];
2190 // consider that string to have fulfilled the localization requirement.
2191 String8 region(config.string(), 2);
2192 if (configSet.find(region) == configSet.end()) {
2193 if (configSet.count(defaultLocale) == 0) {
2194 fprintf(stdout, "aapt: error: "
2195 "*** string '%s' has no default or required localization "
2196 "for '%s' in %s\n",
2197 String8(nameIter->first).string(),
2198 config.string(),
2199 mBundle->getResourceSourceDirs()[0]);
2200 err = UNKNOWN_ERROR;
2201 }
2202 }
2203 }
2204 }
2205 } while (comma != NULL);
2206 }
2207 }
2208
2209 return err;
2210}
2211
2212
2213status_t
2214ResourceFilter::parse(const char* arg)
2215{
2216 if (arg == NULL) {
2217 return 0;
2218 }
2219
2220 const char* p = arg;
2221 const char* q;
2222
2223 while (true) {
2224 q = strchr(p, ',');
2225 if (q == NULL) {
2226 q = p + strlen(p);
2227 }
2228
2229 String8 part(p, q-p);
2230
2231 if (part == "zz_ZZ") {
2232 mContainsPseudo = true;
2233 }
2234 int axis;
2235 uint32_t value;
2236 if (AaptGroupEntry::parseNamePart(part, &axis, &value)) {
2237 fprintf(stderr, "Invalid configuration: %s\n", arg);
2238 fprintf(stderr, " ");
2239 for (int i=0; i<p-arg; i++) {
2240 fprintf(stderr, " ");
2241 }
2242 for (int i=0; i<q-p; i++) {
2243 fprintf(stderr, "^");
2244 }
2245 fprintf(stderr, "\n");
2246 return 1;
2247 }
2248
2249 ssize_t index = mData.indexOfKey(axis);
2250 if (index < 0) {
2251 mData.add(axis, SortedVector<uint32_t>());
2252 }
2253 SortedVector<uint32_t>& sv = mData.editValueFor(axis);
2254 sv.add(value);
2255 // if it's a locale with a region, also match an unmodified locale of the
2256 // same language
2257 if (axis == AXIS_LANGUAGE) {
2258 if (value & 0xffff0000) {
2259 sv.add(value & 0x0000ffff);
2260 }
2261 }
2262 p = q;
2263 if (!*p) break;
2264 p++;
2265 }
2266
2267 return NO_ERROR;
2268}
2269
2270bool
2271ResourceFilter::match(int axis, uint32_t value)
2272{
2273 if (value == 0) {
2274 // they didn't specify anything so take everything
2275 return true;
2276 }
2277 ssize_t index = mData.indexOfKey(axis);
2278 if (index < 0) {
2279 // we didn't request anything on this axis so take everything
2280 return true;
2281 }
2282 const SortedVector<uint32_t>& sv = mData.valueAt(index);
2283 return sv.indexOf(value) >= 0;
2284}
2285
2286bool
2287ResourceFilter::match(const ResTable_config& config)
2288{
2289 if (config.locale) {
2290 uint32_t locale = (config.country[1] << 24) | (config.country[0] << 16)
2291 | (config.language[1] << 8) | (config.language[0]);
2292 if (!match(AXIS_LANGUAGE, locale)) {
2293 return false;
2294 }
2295 }
2296 if (!match(AXIS_ORIENTATION, config.orientation)) {
2297 return false;
2298 }
2299 if (!match(AXIS_DENSITY, config.density)) {
2300 return false;
2301 }
2302 if (!match(AXIS_TOUCHSCREEN, config.touchscreen)) {
2303 return false;
2304 }
2305 if (!match(AXIS_KEYSHIDDEN, config.inputFlags)) {
2306 return false;
2307 }
2308 if (!match(AXIS_KEYBOARD, config.keyboard)) {
2309 return false;
2310 }
2311 if (!match(AXIS_NAVIGATION, config.navigation)) {
2312 return false;
2313 }
2314 if (!match(AXIS_SCREENSIZE, config.screenSize)) {
2315 return false;
2316 }
2317 if (!match(AXIS_VERSION, config.version)) {
2318 return false;
2319 }
2320 return true;
2321}
2322
2323status_t ResourceTable::flatten(Bundle* bundle, const sp<AaptFile>& dest)
2324{
2325 ResourceFilter filter;
2326 status_t err = filter.parse(bundle->getConfigurations());
2327 if (err != NO_ERROR) {
2328 return err;
2329 }
2330
2331 const size_t N = mOrderedPackages.size();
2332 size_t pi;
2333
2334 // Iterate through all data, collecting all values (strings,
2335 // references, etc).
2336 StringPool valueStrings;
2337 for (pi=0; pi<N; pi++) {
2338 sp<Package> p = mOrderedPackages.itemAt(pi);
2339 if (p->getTypes().size() == 0) {
2340 // Empty, skip!
2341 continue;
2342 }
2343
2344 StringPool typeStrings;
2345 StringPool keyStrings;
2346
2347 const size_t N = p->getOrderedTypes().size();
2348 for (size_t ti=0; ti<N; ti++) {
2349 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2350 if (t == NULL) {
2351 typeStrings.add(String16("<empty>"), false);
2352 continue;
2353 }
2354 typeStrings.add(t->getName(), false);
2355
2356 const size_t N = t->getOrderedConfigs().size();
2357 for (size_t ci=0; ci<N; ci++) {
2358 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2359 if (c == NULL) {
2360 continue;
2361 }
2362 const size_t N = c->getEntries().size();
2363 for (size_t ei=0; ei<N; ei++) {
2364 ConfigDescription config = c->getEntries().keyAt(ei);
2365 if (!filter.match(config)) {
2366 continue;
2367 }
2368 sp<Entry> e = c->getEntries().valueAt(ei);
2369 if (e == NULL) {
2370 continue;
2371 }
2372 e->setNameIndex(keyStrings.add(e->getName(), true));
2373 status_t err = e->prepareFlatten(&valueStrings, this);
2374 if (err != NO_ERROR) {
2375 return err;
2376 }
2377 }
2378 }
2379 }
2380
2381 p->setTypeStrings(typeStrings.createStringBlock());
2382 p->setKeyStrings(keyStrings.createStringBlock());
2383 }
2384
2385 ssize_t strAmt = 0;
2386
2387 // Now build the array of package chunks.
2388 Vector<sp<AaptFile> > flatPackages;
2389 for (pi=0; pi<N; pi++) {
2390 sp<Package> p = mOrderedPackages.itemAt(pi);
2391 if (p->getTypes().size() == 0) {
2392 // Empty, skip!
2393 continue;
2394 }
2395
2396 const size_t N = p->getTypeStrings().size();
2397
2398 const size_t baseSize = sizeof(ResTable_package);
2399
2400 // Start the package data.
2401 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2402 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2403 if (header == NULL) {
2404 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2405 return NO_MEMORY;
2406 }
2407 memset(header, 0, sizeof(*header));
2408 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2409 header->header.headerSize = htods(sizeof(*header));
2410 header->id = htodl(p->getAssignedId());
2411 strcpy16_htod(header->name, p->getName().string());
2412
2413 // Write the string blocks.
2414 const size_t typeStringsStart = data->getSize();
2415 sp<AaptFile> strFile = p->getTypeStringsData();
2416 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
2417 #if PRINT_STRING_METRICS
2418 fprintf(stderr, "**** type strings: %d\n", amt);
2419 #endif
2420 strAmt += amt;
2421 if (amt < 0) {
2422 return amt;
2423 }
2424 const size_t keyStringsStart = data->getSize();
2425 strFile = p->getKeyStringsData();
2426 amt = data->writeData(strFile->getData(), strFile->getSize());
2427 #if PRINT_STRING_METRICS
2428 fprintf(stderr, "**** key strings: %d\n", amt);
2429 #endif
2430 strAmt += amt;
2431 if (amt < 0) {
2432 return amt;
2433 }
2434
2435 // Build the type chunks inside of this package.
2436 for (size_t ti=0; ti<N; ti++) {
2437 // Retrieve them in the same order as the type string block.
2438 size_t len;
2439 String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2440 sp<Type> t = p->getTypes().valueFor(typeName);
2441 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2442 "Type name %s not found",
2443 String8(typeName).string());
2444
2445 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
2446
2447 // First write the typeSpec chunk, containing information about
2448 // each resource entry in this type.
2449 {
2450 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2451 const size_t typeSpecStart = data->getSize();
2452 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2453 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
2454 if (tsHeader == NULL) {
2455 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
2456 return NO_MEMORY;
2457 }
2458 memset(tsHeader, 0, sizeof(*tsHeader));
2459 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
2460 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
2461 tsHeader->header.size = htodl(typeSpecSize);
2462 tsHeader->id = ti+1;
2463 tsHeader->entryCount = htodl(N);
2464
2465 uint32_t* typeSpecFlags = (uint32_t*)
2466 (((uint8_t*)data->editData())
2467 + typeSpecStart + sizeof(ResTable_typeSpec));
2468 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
2469
2470 for (size_t ei=0; ei<N; ei++) {
2471 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2472 if (cl->getPublic()) {
2473 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
2474 }
2475 const size_t CN = cl->getEntries().size();
2476 for (size_t ci=0; ci<CN; ci++) {
2477 if (!filter.match(cl->getEntries().keyAt(ci))) {
2478 continue;
2479 }
2480 for (size_t cj=ci+1; cj<CN; cj++) {
2481 if (!filter.match(cl->getEntries().keyAt(cj))) {
2482 continue;
2483 }
2484 typeSpecFlags[ei] |= htodl(
2485 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
2486 }
2487 }
2488 }
2489 }
2490
2491 // We need to write one type chunk for each configuration for
2492 // which we have entries in this type.
2493 const size_t NC = t->getUniqueConfigs().size();
2494
2495 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
2496
2497 for (size_t ci=0; ci<NC; ci++) {
2498 ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
2499
2500 NOISY(printf("Writing config %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2501 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
2502 ti+1,
2503 config.mcc, config.mnc,
2504 config.language[0] ? config.language[0] : '-',
2505 config.language[1] ? config.language[1] : '-',
2506 config.country[0] ? config.country[0] : '-',
2507 config.country[1] ? config.country[1] : '-',
2508 config.orientation,
2509 config.touchscreen,
2510 config.density,
2511 config.keyboard,
2512 config.inputFlags,
2513 config.navigation,
2514 config.screenWidth,
2515 config.screenHeight));
2516
2517 if (!filter.match(config)) {
2518 continue;
2519 }
2520
2521 const size_t typeStart = data->getSize();
2522
2523 ResTable_type* tHeader = (ResTable_type*)
2524 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
2525 if (tHeader == NULL) {
2526 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
2527 return NO_MEMORY;
2528 }
2529
2530 memset(tHeader, 0, sizeof(*tHeader));
2531 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
2532 tHeader->header.headerSize = htods(sizeof(*tHeader));
2533 tHeader->id = ti+1;
2534 tHeader->entryCount = htodl(N);
2535 tHeader->entriesStart = htodl(typeSize);
2536 tHeader->config = config;
2537 NOISY(printf("Writing type %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2538 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
2539 ti+1,
2540 tHeader->config.mcc, tHeader->config.mnc,
2541 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
2542 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
2543 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
2544 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
2545 tHeader->config.orientation,
2546 tHeader->config.touchscreen,
2547 tHeader->config.density,
2548 tHeader->config.keyboard,
2549 tHeader->config.inputFlags,
2550 tHeader->config.navigation,
2551 tHeader->config.screenWidth,
2552 tHeader->config.screenHeight));
2553 tHeader->config.swapHtoD();
2554
2555 // Build the entries inside of this type.
2556 for (size_t ei=0; ei<N; ei++) {
2557 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2558 sp<Entry> e = cl->getEntries().valueFor(config);
2559
2560 // Set the offset for this entry in its type.
2561 uint32_t* index = (uint32_t*)
2562 (((uint8_t*)data->editData())
2563 + typeStart + sizeof(ResTable_type));
2564 if (e != NULL) {
2565 index[ei] = htodl(data->getSize()-typeStart-typeSize);
2566
2567 // Create the entry.
2568 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
2569 if (amt < 0) {
2570 return amt;
2571 }
2572 } else {
2573 index[ei] = htodl(ResTable_type::NO_ENTRY);
2574 }
2575 }
2576
2577 // Fill in the rest of the type information.
2578 tHeader = (ResTable_type*)
2579 (((uint8_t*)data->editData()) + typeStart);
2580 tHeader->header.size = htodl(data->getSize()-typeStart);
2581 }
2582 }
2583
2584 // Fill in the rest of the package information.
2585 header = (ResTable_package*)data->editData();
2586 header->header.size = htodl(data->getSize());
2587 header->typeStrings = htodl(typeStringsStart);
2588 header->lastPublicType = htodl(p->getTypeStrings().size());
2589 header->keyStrings = htodl(keyStringsStart);
2590 header->lastPublicKey = htodl(p->getKeyStrings().size());
2591
2592 flatPackages.add(data);
2593 }
2594
2595 // And now write out the final chunks.
2596 const size_t dataStart = dest->getSize();
2597
2598 {
2599 // blah
2600 ResTable_header header;
2601 memset(&header, 0, sizeof(header));
2602 header.header.type = htods(RES_TABLE_TYPE);
2603 header.header.headerSize = htods(sizeof(header));
2604 header.packageCount = htodl(flatPackages.size());
2605 status_t err = dest->writeData(&header, sizeof(header));
2606 if (err != NO_ERROR) {
2607 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
2608 return err;
2609 }
2610 }
2611
2612 ssize_t strStart = dest->getSize();
2613 err = valueStrings.writeStringBlock(dest);
2614 if (err != NO_ERROR) {
2615 return err;
2616 }
2617
2618 ssize_t amt = (dest->getSize()-strStart);
2619 strAmt += amt;
2620 #if PRINT_STRING_METRICS
2621 fprintf(stderr, "**** value strings: %d\n", amt);
2622 fprintf(stderr, "**** total strings: %d\n", strAmt);
2623 #endif
2624
2625 for (pi=0; pi<flatPackages.size(); pi++) {
2626 err = dest->writeData(flatPackages[pi]->getData(),
2627 flatPackages[pi]->getSize());
2628 if (err != NO_ERROR) {
2629 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
2630 return err;
2631 }
2632 }
2633
2634 ResTable_header* header = (ResTable_header*)
2635 (((uint8_t*)dest->getData()) + dataStart);
2636 header->header.size = htodl(dest->getSize() - dataStart);
2637
2638 NOISY(aout << "Resource table:"
2639 << HexDump(dest->getData(), dest->getSize()) << endl);
2640
2641 #if PRINT_STRING_METRICS
2642 fprintf(stderr, "**** total resource table size: %d / %d%% strings\n",
2643 dest->getSize(), (strAmt*100)/dest->getSize());
2644 #endif
2645
2646 return NO_ERROR;
2647}
2648
2649void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
2650{
2651 fprintf(fp,
2652 "<!-- This file contains <public> resource definitions for all\n"
2653 " resources that were generated from the source data. -->\n"
2654 "\n"
2655 "<resources>\n");
2656
2657 writePublicDefinitions(package, fp, true);
2658 writePublicDefinitions(package, fp, false);
2659
2660 fprintf(fp,
2661 "\n"
2662 "</resources>\n");
2663}
2664
2665void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
2666{
2667 bool didHeader = false;
2668
2669 sp<Package> pkg = mPackages.valueFor(package);
2670 if (pkg != NULL) {
2671 const size_t NT = pkg->getOrderedTypes().size();
2672 for (size_t i=0; i<NT; i++) {
2673 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
2674 if (t == NULL) {
2675 continue;
2676 }
2677
2678 bool didType = false;
2679
2680 const size_t NC = t->getOrderedConfigs().size();
2681 for (size_t j=0; j<NC; j++) {
2682 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
2683 if (c == NULL) {
2684 continue;
2685 }
2686
2687 if (c->getPublic() != pub) {
2688 continue;
2689 }
2690
2691 if (!didType) {
2692 fprintf(fp, "\n");
2693 didType = true;
2694 }
2695 if (!didHeader) {
2696 if (pub) {
2697 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
2698 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
2699 } else {
2700 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
2701 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
2702 }
2703 didHeader = true;
2704 }
2705 if (!pub) {
2706 const size_t NE = c->getEntries().size();
2707 for (size_t k=0; k<NE; k++) {
2708 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
2709 if (pos.file != "") {
2710 fprintf(fp," <!-- Declared at %s:%d -->\n",
2711 pos.file.string(), pos.line);
2712 }
2713 }
2714 }
2715 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
2716 String8(t->getName()).string(),
2717 String8(c->getName()).string(),
2718 getResId(pkg, t, c->getEntryIndex()));
2719 }
2720 }
2721 }
2722}
2723
2724ResourceTable::Item::Item(const SourcePos& _sourcePos,
2725 bool _isId,
2726 const String16& _value,
2727 const Vector<StringPool::entry_style_span>* _style,
2728 int32_t _format)
2729 : sourcePos(_sourcePos)
2730 , isId(_isId)
2731 , value(_value)
2732 , format(_format)
2733 , bagKeyId(0)
2734 , evaluating(false)
2735{
2736 if (_style) {
2737 style = *_style;
2738 }
2739}
2740
2741status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
2742{
2743 if (mType == TYPE_BAG) {
2744 return NO_ERROR;
2745 }
2746 if (mType == TYPE_UNKNOWN) {
2747 mType = TYPE_BAG;
2748 return NO_ERROR;
2749 }
2750 sourcePos.error("Resource entry %s is already defined as a single item.\n"
2751 "%s:%d: Originally defined here.\n",
2752 String8(mName).string(),
2753 mItem.sourcePos.file.string(), mItem.sourcePos.line);
2754 return UNKNOWN_ERROR;
2755}
2756
2757status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
2758 const String16& value,
2759 const Vector<StringPool::entry_style_span>* style,
2760 int32_t format,
2761 const bool overwrite)
2762{
2763 Item item(sourcePos, false, value, style);
2764
2765 if (mType == TYPE_BAG) {
2766 const Item& item(mBag.valueAt(0));
2767 sourcePos.error("Resource entry %s is already defined as a bag.\n"
2768 "%s:%d: Originally defined here.\n",
2769 String8(mName).string(),
2770 item.sourcePos.file.string(), item.sourcePos.line);
2771 return UNKNOWN_ERROR;
2772 }
2773 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
2774 sourcePos.error("Resource entry %s is already defined.\n"
2775 "%s:%d: Originally defined here.\n",
2776 String8(mName).string(),
2777 mItem.sourcePos.file.string(), mItem.sourcePos.line);
2778 return UNKNOWN_ERROR;
2779 }
2780
2781 mType = TYPE_ITEM;
2782 mItem = item;
2783 mItemFormat = format;
2784 return NO_ERROR;
2785}
2786
2787status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
2788 const String16& key, const String16& value,
2789 const Vector<StringPool::entry_style_span>* style,
2790 bool replace, bool isId, int32_t format)
2791{
2792 status_t err = makeItABag(sourcePos);
2793 if (err != NO_ERROR) {
2794 return err;
2795 }
2796
2797 Item item(sourcePos, isId, value, style, format);
2798
2799 // XXX NOTE: there is an error if you try to have a bag with two keys,
2800 // one an attr and one an id, with the same name. Not something we
2801 // currently ever have to worry about.
2802 ssize_t origKey = mBag.indexOfKey(key);
2803 if (origKey >= 0) {
2804 if (!replace) {
2805 const Item& item(mBag.valueAt(origKey));
2806 sourcePos.error("Resource entry %s already has bag item %s.\n"
2807 "%s:%d: Originally defined here.\n",
2808 String8(mName).string(), String8(key).string(),
2809 item.sourcePos.file.string(), item.sourcePos.line);
2810 return UNKNOWN_ERROR;
2811 }
2812 //printf("Replacing %s with %s\n",
2813 // String8(mBag.valueFor(key).value).string(), String8(value).string());
2814 mBag.replaceValueFor(key, item);
2815 }
2816
2817 mBag.add(key, item);
2818 return NO_ERROR;
2819}
2820
76486813
RG
2821status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
2822{
2823 status_t err = makeItABag(sourcePos);
2824 if (err != NO_ERROR) {
2825 return err;
2826 }
2827
2828 mBag.clear();
2829 return NO_ERROR;
2830}
2831
a534180c
TAOSP
2832status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
2833 const String16& package)
2834{
2835 const String16 attr16("attr");
2836 const String16 id16("id");
2837 const size_t N = mBag.size();
2838 for (size_t i=0; i<N; i++) {
2839 const String16& key = mBag.keyAt(i);
2840 const Item& it = mBag.valueAt(i);
2841 if (it.isId) {
2842 if (!table->hasBagOrEntry(key, &id16, &package)) {
2843 String16 value("false");
2844 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
2845 id16, key, value);
2846 if (err != NO_ERROR) {
2847 return err;
2848 }
2849 }
2850 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
2851
2852#if 1
2853// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
2854// String8(key).string());
2855// const Item& item(mBag.valueAt(i));
2856// fprintf(stderr, "Referenced from file %s line %d\n",
2857// item.sourcePos.file.string(), item.sourcePos.line);
2858// return UNKNOWN_ERROR;
2859#else
2860 char numberStr[16];
2861 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
2862 status_t err = table->addBag(SourcePos("<generated>", 0), package,
2863 attr16, key, String16(""),
2864 String16("^type"),
2865 String16(numberStr), NULL, NULL);
2866 if (err != NO_ERROR) {
2867 return err;
2868 }
2869#endif
2870 }
2871 }
2872 return NO_ERROR;
2873}
2874
2875status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
2876 const String16& package)
2877{
2878 bool hasErrors = false;
2879
2880 if (mType == TYPE_BAG) {
2881 const char* errorMsg;
2882 const String16 style16("style");
2883 const String16 attr16("attr");
2884 const String16 id16("id");
2885 mParentId = 0;
2886 if (mParent.size() > 0) {
2887 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
2888 if (mParentId == 0) {
2889 mPos.error("Error retrieving parent for item: %s '%s'.\n",
2890 errorMsg, String8(mParent).string());
2891 hasErrors = true;
2892 }
2893 }
2894 const size_t N = mBag.size();
2895 for (size_t i=0; i<N; i++) {
2896 const String16& key = mBag.keyAt(i);
2897 Item& it = mBag.editValueAt(i);
2898 it.bagKeyId = table->getResId(key,
2899 it.isId ? &id16 : &attr16, NULL, &errorMsg);
2900 //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
2901 if (it.bagKeyId == 0) {
2902 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
2903 String8(it.isId ? id16 : attr16).string(),
2904 String8(key).string());
2905 hasErrors = true;
2906 }
2907 }
2908 }
2909 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
2910}
2911
2912status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table)
2913{
2914 if (mType == TYPE_ITEM) {
2915 Item& it = mItem;
2916 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
2917 if (!table->stringToValue(&it.parsedValue, strings,
2918 it.value, false, true, 0,
2919 &it.style, NULL, &ac, mItemFormat)) {
2920 return UNKNOWN_ERROR;
2921 }
2922 } else if (mType == TYPE_BAG) {
2923 const size_t N = mBag.size();
2924 for (size_t i=0; i<N; i++) {
2925 const String16& key = mBag.keyAt(i);
2926 Item& it = mBag.editValueAt(i);
2927 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
2928 if (!table->stringToValue(&it.parsedValue, strings,
2929 it.value, false, true, it.bagKeyId,
2930 &it.style, NULL, &ac, it.format)) {
2931 return UNKNOWN_ERROR;
2932 }
2933 }
2934 } else {
2935 mPos.error("Error: entry %s is not a single item or a bag.\n",
2936 String8(mName).string());
2937 return UNKNOWN_ERROR;
2938 }
2939 return NO_ERROR;
2940}
2941
2942ssize_t ResourceTable::Entry::flatten(Bundle* bundle, const sp<AaptFile>& data, bool isPublic)
2943{
2944 size_t amt = 0;
2945 ResTable_entry header;
2946 memset(&header, 0, sizeof(header));
2947 header.size = htods(sizeof(header));
2948 const type ty = this != NULL ? mType : TYPE_ITEM;
2949 if (this != NULL) {
2950 if (ty == TYPE_BAG) {
2951 header.flags |= htods(header.FLAG_COMPLEX);
2952 }
2953 if (isPublic) {
2954 header.flags |= htods(header.FLAG_PUBLIC);
2955 }
2956 header.key.index = htodl(mNameIndex);
2957 }
2958 if (ty != TYPE_BAG) {
2959 status_t err = data->writeData(&header, sizeof(header));
2960 if (err != NO_ERROR) {
2961 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
2962 return err;
2963 }
2964
2965 const Item& it = mItem;
2966 Res_value par;
2967 memset(&par, 0, sizeof(par));
2968 par.size = htods(it.parsedValue.size);
2969 par.dataType = it.parsedValue.dataType;
2970 par.res0 = it.parsedValue.res0;
2971 par.data = htodl(it.parsedValue.data);
2972 #if 0
2973 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
2974 String8(mName).string(), it.parsedValue.dataType,
2975 it.parsedValue.data, par.res0);
2976 #endif
2977 err = data->writeData(&par, it.parsedValue.size);
2978 if (err != NO_ERROR) {
2979 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
2980 return err;
2981 }
2982 amt += it.parsedValue.size;
2983 } else {
2984 size_t N = mBag.size();
2985 size_t i;
2986 // Create correct ordering of items.
2987 KeyedVector<uint32_t, const Item*> items;
2988 for (i=0; i<N; i++) {
2989 const Item& it = mBag.valueAt(i);
2990 items.add(it.bagKeyId, &it);
2991 }
2992 N = items.size();
2993
2994 ResTable_map_entry mapHeader;
2995 memcpy(&mapHeader, &header, sizeof(header));
2996 mapHeader.size = htods(sizeof(mapHeader));
2997 mapHeader.parent.ident = htodl(mParentId);
2998 mapHeader.count = htodl(N);
2999 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3000 if (err != NO_ERROR) {
3001 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3002 return err;
3003 }
3004
3005 for (i=0; i<N; i++) {
3006 const Item& it = *items.valueAt(i);
3007 ResTable_map map;
3008 map.name.ident = htodl(it.bagKeyId);
3009 map.value.size = htods(it.parsedValue.size);
3010 map.value.dataType = it.parsedValue.dataType;
3011 map.value.res0 = it.parsedValue.res0;
3012 map.value.data = htodl(it.parsedValue.data);
3013 err = data->writeData(&map, sizeof(map));
3014 if (err != NO_ERROR) {
3015 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3016 return err;
3017 }
3018 amt += sizeof(map);
3019 }
3020 }
3021 return amt;
3022}
3023
3024void ResourceTable::ConfigList::appendComment(const String16& comment,
3025 bool onlyIfEmpty)
3026{
3027 if (comment.size() <= 0) {
3028 return;
3029 }
3030 if (onlyIfEmpty && mComment.size() > 0) {
3031 return;
3032 }
3033 if (mComment.size() > 0) {
3034 mComment.append(String16("\n"));
3035 }
3036 mComment.append(comment);
3037}
3038
3039void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3040{
3041 if (comment.size() <= 0) {
3042 return;
3043 }
3044 if (mTypeComment.size() > 0) {
3045 mTypeComment.append(String16("\n"));
3046 }
3047 mTypeComment.append(comment);
3048}
3049
3050status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3051 const String16& name,
3052 const uint32_t ident)
3053{
3054 #if 0
3055 int32_t entryIdx = Res_GETENTRY(ident);
3056 if (entryIdx < 0) {
3057 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3058 String8(mName).string(), String8(name).string(), ident);
3059 return UNKNOWN_ERROR;
3060 }
3061 #endif
3062
3063 int32_t typeIdx = Res_GETTYPE(ident);
3064 if (typeIdx >= 0) {
3065 typeIdx++;
3066 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3067 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3068 " public identifiers (0x%x vs 0x%x).\n",
3069 String8(mName).string(), String8(name).string(),
3070 mPublicIndex, typeIdx);
3071 return UNKNOWN_ERROR;
3072 }
3073 mPublicIndex = typeIdx;
3074 }
3075
3076 if (mFirstPublicSourcePos == NULL) {
3077 mFirstPublicSourcePos = new SourcePos(sourcePos);
3078 }
3079
3080 if (mPublic.indexOfKey(name) < 0) {
3081 mPublic.add(name, Public(sourcePos, String16(), ident));
3082 } else {
3083 Public& p = mPublic.editValueFor(name);
3084 if (p.ident != ident) {
3085 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3086 " (0x%08x vs 0x%08x).\n"
3087 "%s:%d: Originally defined here.\n",
3088 String8(mName).string(), String8(name).string(), p.ident, ident,
3089 p.sourcePos.file.string(), p.sourcePos.line);
3090 return UNKNOWN_ERROR;
3091 }
3092 }
3093
3094 return NO_ERROR;
3095}
3096
3097sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3098 const SourcePos& sourcePos,
3099 const ResTable_config* config,
3100 bool doSetIndex)
3101{
3102 int pos = -1;
3103 sp<ConfigList> c = mConfigs.valueFor(entry);
3104 if (c == NULL) {
3105 c = new ConfigList(entry, sourcePos);
3106 mConfigs.add(entry, c);
3107 pos = (int)mOrderedConfigs.size();
3108 mOrderedConfigs.add(c);
3109 if (doSetIndex) {
3110 c->setEntryIndex(pos);
3111 }
3112 }
3113
3114 ConfigDescription cdesc;
3115 if (config) cdesc = *config;
3116
3117 sp<Entry> e = c->getEntries().valueFor(cdesc);
3118 if (e == NULL) {
3119 if (config != NULL) {
3120 NOISY(printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
3121 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
3122 sourcePos.file.string(), sourcePos.line,
3123 config->mcc, config->mnc,
3124 config->language[0] ? config->language[0] : '-',
3125 config->language[1] ? config->language[1] : '-',
3126 config->country[0] ? config->country[0] : '-',
3127 config->country[1] ? config->country[1] : '-',
3128 config->orientation,
3129 config->touchscreen,
3130 config->density,
3131 config->keyboard,
3132 config->inputFlags,
3133 config->navigation,
3134 config->screenWidth,
3135 config->screenHeight));
3136 } else {
3137 NOISY(printf("New entry at %s:%d: NULL config\n",
3138 sourcePos.file.string(), sourcePos.line));
3139 }
3140 e = new Entry(entry, sourcePos);
3141 c->addEntry(cdesc, e);
3142 /*
3143 if (doSetIndex) {
3144 if (pos < 0) {
3145 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3146 if (mOrderedConfigs[pos] == c) {
3147 break;
3148 }
3149 }
3150 if (pos >= (int)mOrderedConfigs.size()) {
3151 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3152 return NULL;
3153 }
3154 }
3155 e->setEntryIndex(pos);
3156 }
3157 */
3158 }
3159
3160 mUniqueConfigs.add(cdesc);
3161
3162 return e;
3163}
3164
3165status_t ResourceTable::Type::applyPublicEntryOrder()
3166{
3167 size_t N = mOrderedConfigs.size();
3168 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3169 bool hasError = false;
3170
3171 size_t i;
3172 for (i=0; i<N; i++) {
3173 mOrderedConfigs.replaceAt(NULL, i);
3174 }
3175
3176 const size_t NP = mPublic.size();
3177 //printf("Ordering %d configs from %d public defs\n", N, NP);
3178 size_t j;
3179 for (j=0; j<NP; j++) {
3180 const String16& name = mPublic.keyAt(j);
3181 const Public& p = mPublic.valueAt(j);
3182 int32_t idx = Res_GETENTRY(p.ident);
3183 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3184 // String8(mName).string(), String8(name).string(), p.ident, N);
3185 bool found = false;
3186 for (i=0; i<N; i++) {
3187 sp<ConfigList> e = origOrder.itemAt(i);
3188 //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3189 if (e->getName() == name) {
3190 if (idx >= (int32_t)mOrderedConfigs.size()) {
3191 p.sourcePos.error("Public entry identifier 0x%x entry index "
3192 "is larger than available symbols (index %d, total symbols %d).\n",
3193 p.ident, idx, mOrderedConfigs.size());
3194 hasError = true;
3195 } else if (mOrderedConfigs.itemAt(idx) == NULL) {
3196 e->setPublic(true);
3197 e->setPublicSourcePos(p.sourcePos);
3198 mOrderedConfigs.replaceAt(e, idx);
3199 origOrder.removeAt(i);
3200 N--;
3201 found = true;
3202 break;
3203 } else {
3204 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3205
3206 p.sourcePos.error("Multiple entry names declared for public entry"
3207 " identifier 0x%x in type %s (%s vs %s).\n"
3208 "%s:%d: Originally defined here.",
3209 idx+1, String8(mName).string(),
3210 String8(oe->getName()).string(),
3211 String8(name).string(),
3212 oe->getPublicSourcePos().file.string(),
3213 oe->getPublicSourcePos().line);
3214 hasError = true;
3215 }
3216 }
3217 }
3218
3219 if (!found) {
3220 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3221 String8(mName).string(), String8(name).string());
3222 hasError = true;
3223 }
3224 }
3225
3226 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3227
3228 if (N != origOrder.size()) {
3229 printf("Internal error: remaining private symbol count mismatch\n");
3230 N = origOrder.size();
3231 }
3232
3233 j = 0;
3234 for (i=0; i<N; i++) {
3235 sp<ConfigList> e = origOrder.itemAt(i);
3236 // There will always be enough room for the remaining entries.
3237 while (mOrderedConfigs.itemAt(j) != NULL) {
3238 j++;
3239 }
3240 mOrderedConfigs.replaceAt(e, j);
3241 j++;
3242 }
3243
3244 return hasError ? UNKNOWN_ERROR : NO_ERROR;
3245}
3246
3247ResourceTable::Package::Package(const String16& name, ssize_t includedId)
3248 : mName(name), mIncludedId(includedId),
3249 mTypeStringsMapping(0xffffffff),
3250 mKeyStringsMapping(0xffffffff)
3251{
3252}
3253
3254sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
3255 const SourcePos& sourcePos,
3256 bool doSetIndex)
3257{
3258 sp<Type> t = mTypes.valueFor(type);
3259 if (t == NULL) {
3260 t = new Type(type, sourcePos);
3261 mTypes.add(type, t);
3262 mOrderedTypes.add(t);
3263 if (doSetIndex) {
3264 // For some reason the type's index is set to one plus the index
3265 // in the mOrderedTypes list, rather than just the index.
3266 t->setIndex(mOrderedTypes.size());
3267 }
3268 }
3269 return t;
3270}
3271
3272status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
3273{
3274 mTypeStringsData = data;
3275 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
3276 if (err != NO_ERROR) {
3277 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
3278 }
3279 return err;
3280}
3281
3282status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
3283{
3284 mKeyStringsData = data;
3285 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
3286 if (err != NO_ERROR) {
3287 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
3288 }
3289 return err;
3290}
3291
3292status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
3293 ResStringPool* strings,
3294 DefaultKeyedVector<String16, uint32_t>* mappings)
3295{
3296 if (data->getData() == NULL) {
3297 return UNKNOWN_ERROR;
3298 }
3299
3300 NOISY(aout << "Setting restable string pool: "
3301 << HexDump(data->getData(), data->getSize()) << endl);
3302
3303 status_t err = strings->setTo(data->getData(), data->getSize());
3304 if (err == NO_ERROR) {
3305 const size_t N = strings->size();
3306 for (size_t i=0; i<N; i++) {
3307 size_t len;
3308 mappings->add(String16(strings->stringAt(i, &len)), i);
3309 }
3310 }
3311 return err;
3312}
3313
3314status_t ResourceTable::Package::applyPublicTypeOrder()
3315{
3316 size_t N = mOrderedTypes.size();
3317 Vector<sp<Type> > origOrder(mOrderedTypes);
3318
3319 size_t i;
3320 for (i=0; i<N; i++) {
3321 mOrderedTypes.replaceAt(NULL, i);
3322 }
3323
3324 for (i=0; i<N; i++) {
3325 sp<Type> t = origOrder.itemAt(i);
3326 int32_t idx = t->getPublicIndex();
3327 if (idx > 0) {
3328 idx--;
3329 while (idx >= (int32_t)mOrderedTypes.size()) {
3330 mOrderedTypes.add();
3331 }
3332 if (mOrderedTypes.itemAt(idx) != NULL) {
3333 sp<Type> ot = mOrderedTypes.itemAt(idx);
3334 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
3335 " identifier 0x%x (%s vs %s).\n"
3336 "%s:%d: Originally defined here.",
3337 idx, String8(ot->getName()).string(),
3338 String8(t->getName()).string(),
3339 ot->getFirstPublicSourcePos().file.string(),
3340 ot->getFirstPublicSourcePos().line);
3341 return UNKNOWN_ERROR;
3342 }
3343 mOrderedTypes.replaceAt(t, idx);
3344 origOrder.removeAt(i);
3345 i--;
3346 N--;
3347 }
3348 }
3349
3350 size_t j=0;
3351 for (i=0; i<N; i++) {
3352 sp<Type> t = origOrder.itemAt(i);
3353 // There will always be enough room for the remaining types.
3354 while (mOrderedTypes.itemAt(j) != NULL) {
3355 j++;
3356 }
3357 mOrderedTypes.replaceAt(t, j);
3358 }
3359
3360 return NO_ERROR;
3361}
3362
3363sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
3364{
3365 sp<Package> p = mPackages.valueFor(package);
3366 if (p == NULL) {
3367 if (mIsAppPackage) {
3368 if (mHaveAppPackage) {
3369 fprintf(stderr, "Adding multiple application package resources; only one is allowed.\n"
3370 "Use -x to create extended resources.\n");
3371 return NULL;
3372 }
3373 mHaveAppPackage = true;
3374 p = new Package(package, 127);
3375 } else {
3376 p = new Package(package, mNextPackageId);
3377 }
3378 //printf("*** NEW PACKAGE: \"%s\" id=%d\n",
3379 // String8(package).string(), p->getAssignedId());
3380 mPackages.add(package, p);
3381 mOrderedPackages.add(p);
3382 mNextPackageId++;
3383 }
3384 return p;
3385}
3386
3387sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
3388 const String16& type,
3389 const SourcePos& sourcePos,
3390 bool doSetIndex)
3391{
3392 sp<Package> p = getPackage(package);
3393 if (p == NULL) {
3394 return NULL;
3395 }
3396 return p->getType(type, sourcePos, doSetIndex);
3397}
3398
3399sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
3400 const String16& type,
3401 const String16& name,
3402 const SourcePos& sourcePos,
3403 const ResTable_config* config,
3404 bool doSetIndex)
3405{
3406 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
3407 if (t == NULL) {
3408 return NULL;
3409 }
3410 return t->getEntry(name, sourcePos, config, doSetIndex);
3411}
3412
3413sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
3414 const ResTable_config* config) const
3415{
3416 int pid = Res_GETPACKAGE(resID)+1;
3417 const size_t N = mOrderedPackages.size();
3418 size_t i;
3419 sp<Package> p;
3420 for (i=0; i<N; i++) {
3421 sp<Package> check = mOrderedPackages[i];
3422 if (check->getAssignedId() == pid) {
3423 p = check;
3424 break;
3425 }
3426
3427 }
3428 if (p == NULL) {
3429 fprintf(stderr, "WARNING: Package not found for resource #%08x\n", resID);
3430 return NULL;
3431 }
3432
3433 int tid = Res_GETTYPE(resID);
3434 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
3435 fprintf(stderr, "WARNING: Type not found for resource #%08x\n", resID);
3436 return NULL;
3437 }
3438 sp<Type> t = p->getOrderedTypes()[tid];
3439
3440 int eid = Res_GETENTRY(resID);
3441 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
3442 fprintf(stderr, "WARNING: Entry not found for resource #%08x\n", resID);
3443 return NULL;
3444 }
3445
3446 sp<ConfigList> c = t->getOrderedConfigs()[eid];
3447 if (c == NULL) {
3448 fprintf(stderr, "WARNING: Entry not found for resource #%08x\n", resID);
3449 return NULL;
3450 }
3451
3452 ConfigDescription cdesc;
3453 if (config) cdesc = *config;
3454 sp<Entry> e = c->getEntries().valueFor(cdesc);
3455 if (c == NULL) {
3456 fprintf(stderr, "WARNING: Entry configuration not found for resource #%08x\n", resID);
3457 return NULL;
3458 }
3459
3460 return e;
3461}
3462
3463const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
3464{
3465 sp<const Entry> e = getEntry(resID);
3466 if (e == NULL) {
3467 return NULL;
3468 }
3469
3470 const size_t N = e->getBag().size();
3471 for (size_t i=0; i<N; i++) {
3472 const Item& it = e->getBag().valueAt(i);
3473 if (it.bagKeyId == 0) {
3474 fprintf(stderr, "WARNING: ID not yet assigned to '%s' in bag '%s'\n",
3475 String8(e->getName()).string(),
3476 String8(e->getBag().keyAt(i)).string());
3477 }
3478 if (it.bagKeyId == attrID) {
3479 return &it;
3480 }
3481 }
3482
3483 return NULL;
3484}
3485
3486bool ResourceTable::getItemValue(
3487 uint32_t resID, uint32_t attrID, Res_value* outValue)
3488{
3489 const Item* item = getItem(resID, attrID);
3490
3491 bool res = false;
3492 if (item != NULL) {
3493 if (item->evaluating) {
3494 sp<const Entry> e = getEntry(resID);
3495 const size_t N = e->getBag().size();
3496 size_t i;
3497 for (i=0; i<N; i++) {
3498 if (&e->getBag().valueAt(i) == item) {
3499 break;
3500 }
3501 }
3502 fprintf(stderr, "WARNING: Circular reference detected in key '%s' of bag '%s'\n",
3503 String8(e->getName()).string(),
3504 String8(e->getBag().keyAt(i)).string());
3505 return false;
3506 }
3507 item->evaluating = true;
3508 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
3509 NOISY(
3510 if (res) {
3511 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
3512 resID, attrID, String8(getEntry(resID)->getName()).string(),
3513 outValue->dataType, outValue->data);
3514 } else {
3515 printf("getItemValue of #%08x[#%08x]: failed\n",
3516 resID, attrID);
3517 }
3518 );
3519 item->evaluating = false;
3520 }
3521 return res;
3522}