]> git.saurik.com Git - android/aapt.git/blame - ResourceTable.cpp
am 6f9e2c64: Merge "Find layout classes in all "layout-*" dirs." into eclair
[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 }
7e486e33
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."));
3ff93dd6 483 enumOrFlagsComment.append(String16("</p>\n<table>\n"
a534180c
TAOSP
484 "<colgroup align=\"left\" />\n"
485 "<colgroup align=\"left\" />\n"
486 "<colgroup align=\"left\" />\n"
3ff93dd6 487 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>"));
a534180c
TAOSP
488 }
489
3ff93dd6 490 enumOrFlagsComment.append(String16("\n<tr><td><code>"));
a534180c 491 enumOrFlagsComment.append(itemIdent);
3ff93dd6 492 enumOrFlagsComment.append(String16("</code></td><td>"));
a534180c 493 enumOrFlagsComment.append(value);
3ff93dd6 494 enumOrFlagsComment.append(String16("</td><td>"));
a534180c
TAOSP
495 if (block.getComment(&len)) {
496 enumOrFlagsComment.append(String16(block.getComment(&len)));
497 }
3ff93dd6 498 enumOrFlagsComment.append(String16("</td></tr>"));
a534180c
TAOSP
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");
3b8452c9 664 const String16 public_padding16("public-padding");
a534180c 665 const String16 private_symbols16("private-symbols");
a8c9cd56 666 const String16 add_resource16("add-resource");
a534180c
TAOSP
667 const String16 skip16("skip");
668 const String16 eat_comment16("eat-comment");
669
670 // Data creation tags.
671 const String16 bag16("bag");
672 const String16 item16("item");
673
674 // Attribute type constants.
675 const String16 enum16("enum");
676
677 // plural values
678 const String16 other16("other");
679 const String16 quantityOther16("^other");
680 const String16 zero16("zero");
681 const String16 quantityZero16("^zero");
682 const String16 one16("one");
683 const String16 quantityOne16("^one");
684 const String16 two16("two");
685 const String16 quantityTwo16("^two");
686 const String16 few16("few");
687 const String16 quantityFew16("^few");
688 const String16 many16("many");
689 const String16 quantityMany16("^many");
690
691 // useful attribute names and special values
692 const String16 name16("name");
693 const String16 translatable16("translatable");
694 const String16 false16("false");
695
696 const String16 myPackage(assets->getPackage());
697
698 bool hasErrors = false;
699
3b8452c9 700 DefaultKeyedVector<String16, uint32_t> nextPublicId(0);
a534180c
TAOSP
701
702 ResXMLTree::event_code_t code;
703 do {
704 code = block.next();
705 } while (code == ResXMLTree::START_NAMESPACE);
706
707 size_t len;
708 if (code != ResXMLTree::START_TAG) {
709 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
710 "No start tag found\n");
711 return UNKNOWN_ERROR;
712 }
713 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
714 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
715 "Invalid start tag %s\n", String8(block.getElementName(&len)).string());
716 return UNKNOWN_ERROR;
717 }
718
719 ResTable_config curParams(defParams);
720
721 ResTable_config pseudoParams(curParams);
722 pseudoParams.language[0] = 'z';
723 pseudoParams.language[1] = 'z';
724 pseudoParams.country[0] = 'Z';
725 pseudoParams.country[1] = 'Z';
726
727 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
728 if (code == ResXMLTree::START_TAG) {
729 const String16* curTag = NULL;
730 String16 curType;
731 int32_t curFormat = ResTable_map::TYPE_ANY;
732 bool curIsBag = false;
eca7446f 733 bool curIsBagReplaceOnOverwrite = false;
a534180c
TAOSP
734 bool curIsStyled = false;
735 bool curIsPseudolocalizable = false;
736 bool localHasErrors = false;
737
738 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
739 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
740 && code != ResXMLTree::BAD_DOCUMENT) {
741 if (code == ResXMLTree::END_TAG) {
742 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
743 break;
744 }
745 }
746 }
747 continue;
748
749 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
750 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
751 && code != ResXMLTree::BAD_DOCUMENT) {
752 if (code == ResXMLTree::END_TAG) {
753 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
754 break;
755 }
756 }
757 }
758 continue;
759
760 } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
761 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
762
763 String16 type;
764 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
765 if (typeIdx < 0) {
766 srcPos.error("A 'type' attribute is required for <public>\n");
767 hasErrors = localHasErrors = true;
768 }
769 type = String16(block.getAttributeStringValue(typeIdx, &len));
770
771 String16 name;
772 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
773 if (nameIdx < 0) {
774 srcPos.error("A 'name' attribute is required for <public>\n");
775 hasErrors = localHasErrors = true;
776 }
777 name = String16(block.getAttributeStringValue(nameIdx, &len));
778
779 uint32_t ident = 0;
780 ssize_t identIdx = block.indexOfAttribute(NULL, "id");
781 if (identIdx >= 0) {
782 const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
783 Res_value identValue;
784 if (!ResTable::stringToInt(identStr, len, &identValue)) {
785 srcPos.error("Given 'id' attribute is not an integer: %s\n",
786 String8(block.getAttributeStringValue(identIdx, &len)).string());
787 hasErrors = localHasErrors = true;
788 } else {
789 ident = identValue.data;
3b8452c9 790 nextPublicId.replaceValueFor(type, ident+1);
a534180c 791 }
3b8452c9 792 } else if (nextPublicId.indexOfKey(type) < 0) {
a534180c
TAOSP
793 srcPos.error("No 'id' attribute supplied <public>,"
794 " and no previous id defined in this file.\n");
795 hasErrors = localHasErrors = true;
796 } else if (!localHasErrors) {
3b8452c9
DH
797 ident = nextPublicId.valueFor(type);
798 nextPublicId.replaceValueFor(type, ident+1);
a534180c
TAOSP
799 }
800
801 if (!localHasErrors) {
802 err = outTable->addPublic(srcPos, myPackage, type, name, ident);
803 if (err < NO_ERROR) {
804 hasErrors = localHasErrors = true;
805 }
806 }
807 if (!localHasErrors) {
808 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
809 if (symbols != NULL) {
810 symbols = symbols->addNestedSymbol(String8(type), srcPos);
811 }
812 if (symbols != NULL) {
813 symbols->makeSymbolPublic(String8(name), srcPos);
814 String16 comment(
815 block.getComment(&len) ? block.getComment(&len) : nulStr);
816 symbols->appendComment(String8(name), comment, srcPos);
817 } else {
818 srcPos.error("Unable to create symbols!\n");
819 hasErrors = localHasErrors = true;
820 }
821 }
822
823 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
824 if (code == ResXMLTree::END_TAG) {
825 if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
826 break;
827 }
828 }
829 }
830 continue;
831
3b8452c9
DH
832 } else if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
833 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
834
835 String16 type;
836 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
837 if (typeIdx < 0) {
838 srcPos.error("A 'type' attribute is required for <public-padding>\n");
839 hasErrors = localHasErrors = true;
840 }
841 type = String16(block.getAttributeStringValue(typeIdx, &len));
842
843 String16 name;
844 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
845 if (nameIdx < 0) {
846 srcPos.error("A 'name' attribute is required for <public-padding>\n");
847 hasErrors = localHasErrors = true;
848 }
849 name = String16(block.getAttributeStringValue(nameIdx, &len));
850
851 uint32_t start = 0;
852 ssize_t startIdx = block.indexOfAttribute(NULL, "start");
853 if (startIdx >= 0) {
854 const char16_t* startStr = block.getAttributeStringValue(startIdx, &len);
855 Res_value startValue;
856 if (!ResTable::stringToInt(startStr, len, &startValue)) {
857 srcPos.error("Given 'start' attribute is not an integer: %s\n",
858 String8(block.getAttributeStringValue(startIdx, &len)).string());
859 hasErrors = localHasErrors = true;
860 } else {
861 start = startValue.data;
862 }
863 } else if (nextPublicId.indexOfKey(type) < 0) {
864 srcPos.error("No 'start' attribute supplied <public-padding>,"
865 " and no previous id defined in this file.\n");
866 hasErrors = localHasErrors = true;
867 } else if (!localHasErrors) {
868 start = nextPublicId.valueFor(type);
869 }
870
871 uint32_t end = 0;
872 ssize_t endIdx = block.indexOfAttribute(NULL, "end");
873 if (endIdx >= 0) {
874 const char16_t* endStr = block.getAttributeStringValue(endIdx, &len);
875 Res_value endValue;
876 if (!ResTable::stringToInt(endStr, len, &endValue)) {
877 srcPos.error("Given 'end' attribute is not an integer: %s\n",
878 String8(block.getAttributeStringValue(endIdx, &len)).string());
879 hasErrors = localHasErrors = true;
880 } else {
881 end = endValue.data;
882 }
883 } else {
884 srcPos.error("No 'end' attribute supplied <public-padding>\n");
885 hasErrors = localHasErrors = true;
886 }
887
888 if (end >= start) {
889 nextPublicId.replaceValueFor(type, end+1);
890 } else {
891 srcPos.error("Padding start '%ul' is after end '%ul'\n",
892 start, end);
893 hasErrors = localHasErrors = true;
894 }
895
896 String16 comment(
897 block.getComment(&len) ? block.getComment(&len) : nulStr);
898 for (uint32_t curIdent=start; curIdent<=end; curIdent++) {
899 if (localHasErrors) {
900 break;
901 }
902 String16 curName(name);
903 char buf[64];
904 sprintf(buf, "%d", (int)(end-curIdent+1));
905 curName.append(String16(buf));
906
907 err = outTable->addEntry(srcPos, myPackage, type, curName,
908 String16("padding"), NULL, &curParams, false,
909 ResTable_map::TYPE_STRING, overwrite);
910 if (err < NO_ERROR) {
911 hasErrors = localHasErrors = true;
912 break;
913 }
914 err = outTable->addPublic(srcPos, myPackage, type,
915 curName, curIdent);
916 if (err < NO_ERROR) {
917 hasErrors = localHasErrors = true;
918 break;
919 }
920 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
921 if (symbols != NULL) {
922 symbols = symbols->addNestedSymbol(String8(type), srcPos);
923 }
924 if (symbols != NULL) {
925 symbols->makeSymbolPublic(String8(curName), srcPos);
926 symbols->appendComment(String8(curName), comment, srcPos);
927 } else {
928 srcPos.error("Unable to create symbols!\n");
929 hasErrors = localHasErrors = true;
930 }
931 }
932
933 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
934 if (code == ResXMLTree::END_TAG) {
935 if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
936 break;
937 }
938 }
939 }
940 continue;
941
a534180c
TAOSP
942 } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
943 String16 pkg;
944 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
945 if (pkgIdx < 0) {
946 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
947 "A 'package' attribute is required for <private-symbols>\n");
948 hasErrors = localHasErrors = true;
949 }
950 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
951 if (!localHasErrors) {
952 assets->setSymbolsPrivatePackage(String8(pkg));
953 }
954
955 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
956 if (code == ResXMLTree::END_TAG) {
957 if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
958 break;
959 }
960 }
961 }
962 continue;
963
a8c9cd56
DH
964 } else if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
965 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
966
967 String16 typeName;
968 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
969 if (typeIdx < 0) {
970 srcPos.error("A 'type' attribute is required for <add-resource>\n");
971 hasErrors = localHasErrors = true;
972 }
973 typeName = String16(block.getAttributeStringValue(typeIdx, &len));
974
975 String16 name;
976 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
977 if (nameIdx < 0) {
978 srcPos.error("A 'name' attribute is required for <add-resource>\n");
979 hasErrors = localHasErrors = true;
980 }
981 name = String16(block.getAttributeStringValue(nameIdx, &len));
982
983 outTable->canAddEntry(srcPos, myPackage, typeName, name);
984
985 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
986 if (code == ResXMLTree::END_TAG) {
706a572f 987 if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
a8c9cd56
DH
988 break;
989 }
990 }
991 }
992 continue;
993
a534180c
TAOSP
994 } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
995 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
996
997 String16 ident;
998 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
999 if (identIdx < 0) {
1000 srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
1001 hasErrors = localHasErrors = true;
1002 }
1003 ident = String16(block.getAttributeStringValue(identIdx, &len));
1004
1005 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1006 if (!localHasErrors) {
1007 if (symbols != NULL) {
1008 symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
1009 }
1010 sp<AaptSymbols> styleSymbols = symbols;
1011 if (symbols != NULL) {
1012 symbols = symbols->addNestedSymbol(String8(ident), srcPos);
1013 }
1014 if (symbols == NULL) {
1015 srcPos.error("Unable to create symbols!\n");
1016 return UNKNOWN_ERROR;
1017 }
1018
1019 String16 comment(
1020 block.getComment(&len) ? block.getComment(&len) : nulStr);
1021 styleSymbols->appendComment(String8(ident), comment, srcPos);
1022 } else {
1023 symbols = NULL;
1024 }
1025
1026 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1027 if (code == ResXMLTree::START_TAG) {
1028 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1029 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1030 && code != ResXMLTree::BAD_DOCUMENT) {
1031 if (code == ResXMLTree::END_TAG) {
1032 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1033 break;
1034 }
1035 }
1036 }
1037 continue;
1038 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1039 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1040 && code != ResXMLTree::BAD_DOCUMENT) {
1041 if (code == ResXMLTree::END_TAG) {
1042 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1043 break;
1044 }
1045 }
1046 }
1047 continue;
1048 } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
1049 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1050 "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
1051 String8(block.getElementName(&len)).string());
1052 return UNKNOWN_ERROR;
1053 }
1054
1055 String16 comment(
1056 block.getComment(&len) ? block.getComment(&len) : nulStr);
1057 String16 itemIdent;
1058 err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
1059 if (err != NO_ERROR) {
1060 hasErrors = localHasErrors = true;
1061 }
1062
1063 if (symbols != NULL) {
1064 SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
1065 symbols->addSymbol(String8(itemIdent), 0, srcPos);
1066 symbols->appendComment(String8(itemIdent), comment, srcPos);
1067 //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
1068 // String8(comment).string());
1069 }
1070 } else if (code == ResXMLTree::END_TAG) {
1071 if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1072 break;
1073 }
1074
1075 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1076 "Found tag </%s> where </attr> is expected\n",
1077 String8(block.getElementName(&len)).string());
1078 return UNKNOWN_ERROR;
1079 }
1080 }
1081 continue;
1082
1083 } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
1084 err = compileAttribute(in, block, myPackage, outTable, NULL);
1085 if (err != NO_ERROR) {
1086 hasErrors = true;
1087 }
1088 continue;
1089
1090 } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
1091 curTag = &item16;
1092 ssize_t attri = block.indexOfAttribute(NULL, "type");
1093 if (attri >= 0) {
1094 curType = String16(block.getAttributeStringValue(attri, &len));
1095 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1096 if (formatIdx >= 0) {
1097 String16 formatStr = String16(block.getAttributeStringValue(
1098 formatIdx, &len));
1099 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1100 gFormatFlags);
1101 if (curFormat == 0) {
1102 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1103 "Tag <item> 'format' attribute value \"%s\" not valid\n",
1104 String8(formatStr).string());
1105 hasErrors = localHasErrors = true;
1106 }
1107 }
1108 } else {
1109 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1110 "A 'type' attribute is required for <item>\n");
1111 hasErrors = localHasErrors = true;
1112 }
1113 curIsStyled = true;
1114 } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
1115 // Note the existence and locale of every string we process
1116 char rawLocale[16];
1117 curParams.getLocale(rawLocale);
1118 String8 locale(rawLocale);
1119 String16 name;
1120 String16 translatable;
1121
1122 size_t n = block.getAttributeCount();
1123 for (size_t i = 0; i < n; i++) {
1124 size_t length;
1125 const uint16_t* attr = block.getAttributeName(i, &length);
1126 if (strcmp16(attr, name16.string()) == 0) {
1127 name.setTo(block.getAttributeStringValue(i, &length));
1128 } else if (strcmp16(attr, translatable16.string()) == 0) {
1129 translatable.setTo(block.getAttributeStringValue(i, &length));
1130 }
1131 }
1132
1133 if (name.size() > 0) {
1134 if (translatable == false16) {
1135 // Untranslatable strings must only exist in the default [empty] locale
1136 if (locale.size() > 0) {
1137 fprintf(stderr, "aapt: warning: string '%s' in %s marked untranslatable but exists"
1138 " in locale '%s'\n", String8(name).string(),
1139 bundle->getResourceSourceDirs()[0],
1140 locale.string());
1141 // hasErrors = localHasErrors = true;
1142 } else {
1143 // Intentionally empty block:
1144 //
1145 // Don't add untranslatable strings to the localization table; that
1146 // way if we later see localizations of them, they'll be flagged as
1147 // having no default translation.
1148 }
1149 } else {
1150 outTable->addLocalization(name, locale);
1151 }
1152 }
1153
1154 curTag = &string16;
1155 curType = string16;
1156 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1157 curIsStyled = true;
1158 curIsPseudolocalizable = true;
1159 } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
1160 curTag = &drawable16;
1161 curType = drawable16;
1162 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1163 } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
1164 curTag = &color16;
1165 curType = color16;
1166 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1167 } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
1168 curTag = &bool16;
1169 curType = bool16;
1170 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
1171 } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
1172 curTag = &integer16;
1173 curType = integer16;
1174 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1175 } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
1176 curTag = &dimen16;
1177 curType = dimen16;
1178 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
1179 } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) {
1180 curTag = &fraction16;
1181 curType = fraction16;
1182 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
1183 } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
1184 curTag = &bag16;
1185 curIsBag = true;
1186 ssize_t attri = block.indexOfAttribute(NULL, "type");
1187 if (attri >= 0) {
1188 curType = String16(block.getAttributeStringValue(attri, &len));
1189 } else {
1190 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1191 "A 'type' attribute is required for <bag>\n");
1192 hasErrors = localHasErrors = true;
1193 }
1194 } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
1195 curTag = &style16;
1196 curType = style16;
1197 curIsBag = true;
1198 } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
1199 curTag = &plurals16;
1200 curType = plurals16;
1201 curIsBag = true;
1202 } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
1203 curTag = &array16;
1204 curType = array16;
1205 curIsBag = true;
eca7446f 1206 curIsBagReplaceOnOverwrite = true;
a534180c
TAOSP
1207 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1208 if (formatIdx >= 0) {
1209 String16 formatStr = String16(block.getAttributeStringValue(
1210 formatIdx, &len));
1211 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1212 gFormatFlags);
1213 if (curFormat == 0) {
1214 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1215 "Tag <array> 'format' attribute value \"%s\" not valid\n",
1216 String8(formatStr).string());
1217 hasErrors = localHasErrors = true;
1218 }
1219 }
1220 } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
1221 curTag = &string_array16;
1222 curType = array16;
1223 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1224 curIsBag = true;
eca7446f 1225 curIsBagReplaceOnOverwrite = true;
a534180c
TAOSP
1226 curIsPseudolocalizable = true;
1227 } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
1228 curTag = &integer_array16;
1229 curType = array16;
1230 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1231 curIsBag = true;
eca7446f 1232 curIsBagReplaceOnOverwrite = true;
a534180c
TAOSP
1233 } else {
1234 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1235 "Found tag %s where item is expected\n",
1236 String8(block.getElementName(&len)).string());
1237 return UNKNOWN_ERROR;
1238 }
1239
1240 String16 ident;
1241 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1242 if (identIdx >= 0) {
1243 ident = String16(block.getAttributeStringValue(identIdx, &len));
1244 } else {
1245 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1246 "A 'name' attribute is required for <%s>\n",
1247 String8(*curTag).string());
1248 hasErrors = localHasErrors = true;
1249 }
1250
1251 String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1252
1253 if (curIsBag) {
1254 // Figure out the parent of this bag...
1255 String16 parentIdent;
1256 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1257 if (parentIdentIdx >= 0) {
1258 parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1259 } else {
1260 ssize_t sep = ident.findLast('.');
1261 if (sep >= 0) {
1262 parentIdent.setTo(ident, sep);
1263 }
1264 }
1265
1266 if (!localHasErrors) {
eca7446f
RG
1267 err = outTable->startBag(SourcePos(in->getPrintableSource(),
1268 block.getLineNumber()), myPackage, curType, ident,
1269 parentIdent, &curParams,
1270 overwrite, curIsBagReplaceOnOverwrite);
a534180c
TAOSP
1271 if (err != NO_ERROR) {
1272 hasErrors = localHasErrors = true;
1273 }
1274 }
1275
1276 ssize_t elmIndex = 0;
1277 char elmIndexStr[14];
1278 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1279 && code != ResXMLTree::BAD_DOCUMENT) {
1280
1281 if (code == ResXMLTree::START_TAG) {
1282 if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
1283 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1284 "Tag <%s> can not appear inside <%s>, only <item>\n",
1285 String8(block.getElementName(&len)).string(),
1286 String8(*curTag).string());
1287 return UNKNOWN_ERROR;
1288 }
1289
1290 String16 itemIdent;
1291 if (curType == array16) {
1292 sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1293 itemIdent = String16(elmIndexStr);
1294 } else if (curType == plurals16) {
1295 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1296 if (itemIdentIdx >= 0) {
1297 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1298 if (quantity16 == other16) {
1299 itemIdent = quantityOther16;
1300 }
1301 else if (quantity16 == zero16) {
1302 itemIdent = quantityZero16;
1303 }
1304 else if (quantity16 == one16) {
1305 itemIdent = quantityOne16;
1306 }
1307 else if (quantity16 == two16) {
1308 itemIdent = quantityTwo16;
1309 }
1310 else if (quantity16 == few16) {
1311 itemIdent = quantityFew16;
1312 }
1313 else if (quantity16 == many16) {
1314 itemIdent = quantityMany16;
1315 }
1316 else {
1317 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1318 "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1319 hasErrors = localHasErrors = true;
1320 }
1321 } else {
1322 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1323 "A 'quantity' attribute is required for <item> inside <plurals>\n");
1324 hasErrors = localHasErrors = true;
1325 }
1326 } else {
1327 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1328 if (itemIdentIdx >= 0) {
1329 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1330 } else {
1331 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1332 "A 'name' attribute is required for <item>\n");
1333 hasErrors = localHasErrors = true;
1334 }
1335 }
1336
1337 ResXMLParser::ResXMLPosition parserPosition;
1338 block.getPosition(&parserPosition);
1339
1340 err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
1341 ident, parentIdent, itemIdent, curFormat,
1342 false, overwrite, outTable);
1343 if (err == NO_ERROR) {
1344 if (curIsPseudolocalizable && localeIsDefined(curParams)
1345 && bundle->getPseudolocalize()) {
1346 // pseudolocalize here
1347#if 1
1348 block.setPosition(parserPosition);
1349 err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1350 curType, ident, parentIdent, itemIdent, curFormat, true,
1351 overwrite, outTable);
1352#endif
1353 }
1354 }
1355 if (err != NO_ERROR) {
1356 hasErrors = localHasErrors = true;
1357 }
1358 } else if (code == ResXMLTree::END_TAG) {
1359 if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
1360 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1361 "Found tag </%s> where </%s> is expected\n",
1362 String8(block.getElementName(&len)).string(),
1363 String8(*curTag).string());
1364 return UNKNOWN_ERROR;
1365 }
1366 break;
1367 }
1368 }
1369 } else {
1370 ResXMLParser::ResXMLPosition parserPosition;
1371 block.getPosition(&parserPosition);
1372
1373 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
1374 *curTag, curIsStyled, curFormat, false, overwrite, outTable);
1375
1376 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1377 hasErrors = localHasErrors = true;
1378 }
1379 else if (err == NO_ERROR) {
1380 if (curIsPseudolocalizable && localeIsDefined(curParams)
1381 && bundle->getPseudolocalize()) {
1382 // pseudolocalize here
1383 block.setPosition(parserPosition);
1384 err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
03938ad3 1385 ident, *curTag, curIsStyled, curFormat, true, overwrite, outTable);
a534180c
TAOSP
1386 if (err != NO_ERROR) {
1387 hasErrors = localHasErrors = true;
1388 }
1389 }
1390 }
1391 }
1392
1393#if 0
1394 if (comment.size() > 0) {
1395 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
1396 String8(curType).string(), String8(ident).string(),
1397 String8(comment).string());
1398 }
1399#endif
1400 if (!localHasErrors) {
1401 outTable->appendComment(myPackage, curType, ident, comment, false);
1402 }
1403 }
1404 else if (code == ResXMLTree::END_TAG) {
1405 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
1406 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1407 "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
1408 return UNKNOWN_ERROR;
1409 }
1410 }
1411 else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1412 }
1413 else if (code == ResXMLTree::TEXT) {
1414 if (isWhitespace(block.getText(&len))) {
1415 continue;
1416 }
1417 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1418 "Found text \"%s\" where item tag is expected\n",
1419 String8(block.getText(&len)).string());
1420 return UNKNOWN_ERROR;
1421 }
1422 }
1423
1424 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1425}
1426
1427ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage)
1428 : mAssetsPackage(assetsPackage), mNextPackageId(1), mHaveAppPackage(false),
1429 mIsAppPackage(!bundle->getExtending()),
1430 mNumLocal(0),
1431 mBundle(bundle)
1432{
1433}
1434
1435status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1436{
1437 status_t err = assets->buildIncludedResources(bundle);
1438 if (err != NO_ERROR) {
1439 return err;
1440 }
1441
1442 // For future reference to included resources.
1443 mAssets = assets;
1444
1445 const ResTable& incl = assets->getIncludedResources();
1446
1447 // Retrieve all the packages.
1448 const size_t N = incl.getBasePackageCount();
1449 for (size_t phase=0; phase<2; phase++) {
1450 for (size_t i=0; i<N; i++) {
1451 String16 name(incl.getBasePackageName(i));
1452 uint32_t id = incl.getBasePackageId(i);
1453 // First time through: only add base packages (id
1454 // is not 0); second time through add the other
1455 // packages.
1456 if (phase != 0) {
1457 if (id != 0) {
1458 // Skip base packages -- already one.
1459 id = 0;
1460 } else {
1461 // Assign a dynamic id.
1462 id = mNextPackageId;
1463 }
1464 } else if (id != 0) {
1465 if (id == 127) {
1466 if (mHaveAppPackage) {
7e486e33 1467 fprintf(stderr, "Included resources have two application packages!\n");
a534180c
TAOSP
1468 return UNKNOWN_ERROR;
1469 }
1470 mHaveAppPackage = true;
1471 }
1472 if (mNextPackageId > id) {
1473 fprintf(stderr, "Included base package ID %d already in use!\n", id);
1474 return UNKNOWN_ERROR;
1475 }
1476 }
1477 if (id != 0) {
1478 NOISY(printf("Including package %s with ID=%d\n",
1479 String8(name).string(), id));
1480 sp<Package> p = new Package(name, id);
1481 mPackages.add(name, p);
1482 mOrderedPackages.add(p);
1483
1484 if (id >= mNextPackageId) {
1485 mNextPackageId = id+1;
1486 }
1487 }
1488 }
1489 }
1490
1491 // Every resource table always has one first entry, the bag attributes.
1492 const SourcePos unknown(String8("????"), 0);
1493 sp<Type> attr = getType(mAssetsPackage, String16("attr"), unknown);
1494
1495 return NO_ERROR;
1496}
1497
1498status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1499 const String16& package,
1500 const String16& type,
1501 const String16& name,
1502 const uint32_t ident)
1503{
1504 uint32_t rid = mAssets->getIncludedResources()
1505 .identifierForName(name.string(), name.size(),
1506 type.string(), type.size(),
1507 package.string(), package.size());
1508 if (rid != 0) {
1509 sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
1510 String8(type).string(), String8(name).string(),
1511 String8(package).string());
1512 return UNKNOWN_ERROR;
1513 }
1514
1515 sp<Type> t = getType(package, type, sourcePos);
1516 if (t == NULL) {
1517 return UNKNOWN_ERROR;
1518 }
1519 return t->addPublic(sourcePos, name, ident);
1520}
1521
1522status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1523 const String16& package,
1524 const String16& type,
1525 const String16& name,
1526 const String16& value,
1527 const Vector<StringPool::entry_style_span>* style,
1528 const ResTable_config* params,
1529 const bool doSetIndex,
1530 const int32_t format,
1531 const bool overwrite)
1532{
1533 // Check for adding entries in other packages... for now we do
1534 // nothing. We need to do the right thing here to support skinning.
1535 uint32_t rid = mAssets->getIncludedResources()
1536 .identifierForName(name.string(), name.size(),
1537 type.string(), type.size(),
1538 package.string(), package.size());
1539 if (rid != 0) {
1540 return NO_ERROR;
1541 }
1542
1543#if 0
1544 if (name == String16("left")) {
1545 printf("Adding entry left: file=%s, line=%d, type=%s, value=%s\n",
1546 sourcePos.file.string(), sourcePos.line, String8(type).string(),
1547 String8(value).string());
1548 }
1549#endif
6c9f72e4
RG
1550
1551 sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite,
1552 params, doSetIndex);
a534180c
TAOSP
1553 if (e == NULL) {
1554 return UNKNOWN_ERROR;
1555 }
1556 status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1557 if (err == NO_ERROR) {
1558 mNumLocal++;
1559 }
1560 return err;
1561}
1562
1563status_t ResourceTable::startBag(const SourcePos& sourcePos,
1564 const String16& package,
1565 const String16& type,
1566 const String16& name,
1567 const String16& bagParent,
1568 const ResTable_config* params,
eca7446f 1569 bool overlay,
a534180c
TAOSP
1570 bool replace, bool isId)
1571{
76486813
RG
1572 status_t result = NO_ERROR;
1573
a534180c
TAOSP
1574 // Check for adding entries in other packages... for now we do
1575 // nothing. We need to do the right thing here to support skinning.
1576 uint32_t rid = mAssets->getIncludedResources()
1577 .identifierForName(name.string(), name.size(),
1578 type.string(), type.size(),
1579 package.string(), package.size());
1580 if (rid != 0) {
1581 return NO_ERROR;
1582 }
1583
1584#if 0
1585 if (name == String16("left")) {
1586 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1587 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1588 }
1589#endif
eca7446f 1590 if (overlay && !hasBagOrEntry(package, type, name)) {
a8c9cd56
DH
1591 bool canAdd = false;
1592 sp<Package> p = mPackages.valueFor(package);
1593 if (p != NULL) {
1594 sp<Type> t = p->getTypes().valueFor(type);
1595 if (t != NULL) {
1596 if (t->getCanAddEntries().indexOf(name) >= 0) {
1597 canAdd = true;
1598 }
1599 }
1600 }
1601 if (!canAdd) {
1602 sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
1603 String8(name).string());
1604 return UNKNOWN_ERROR;
1605 }
eca7446f 1606 }
6c9f72e4 1607 sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params);
a534180c
TAOSP
1608 if (e == NULL) {
1609 return UNKNOWN_ERROR;
1610 }
1611
1612 // If a parent is explicitly specified, set it.
1613 if (bagParent.size() > 0) {
1614 String16 curPar = e->getParent();
1615 if (curPar.size() > 0 && curPar != bagParent) {
1616 sourcePos.error("Conflicting parents specified, was '%s', now '%s'\n",
1617 String8(e->getParent()).string(),
1618 String8(bagParent).string());
1619 return UNKNOWN_ERROR;
1620 }
1621 e->setParent(bagParent);
1622 }
76486813
RG
1623
1624 if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1625 return result;
1626 }
9d911eb6 1627
eca7446f 1628 if (overlay && replace) {
9d911eb6
RG
1629 return e->emptyBag(sourcePos);
1630 }
1631 return result;
a534180c
TAOSP
1632}
1633
1634status_t ResourceTable::addBag(const SourcePos& sourcePos,
1635 const String16& package,
1636 const String16& type,
1637 const String16& name,
1638 const String16& bagParent,
1639 const String16& bagKey,
1640 const String16& value,
1641 const Vector<StringPool::entry_style_span>* style,
1642 const ResTable_config* params,
1643 bool replace, bool isId, const int32_t format)
1644{
1645 // Check for adding entries in other packages... for now we do
1646 // nothing. We need to do the right thing here to support skinning.
1647 uint32_t rid = mAssets->getIncludedResources()
1648 .identifierForName(name.string(), name.size(),
1649 type.string(), type.size(),
1650 package.string(), package.size());
1651 if (rid != 0) {
1652 return NO_ERROR;
1653 }
1654
1655#if 0
1656 if (name == String16("left")) {
1657 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1658 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1659 }
1660#endif
6c9f72e4 1661 sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
a534180c
TAOSP
1662 if (e == NULL) {
1663 return UNKNOWN_ERROR;
1664 }
1665
1666 // If a parent is explicitly specified, set it.
1667 if (bagParent.size() > 0) {
1668 String16 curPar = e->getParent();
1669 if (curPar.size() > 0 && curPar != bagParent) {
1670 sourcePos.error("Conflicting parents specified, was '%s', now '%s'\n",
1671 String8(e->getParent()).string(),
1672 String8(bagParent).string());
1673 return UNKNOWN_ERROR;
1674 }
1675 e->setParent(bagParent);
1676 }
1677
1678 const bool first = e->getBag().indexOfKey(bagKey) < 0;
1679 status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1680 if (err == NO_ERROR && first) {
1681 mNumLocal++;
1682 }
1683 return err;
1684}
1685
1686bool ResourceTable::hasBagOrEntry(const String16& package,
1687 const String16& type,
1688 const String16& name) const
1689{
1690 // First look for this in the included resources...
1691 uint32_t rid = mAssets->getIncludedResources()
1692 .identifierForName(name.string(), name.size(),
1693 type.string(), type.size(),
1694 package.string(), package.size());
1695 if (rid != 0) {
1696 return true;
1697 }
1698
1699 sp<Package> p = mPackages.valueFor(package);
1700 if (p != NULL) {
1701 sp<Type> t = p->getTypes().valueFor(type);
1702 if (t != NULL) {
1703 sp<ConfigList> c = t->getConfigs().valueFor(name);
1704 if (c != NULL) return true;
1705 }
1706 }
1707
1708 return false;
1709}
1710
1711bool ResourceTable::hasBagOrEntry(const String16& ref,
1712 const String16* defType,
1713 const String16* defPackage)
1714{
1715 String16 package, type, name;
1716 if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
1717 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
1718 return false;
1719 }
1720 return hasBagOrEntry(package, type, name);
1721}
1722
1723bool ResourceTable::appendComment(const String16& package,
1724 const String16& type,
1725 const String16& name,
1726 const String16& comment,
1727 bool onlyIfEmpty)
1728{
1729 if (comment.size() <= 0) {
1730 return true;
1731 }
1732
1733 sp<Package> p = mPackages.valueFor(package);
1734 if (p != NULL) {
1735 sp<Type> t = p->getTypes().valueFor(type);
1736 if (t != NULL) {
1737 sp<ConfigList> c = t->getConfigs().valueFor(name);
1738 if (c != NULL) {
1739 c->appendComment(comment, onlyIfEmpty);
1740 return true;
1741 }
1742 }
1743 }
1744 return false;
1745}
1746
1747bool ResourceTable::appendTypeComment(const String16& package,
1748 const String16& type,
1749 const String16& name,
1750 const String16& comment)
1751{
1752 if (comment.size() <= 0) {
1753 return true;
1754 }
1755
1756 sp<Package> p = mPackages.valueFor(package);
1757 if (p != NULL) {
1758 sp<Type> t = p->getTypes().valueFor(type);
1759 if (t != NULL) {
1760 sp<ConfigList> c = t->getConfigs().valueFor(name);
1761 if (c != NULL) {
1762 c->appendTypeComment(comment);
1763 return true;
1764 }
1765 }
1766 }
1767 return false;
1768}
1769
a8c9cd56
DH
1770void ResourceTable::canAddEntry(const SourcePos& pos,
1771 const String16& package, const String16& type, const String16& name)
1772{
1773 sp<Type> t = getType(package, type, pos);
1774 if (t != NULL) {
1775 t->canAddEntry(name);
1776 }
1777}
1778
a534180c
TAOSP
1779size_t ResourceTable::size() const {
1780 return mPackages.size();
1781}
1782
1783size_t ResourceTable::numLocalResources() const {
1784 return mNumLocal;
1785}
1786
1787bool ResourceTable::hasResources() const {
1788 return mNumLocal > 0;
1789}
1790
1791sp<AaptFile> ResourceTable::flatten(Bundle* bundle)
1792{
1793 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
1794 status_t err = flatten(bundle, data);
1795 return err == NO_ERROR ? data : NULL;
1796}
1797
1798inline uint32_t ResourceTable::getResId(const sp<Package>& p,
1799 const sp<Type>& t,
1800 uint32_t nameId)
1801{
1802 return makeResId(p->getAssignedId(), t->getIndex(), nameId);
1803}
1804
1805uint32_t ResourceTable::getResId(const String16& package,
1806 const String16& type,
1807 const String16& name,
1808 bool onlyPublic) const
1809{
1810 sp<Package> p = mPackages.valueFor(package);
1811 if (p == NULL) return 0;
1812
1813 // First look for this in the included resources...
1814 uint32_t specFlags = 0;
1815 uint32_t rid = mAssets->getIncludedResources()
1816 .identifierForName(name.string(), name.size(),
1817 type.string(), type.size(),
1818 package.string(), package.size(),
1819 &specFlags);
1820 if (rid != 0) {
1821 if (onlyPublic) {
1822 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
1823 return 0;
1824 }
1825 }
1826
1827 if (Res_INTERNALID(rid)) {
1828 return rid;
1829 }
1830 return Res_MAKEID(p->getAssignedId()-1,
1831 Res_GETTYPE(rid),
1832 Res_GETENTRY(rid));
1833 }
1834
1835 sp<Type> t = p->getTypes().valueFor(type);
1836 if (t == NULL) return 0;
1837 sp<ConfigList> c = t->getConfigs().valueFor(name);
1838 if (c == NULL) return 0;
1839 int32_t ei = c->getEntryIndex();
1840 if (ei < 0) return 0;
1841 return getResId(p, t, ei);
1842}
1843
1844uint32_t ResourceTable::getResId(const String16& ref,
1845 const String16* defType,
1846 const String16* defPackage,
1847 const char** outErrorMsg,
1848 bool onlyPublic) const
1849{
1850 String16 package, type, name;
1851 if (!ResTable::expandResourceRef(
1852 ref.string(), ref.size(), &package, &type, &name,
1853 defType, defPackage ? defPackage:&mAssetsPackage,
1854 outErrorMsg)) {
1855 NOISY(printf("Expanding resource: ref=%s\n",
1856 String8(ref).string()));
1857 NOISY(printf("Expanding resource: defType=%s\n",
1858 defType ? String8(*defType).string() : "NULL"));
1859 NOISY(printf("Expanding resource: defPackage=%s\n",
1860 defPackage ? String8(*defPackage).string() : "NULL"));
1861 NOISY(printf("Expanding resource: ref=%s\n", String8(ref).string()));
1862 NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
1863 String8(package).string(), String8(type).string(),
1864 String8(name).string()));
1865 return 0;
1866 }
1867 uint32_t res = getResId(package, type, name, onlyPublic);
1868 NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
1869 String8(package).string(), String8(type).string(),
1870 String8(name).string(), res));
1871 if (res == 0) {
1872 if (outErrorMsg)
1873 *outErrorMsg = "No resource found that matches the given name";
1874 }
1875 return res;
1876}
1877
1878bool ResourceTable::isValidResourceName(const String16& s)
1879{
1880 const char16_t* p = s.string();
1881 bool first = true;
1882 while (*p) {
1883 if ((*p >= 'a' && *p <= 'z')
1884 || (*p >= 'A' && *p <= 'Z')
1885 || *p == '_'
1886 || (!first && *p >= '0' && *p <= '9')) {
1887 first = false;
1888 p++;
1889 continue;
1890 }
1891 return false;
1892 }
1893 return true;
1894}
1895
1896bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
1897 const String16& str,
1898 bool preserveSpaces, bool coerceType,
1899 uint32_t attrID,
1900 const Vector<StringPool::entry_style_span>* style,
1901 String16* outStr, void* accessorCookie,
1902 uint32_t attrType)
1903{
1904 String16 finalStr;
1905
1906 bool res = true;
1907 if (style == NULL || style->size() == 0) {
1908 // Text is not styled so it can be any type... let's figure it out.
1909 res = mAssets->getIncludedResources()
1910 .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
1911 coerceType, attrID, NULL, &mAssetsPackage, this,
1912 accessorCookie, attrType);
1913 } else {
1914 // Styled text can only be a string, and while collecting the style
1915 // information we have already processed that string!
1916 outValue->size = sizeof(Res_value);
1917 outValue->res0 = 0;
1918 outValue->dataType = outValue->TYPE_STRING;
1919 outValue->data = 0;
1920 finalStr = str;
1921 }
1922
1923 if (!res) {
1924 return false;
1925 }
1926
1927 if (outValue->dataType == outValue->TYPE_STRING) {
1928 // Should do better merging styles.
1929 if (pool) {
1930 if (style != NULL && style->size() > 0) {
1931 outValue->data = pool->add(finalStr, *style);
1932 } else {
1933 outValue->data = pool->add(finalStr, true);
1934 }
1935 } else {
1936 // Caller will fill this in later.
1937 outValue->data = 0;
1938 }
1939
1940 if (outStr) {
1941 *outStr = finalStr;
1942 }
1943
1944 }
1945
1946 return true;
1947}
1948
1949uint32_t ResourceTable::getCustomResource(
1950 const String16& package, const String16& type, const String16& name) const
1951{
1952 //printf("getCustomResource: %s %s %s\n", String8(package).string(),
1953 // String8(type).string(), String8(name).string());
1954 sp<Package> p = mPackages.valueFor(package);
1955 if (p == NULL) return 0;
1956 sp<Type> t = p->getTypes().valueFor(type);
1957 if (t == NULL) return 0;
1958 sp<ConfigList> c = t->getConfigs().valueFor(name);
1959 if (c == NULL) return 0;
1960 int32_t ei = c->getEntryIndex();
1961 if (ei < 0) return 0;
1962 return getResId(p, t, ei);
1963}
1964
1965uint32_t ResourceTable::getCustomResourceWithCreation(
1966 const String16& package, const String16& type, const String16& name,
1967 const bool createIfNotFound)
1968{
1969 uint32_t resId = getCustomResource(package, type, name);
1970 if (resId != 0 || !createIfNotFound) {
1971 return resId;
1972 }
1973 String16 value("false");
1974
1975 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
1976 if (status == NO_ERROR) {
1977 resId = getResId(package, type, name);
1978 return resId;
1979 }
1980 return 0;
1981}
1982
1983uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
1984{
1985 return origPackage;
1986}
1987
1988bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
1989{
1990 //printf("getAttributeType #%08x\n", attrID);
1991 Res_value value;
1992 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
1993 //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
1994 // String8(getEntry(attrID)->getName()).string(), value.data);
1995 *outType = value.data;
1996 return true;
1997 }
1998 return false;
1999}
2000
2001bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2002{
2003 //printf("getAttributeMin #%08x\n", attrID);
2004 Res_value value;
2005 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2006 *outMin = value.data;
2007 return true;
2008 }
2009 return false;
2010}
2011
2012bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2013{
2014 //printf("getAttributeMax #%08x\n", attrID);
2015 Res_value value;
2016 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2017 *outMax = value.data;
2018 return true;
2019 }
2020 return false;
2021}
2022
2023uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2024{
2025 //printf("getAttributeL10N #%08x\n", attrID);
2026 Res_value value;
2027 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2028 return value.data;
2029 }
2030 return ResTable_map::L10N_NOT_REQUIRED;
2031}
2032
2033bool ResourceTable::getLocalizationSetting()
2034{
2035 return mBundle->getRequireLocalization();
2036}
2037
2038void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2039{
2040 if (accessorCookie != NULL && fmt != NULL) {
2041 AccessorCookie* ac = (AccessorCookie*)accessorCookie;
2042 int retval=0;
2043 char buf[1024];
2044 va_list ap;
2045 va_start(ap, fmt);
2046 retval = vsnprintf(buf, sizeof(buf), fmt, ap);
2047 va_end(ap);
2048 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
2049 buf, ac->attr.string(), ac->value.string());
2050 }
2051}
2052
2053bool ResourceTable::getAttributeKeys(
2054 uint32_t attrID, Vector<String16>* outKeys)
2055{
2056 sp<const Entry> e = getEntry(attrID);
2057 if (e != NULL) {
2058 const size_t N = e->getBag().size();
2059 for (size_t i=0; i<N; i++) {
2060 const String16& key = e->getBag().keyAt(i);
2061 if (key.size() > 0 && key.string()[0] != '^') {
2062 outKeys->add(key);
2063 }
2064 }
2065 return true;
2066 }
2067 return false;
2068}
2069
2070bool ResourceTable::getAttributeEnum(
2071 uint32_t attrID, const char16_t* name, size_t nameLen,
2072 Res_value* outValue)
2073{
2074 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
2075 String16 nameStr(name, nameLen);
2076 sp<const Entry> e = getEntry(attrID);
2077 if (e != NULL) {
2078 const size_t N = e->getBag().size();
2079 for (size_t i=0; i<N; i++) {
2080 //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
2081 // String8(e->getBag().keyAt(i)).string());
2082 if (e->getBag().keyAt(i) == nameStr) {
2083 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2084 }
2085 }
2086 }
2087 return false;
2088}
2089
2090bool ResourceTable::getAttributeFlags(
2091 uint32_t attrID, const char16_t* name, size_t nameLen,
2092 Res_value* outValue)
2093{
2094 outValue->dataType = Res_value::TYPE_INT_HEX;
2095 outValue->data = 0;
2096
2097 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
2098 String16 nameStr(name, nameLen);
2099 sp<const Entry> e = getEntry(attrID);
2100 if (e != NULL) {
2101 const size_t N = e->getBag().size();
2102
2103 const char16_t* end = name + nameLen;
2104 const char16_t* pos = name;
2105 bool failed = false;
2106 while (pos < end && !failed) {
2107 const char16_t* start = pos;
2108 end++;
2109 while (pos < end && *pos != '|') {
2110 pos++;
2111 }
2112
2113 String16 nameStr(start, pos-start);
2114 size_t i;
2115 for (i=0; i<N; i++) {
2116 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
2117 // String8(e->getBag().keyAt(i)).string());
2118 if (e->getBag().keyAt(i) == nameStr) {
2119 Res_value val;
2120 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2121 if (!got) {
2122 return false;
2123 }
2124 //printf("Got value: 0x%08x\n", val.data);
2125 outValue->data |= val.data;
2126 break;
2127 }
2128 }
2129
2130 if (i >= N) {
2131 // Didn't find this flag identifier.
2132 return false;
2133 }
2134 if (pos < end) {
2135 pos++;
2136 }
2137 }
2138
2139 return true;
2140 }
2141 return false;
2142}
2143
2144status_t ResourceTable::assignResourceIds()
2145{
2146 const size_t N = mOrderedPackages.size();
2147 size_t pi;
2148 status_t firstError = NO_ERROR;
2149
2150 // First generate all bag attributes and assign indices.
2151 for (pi=0; pi<N; pi++) {
2152 sp<Package> p = mOrderedPackages.itemAt(pi);
2153 if (p == NULL || p->getTypes().size() == 0) {
2154 // Empty, skip!
2155 continue;
2156 }
2157
2158 status_t err = p->applyPublicTypeOrder();
2159 if (err != NO_ERROR && firstError == NO_ERROR) {
2160 firstError = err;
2161 }
2162
2163 // Generate attributes...
2164 const size_t N = p->getOrderedTypes().size();
2165 size_t ti;
2166 for (ti=0; ti<N; ti++) {
2167 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2168 if (t == NULL) {
2169 continue;
2170 }
2171 const size_t N = t->getOrderedConfigs().size();
2172 for (size_t ci=0; ci<N; ci++) {
2173 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2174 if (c == NULL) {
2175 continue;
2176 }
2177 const size_t N = c->getEntries().size();
2178 for (size_t ei=0; ei<N; ei++) {
2179 sp<Entry> e = c->getEntries().valueAt(ei);
2180 if (e == NULL) {
2181 continue;
2182 }
2183 status_t err = e->generateAttributes(this, p->getName());
2184 if (err != NO_ERROR && firstError == NO_ERROR) {
2185 firstError = err;
2186 }
2187 }
2188 }
2189 }
2190
2191 const SourcePos unknown(String8("????"), 0);
2192 sp<Type> attr = p->getType(String16("attr"), unknown);
2193
2194 // Assign indices...
2195 for (ti=0; ti<N; ti++) {
2196 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2197 if (t == NULL) {
2198 continue;
2199 }
2200 err = t->applyPublicEntryOrder();
2201 if (err != NO_ERROR && firstError == NO_ERROR) {
2202 firstError = err;
2203 }
2204
2205 const size_t N = t->getOrderedConfigs().size();
2206 t->setIndex(ti+1);
2207
2208 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2209 "First type is not attr!");
2210
2211 for (size_t ei=0; ei<N; ei++) {
2212 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2213 if (c == NULL) {
2214 continue;
2215 }
2216 c->setEntryIndex(ei);
2217 }
2218 }
2219
2220 // Assign resource IDs to keys in bags...
2221 for (ti=0; ti<N; ti++) {
2222 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2223 if (t == NULL) {
2224 continue;
2225 }
2226 const size_t N = t->getOrderedConfigs().size();
2227 for (size_t ci=0; ci<N; ci++) {
2228 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2229 //printf("Ordered config #%d: %p\n", ci, c.get());
2230 const size_t N = c->getEntries().size();
2231 for (size_t ei=0; ei<N; ei++) {
2232 sp<Entry> e = c->getEntries().valueAt(ei);
2233 if (e == NULL) {
2234 continue;
2235 }
2236 status_t err = e->assignResourceIds(this, p->getName());
2237 if (err != NO_ERROR && firstError == NO_ERROR) {
2238 firstError = err;
2239 }
2240 }
2241 }
2242 }
2243 }
2244 return firstError;
2245}
2246
2247status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols) {
2248 const size_t N = mOrderedPackages.size();
2249 size_t pi;
2250
2251 for (pi=0; pi<N; pi++) {
2252 sp<Package> p = mOrderedPackages.itemAt(pi);
2253 if (p->getTypes().size() == 0) {
2254 // Empty, skip!
2255 continue;
2256 }
2257
2258 const size_t N = p->getOrderedTypes().size();
2259 size_t ti;
2260
2261 for (ti=0; ti<N; ti++) {
2262 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2263 if (t == NULL) {
2264 continue;
2265 }
2266 const size_t N = t->getOrderedConfigs().size();
2267 sp<AaptSymbols> typeSymbols;
2268 typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2269 for (size_t ci=0; ci<N; ci++) {
2270 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2271 if (c == NULL) {
2272 continue;
2273 }
2274 uint32_t rid = getResId(p, t, ci);
2275 if (rid == 0) {
2276 return UNKNOWN_ERROR;
2277 }
2278 if (Res_GETPACKAGE(rid) == (size_t)(p->getAssignedId()-1)) {
2279 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2280
2281 String16 comment(c->getComment());
2282 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
2283 //printf("Type symbol %s comment: %s\n", String8(e->getName()).string(),
2284 // String8(comment).string());
2285 comment = c->getTypeComment();
2286 typeSymbols->appendTypeComment(String8(c->getName()), comment);
2287 } else {
2288#if 0
2289 printf("**** NO MATCH: 0x%08x vs 0x%08x\n",
2290 Res_GETPACKAGE(rid), p->getAssignedId());
2291#endif
2292 }
2293 }
2294 }
2295 }
2296 return NO_ERROR;
2297}
2298
2299
2300void
2301ResourceTable::addLocalization(const String16& name, const String8& locale)
2302{
2303 mLocalizations[name].insert(locale);
2304}
2305
2306
2307/*!
2308 * Flag various sorts of localization problems. '+' indicates checks already implemented;
2309 * '-' indicates checks that will be implemented in the future.
2310 *
2311 * + A localized string for which no default-locale version exists => warning
2312 * + A string for which no version in an explicitly-requested locale exists => warning
2313 * + A localized translation of an translateable="false" string => warning
2314 * - A localized string not provided in every locale used by the table
2315 */
2316status_t
2317ResourceTable::validateLocalizations(void)
2318{
2319 status_t err = NO_ERROR;
2320 const String8 defaultLocale;
2321
2322 // For all strings...
2323 for (map<String16, set<String8> >::iterator nameIter = mLocalizations.begin();
2324 nameIter != mLocalizations.end();
2325 nameIter++) {
2326 const set<String8>& configSet = nameIter->second; // naming convenience
2327
2328 // Look for strings with no default localization
2329 if (configSet.count(defaultLocale) == 0) {
2330 fprintf(stdout, "aapt: warning: string '%s' has no default translation in %s; found:",
2331 String8(nameIter->first).string(), mBundle->getResourceSourceDirs()[0]);
2332 for (set<String8>::iterator locales = configSet.begin();
2333 locales != configSet.end();
2334 locales++) {
2335 fprintf(stdout, " %s", (*locales).string());
2336 }
2337 fprintf(stdout, "\n");
2338 // !!! TODO: throw an error here in some circumstances
2339 }
2340
2341 // Check that all requested localizations are present for this string
2342 if (mBundle->getConfigurations() != NULL && mBundle->getRequireLocalization()) {
2343 const char* allConfigs = mBundle->getConfigurations();
2344 const char* start = allConfigs;
2345 const char* comma;
2346
2347 do {
2348 String8 config;
2349 comma = strchr(start, ',');
2350 if (comma != NULL) {
2351 config.setTo(start, comma - start);
2352 start = comma + 1;
2353 } else {
2354 config.setTo(start);
2355 }
2356
2357 // don't bother with the pseudolocale "zz_ZZ"
2358 if (config != "zz_ZZ") {
2359 if (configSet.find(config) == configSet.end()) {
2360 // okay, no specific localization found. it's possible that we are
2361 // requiring a specific regional localization [e.g. de_DE] but there is an
2362 // available string in the generic language localization [e.g. de];
2363 // consider that string to have fulfilled the localization requirement.
2364 String8 region(config.string(), 2);
2365 if (configSet.find(region) == configSet.end()) {
2366 if (configSet.count(defaultLocale) == 0) {
1782ef54 2367 fprintf(stdout, "aapt: warning: "
a534180c
TAOSP
2368 "*** string '%s' has no default or required localization "
2369 "for '%s' in %s\n",
2370 String8(nameIter->first).string(),
2371 config.string(),
2372 mBundle->getResourceSourceDirs()[0]);
a534180c
TAOSP
2373 }
2374 }
2375 }
2376 }
2377 } while (comma != NULL);
2378 }
2379 }
2380
2381 return err;
2382}
2383
2384
2385status_t
2386ResourceFilter::parse(const char* arg)
2387{
2388 if (arg == NULL) {
2389 return 0;
2390 }
2391
2392 const char* p = arg;
2393 const char* q;
2394
2395 while (true) {
2396 q = strchr(p, ',');
2397 if (q == NULL) {
2398 q = p + strlen(p);
2399 }
2400
2401 String8 part(p, q-p);
2402
2403 if (part == "zz_ZZ") {
2404 mContainsPseudo = true;
2405 }
2406 int axis;
2407 uint32_t value;
2408 if (AaptGroupEntry::parseNamePart(part, &axis, &value)) {
2409 fprintf(stderr, "Invalid configuration: %s\n", arg);
2410 fprintf(stderr, " ");
2411 for (int i=0; i<p-arg; i++) {
2412 fprintf(stderr, " ");
2413 }
2414 for (int i=0; i<q-p; i++) {
2415 fprintf(stderr, "^");
2416 }
2417 fprintf(stderr, "\n");
2418 return 1;
2419 }
2420
2421 ssize_t index = mData.indexOfKey(axis);
2422 if (index < 0) {
2423 mData.add(axis, SortedVector<uint32_t>());
2424 }
2425 SortedVector<uint32_t>& sv = mData.editValueFor(axis);
2426 sv.add(value);
2427 // if it's a locale with a region, also match an unmodified locale of the
2428 // same language
2429 if (axis == AXIS_LANGUAGE) {
2430 if (value & 0xffff0000) {
2431 sv.add(value & 0x0000ffff);
2432 }
2433 }
2434 p = q;
2435 if (!*p) break;
2436 p++;
2437 }
2438
2439 return NO_ERROR;
2440}
2441
2442bool
2443ResourceFilter::match(int axis, uint32_t value)
2444{
2445 if (value == 0) {
2446 // they didn't specify anything so take everything
2447 return true;
2448 }
2449 ssize_t index = mData.indexOfKey(axis);
2450 if (index < 0) {
2451 // we didn't request anything on this axis so take everything
2452 return true;
2453 }
2454 const SortedVector<uint32_t>& sv = mData.valueAt(index);
2455 return sv.indexOf(value) >= 0;
2456}
2457
2458bool
2459ResourceFilter::match(const ResTable_config& config)
2460{
2461 if (config.locale) {
2462 uint32_t locale = (config.country[1] << 24) | (config.country[0] << 16)
2463 | (config.language[1] << 8) | (config.language[0]);
2464 if (!match(AXIS_LANGUAGE, locale)) {
2465 return false;
2466 }
2467 }
2468 if (!match(AXIS_ORIENTATION, config.orientation)) {
2469 return false;
2470 }
2471 if (!match(AXIS_DENSITY, config.density)) {
2472 return false;
2473 }
2474 if (!match(AXIS_TOUCHSCREEN, config.touchscreen)) {
2475 return false;
2476 }
2477 if (!match(AXIS_KEYSHIDDEN, config.inputFlags)) {
2478 return false;
2479 }
2480 if (!match(AXIS_KEYBOARD, config.keyboard)) {
2481 return false;
2482 }
2483 if (!match(AXIS_NAVIGATION, config.navigation)) {
2484 return false;
2485 }
2486 if (!match(AXIS_SCREENSIZE, config.screenSize)) {
2487 return false;
2488 }
2489 if (!match(AXIS_VERSION, config.version)) {
2490 return false;
2491 }
2492 return true;
2493}
2494
2495status_t ResourceTable::flatten(Bundle* bundle, const sp<AaptFile>& dest)
2496{
2497 ResourceFilter filter;
2498 status_t err = filter.parse(bundle->getConfigurations());
2499 if (err != NO_ERROR) {
2500 return err;
2501 }
2502
2503 const size_t N = mOrderedPackages.size();
2504 size_t pi;
2505
2506 // Iterate through all data, collecting all values (strings,
2507 // references, etc).
2508 StringPool valueStrings;
2509 for (pi=0; pi<N; pi++) {
2510 sp<Package> p = mOrderedPackages.itemAt(pi);
2511 if (p->getTypes().size() == 0) {
2512 // Empty, skip!
2513 continue;
2514 }
2515
2516 StringPool typeStrings;
2517 StringPool keyStrings;
2518
2519 const size_t N = p->getOrderedTypes().size();
2520 for (size_t ti=0; ti<N; ti++) {
2521 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2522 if (t == NULL) {
2523 typeStrings.add(String16("<empty>"), false);
2524 continue;
2525 }
2526 typeStrings.add(t->getName(), false);
2527
2528 const size_t N = t->getOrderedConfigs().size();
2529 for (size_t ci=0; ci<N; ci++) {
2530 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2531 if (c == NULL) {
2532 continue;
2533 }
2534 const size_t N = c->getEntries().size();
2535 for (size_t ei=0; ei<N; ei++) {
2536 ConfigDescription config = c->getEntries().keyAt(ei);
2537 if (!filter.match(config)) {
2538 continue;
2539 }
2540 sp<Entry> e = c->getEntries().valueAt(ei);
2541 if (e == NULL) {
2542 continue;
2543 }
2544 e->setNameIndex(keyStrings.add(e->getName(), true));
2545 status_t err = e->prepareFlatten(&valueStrings, this);
2546 if (err != NO_ERROR) {
2547 return err;
2548 }
2549 }
2550 }
2551 }
2552
2553 p->setTypeStrings(typeStrings.createStringBlock());
2554 p->setKeyStrings(keyStrings.createStringBlock());
2555 }
2556
2557 ssize_t strAmt = 0;
2558
2559 // Now build the array of package chunks.
2560 Vector<sp<AaptFile> > flatPackages;
2561 for (pi=0; pi<N; pi++) {
2562 sp<Package> p = mOrderedPackages.itemAt(pi);
2563 if (p->getTypes().size() == 0) {
2564 // Empty, skip!
2565 continue;
2566 }
2567
2568 const size_t N = p->getTypeStrings().size();
2569
2570 const size_t baseSize = sizeof(ResTable_package);
2571
2572 // Start the package data.
2573 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2574 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2575 if (header == NULL) {
2576 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2577 return NO_MEMORY;
2578 }
2579 memset(header, 0, sizeof(*header));
2580 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2581 header->header.headerSize = htods(sizeof(*header));
2582 header->id = htodl(p->getAssignedId());
2583 strcpy16_htod(header->name, p->getName().string());
2584
2585 // Write the string blocks.
2586 const size_t typeStringsStart = data->getSize();
2587 sp<AaptFile> strFile = p->getTypeStringsData();
2588 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
2589 #if PRINT_STRING_METRICS
2590 fprintf(stderr, "**** type strings: %d\n", amt);
2591 #endif
2592 strAmt += amt;
2593 if (amt < 0) {
2594 return amt;
2595 }
2596 const size_t keyStringsStart = data->getSize();
2597 strFile = p->getKeyStringsData();
2598 amt = data->writeData(strFile->getData(), strFile->getSize());
2599 #if PRINT_STRING_METRICS
2600 fprintf(stderr, "**** key strings: %d\n", amt);
2601 #endif
2602 strAmt += amt;
2603 if (amt < 0) {
2604 return amt;
2605 }
2606
2607 // Build the type chunks inside of this package.
2608 for (size_t ti=0; ti<N; ti++) {
2609 // Retrieve them in the same order as the type string block.
2610 size_t len;
2611 String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2612 sp<Type> t = p->getTypes().valueFor(typeName);
2613 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2614 "Type name %s not found",
2615 String8(typeName).string());
2616
2617 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
2618
2619 // First write the typeSpec chunk, containing information about
2620 // each resource entry in this type.
2621 {
2622 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2623 const size_t typeSpecStart = data->getSize();
2624 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2625 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
2626 if (tsHeader == NULL) {
2627 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
2628 return NO_MEMORY;
2629 }
2630 memset(tsHeader, 0, sizeof(*tsHeader));
2631 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
2632 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
2633 tsHeader->header.size = htodl(typeSpecSize);
2634 tsHeader->id = ti+1;
2635 tsHeader->entryCount = htodl(N);
2636
2637 uint32_t* typeSpecFlags = (uint32_t*)
2638 (((uint8_t*)data->editData())
2639 + typeSpecStart + sizeof(ResTable_typeSpec));
2640 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
2641
2642 for (size_t ei=0; ei<N; ei++) {
2643 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2644 if (cl->getPublic()) {
2645 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
2646 }
2647 const size_t CN = cl->getEntries().size();
2648 for (size_t ci=0; ci<CN; ci++) {
2649 if (!filter.match(cl->getEntries().keyAt(ci))) {
2650 continue;
2651 }
2652 for (size_t cj=ci+1; cj<CN; cj++) {
2653 if (!filter.match(cl->getEntries().keyAt(cj))) {
2654 continue;
2655 }
2656 typeSpecFlags[ei] |= htodl(
2657 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
2658 }
2659 }
2660 }
2661 }
2662
2663 // We need to write one type chunk for each configuration for
2664 // which we have entries in this type.
2665 const size_t NC = t->getUniqueConfigs().size();
2666
2667 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
2668
2669 for (size_t ci=0; ci<NC; ci++) {
2670 ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
2671
2672 NOISY(printf("Writing config %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2673 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
2674 ti+1,
2675 config.mcc, config.mnc,
2676 config.language[0] ? config.language[0] : '-',
2677 config.language[1] ? config.language[1] : '-',
2678 config.country[0] ? config.country[0] : '-',
2679 config.country[1] ? config.country[1] : '-',
2680 config.orientation,
2681 config.touchscreen,
2682 config.density,
2683 config.keyboard,
2684 config.inputFlags,
2685 config.navigation,
2686 config.screenWidth,
2687 config.screenHeight));
2688
2689 if (!filter.match(config)) {
2690 continue;
2691 }
2692
2693 const size_t typeStart = data->getSize();
2694
2695 ResTable_type* tHeader = (ResTable_type*)
2696 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
2697 if (tHeader == NULL) {
2698 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
2699 return NO_MEMORY;
2700 }
2701
2702 memset(tHeader, 0, sizeof(*tHeader));
2703 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
2704 tHeader->header.headerSize = htods(sizeof(*tHeader));
2705 tHeader->id = ti+1;
2706 tHeader->entryCount = htodl(N);
2707 tHeader->entriesStart = htodl(typeSize);
2708 tHeader->config = config;
2709 NOISY(printf("Writing type %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
2710 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
2711 ti+1,
2712 tHeader->config.mcc, tHeader->config.mnc,
2713 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
2714 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
2715 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
2716 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
2717 tHeader->config.orientation,
2718 tHeader->config.touchscreen,
2719 tHeader->config.density,
2720 tHeader->config.keyboard,
2721 tHeader->config.inputFlags,
2722 tHeader->config.navigation,
2723 tHeader->config.screenWidth,
2724 tHeader->config.screenHeight));
2725 tHeader->config.swapHtoD();
2726
2727 // Build the entries inside of this type.
2728 for (size_t ei=0; ei<N; ei++) {
2729 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2730 sp<Entry> e = cl->getEntries().valueFor(config);
2731
2732 // Set the offset for this entry in its type.
2733 uint32_t* index = (uint32_t*)
2734 (((uint8_t*)data->editData())
2735 + typeStart + sizeof(ResTable_type));
2736 if (e != NULL) {
2737 index[ei] = htodl(data->getSize()-typeStart-typeSize);
2738
2739 // Create the entry.
2740 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
2741 if (amt < 0) {
2742 return amt;
2743 }
2744 } else {
2745 index[ei] = htodl(ResTable_type::NO_ENTRY);
2746 }
2747 }
2748
2749 // Fill in the rest of the type information.
2750 tHeader = (ResTable_type*)
2751 (((uint8_t*)data->editData()) + typeStart);
2752 tHeader->header.size = htodl(data->getSize()-typeStart);
2753 }
2754 }
2755
2756 // Fill in the rest of the package information.
2757 header = (ResTable_package*)data->editData();
2758 header->header.size = htodl(data->getSize());
2759 header->typeStrings = htodl(typeStringsStart);
2760 header->lastPublicType = htodl(p->getTypeStrings().size());
2761 header->keyStrings = htodl(keyStringsStart);
2762 header->lastPublicKey = htodl(p->getKeyStrings().size());
2763
2764 flatPackages.add(data);
2765 }
2766
2767 // And now write out the final chunks.
2768 const size_t dataStart = dest->getSize();
2769
2770 {
2771 // blah
2772 ResTable_header header;
2773 memset(&header, 0, sizeof(header));
2774 header.header.type = htods(RES_TABLE_TYPE);
2775 header.header.headerSize = htods(sizeof(header));
2776 header.packageCount = htodl(flatPackages.size());
2777 status_t err = dest->writeData(&header, sizeof(header));
2778 if (err != NO_ERROR) {
2779 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
2780 return err;
2781 }
2782 }
2783
2784 ssize_t strStart = dest->getSize();
2785 err = valueStrings.writeStringBlock(dest);
2786 if (err != NO_ERROR) {
2787 return err;
2788 }
2789
2790 ssize_t amt = (dest->getSize()-strStart);
2791 strAmt += amt;
2792 #if PRINT_STRING_METRICS
2793 fprintf(stderr, "**** value strings: %d\n", amt);
2794 fprintf(stderr, "**** total strings: %d\n", strAmt);
2795 #endif
2796
2797 for (pi=0; pi<flatPackages.size(); pi++) {
2798 err = dest->writeData(flatPackages[pi]->getData(),
2799 flatPackages[pi]->getSize());
2800 if (err != NO_ERROR) {
2801 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
2802 return err;
2803 }
2804 }
2805
2806 ResTable_header* header = (ResTable_header*)
2807 (((uint8_t*)dest->getData()) + dataStart);
2808 header->header.size = htodl(dest->getSize() - dataStart);
2809
2810 NOISY(aout << "Resource table:"
2811 << HexDump(dest->getData(), dest->getSize()) << endl);
2812
2813 #if PRINT_STRING_METRICS
2814 fprintf(stderr, "**** total resource table size: %d / %d%% strings\n",
2815 dest->getSize(), (strAmt*100)/dest->getSize());
2816 #endif
2817
2818 return NO_ERROR;
2819}
2820
2821void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
2822{
2823 fprintf(fp,
2824 "<!-- This file contains <public> resource definitions for all\n"
2825 " resources that were generated from the source data. -->\n"
2826 "\n"
2827 "<resources>\n");
2828
2829 writePublicDefinitions(package, fp, true);
2830 writePublicDefinitions(package, fp, false);
2831
2832 fprintf(fp,
2833 "\n"
2834 "</resources>\n");
2835}
2836
2837void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
2838{
2839 bool didHeader = false;
2840
2841 sp<Package> pkg = mPackages.valueFor(package);
2842 if (pkg != NULL) {
2843 const size_t NT = pkg->getOrderedTypes().size();
2844 for (size_t i=0; i<NT; i++) {
2845 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
2846 if (t == NULL) {
2847 continue;
2848 }
2849
2850 bool didType = false;
2851
2852 const size_t NC = t->getOrderedConfigs().size();
2853 for (size_t j=0; j<NC; j++) {
2854 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
2855 if (c == NULL) {
2856 continue;
2857 }
2858
2859 if (c->getPublic() != pub) {
2860 continue;
2861 }
2862
2863 if (!didType) {
2864 fprintf(fp, "\n");
2865 didType = true;
2866 }
2867 if (!didHeader) {
2868 if (pub) {
2869 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
2870 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
2871 } else {
2872 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
2873 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
2874 }
2875 didHeader = true;
2876 }
2877 if (!pub) {
2878 const size_t NE = c->getEntries().size();
2879 for (size_t k=0; k<NE; k++) {
2880 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
2881 if (pos.file != "") {
2882 fprintf(fp," <!-- Declared at %s:%d -->\n",
2883 pos.file.string(), pos.line);
2884 }
2885 }
2886 }
2887 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
2888 String8(t->getName()).string(),
2889 String8(c->getName()).string(),
2890 getResId(pkg, t, c->getEntryIndex()));
2891 }
2892 }
2893 }
2894}
2895
2896ResourceTable::Item::Item(const SourcePos& _sourcePos,
2897 bool _isId,
2898 const String16& _value,
2899 const Vector<StringPool::entry_style_span>* _style,
2900 int32_t _format)
2901 : sourcePos(_sourcePos)
2902 , isId(_isId)
2903 , value(_value)
2904 , format(_format)
2905 , bagKeyId(0)
2906 , evaluating(false)
2907{
2908 if (_style) {
2909 style = *_style;
2910 }
2911}
2912
2913status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
2914{
2915 if (mType == TYPE_BAG) {
2916 return NO_ERROR;
2917 }
2918 if (mType == TYPE_UNKNOWN) {
2919 mType = TYPE_BAG;
2920 return NO_ERROR;
2921 }
2922 sourcePos.error("Resource entry %s is already defined as a single item.\n"
2923 "%s:%d: Originally defined here.\n",
2924 String8(mName).string(),
2925 mItem.sourcePos.file.string(), mItem.sourcePos.line);
2926 return UNKNOWN_ERROR;
2927}
2928
2929status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
2930 const String16& value,
2931 const Vector<StringPool::entry_style_span>* style,
2932 int32_t format,
2933 const bool overwrite)
2934{
2935 Item item(sourcePos, false, value, style);
2936
2937 if (mType == TYPE_BAG) {
2938 const Item& item(mBag.valueAt(0));
2939 sourcePos.error("Resource entry %s is already defined as a bag.\n"
2940 "%s:%d: Originally defined here.\n",
2941 String8(mName).string(),
2942 item.sourcePos.file.string(), item.sourcePos.line);
2943 return UNKNOWN_ERROR;
2944 }
2945 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
2946 sourcePos.error("Resource entry %s is already defined.\n"
2947 "%s:%d: Originally defined here.\n",
2948 String8(mName).string(),
2949 mItem.sourcePos.file.string(), mItem.sourcePos.line);
2950 return UNKNOWN_ERROR;
2951 }
6c9f72e4 2952
a534180c
TAOSP
2953 mType = TYPE_ITEM;
2954 mItem = item;
2955 mItemFormat = format;
2956 return NO_ERROR;
2957}
2958
2959status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
2960 const String16& key, const String16& value,
2961 const Vector<StringPool::entry_style_span>* style,
2962 bool replace, bool isId, int32_t format)
2963{
2964 status_t err = makeItABag(sourcePos);
2965 if (err != NO_ERROR) {
2966 return err;
2967 }
2968
2969 Item item(sourcePos, isId, value, style, format);
2970
2971 // XXX NOTE: there is an error if you try to have a bag with two keys,
2972 // one an attr and one an id, with the same name. Not something we
2973 // currently ever have to worry about.
2974 ssize_t origKey = mBag.indexOfKey(key);
2975 if (origKey >= 0) {
2976 if (!replace) {
2977 const Item& item(mBag.valueAt(origKey));
2978 sourcePos.error("Resource entry %s already has bag item %s.\n"
2979 "%s:%d: Originally defined here.\n",
2980 String8(mName).string(), String8(key).string(),
2981 item.sourcePos.file.string(), item.sourcePos.line);
2982 return UNKNOWN_ERROR;
2983 }
2984 //printf("Replacing %s with %s\n",
2985 // String8(mBag.valueFor(key).value).string(), String8(value).string());
2986 mBag.replaceValueFor(key, item);
2987 }
2988
2989 mBag.add(key, item);
2990 return NO_ERROR;
2991}
2992
76486813
RG
2993status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
2994{
2995 status_t err = makeItABag(sourcePos);
2996 if (err != NO_ERROR) {
2997 return err;
2998 }
2999
3000 mBag.clear();
3001 return NO_ERROR;
3002}
3003
a534180c
TAOSP
3004status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3005 const String16& package)
3006{
3007 const String16 attr16("attr");
3008 const String16 id16("id");
3009 const size_t N = mBag.size();
3010 for (size_t i=0; i<N; i++) {
3011 const String16& key = mBag.keyAt(i);
3012 const Item& it = mBag.valueAt(i);
3013 if (it.isId) {
3014 if (!table->hasBagOrEntry(key, &id16, &package)) {
3015 String16 value("false");
3016 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3017 id16, key, value);
3018 if (err != NO_ERROR) {
3019 return err;
3020 }
3021 }
3022 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3023
3024#if 1
3025// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3026// String8(key).string());
3027// const Item& item(mBag.valueAt(i));
3028// fprintf(stderr, "Referenced from file %s line %d\n",
3029// item.sourcePos.file.string(), item.sourcePos.line);
3030// return UNKNOWN_ERROR;
3031#else
3032 char numberStr[16];
3033 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3034 status_t err = table->addBag(SourcePos("<generated>", 0), package,
3035 attr16, key, String16(""),
3036 String16("^type"),
3037 String16(numberStr), NULL, NULL);
3038 if (err != NO_ERROR) {
3039 return err;
3040 }
3041#endif
3042 }
3043 }
3044 return NO_ERROR;
3045}
3046
3047status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
3048 const String16& package)
3049{
3050 bool hasErrors = false;
3051
3052 if (mType == TYPE_BAG) {
3053 const char* errorMsg;
3054 const String16 style16("style");
3055 const String16 attr16("attr");
3056 const String16 id16("id");
3057 mParentId = 0;
3058 if (mParent.size() > 0) {
3059 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
3060 if (mParentId == 0) {
3061 mPos.error("Error retrieving parent for item: %s '%s'.\n",
3062 errorMsg, String8(mParent).string());
3063 hasErrors = true;
3064 }
3065 }
3066 const size_t N = mBag.size();
3067 for (size_t i=0; i<N; i++) {
3068 const String16& key = mBag.keyAt(i);
3069 Item& it = mBag.editValueAt(i);
3070 it.bagKeyId = table->getResId(key,
3071 it.isId ? &id16 : &attr16, NULL, &errorMsg);
3072 //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
3073 if (it.bagKeyId == 0) {
3074 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3075 String8(it.isId ? id16 : attr16).string(),
3076 String8(key).string());
3077 hasErrors = true;
3078 }
3079 }
3080 }
3081 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
3082}
3083
3084status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table)
3085{
3086 if (mType == TYPE_ITEM) {
3087 Item& it = mItem;
3088 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3089 if (!table->stringToValue(&it.parsedValue, strings,
3090 it.value, false, true, 0,
3091 &it.style, NULL, &ac, mItemFormat)) {
3092 return UNKNOWN_ERROR;
3093 }
3094 } else if (mType == TYPE_BAG) {
3095 const size_t N = mBag.size();
3096 for (size_t i=0; i<N; i++) {
3097 const String16& key = mBag.keyAt(i);
3098 Item& it = mBag.editValueAt(i);
3099 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3100 if (!table->stringToValue(&it.parsedValue, strings,
3101 it.value, false, true, it.bagKeyId,
3102 &it.style, NULL, &ac, it.format)) {
3103 return UNKNOWN_ERROR;
3104 }
3105 }
3106 } else {
3107 mPos.error("Error: entry %s is not a single item or a bag.\n",
3108 String8(mName).string());
3109 return UNKNOWN_ERROR;
3110 }
3111 return NO_ERROR;
3112}
3113
3114ssize_t ResourceTable::Entry::flatten(Bundle* bundle, const sp<AaptFile>& data, bool isPublic)
3115{
3116 size_t amt = 0;
3117 ResTable_entry header;
3118 memset(&header, 0, sizeof(header));
3119 header.size = htods(sizeof(header));
3120 const type ty = this != NULL ? mType : TYPE_ITEM;
3121 if (this != NULL) {
3122 if (ty == TYPE_BAG) {
3123 header.flags |= htods(header.FLAG_COMPLEX);
3124 }
3125 if (isPublic) {
3126 header.flags |= htods(header.FLAG_PUBLIC);
3127 }
3128 header.key.index = htodl(mNameIndex);
3129 }
3130 if (ty != TYPE_BAG) {
3131 status_t err = data->writeData(&header, sizeof(header));
3132 if (err != NO_ERROR) {
3133 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3134 return err;
3135 }
3136
3137 const Item& it = mItem;
3138 Res_value par;
3139 memset(&par, 0, sizeof(par));
3140 par.size = htods(it.parsedValue.size);
3141 par.dataType = it.parsedValue.dataType;
3142 par.res0 = it.parsedValue.res0;
3143 par.data = htodl(it.parsedValue.data);
3144 #if 0
3145 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3146 String8(mName).string(), it.parsedValue.dataType,
3147 it.parsedValue.data, par.res0);
3148 #endif
3149 err = data->writeData(&par, it.parsedValue.size);
3150 if (err != NO_ERROR) {
3151 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3152 return err;
3153 }
3154 amt += it.parsedValue.size;
3155 } else {
3156 size_t N = mBag.size();
3157 size_t i;
3158 // Create correct ordering of items.
3159 KeyedVector<uint32_t, const Item*> items;
3160 for (i=0; i<N; i++) {
3161 const Item& it = mBag.valueAt(i);
3162 items.add(it.bagKeyId, &it);
3163 }
3164 N = items.size();
3165
3166 ResTable_map_entry mapHeader;
3167 memcpy(&mapHeader, &header, sizeof(header));
3168 mapHeader.size = htods(sizeof(mapHeader));
3169 mapHeader.parent.ident = htodl(mParentId);
3170 mapHeader.count = htodl(N);
3171 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3172 if (err != NO_ERROR) {
3173 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3174 return err;
3175 }
3176
3177 for (i=0; i<N; i++) {
3178 const Item& it = *items.valueAt(i);
3179 ResTable_map map;
3180 map.name.ident = htodl(it.bagKeyId);
3181 map.value.size = htods(it.parsedValue.size);
3182 map.value.dataType = it.parsedValue.dataType;
3183 map.value.res0 = it.parsedValue.res0;
3184 map.value.data = htodl(it.parsedValue.data);
3185 err = data->writeData(&map, sizeof(map));
3186 if (err != NO_ERROR) {
3187 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3188 return err;
3189 }
3190 amt += sizeof(map);
3191 }
3192 }
3193 return amt;
3194}
3195
3196void ResourceTable::ConfigList::appendComment(const String16& comment,
3197 bool onlyIfEmpty)
3198{
3199 if (comment.size() <= 0) {
3200 return;
3201 }
3202 if (onlyIfEmpty && mComment.size() > 0) {
3203 return;
3204 }
3205 if (mComment.size() > 0) {
3206 mComment.append(String16("\n"));
3207 }
3208 mComment.append(comment);
3209}
3210
3211void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3212{
3213 if (comment.size() <= 0) {
3214 return;
3215 }
3216 if (mTypeComment.size() > 0) {
3217 mTypeComment.append(String16("\n"));
3218 }
3219 mTypeComment.append(comment);
3220}
3221
3222status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3223 const String16& name,
3224 const uint32_t ident)
3225{
3226 #if 0
3227 int32_t entryIdx = Res_GETENTRY(ident);
3228 if (entryIdx < 0) {
3229 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3230 String8(mName).string(), String8(name).string(), ident);
3231 return UNKNOWN_ERROR;
3232 }
3233 #endif
3234
3235 int32_t typeIdx = Res_GETTYPE(ident);
3236 if (typeIdx >= 0) {
3237 typeIdx++;
3238 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3239 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3240 " public identifiers (0x%x vs 0x%x).\n",
3241 String8(mName).string(), String8(name).string(),
3242 mPublicIndex, typeIdx);
3243 return UNKNOWN_ERROR;
3244 }
3245 mPublicIndex = typeIdx;
3246 }
3247
3248 if (mFirstPublicSourcePos == NULL) {
3249 mFirstPublicSourcePos = new SourcePos(sourcePos);
3250 }
3251
3252 if (mPublic.indexOfKey(name) < 0) {
3253 mPublic.add(name, Public(sourcePos, String16(), ident));
3254 } else {
3255 Public& p = mPublic.editValueFor(name);
3256 if (p.ident != ident) {
3257 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3258 " (0x%08x vs 0x%08x).\n"
3259 "%s:%d: Originally defined here.\n",
3260 String8(mName).string(), String8(name).string(), p.ident, ident,
3261 p.sourcePos.file.string(), p.sourcePos.line);
3262 return UNKNOWN_ERROR;
3263 }
3264 }
3265
3266 return NO_ERROR;
3267}
3268
a8c9cd56
DH
3269void ResourceTable::Type::canAddEntry(const String16& name)
3270{
3271 mCanAddEntries.add(name);
3272}
3273
a534180c
TAOSP
3274sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3275 const SourcePos& sourcePos,
3276 const ResTable_config* config,
6c9f72e4
RG
3277 bool doSetIndex,
3278 bool overlay)
a534180c
TAOSP
3279{
3280 int pos = -1;
3281 sp<ConfigList> c = mConfigs.valueFor(entry);
3282 if (c == NULL) {
a8c9cd56
DH
3283 if (overlay == true && mCanAddEntries.indexOf(entry) < 0) {
3284 sourcePos.error("Resource at %s appears in overlay but not"
3285 " in the base package; use <add-resource> to add.\n",
3286 String8(entry).string());
6c9f72e4
RG
3287 return NULL;
3288 }
a534180c
TAOSP
3289 c = new ConfigList(entry, sourcePos);
3290 mConfigs.add(entry, c);
3291 pos = (int)mOrderedConfigs.size();
3292 mOrderedConfigs.add(c);
3293 if (doSetIndex) {
3294 c->setEntryIndex(pos);
3295 }
3296 }
3297
3298 ConfigDescription cdesc;
3299 if (config) cdesc = *config;
3300
3301 sp<Entry> e = c->getEntries().valueFor(cdesc);
3302 if (e == NULL) {
3303 if (config != NULL) {
3304 NOISY(printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
3305 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d w:%d h:%d\n",
3306 sourcePos.file.string(), sourcePos.line,
3307 config->mcc, config->mnc,
3308 config->language[0] ? config->language[0] : '-',
3309 config->language[1] ? config->language[1] : '-',
3310 config->country[0] ? config->country[0] : '-',
3311 config->country[1] ? config->country[1] : '-',
3312 config->orientation,
3313 config->touchscreen,
3314 config->density,
3315 config->keyboard,
3316 config->inputFlags,
3317 config->navigation,
3318 config->screenWidth,
3319 config->screenHeight));
3320 } else {
3321 NOISY(printf("New entry at %s:%d: NULL config\n",
3322 sourcePos.file.string(), sourcePos.line));
3323 }
3324 e = new Entry(entry, sourcePos);
3325 c->addEntry(cdesc, e);
3326 /*
3327 if (doSetIndex) {
3328 if (pos < 0) {
3329 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3330 if (mOrderedConfigs[pos] == c) {
3331 break;
3332 }
3333 }
3334 if (pos >= (int)mOrderedConfigs.size()) {
3335 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3336 return NULL;
3337 }
3338 }
3339 e->setEntryIndex(pos);
3340 }
3341 */
3342 }
3343
3344 mUniqueConfigs.add(cdesc);
3345
3346 return e;
3347}
3348
3349status_t ResourceTable::Type::applyPublicEntryOrder()
3350{
3351 size_t N = mOrderedConfigs.size();
3352 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3353 bool hasError = false;
3354
3355 size_t i;
3356 for (i=0; i<N; i++) {
3357 mOrderedConfigs.replaceAt(NULL, i);
3358 }
3359
3360 const size_t NP = mPublic.size();
3361 //printf("Ordering %d configs from %d public defs\n", N, NP);
3362 size_t j;
3363 for (j=0; j<NP; j++) {
3364 const String16& name = mPublic.keyAt(j);
3365 const Public& p = mPublic.valueAt(j);
3366 int32_t idx = Res_GETENTRY(p.ident);
3367 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3368 // String8(mName).string(), String8(name).string(), p.ident, N);
3369 bool found = false;
3370 for (i=0; i<N; i++) {
3371 sp<ConfigList> e = origOrder.itemAt(i);
3372 //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3373 if (e->getName() == name) {
3374 if (idx >= (int32_t)mOrderedConfigs.size()) {
3375 p.sourcePos.error("Public entry identifier 0x%x entry index "
3376 "is larger than available symbols (index %d, total symbols %d).\n",
3377 p.ident, idx, mOrderedConfigs.size());
3378 hasError = true;
3379 } else if (mOrderedConfigs.itemAt(idx) == NULL) {
3380 e->setPublic(true);
3381 e->setPublicSourcePos(p.sourcePos);
3382 mOrderedConfigs.replaceAt(e, idx);
3383 origOrder.removeAt(i);
3384 N--;
3385 found = true;
3386 break;
3387 } else {
3388 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3389
3390 p.sourcePos.error("Multiple entry names declared for public entry"
3391 " identifier 0x%x in type %s (%s vs %s).\n"
3392 "%s:%d: Originally defined here.",
3393 idx+1, String8(mName).string(),
3394 String8(oe->getName()).string(),
3395 String8(name).string(),
3396 oe->getPublicSourcePos().file.string(),
3397 oe->getPublicSourcePos().line);
3398 hasError = true;
3399 }
3400 }
3401 }
3402
3403 if (!found) {
3404 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3405 String8(mName).string(), String8(name).string());
3406 hasError = true;
3407 }
3408 }
3409
3410 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3411
3412 if (N != origOrder.size()) {
3413 printf("Internal error: remaining private symbol count mismatch\n");
3414 N = origOrder.size();
3415 }
3416
3417 j = 0;
3418 for (i=0; i<N; i++) {
3419 sp<ConfigList> e = origOrder.itemAt(i);
3420 // There will always be enough room for the remaining entries.
3421 while (mOrderedConfigs.itemAt(j) != NULL) {
3422 j++;
3423 }
3424 mOrderedConfigs.replaceAt(e, j);
3425 j++;
3426 }
3427
3428 return hasError ? UNKNOWN_ERROR : NO_ERROR;
3429}
3430
3431ResourceTable::Package::Package(const String16& name, ssize_t includedId)
3432 : mName(name), mIncludedId(includedId),
3433 mTypeStringsMapping(0xffffffff),
3434 mKeyStringsMapping(0xffffffff)
3435{
3436}
3437
3438sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
3439 const SourcePos& sourcePos,
3440 bool doSetIndex)
3441{
3442 sp<Type> t = mTypes.valueFor(type);
3443 if (t == NULL) {
3444 t = new Type(type, sourcePos);
3445 mTypes.add(type, t);
3446 mOrderedTypes.add(t);
3447 if (doSetIndex) {
3448 // For some reason the type's index is set to one plus the index
3449 // in the mOrderedTypes list, rather than just the index.
3450 t->setIndex(mOrderedTypes.size());
3451 }
3452 }
3453 return t;
3454}
3455
3456status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
3457{
3458 mTypeStringsData = data;
3459 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
3460 if (err != NO_ERROR) {
3461 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
3462 }
3463 return err;
3464}
3465
3466status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
3467{
3468 mKeyStringsData = data;
3469 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
3470 if (err != NO_ERROR) {
3471 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
3472 }
3473 return err;
3474}
3475
3476status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
3477 ResStringPool* strings,
3478 DefaultKeyedVector<String16, uint32_t>* mappings)
3479{
3480 if (data->getData() == NULL) {
3481 return UNKNOWN_ERROR;
3482 }
3483
3484 NOISY(aout << "Setting restable string pool: "
3485 << HexDump(data->getData(), data->getSize()) << endl);
3486
3487 status_t err = strings->setTo(data->getData(), data->getSize());
3488 if (err == NO_ERROR) {
3489 const size_t N = strings->size();
3490 for (size_t i=0; i<N; i++) {
3491 size_t len;
3492 mappings->add(String16(strings->stringAt(i, &len)), i);
3493 }
3494 }
3495 return err;
3496}
3497
3498status_t ResourceTable::Package::applyPublicTypeOrder()
3499{
3500 size_t N = mOrderedTypes.size();
3501 Vector<sp<Type> > origOrder(mOrderedTypes);
3502
3503 size_t i;
3504 for (i=0; i<N; i++) {
3505 mOrderedTypes.replaceAt(NULL, i);
3506 }
3507
3508 for (i=0; i<N; i++) {
3509 sp<Type> t = origOrder.itemAt(i);
3510 int32_t idx = t->getPublicIndex();
3511 if (idx > 0) {
3512 idx--;
3513 while (idx >= (int32_t)mOrderedTypes.size()) {
3514 mOrderedTypes.add();
3515 }
3516 if (mOrderedTypes.itemAt(idx) != NULL) {
3517 sp<Type> ot = mOrderedTypes.itemAt(idx);
3518 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
3519 " identifier 0x%x (%s vs %s).\n"
3520 "%s:%d: Originally defined here.",
3521 idx, String8(ot->getName()).string(),
3522 String8(t->getName()).string(),
3523 ot->getFirstPublicSourcePos().file.string(),
3524 ot->getFirstPublicSourcePos().line);
3525 return UNKNOWN_ERROR;
3526 }
3527 mOrderedTypes.replaceAt(t, idx);
3528 origOrder.removeAt(i);
3529 i--;
3530 N--;
3531 }
3532 }
3533
3534 size_t j=0;
3535 for (i=0; i<N; i++) {
3536 sp<Type> t = origOrder.itemAt(i);
3537 // There will always be enough room for the remaining types.
3538 while (mOrderedTypes.itemAt(j) != NULL) {
3539 j++;
3540 }
3541 mOrderedTypes.replaceAt(t, j);
3542 }
3543
3544 return NO_ERROR;
3545}
3546
3547sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
3548{
3549 sp<Package> p = mPackages.valueFor(package);
3550 if (p == NULL) {
3551 if (mIsAppPackage) {
3552 if (mHaveAppPackage) {
3553 fprintf(stderr, "Adding multiple application package resources; only one is allowed.\n"
3554 "Use -x to create extended resources.\n");
3555 return NULL;
3556 }
3557 mHaveAppPackage = true;
3558 p = new Package(package, 127);
3559 } else {
3560 p = new Package(package, mNextPackageId);
3561 }
3562 //printf("*** NEW PACKAGE: \"%s\" id=%d\n",
3563 // String8(package).string(), p->getAssignedId());
3564 mPackages.add(package, p);
3565 mOrderedPackages.add(p);
3566 mNextPackageId++;
3567 }
3568 return p;
3569}
3570
3571sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
3572 const String16& type,
3573 const SourcePos& sourcePos,
3574 bool doSetIndex)
3575{
3576 sp<Package> p = getPackage(package);
3577 if (p == NULL) {
3578 return NULL;
3579 }
3580 return p->getType(type, sourcePos, doSetIndex);
3581}
3582
3583sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
3584 const String16& type,
3585 const String16& name,
3586 const SourcePos& sourcePos,
6c9f72e4 3587 bool overlay,
a534180c
TAOSP
3588 const ResTable_config* config,
3589 bool doSetIndex)
3590{
3591 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
3592 if (t == NULL) {
3593 return NULL;
3594 }
6c9f72e4 3595 return t->getEntry(name, sourcePos, config, doSetIndex, overlay);
a534180c
TAOSP
3596}
3597
3598sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
3599 const ResTable_config* config) const
3600{
3601 int pid = Res_GETPACKAGE(resID)+1;
3602 const size_t N = mOrderedPackages.size();
3603 size_t i;
3604 sp<Package> p;
3605 for (i=0; i<N; i++) {
3606 sp<Package> check = mOrderedPackages[i];
3607 if (check->getAssignedId() == pid) {
3608 p = check;
3609 break;
3610 }
3611
3612 }
3613 if (p == NULL) {
406a85e3 3614 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
a534180c
TAOSP
3615 return NULL;
3616 }
3617
3618 int tid = Res_GETTYPE(resID);
3619 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
406a85e3 3620 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
a534180c
TAOSP
3621 return NULL;
3622 }
3623 sp<Type> t = p->getOrderedTypes()[tid];
3624
3625 int eid = Res_GETENTRY(resID);
3626 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
406a85e3 3627 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
a534180c
TAOSP
3628 return NULL;
3629 }
3630
3631 sp<ConfigList> c = t->getOrderedConfigs()[eid];
3632 if (c == NULL) {
406a85e3 3633 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
a534180c
TAOSP
3634 return NULL;
3635 }
3636
3637 ConfigDescription cdesc;
3638 if (config) cdesc = *config;
3639 sp<Entry> e = c->getEntries().valueFor(cdesc);
3640 if (c == NULL) {
406a85e3 3641 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
a534180c
TAOSP
3642 return NULL;
3643 }
3644
3645 return e;
3646}
3647
3648const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
3649{
3650 sp<const Entry> e = getEntry(resID);
3651 if (e == NULL) {
3652 return NULL;
3653 }
3654
3655 const size_t N = e->getBag().size();
3656 for (size_t i=0; i<N; i++) {
3657 const Item& it = e->getBag().valueAt(i);
3658 if (it.bagKeyId == 0) {
406a85e3 3659 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
a534180c
TAOSP
3660 String8(e->getName()).string(),
3661 String8(e->getBag().keyAt(i)).string());
3662 }
3663 if (it.bagKeyId == attrID) {
3664 return &it;
3665 }
3666 }
3667
3668 return NULL;
3669}
3670
3671bool ResourceTable::getItemValue(
3672 uint32_t resID, uint32_t attrID, Res_value* outValue)
3673{
3674 const Item* item = getItem(resID, attrID);
3675
3676 bool res = false;
3677 if (item != NULL) {
3678 if (item->evaluating) {
3679 sp<const Entry> e = getEntry(resID);
3680 const size_t N = e->getBag().size();
3681 size_t i;
3682 for (i=0; i<N; i++) {
3683 if (&e->getBag().valueAt(i) == item) {
3684 break;
3685 }
3686 }
406a85e3 3687 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
a534180c
TAOSP
3688 String8(e->getName()).string(),
3689 String8(e->getBag().keyAt(i)).string());
3690 return false;
3691 }
3692 item->evaluating = true;
3693 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
3694 NOISY(
3695 if (res) {
3696 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
3697 resID, attrID, String8(getEntry(resID)->getName()).string(),
3698 outValue->dataType, outValue->data);
3699 } else {
3700 printf("getItemValue of #%08x[#%08x]: failed\n",
3701 resID, attrID);
3702 }
3703 );
3704 item->evaluating = false;
3705 }
3706 return res;
3707}