blob: 26b5bd6401e83088dbc94747e0f80108a462b604 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001//
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"
Dianne Hackborne6b68032011-10-13 16:26:02 -070010#include "ResourceFilter.h"
Christopher Tated8dde13a2012-11-16 15:58:08 -080011#include "ResourceIdCache.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012
Mathias Agopianb13b9bd2012-02-17 18:27:36 -080013#include <androidfw/ResourceTypes.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014#include <utils/ByteOrder.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015#include <stdarg.h>
16
17#define NOISY(x) //x
18
19status_t compileXmlFile(const sp<AaptAssets>& assets,
20 const sp<AaptFile>& target,
21 ResourceTable* table,
22 int options)
23{
24 sp<XMLNode> root = XMLNode::parse(target);
25 if (root == NULL) {
26 return UNKNOWN_ERROR;
27 }
Anton Krumina2ef5c02014-03-12 14:46:44 -070028
Dianne Hackborna96cbb42009-05-13 15:06:13 -070029 return compileXmlFile(assets, root, target, table, options);
30}
31
32status_t compileXmlFile(const sp<AaptAssets>& assets,
Dianne Hackborncf244ad2010-03-09 15:00:30 -080033 const sp<AaptFile>& target,
34 const sp<AaptFile>& outTarget,
35 ResourceTable* table,
36 int options)
37{
38 sp<XMLNode> root = XMLNode::parse(target);
39 if (root == NULL) {
40 return UNKNOWN_ERROR;
41 }
42
43 return compileXmlFile(assets, root, outTarget, table, options);
44}
45
46status_t compileXmlFile(const sp<AaptAssets>& assets,
Dianne Hackborna96cbb42009-05-13 15:06:13 -070047 const sp<XMLNode>& root,
48 const sp<AaptFile>& target,
49 ResourceTable* table,
50 int options)
51{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052 if ((options&XML_COMPILE_STRIP_WHITESPACE) != 0) {
53 root->removeWhitespace(true, NULL);
54 } else if ((options&XML_COMPILE_COMPACT_WHITESPACE) != 0) {
55 root->removeWhitespace(false, NULL);
56 }
57
Kenny Root19138462009-12-04 09:38:48 -080058 if ((options&XML_COMPILE_UTF8) != 0) {
59 root->setUTF8(true);
60 }
61
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 bool hasErrors = false;
63
64 if ((options&XML_COMPILE_ASSIGN_ATTRIBUTE_IDS) != 0) {
65 status_t err = root->assignResourceIds(assets, table);
66 if (err != NO_ERROR) {
67 hasErrors = true;
68 }
69 }
70
71 status_t err = root->parseValues(assets, table);
72 if (err != NO_ERROR) {
73 hasErrors = true;
74 }
75
76 if (hasErrors) {
77 return UNKNOWN_ERROR;
78 }
79
80 NOISY(printf("Input XML Resource:\n"));
81 NOISY(root->print());
82 err = root->flatten(target,
83 (options&XML_COMPILE_STRIP_COMMENTS) != 0,
84 (options&XML_COMPILE_STRIP_RAW_VALUES) != 0);
85 if (err != NO_ERROR) {
86 return err;
87 }
88
89 NOISY(printf("Output XML Resource:\n"));
90 NOISY(ResXMLTree tree;
91 tree.setTo(target->getData(), target->getSize());
92 printXMLBlock(&tree));
93
94 target->setCompressionMethod(ZipEntry::kCompressDeflated);
95
96 return err;
97}
98
99#undef NOISY
100#define NOISY(x) //x
101
102struct flag_entry
103{
104 const char16_t* name;
105 size_t nameLen;
106 uint32_t value;
107 const char* description;
108};
109
110static const char16_t referenceArray[] =
111 { 'r', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e' };
112static const char16_t stringArray[] =
113 { 's', 't', 'r', 'i', 'n', 'g' };
114static const char16_t integerArray[] =
115 { 'i', 'n', 't', 'e', 'g', 'e', 'r' };
116static const char16_t booleanArray[] =
117 { 'b', 'o', 'o', 'l', 'e', 'a', 'n' };
118static const char16_t colorArray[] =
119 { 'c', 'o', 'l', 'o', 'r' };
120static const char16_t floatArray[] =
121 { 'f', 'l', 'o', 'a', 't' };
122static const char16_t dimensionArray[] =
123 { 'd', 'i', 'm', 'e', 'n', 's', 'i', 'o', 'n' };
124static const char16_t fractionArray[] =
125 { 'f', 'r', 'a', 'c', 't', 'i', 'o', 'n' };
126static const char16_t enumArray[] =
127 { 'e', 'n', 'u', 'm' };
128static const char16_t flagsArray[] =
129 { 'f', 'l', 'a', 'g', 's' };
130
131static const flag_entry gFormatFlags[] = {
132 { referenceArray, sizeof(referenceArray)/2, ResTable_map::TYPE_REFERENCE,
133 "a reference to another resource, in the form \"<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>\"\n"
134 "or to a theme attribute in the form \"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\"."},
135 { stringArray, sizeof(stringArray)/2, ResTable_map::TYPE_STRING,
136 "a string value, using '\\\\;' to escape characters such as '\\\\n' or '\\\\uxxxx' for a unicode character." },
137 { integerArray, sizeof(integerArray)/2, ResTable_map::TYPE_INTEGER,
138 "an integer value, such as \"<code>100</code>\"." },
139 { booleanArray, sizeof(booleanArray)/2, ResTable_map::TYPE_BOOLEAN,
140 "a boolean value, either \"<code>true</code>\" or \"<code>false</code>\"." },
141 { colorArray, sizeof(colorArray)/2, ResTable_map::TYPE_COLOR,
142 "a color value, in the form of \"<code>#<i>rgb</i></code>\", \"<code>#<i>argb</i></code>\",\n"
143 "\"<code>#<i>rrggbb</i></code>\", or \"<code>#<i>aarrggbb</i></code>\"." },
144 { floatArray, sizeof(floatArray)/2, ResTable_map::TYPE_FLOAT,
145 "a floating point value, such as \"<code>1.2</code>\"."},
146 { dimensionArray, sizeof(dimensionArray)/2, ResTable_map::TYPE_DIMENSION,
147 "a dimension value, which is a floating point number appended with a unit such as \"<code>14.5sp</code>\".\n"
148 "Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),\n"
149 "in (inches), mm (millimeters)." },
150 { fractionArray, sizeof(fractionArray)/2, ResTable_map::TYPE_FRACTION,
151 "a fractional value, which is a floating point number appended with either % or %p, such as \"<code>14.5%</code>\".\n"
152 "The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to\n"
153 "some parent container." },
154 { enumArray, sizeof(enumArray)/2, ResTable_map::TYPE_ENUM, NULL },
155 { flagsArray, sizeof(flagsArray)/2, ResTable_map::TYPE_FLAGS, NULL },
156 { NULL, 0, 0, NULL }
157};
158
159static const char16_t suggestedArray[] = { 's', 'u', 'g', 'g', 'e', 's', 't', 'e', 'd' };
160
161static const flag_entry l10nRequiredFlags[] = {
162 { suggestedArray, sizeof(suggestedArray)/2, ResTable_map::L10N_SUGGESTED, NULL },
163 { NULL, 0, 0, NULL }
164};
165
166static const char16_t nulStr[] = { 0 };
167
168static uint32_t parse_flags(const char16_t* str, size_t len,
169 const flag_entry* flags, bool* outError = NULL)
170{
171 while (len > 0 && isspace(*str)) {
172 str++;
173 len--;
174 }
175 while (len > 0 && isspace(str[len-1])) {
176 len--;
177 }
178
179 const char16_t* const end = str + len;
180 uint32_t value = 0;
181
182 while (str < end) {
183 const char16_t* div = str;
184 while (div < end && *div != '|') {
185 div++;
186 }
187
188 const flag_entry* cur = flags;
189 while (cur->name) {
190 if (strzcmp16(cur->name, cur->nameLen, str, div-str) == 0) {
191 value |= cur->value;
192 break;
193 }
194 cur++;
195 }
196
197 if (!cur->name) {
198 if (outError) *outError = true;
199 return 0;
200 }
201
202 str = div < end ? div+1 : div;
203 }
204
205 if (outError) *outError = false;
206 return value;
207}
208
209static String16 mayOrMust(int type, int flags)
210{
211 if ((type&(~flags)) == 0) {
212 return String16("<p>Must");
213 }
214
215 return String16("<p>May");
216}
217
218static void appendTypeInfo(ResourceTable* outTable, const String16& pkg,
219 const String16& typeName, const String16& ident, int type,
220 const flag_entry* flags)
221{
222 bool hadType = false;
223 while (flags->name) {
224 if ((type&flags->value) != 0 && flags->description != NULL) {
225 String16 fullMsg(mayOrMust(type, flags->value));
226 fullMsg.append(String16(" be "));
227 fullMsg.append(String16(flags->description));
228 outTable->appendTypeComment(pkg, typeName, ident, fullMsg);
229 hadType = true;
230 }
231 flags++;
232 }
233 if (hadType && (type&ResTable_map::TYPE_REFERENCE) == 0) {
234 outTable->appendTypeComment(pkg, typeName, ident,
235 String16("<p>This may also be a reference to a resource (in the form\n"
236 "\"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>\") or\n"
237 "theme attribute (in the form\n"
238 "\"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>\")\n"
239 "containing a value of this type."));
240 }
241}
242
243struct PendingAttribute
244{
245 const String16 myPackage;
246 const SourcePos sourcePos;
247 const bool appendComment;
248 int32_t type;
249 String16 ident;
250 String16 comment;
251 bool hasErrors;
252 bool added;
253
254 PendingAttribute(String16 _package, const sp<AaptFile>& in,
255 ResXMLTree& block, bool _appendComment)
256 : myPackage(_package)
257 , sourcePos(in->getPrintableSource(), block.getLineNumber())
258 , appendComment(_appendComment)
259 , type(ResTable_map::TYPE_ANY)
260 , hasErrors(false)
261 , added(false)
262 {
263 }
264
265 status_t createIfNeeded(ResourceTable* outTable)
266 {
267 if (added || hasErrors) {
268 return NO_ERROR;
269 }
270 added = true;
271
272 String16 attr16("attr");
273
274 if (outTable->hasBagOrEntry(myPackage, attr16, ident)) {
275 sourcePos.error("Attribute \"%s\" has already been defined\n",
276 String8(ident).string());
277 hasErrors = true;
278 return UNKNOWN_ERROR;
279 }
280
281 char numberStr[16];
282 sprintf(numberStr, "%d", type);
283 status_t err = outTable->addBag(sourcePos, myPackage,
284 attr16, ident, String16(""),
285 String16("^type"),
286 String16(numberStr), NULL, NULL);
287 if (err != NO_ERROR) {
288 hasErrors = true;
289 return err;
290 }
291 outTable->appendComment(myPackage, attr16, ident, comment, appendComment);
292 //printf("Attribute %s comment: %s\n", String8(ident).string(),
293 // String8(comment).string());
294 return err;
295 }
296};
297
298static status_t compileAttribute(const sp<AaptFile>& in,
299 ResXMLTree& block,
300 const String16& myPackage,
301 ResourceTable* outTable,
302 String16* outIdent = NULL,
303 bool inStyleable = false)
304{
305 PendingAttribute attr(myPackage, in, block, inStyleable);
306
307 const String16 attr16("attr");
308 const String16 id16("id");
309
310 // Attribute type constants.
311 const String16 enum16("enum");
312 const String16 flag16("flag");
313
314 ResXMLTree::event_code_t code;
315 size_t len;
316 status_t err;
317
318 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
319 if (identIdx >= 0) {
320 attr.ident = String16(block.getAttributeStringValue(identIdx, &len));
321 if (outIdent) {
322 *outIdent = attr.ident;
323 }
324 } else {
325 attr.sourcePos.error("A 'name' attribute is required for <attr>\n");
326 attr.hasErrors = true;
327 }
328
329 attr.comment = String16(
330 block.getComment(&len) ? block.getComment(&len) : nulStr);
331
332 ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
333 if (typeIdx >= 0) {
334 String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
335 attr.type = parse_flags(typeStr.string(), typeStr.size(), gFormatFlags);
336 if (attr.type == 0) {
337 attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
338 String8(typeStr).string());
339 attr.hasErrors = true;
340 }
341 attr.createIfNeeded(outTable);
342 } else if (!inStyleable) {
343 // Attribute definitions outside of styleables always define the
344 // attribute as a generic value.
345 attr.createIfNeeded(outTable);
346 }
347
348 //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).string(), attr.type);
349
350 ssize_t minIdx = block.indexOfAttribute(NULL, "min");
351 if (minIdx >= 0) {
352 String16 val = String16(block.getAttributeStringValue(minIdx, &len));
353 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
354 attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
355 String8(val).string());
356 attr.hasErrors = true;
357 }
358 attr.createIfNeeded(outTable);
359 if (!attr.hasErrors) {
360 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
361 String16(""), String16("^min"), String16(val), NULL, NULL);
362 if (err != NO_ERROR) {
363 attr.hasErrors = true;
364 }
365 }
366 }
367
368 ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
369 if (maxIdx >= 0) {
370 String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
371 if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
372 attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
373 String8(val).string());
374 attr.hasErrors = true;
375 }
376 attr.createIfNeeded(outTable);
377 if (!attr.hasErrors) {
378 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
379 String16(""), String16("^max"), String16(val), NULL, NULL);
380 attr.hasErrors = true;
381 }
382 }
383
384 if ((minIdx >= 0 || maxIdx >= 0) && (attr.type&ResTable_map::TYPE_INTEGER) == 0) {
385 attr.sourcePos.error("Tag <attr> must have format=integer attribute if using max or min\n");
386 attr.hasErrors = true;
387 }
388
389 ssize_t l10nIdx = block.indexOfAttribute(NULL, "localization");
390 if (l10nIdx >= 0) {
391 const uint16_t* str = block.getAttributeStringValue(l10nIdx, &len);
392 bool error;
393 uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
394 if (error) {
395 attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
396 String8(str).string());
397 attr.hasErrors = true;
398 }
399 attr.createIfNeeded(outTable);
400 if (!attr.hasErrors) {
Kenny Rootf5a7c122010-02-18 09:43:08 -0800401 char buf[11];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 sprintf(buf, "%d", l10n_required);
403 err = outTable->addBag(attr.sourcePos, myPackage, attr16, attr.ident,
404 String16(""), String16("^l10n"), String16(buf), NULL, NULL);
405 if (err != NO_ERROR) {
406 attr.hasErrors = true;
407 }
408 }
409 }
410
411 String16 enumOrFlagsComment;
412
413 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
414 if (code == ResXMLTree::START_TAG) {
415 uint32_t localType = 0;
416 if (strcmp16(block.getElementName(&len), enum16.string()) == 0) {
417 localType = ResTable_map::TYPE_ENUM;
418 } else if (strcmp16(block.getElementName(&len), flag16.string()) == 0) {
419 localType = ResTable_map::TYPE_FLAGS;
420 } else {
421 SourcePos(in->getPrintableSource(), block.getLineNumber())
422 .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
423 String8(block.getElementName(&len)).string());
424 return UNKNOWN_ERROR;
425 }
426
427 attr.createIfNeeded(outTable);
428
429 if (attr.type == ResTable_map::TYPE_ANY) {
430 // No type was explicitly stated, so supplying enum tags
431 // implicitly creates an enum or flag.
432 attr.type = 0;
433 }
434
435 if ((attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) == 0) {
436 // Wasn't originally specified as an enum, so update its type.
437 attr.type |= localType;
438 if (!attr.hasErrors) {
439 char numberStr[16];
440 sprintf(numberStr, "%d", attr.type);
441 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
442 myPackage, attr16, attr.ident, String16(""),
443 String16("^type"), String16(numberStr), NULL, NULL, true);
444 if (err != NO_ERROR) {
445 attr.hasErrors = true;
446 }
447 }
448 } else if ((uint32_t)(attr.type&(ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS)) != localType) {
449 if (localType == ResTable_map::TYPE_ENUM) {
450 SourcePos(in->getPrintableSource(), block.getLineNumber())
451 .error("<enum> attribute can not be used inside a flags format\n");
452 attr.hasErrors = true;
453 } else {
454 SourcePos(in->getPrintableSource(), block.getLineNumber())
455 .error("<flag> attribute can not be used inside a enum format\n");
456 attr.hasErrors = true;
457 }
458 }
459
460 String16 itemIdent;
461 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
462 if (itemIdentIdx >= 0) {
463 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
464 } else {
465 SourcePos(in->getPrintableSource(), block.getLineNumber())
466 .error("A 'name' attribute is required for <enum> or <flag>\n");
467 attr.hasErrors = true;
468 }
469
470 String16 value;
471 ssize_t valueIdx = block.indexOfAttribute(NULL, "value");
472 if (valueIdx >= 0) {
473 value = String16(block.getAttributeStringValue(valueIdx, &len));
474 } else {
475 SourcePos(in->getPrintableSource(), block.getLineNumber())
476 .error("A 'value' attribute is required for <enum> or <flag>\n");
477 attr.hasErrors = true;
478 }
479 if (!attr.hasErrors && !ResTable::stringToInt(value.string(), value.size(), NULL)) {
480 SourcePos(in->getPrintableSource(), block.getLineNumber())
481 .error("Tag <enum> or <flag> 'value' attribute must be a number,"
482 " not \"%s\"\n",
483 String8(value).string());
484 attr.hasErrors = true;
485 }
486
487 // Make sure an id is defined for this enum/flag identifier...
488 if (!attr.hasErrors && !outTable->hasBagOrEntry(itemIdent, &id16, &myPackage)) {
489 err = outTable->startBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
490 myPackage, id16, itemIdent, String16(), NULL);
491 if (err != NO_ERROR) {
492 attr.hasErrors = true;
493 }
494 }
495
496 if (!attr.hasErrors) {
497 if (enumOrFlagsComment.size() == 0) {
498 enumOrFlagsComment.append(mayOrMust(attr.type,
499 ResTable_map::TYPE_ENUM|ResTable_map::TYPE_FLAGS));
500 enumOrFlagsComment.append((attr.type&ResTable_map::TYPE_ENUM)
501 ? String16(" be one of the following constant values.")
502 : String16(" be one or more (separated by '|') of the following constant values."));
Dirk Dougherty59ad2752009-11-03 15:33:37 -0800503 enumOrFlagsComment.append(String16("</p>\n<table>\n"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 "<colgroup align=\"left\" />\n"
505 "<colgroup align=\"left\" />\n"
506 "<colgroup align=\"left\" />\n"
Dirk Dougherty59ad2752009-11-03 15:33:37 -0800507 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 }
509
Dirk Dougherty59ad2752009-11-03 15:33:37 -0800510 enumOrFlagsComment.append(String16("\n<tr><td><code>"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 enumOrFlagsComment.append(itemIdent);
Dirk Dougherty59ad2752009-11-03 15:33:37 -0800512 enumOrFlagsComment.append(String16("</code></td><td>"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 enumOrFlagsComment.append(value);
Dirk Dougherty59ad2752009-11-03 15:33:37 -0800514 enumOrFlagsComment.append(String16("</td><td>"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 if (block.getComment(&len)) {
516 enumOrFlagsComment.append(String16(block.getComment(&len)));
517 }
Dirk Dougherty59ad2752009-11-03 15:33:37 -0800518 enumOrFlagsComment.append(String16("</td></tr>"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519
520 err = outTable->addBag(SourcePos(in->getPrintableSource(), block.getLineNumber()),
521 myPackage,
522 attr16, attr.ident, String16(""),
523 itemIdent, value, NULL, NULL, false, true);
524 if (err != NO_ERROR) {
525 attr.hasErrors = true;
526 }
527 }
528 } else if (code == ResXMLTree::END_TAG) {
529 if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
530 break;
531 }
532 if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
533 if (strcmp16(block.getElementName(&len), enum16.string()) != 0) {
534 SourcePos(in->getPrintableSource(), block.getLineNumber())
535 .error("Found tag </%s> where </enum> is expected\n",
536 String8(block.getElementName(&len)).string());
537 return UNKNOWN_ERROR;
538 }
539 } else {
540 if (strcmp16(block.getElementName(&len), flag16.string()) != 0) {
541 SourcePos(in->getPrintableSource(), block.getLineNumber())
542 .error("Found tag </%s> where </flag> is expected\n",
543 String8(block.getElementName(&len)).string());
544 return UNKNOWN_ERROR;
545 }
546 }
547 }
548 }
549
550 if (!attr.hasErrors && attr.added) {
551 appendTypeInfo(outTable, myPackage, attr16, attr.ident, attr.type, gFormatFlags);
552 }
553
554 if (!attr.hasErrors && enumOrFlagsComment.size() > 0) {
555 enumOrFlagsComment.append(String16("\n</table>"));
556 outTable->appendTypeComment(myPackage, attr16, attr.ident, enumOrFlagsComment);
557 }
558
559
560 return NO_ERROR;
561}
562
563bool localeIsDefined(const ResTable_config& config)
564{
565 return config.locale == 0;
566}
567
568status_t parseAndAddBag(Bundle* bundle,
569 const sp<AaptFile>& in,
570 ResXMLTree* block,
571 const ResTable_config& config,
572 const String16& myPackage,
573 const String16& curType,
574 const String16& ident,
575 const String16& parentIdent,
576 const String16& itemIdent,
577 int32_t curFormat,
Kenny Root15fe2cb2010-05-28 15:44:32 -0700578 bool isFormatted,
Eric Fischer90964042010-09-15 15:59:21 -0700579 const String16& product,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700580 PseudolocalizationMethod pseudolocalize,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 const bool overwrite,
582 ResourceTable* outTable)
583{
584 status_t err;
585 const String16 item16("item");
Anton Krumina2ef5c02014-03-12 14:46:44 -0700586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 String16 str;
588 Vector<StringPool::entry_style_span> spans;
589 err = parseStyledString(bundle, in->getPrintableSource().string(),
Kenny Root15fe2cb2010-05-28 15:44:32 -0700590 block, item16, &str, &spans, isFormatted,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 pseudolocalize);
592 if (err != NO_ERROR) {
593 return err;
594 }
595
596 NOISY(printf("Adding resource bag entry l=%c%c c=%c%c orien=%d d=%d "
597 " pid=%s, bag=%s, id=%s: %s\n",
598 config.language[0], config.language[1],
599 config.country[0], config.country[1],
600 config.orientation, config.density,
601 String8(parentIdent).string(),
602 String8(ident).string(),
603 String8(itemIdent).string(),
604 String8(str).string()));
605
606 err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
607 myPackage, curType, ident, parentIdent, itemIdent, str,
608 &spans, &config, overwrite, false, curFormat);
609 return err;
610}
611
Eric Fischer90964042010-09-15 15:59:21 -0700612/*
613 * Returns true if needle is one of the elements in the comma-separated list
614 * haystack, false otherwise.
615 */
616bool isInProductList(const String16& needle, const String16& haystack) {
617 const char16_t *needle2 = needle.string();
618 const char16_t *haystack2 = haystack.string();
619 size_t needlesize = needle.size();
620
621 while (*haystack2 != '\0') {
622 if (strncmp16(haystack2, needle2, needlesize) == 0) {
623 if (haystack2[needlesize] == '\0' || haystack2[needlesize] == ',') {
624 return true;
625 }
626 }
627
628 while (*haystack2 != '\0' && *haystack2 != ',') {
629 haystack2++;
630 }
631 if (*haystack2 == ',') {
632 haystack2++;
633 }
634 }
635
636 return false;
637}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638
Adam Lesinski2b8e82f2013-10-04 12:06:38 -0700639/*
640 * A simple container that holds a resource type and name. It is ordered first by type then
641 * by name.
642 */
643struct type_ident_pair_t {
644 String16 type;
645 String16 ident;
646
647 type_ident_pair_t() { };
648 type_ident_pair_t(const String16& t, const String16& i) : type(t), ident(i) { }
649 type_ident_pair_t(const type_ident_pair_t& o) : type(o.type), ident(o.ident) { }
650 inline bool operator < (const type_ident_pair_t& o) const {
651 int cmp = compare_type(type, o.type);
652 if (cmp < 0) {
653 return true;
654 } else if (cmp > 0) {
655 return false;
656 } else {
657 return strictly_order_type(ident, o.ident);
658 }
659 }
660};
661
662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663status_t parseAndAddEntry(Bundle* bundle,
664 const sp<AaptFile>& in,
665 ResXMLTree* block,
666 const ResTable_config& config,
667 const String16& myPackage,
668 const String16& curType,
669 const String16& ident,
670 const String16& curTag,
671 bool curIsStyled,
672 int32_t curFormat,
Kenny Root15fe2cb2010-05-28 15:44:32 -0700673 bool isFormatted,
Eric Fischer90964042010-09-15 15:59:21 -0700674 const String16& product,
Anton Krumina2ef5c02014-03-12 14:46:44 -0700675 PseudolocalizationMethod pseudolocalize,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 const bool overwrite,
Adam Lesinski2b8e82f2013-10-04 12:06:38 -0700677 KeyedVector<type_ident_pair_t, bool>* skippedResourceNames,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 ResourceTable* outTable)
679{
680 status_t err;
681
682 String16 str;
683 Vector<StringPool::entry_style_span> spans;
684 err = parseStyledString(bundle, in->getPrintableSource().string(), block,
685 curTag, &str, curIsStyled ? &spans : NULL,
Kenny Root15fe2cb2010-05-28 15:44:32 -0700686 isFormatted, pseudolocalize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687
688 if (err < NO_ERROR) {
689 return err;
690 }
691
Eric Fischer90964042010-09-15 15:59:21 -0700692 /*
693 * If a product type was specified on the command line
694 * and also in the string, and the two are not the same,
695 * return without adding the string.
696 */
697
698 const char *bundleProduct = bundle->getProduct();
699 if (bundleProduct == NULL) {
700 bundleProduct = "";
701 }
702
703 if (product.size() != 0) {
704 /*
705 * If the command-line-specified product is empty, only "default"
706 * matches. Other variants are skipped. This is so generation
707 * of the R.java file when the product is not known is predictable.
708 */
709
710 if (bundleProduct[0] == '\0') {
711 if (strcmp16(String16("default").string(), product.string()) != 0) {
Adam Lesinski2b8e82f2013-10-04 12:06:38 -0700712 /*
713 * This string has a product other than 'default'. Do not add it,
714 * but record it so that if we do not see the same string with
715 * product 'default' or no product, then report an error.
716 */
717 skippedResourceNames->replaceValueFor(
718 type_ident_pair_t(curType, ident), true);
Eric Fischer90964042010-09-15 15:59:21 -0700719 return NO_ERROR;
720 }
721 } else {
722 /*
723 * The command-line product is not empty.
724 * If the product for this string is on the command-line list,
725 * it matches. "default" also matches, but only if nothing
726 * else has matched already.
727 */
728
729 if (isInProductList(product, String16(bundleProduct))) {
730 ;
731 } else if (strcmp16(String16("default").string(), product.string()) == 0 &&
Eric Fischer914f7e62011-09-27 16:09:41 -0700732 !outTable->hasBagOrEntry(myPackage, curType, ident, config)) {
Eric Fischer90964042010-09-15 15:59:21 -0700733 ;
734 } else {
735 return NO_ERROR;
736 }
737 }
738 }
739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740 NOISY(printf("Adding resource entry l=%c%c c=%c%c orien=%d d=%d id=%s: %s\n",
741 config.language[0], config.language[1],
742 config.country[0], config.country[1],
743 config.orientation, config.density,
744 String8(ident).string(), String8(str).string()));
745
746 err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
747 myPackage, curType, ident, str, &spans, &config,
748 false, curFormat, overwrite);
749
750 return err;
751}
752
753status_t compileResourceFile(Bundle* bundle,
754 const sp<AaptAssets>& assets,
755 const sp<AaptFile>& in,
756 const ResTable_config& defParams,
757 const bool overwrite,
758 ResourceTable* outTable)
759{
760 ResXMLTree block;
761 status_t err = parseXMLResource(in, &block, false, true);
762 if (err != NO_ERROR) {
763 return err;
764 }
765
766 // Top-level tag.
767 const String16 resources16("resources");
768
769 // Identifier declaration tags.
770 const String16 declare_styleable16("declare-styleable");
771 const String16 attr16("attr");
772
773 // Data creation organizational tags.
774 const String16 string16("string");
775 const String16 drawable16("drawable");
776 const String16 color16("color");
777 const String16 bool16("bool");
778 const String16 integer16("integer");
779 const String16 dimen16("dimen");
780 const String16 fraction16("fraction");
781 const String16 style16("style");
782 const String16 plurals16("plurals");
783 const String16 array16("array");
784 const String16 string_array16("string-array");
785 const String16 integer_array16("integer-array");
786 const String16 public16("public");
Dianne Hackbornf479aa02009-05-20 16:01:06 -0700787 const String16 public_padding16("public-padding");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 const String16 private_symbols16("private-symbols");
Dianne Hackborn1644c6d72012-02-06 15:33:21 -0800789 const String16 java_symbol16("java-symbol");
Dianne Hackborn58c27a02009-08-13 13:36:00 -0700790 const String16 add_resource16("add-resource");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 const String16 skip16("skip");
792 const String16 eat_comment16("eat-comment");
793
794 // Data creation tags.
795 const String16 bag16("bag");
796 const String16 item16("item");
797
798 // Attribute type constants.
799 const String16 enum16("enum");
800
801 // plural values
802 const String16 other16("other");
803 const String16 quantityOther16("^other");
804 const String16 zero16("zero");
805 const String16 quantityZero16("^zero");
806 const String16 one16("one");
807 const String16 quantityOne16("^one");
808 const String16 two16("two");
809 const String16 quantityTwo16("^two");
810 const String16 few16("few");
811 const String16 quantityFew16("^few");
812 const String16 many16("many");
813 const String16 quantityMany16("^many");
814
815 // useful attribute names and special values
816 const String16 name16("name");
817 const String16 translatable16("translatable");
Kenny Root15fe2cb2010-05-28 15:44:32 -0700818 const String16 formatted16("formatted");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 const String16 false16("false");
820
821 const String16 myPackage(assets->getPackage());
822
823 bool hasErrors = false;
Kenny Root15fe2cb2010-05-28 15:44:32 -0700824
825 bool fileIsTranslatable = true;
826 if (strstr(in->getPrintableSource().string(), "donottranslate") != NULL) {
827 fileIsTranslatable = false;
828 }
829
Dianne Hackbornf479aa02009-05-20 16:01:06 -0700830 DefaultKeyedVector<String16, uint32_t> nextPublicId(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831
Adam Lesinski2b8e82f2013-10-04 12:06:38 -0700832 // Stores the resource names that were skipped. Typically this happens when
833 // AAPT is invoked without a product specified and a resource has no
834 // 'default' product attribute.
835 KeyedVector<type_ident_pair_t, bool> skippedResourceNames;
836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 ResXMLTree::event_code_t code;
838 do {
839 code = block.next();
840 } while (code == ResXMLTree::START_NAMESPACE);
841
842 size_t len;
843 if (code != ResXMLTree::START_TAG) {
844 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
845 "No start tag found\n");
846 return UNKNOWN_ERROR;
847 }
848 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
849 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
850 "Invalid start tag %s\n", String8(block.getElementName(&len)).string());
851 return UNKNOWN_ERROR;
852 }
853
854 ResTable_config curParams(defParams);
855
856 ResTable_config pseudoParams(curParams);
Anton Krumina2ef5c02014-03-12 14:46:44 -0700857 pseudoParams.language[0] = 'e';
858 pseudoParams.language[1] = 'n';
859 pseudoParams.country[0] = 'X';
860 pseudoParams.country[1] = 'A';
861
862 ResTable_config pseudoBidiParams(curParams);
863 pseudoBidiParams.language[0] = 'a';
864 pseudoBidiParams.language[1] = 'r';
865 pseudoBidiParams.country[0] = 'X';
866 pseudoBidiParams.country[1] = 'B';
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867
868 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
869 if (code == ResXMLTree::START_TAG) {
870 const String16* curTag = NULL;
871 String16 curType;
872 int32_t curFormat = ResTable_map::TYPE_ANY;
873 bool curIsBag = false;
Robert Greenwalt1aa81702009-06-05 15:59:15 -0700874 bool curIsBagReplaceOnOverwrite = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 bool curIsStyled = false;
876 bool curIsPseudolocalizable = false;
Kenny Root15fe2cb2010-05-28 15:44:32 -0700877 bool curIsFormatted = fileIsTranslatable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 bool localHasErrors = false;
879
880 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
881 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
882 && code != ResXMLTree::BAD_DOCUMENT) {
883 if (code == ResXMLTree::END_TAG) {
884 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
885 break;
886 }
887 }
888 }
889 continue;
890
891 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
892 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
893 && code != ResXMLTree::BAD_DOCUMENT) {
894 if (code == ResXMLTree::END_TAG) {
895 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
896 break;
897 }
898 }
899 }
900 continue;
901
902 } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
903 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
904
905 String16 type;
906 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
907 if (typeIdx < 0) {
908 srcPos.error("A 'type' attribute is required for <public>\n");
909 hasErrors = localHasErrors = true;
910 }
911 type = String16(block.getAttributeStringValue(typeIdx, &len));
912
913 String16 name;
914 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
915 if (nameIdx < 0) {
916 srcPos.error("A 'name' attribute is required for <public>\n");
917 hasErrors = localHasErrors = true;
918 }
919 name = String16(block.getAttributeStringValue(nameIdx, &len));
920
921 uint32_t ident = 0;
922 ssize_t identIdx = block.indexOfAttribute(NULL, "id");
923 if (identIdx >= 0) {
924 const char16_t* identStr = block.getAttributeStringValue(identIdx, &len);
925 Res_value identValue;
926 if (!ResTable::stringToInt(identStr, len, &identValue)) {
927 srcPos.error("Given 'id' attribute is not an integer: %s\n",
928 String8(block.getAttributeStringValue(identIdx, &len)).string());
929 hasErrors = localHasErrors = true;
930 } else {
931 ident = identValue.data;
Dianne Hackbornf479aa02009-05-20 16:01:06 -0700932 nextPublicId.replaceValueFor(type, ident+1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 }
Dianne Hackbornf479aa02009-05-20 16:01:06 -0700934 } else if (nextPublicId.indexOfKey(type) < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 srcPos.error("No 'id' attribute supplied <public>,"
936 " and no previous id defined in this file.\n");
937 hasErrors = localHasErrors = true;
938 } else if (!localHasErrors) {
Dianne Hackbornf479aa02009-05-20 16:01:06 -0700939 ident = nextPublicId.valueFor(type);
940 nextPublicId.replaceValueFor(type, ident+1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 }
942
943 if (!localHasErrors) {
944 err = outTable->addPublic(srcPos, myPackage, type, name, ident);
945 if (err < NO_ERROR) {
946 hasErrors = localHasErrors = true;
947 }
948 }
949 if (!localHasErrors) {
950 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
951 if (symbols != NULL) {
952 symbols = symbols->addNestedSymbol(String8(type), srcPos);
953 }
954 if (symbols != NULL) {
955 symbols->makeSymbolPublic(String8(name), srcPos);
956 String16 comment(
957 block.getComment(&len) ? block.getComment(&len) : nulStr);
958 symbols->appendComment(String8(name), comment, srcPos);
959 } else {
960 srcPos.error("Unable to create symbols!\n");
961 hasErrors = localHasErrors = true;
962 }
963 }
964
965 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
966 if (code == ResXMLTree::END_TAG) {
967 if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
968 break;
969 }
970 }
971 }
972 continue;
973
Dianne Hackbornf479aa02009-05-20 16:01:06 -0700974 } else if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
975 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
976
977 String16 type;
978 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
979 if (typeIdx < 0) {
980 srcPos.error("A 'type' attribute is required for <public-padding>\n");
981 hasErrors = localHasErrors = true;
982 }
983 type = String16(block.getAttributeStringValue(typeIdx, &len));
984
985 String16 name;
986 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
987 if (nameIdx < 0) {
988 srcPos.error("A 'name' attribute is required for <public-padding>\n");
989 hasErrors = localHasErrors = true;
990 }
991 name = String16(block.getAttributeStringValue(nameIdx, &len));
992
993 uint32_t start = 0;
994 ssize_t startIdx = block.indexOfAttribute(NULL, "start");
995 if (startIdx >= 0) {
996 const char16_t* startStr = block.getAttributeStringValue(startIdx, &len);
997 Res_value startValue;
998 if (!ResTable::stringToInt(startStr, len, &startValue)) {
999 srcPos.error("Given 'start' attribute is not an integer: %s\n",
1000 String8(block.getAttributeStringValue(startIdx, &len)).string());
1001 hasErrors = localHasErrors = true;
1002 } else {
1003 start = startValue.data;
1004 }
1005 } else if (nextPublicId.indexOfKey(type) < 0) {
1006 srcPos.error("No 'start' attribute supplied <public-padding>,"
1007 " and no previous id defined in this file.\n");
1008 hasErrors = localHasErrors = true;
1009 } else if (!localHasErrors) {
1010 start = nextPublicId.valueFor(type);
1011 }
1012
1013 uint32_t end = 0;
1014 ssize_t endIdx = block.indexOfAttribute(NULL, "end");
1015 if (endIdx >= 0) {
1016 const char16_t* endStr = block.getAttributeStringValue(endIdx, &len);
1017 Res_value endValue;
1018 if (!ResTable::stringToInt(endStr, len, &endValue)) {
1019 srcPos.error("Given 'end' attribute is not an integer: %s\n",
1020 String8(block.getAttributeStringValue(endIdx, &len)).string());
1021 hasErrors = localHasErrors = true;
1022 } else {
1023 end = endValue.data;
1024 }
1025 } else {
1026 srcPos.error("No 'end' attribute supplied <public-padding>\n");
1027 hasErrors = localHasErrors = true;
1028 }
1029
1030 if (end >= start) {
1031 nextPublicId.replaceValueFor(type, end+1);
1032 } else {
1033 srcPos.error("Padding start '%ul' is after end '%ul'\n",
1034 start, end);
1035 hasErrors = localHasErrors = true;
1036 }
1037
1038 String16 comment(
1039 block.getComment(&len) ? block.getComment(&len) : nulStr);
1040 for (uint32_t curIdent=start; curIdent<=end; curIdent++) {
1041 if (localHasErrors) {
1042 break;
1043 }
1044 String16 curName(name);
1045 char buf[64];
1046 sprintf(buf, "%d", (int)(end-curIdent+1));
1047 curName.append(String16(buf));
1048
1049 err = outTable->addEntry(srcPos, myPackage, type, curName,
1050 String16("padding"), NULL, &curParams, false,
1051 ResTable_map::TYPE_STRING, overwrite);
1052 if (err < NO_ERROR) {
1053 hasErrors = localHasErrors = true;
1054 break;
1055 }
1056 err = outTable->addPublic(srcPos, myPackage, type,
1057 curName, curIdent);
1058 if (err < NO_ERROR) {
1059 hasErrors = localHasErrors = true;
1060 break;
1061 }
1062 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1063 if (symbols != NULL) {
1064 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1065 }
1066 if (symbols != NULL) {
1067 symbols->makeSymbolPublic(String8(curName), srcPos);
1068 symbols->appendComment(String8(curName), comment, srcPos);
1069 } else {
1070 srcPos.error("Unable to create symbols!\n");
1071 hasErrors = localHasErrors = true;
1072 }
1073 }
1074
1075 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1076 if (code == ResXMLTree::END_TAG) {
1077 if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
1078 break;
1079 }
1080 }
1081 }
1082 continue;
1083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1085 String16 pkg;
1086 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
1087 if (pkgIdx < 0) {
1088 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1089 "A 'package' attribute is required for <private-symbols>\n");
1090 hasErrors = localHasErrors = true;
1091 }
1092 pkg = String16(block.getAttributeStringValue(pkgIdx, &len));
1093 if (!localHasErrors) {
1094 assets->setSymbolsPrivatePackage(String8(pkg));
1095 }
1096
1097 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1098 if (code == ResXMLTree::END_TAG) {
1099 if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
1100 break;
1101 }
1102 }
1103 }
1104 continue;
1105
Dianne Hackborn1644c6d72012-02-06 15:33:21 -08001106 } else if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1107 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1108
1109 String16 type;
1110 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1111 if (typeIdx < 0) {
1112 srcPos.error("A 'type' attribute is required for <public>\n");
1113 hasErrors = localHasErrors = true;
1114 }
1115 type = String16(block.getAttributeStringValue(typeIdx, &len));
1116
1117 String16 name;
1118 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1119 if (nameIdx < 0) {
1120 srcPos.error("A 'name' attribute is required for <public>\n");
1121 hasErrors = localHasErrors = true;
1122 }
1123 name = String16(block.getAttributeStringValue(nameIdx, &len));
1124
1125 sp<AaptSymbols> symbols = assets->getJavaSymbolsFor(String8("R"));
1126 if (symbols != NULL) {
1127 symbols = symbols->addNestedSymbol(String8(type), srcPos);
1128 }
1129 if (symbols != NULL) {
1130 symbols->makeSymbolJavaSymbol(String8(name), srcPos);
1131 String16 comment(
1132 block.getComment(&len) ? block.getComment(&len) : nulStr);
1133 symbols->appendComment(String8(name), comment, srcPos);
1134 } else {
1135 srcPos.error("Unable to create symbols!\n");
1136 hasErrors = localHasErrors = true;
1137 }
1138
1139 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1140 if (code == ResXMLTree::END_TAG) {
1141 if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
1142 break;
1143 }
1144 }
1145 }
1146 continue;
1147
1148
Dianne Hackborn58c27a02009-08-13 13:36:00 -07001149 } else if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
1150 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1151
1152 String16 typeName;
1153 ssize_t typeIdx = block.indexOfAttribute(NULL, "type");
1154 if (typeIdx < 0) {
1155 srcPos.error("A 'type' attribute is required for <add-resource>\n");
1156 hasErrors = localHasErrors = true;
1157 }
1158 typeName = String16(block.getAttributeStringValue(typeIdx, &len));
1159
1160 String16 name;
1161 ssize_t nameIdx = block.indexOfAttribute(NULL, "name");
1162 if (nameIdx < 0) {
1163 srcPos.error("A 'name' attribute is required for <add-resource>\n");
1164 hasErrors = localHasErrors = true;
1165 }
1166 name = String16(block.getAttributeStringValue(nameIdx, &len));
1167
1168 outTable->canAddEntry(srcPos, myPackage, typeName, name);
1169
1170 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1171 if (code == ResXMLTree::END_TAG) {
Robert Greenwalt93d72512009-09-02 18:23:57 -07001172 if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
Dianne Hackborn58c27a02009-08-13 13:36:00 -07001173 break;
1174 }
1175 }
1176 }
1177 continue;
1178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1180 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
1181
1182 String16 ident;
1183 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1184 if (identIdx < 0) {
1185 srcPos.error("A 'name' attribute is required for <declare-styleable>\n");
1186 hasErrors = localHasErrors = true;
1187 }
1188 ident = String16(block.getAttributeStringValue(identIdx, &len));
1189
1190 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1191 if (!localHasErrors) {
1192 if (symbols != NULL) {
1193 symbols = symbols->addNestedSymbol(String8("styleable"), srcPos);
1194 }
1195 sp<AaptSymbols> styleSymbols = symbols;
1196 if (symbols != NULL) {
1197 symbols = symbols->addNestedSymbol(String8(ident), srcPos);
1198 }
1199 if (symbols == NULL) {
1200 srcPos.error("Unable to create symbols!\n");
1201 return UNKNOWN_ERROR;
1202 }
1203
1204 String16 comment(
1205 block.getComment(&len) ? block.getComment(&len) : nulStr);
1206 styleSymbols->appendComment(String8(ident), comment, srcPos);
1207 } else {
1208 symbols = NULL;
1209 }
1210
1211 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
1212 if (code == ResXMLTree::START_TAG) {
1213 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1214 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1215 && code != ResXMLTree::BAD_DOCUMENT) {
1216 if (code == ResXMLTree::END_TAG) {
1217 if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
1218 break;
1219 }
1220 }
1221 }
1222 continue;
1223 } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1224 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1225 && code != ResXMLTree::BAD_DOCUMENT) {
1226 if (code == ResXMLTree::END_TAG) {
1227 if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
1228 break;
1229 }
1230 }
1231 }
1232 continue;
1233 } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
1234 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1235 "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
1236 String8(block.getElementName(&len)).string());
1237 return UNKNOWN_ERROR;
1238 }
1239
1240 String16 comment(
1241 block.getComment(&len) ? block.getComment(&len) : nulStr);
1242 String16 itemIdent;
1243 err = compileAttribute(in, block, myPackage, outTable, &itemIdent, true);
1244 if (err != NO_ERROR) {
1245 hasErrors = localHasErrors = true;
1246 }
1247
1248 if (symbols != NULL) {
1249 SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
1250 symbols->addSymbol(String8(itemIdent), 0, srcPos);
1251 symbols->appendComment(String8(itemIdent), comment, srcPos);
1252 //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
1253 // String8(comment).string());
1254 }
1255 } else if (code == ResXMLTree::END_TAG) {
1256 if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
1257 break;
1258 }
1259
1260 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1261 "Found tag </%s> where </attr> is expected\n",
1262 String8(block.getElementName(&len)).string());
1263 return UNKNOWN_ERROR;
1264 }
1265 }
1266 continue;
1267
1268 } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
1269 err = compileAttribute(in, block, myPackage, outTable, NULL);
1270 if (err != NO_ERROR) {
1271 hasErrors = true;
1272 }
1273 continue;
1274
1275 } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
1276 curTag = &item16;
1277 ssize_t attri = block.indexOfAttribute(NULL, "type");
1278 if (attri >= 0) {
1279 curType = String16(block.getAttributeStringValue(attri, &len));
1280 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1281 if (formatIdx >= 0) {
1282 String16 formatStr = String16(block.getAttributeStringValue(
1283 formatIdx, &len));
1284 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1285 gFormatFlags);
1286 if (curFormat == 0) {
1287 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1288 "Tag <item> 'format' attribute value \"%s\" not valid\n",
1289 String8(formatStr).string());
1290 hasErrors = localHasErrors = true;
1291 }
1292 }
1293 } else {
1294 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1295 "A 'type' attribute is required for <item>\n");
1296 hasErrors = localHasErrors = true;
1297 }
1298 curIsStyled = true;
1299 } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
1300 // Note the existence and locale of every string we process
Narayan Kamath788fa412014-01-21 15:32:36 +00001301 char rawLocale[RESTABLE_MAX_LOCALE_LEN];
1302 curParams.getBcp47Locale(rawLocale);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 String8 locale(rawLocale);
1304 String16 name;
1305 String16 translatable;
Kenny Root15fe2cb2010-05-28 15:44:32 -07001306 String16 formatted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307
1308 size_t n = block.getAttributeCount();
1309 for (size_t i = 0; i < n; i++) {
1310 size_t length;
1311 const uint16_t* attr = block.getAttributeName(i, &length);
1312 if (strcmp16(attr, name16.string()) == 0) {
1313 name.setTo(block.getAttributeStringValue(i, &length));
1314 } else if (strcmp16(attr, translatable16.string()) == 0) {
1315 translatable.setTo(block.getAttributeStringValue(i, &length));
Kenny Root15fe2cb2010-05-28 15:44:32 -07001316 } else if (strcmp16(attr, formatted16.string()) == 0) {
1317 formatted.setTo(block.getAttributeStringValue(i, &length));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
1319 }
1320
1321 if (name.size() > 0) {
1322 if (translatable == false16) {
Kenny Root15fe2cb2010-05-28 15:44:32 -07001323 curIsFormatted = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 // Untranslatable strings must only exist in the default [empty] locale
1325 if (locale.size() > 0) {
Adam Lesinskie119b222014-03-20 18:04:57 -07001326 SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
1327 "string '%s' marked untranslatable but exists in locale '%s'\n",
1328 String8(name).string(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 locale.string());
1330 // hasErrors = localHasErrors = true;
1331 } else {
1332 // Intentionally empty block:
1333 //
1334 // Don't add untranslatable strings to the localization table; that
1335 // way if we later see localizations of them, they'll be flagged as
1336 // having no default translation.
1337 }
1338 } else {
Adam Lesinskie119b222014-03-20 18:04:57 -07001339 outTable->addLocalization(
1340 name,
1341 locale,
1342 SourcePos(in->getPrintableSource(), block.getLineNumber()));
Anton Krumina2ef5c02014-03-12 14:46:44 -07001343 curIsPseudolocalizable = fileIsTranslatable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 }
Kenny Root15fe2cb2010-05-28 15:44:32 -07001345
1346 if (formatted == false16) {
1347 curIsFormatted = false;
1348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 }
1350
1351 curTag = &string16;
1352 curType = string16;
1353 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1354 curIsStyled = true;
Narayan Kamath7e1b8ff2013-12-10 09:49:59 +00001355 curIsPseudolocalizable = (translatable != false16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
1357 curTag = &drawable16;
1358 curType = drawable16;
1359 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1360 } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
1361 curTag = &color16;
1362 curType = color16;
1363 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
1364 } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
1365 curTag = &bool16;
1366 curType = bool16;
1367 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
1368 } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
1369 curTag = &integer16;
1370 curType = integer16;
1371 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1372 } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
1373 curTag = &dimen16;
1374 curType = dimen16;
1375 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
1376 } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) {
1377 curTag = &fraction16;
1378 curType = fraction16;
1379 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
1380 } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
1381 curTag = &bag16;
1382 curIsBag = true;
1383 ssize_t attri = block.indexOfAttribute(NULL, "type");
1384 if (attri >= 0) {
1385 curType = String16(block.getAttributeStringValue(attri, &len));
1386 } else {
1387 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1388 "A 'type' attribute is required for <bag>\n");
1389 hasErrors = localHasErrors = true;
1390 }
1391 } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
1392 curTag = &style16;
1393 curType = style16;
1394 curIsBag = true;
1395 } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
1396 curTag = &plurals16;
1397 curType = plurals16;
1398 curIsBag = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001399 curIsPseudolocalizable = fileIsTranslatable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
1401 curTag = &array16;
1402 curType = array16;
1403 curIsBag = true;
Robert Greenwalt1aa81702009-06-05 15:59:15 -07001404 curIsBagReplaceOnOverwrite = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 ssize_t formatIdx = block.indexOfAttribute(NULL, "format");
1406 if (formatIdx >= 0) {
1407 String16 formatStr = String16(block.getAttributeStringValue(
1408 formatIdx, &len));
1409 curFormat = parse_flags(formatStr.string(), formatStr.size(),
1410 gFormatFlags);
1411 if (curFormat == 0) {
1412 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1413 "Tag <array> 'format' attribute value \"%s\" not valid\n",
1414 String8(formatStr).string());
1415 hasErrors = localHasErrors = true;
1416 }
1417 }
1418 } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
Josh Stone02feeb42011-01-17 18:34:11 -08001419 // Check whether these strings need valid formats.
1420 // (simplified form of what string16 does above)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001421 bool isTranslatable = false;
Josh Stone02feeb42011-01-17 18:34:11 -08001422 size_t n = block.getAttributeCount();
Narayan Kamath7e1b8ff2013-12-10 09:49:59 +00001423
1424 // Pseudolocalizable by default, unless this string array isn't
1425 // translatable.
Josh Stone02feeb42011-01-17 18:34:11 -08001426 for (size_t i = 0; i < n; i++) {
1427 size_t length;
1428 const uint16_t* attr = block.getAttributeName(i, &length);
Narayan Kamath7e1b8ff2013-12-10 09:49:59 +00001429 if (strcmp16(attr, formatted16.string()) == 0) {
Josh Stone02feeb42011-01-17 18:34:11 -08001430 const uint16_t* value = block.getAttributeStringValue(i, &length);
1431 if (strcmp16(value, false16.string()) == 0) {
1432 curIsFormatted = false;
Josh Stone02feeb42011-01-17 18:34:11 -08001433 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001434 } else if (strcmp16(attr, translatable16.string()) == 0) {
1435 const uint16_t* value = block.getAttributeStringValue(i, &length);
1436 if (strcmp16(value, false16.string()) == 0) {
1437 isTranslatable = false;
1438 }
Josh Stone02feeb42011-01-17 18:34:11 -08001439 }
1440 }
1441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 curTag = &string_array16;
1443 curType = array16;
1444 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
1445 curIsBag = true;
Robert Greenwalt1aa81702009-06-05 15:59:15 -07001446 curIsBagReplaceOnOverwrite = true;
Anton Krumina2ef5c02014-03-12 14:46:44 -07001447 curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
1449 curTag = &integer_array16;
1450 curType = array16;
1451 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
1452 curIsBag = true;
Robert Greenwalt1aa81702009-06-05 15:59:15 -07001453 curIsBagReplaceOnOverwrite = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 } else {
1455 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1456 "Found tag %s where item is expected\n",
1457 String8(block.getElementName(&len)).string());
1458 return UNKNOWN_ERROR;
1459 }
1460
1461 String16 ident;
1462 ssize_t identIdx = block.indexOfAttribute(NULL, "name");
1463 if (identIdx >= 0) {
1464 ident = String16(block.getAttributeStringValue(identIdx, &len));
1465 } else {
1466 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1467 "A 'name' attribute is required for <%s>\n",
1468 String8(*curTag).string());
1469 hasErrors = localHasErrors = true;
1470 }
1471
Dianne Hackborn407f6252010-10-04 11:31:17 -07001472 String16 product;
1473 identIdx = block.indexOfAttribute(NULL, "product");
1474 if (identIdx >= 0) {
1475 product = String16(block.getAttributeStringValue(identIdx, &len));
1476 }
1477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 String16 comment(block.getComment(&len) ? block.getComment(&len) : nulStr);
1479
1480 if (curIsBag) {
1481 // Figure out the parent of this bag...
1482 String16 parentIdent;
1483 ssize_t parentIdentIdx = block.indexOfAttribute(NULL, "parent");
1484 if (parentIdentIdx >= 0) {
1485 parentIdent = String16(block.getAttributeStringValue(parentIdentIdx, &len));
1486 } else {
1487 ssize_t sep = ident.findLast('.');
1488 if (sep >= 0) {
1489 parentIdent.setTo(ident, sep);
1490 }
1491 }
1492
1493 if (!localHasErrors) {
Robert Greenwalt1aa81702009-06-05 15:59:15 -07001494 err = outTable->startBag(SourcePos(in->getPrintableSource(),
1495 block.getLineNumber()), myPackage, curType, ident,
1496 parentIdent, &curParams,
1497 overwrite, curIsBagReplaceOnOverwrite);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 if (err != NO_ERROR) {
1499 hasErrors = localHasErrors = true;
1500 }
1501 }
1502
1503 ssize_t elmIndex = 0;
1504 char elmIndexStr[14];
1505 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1506 && code != ResXMLTree::BAD_DOCUMENT) {
1507
1508 if (code == ResXMLTree::START_TAG) {
1509 if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
1510 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1511 "Tag <%s> can not appear inside <%s>, only <item>\n",
1512 String8(block.getElementName(&len)).string(),
1513 String8(*curTag).string());
1514 return UNKNOWN_ERROR;
1515 }
1516
1517 String16 itemIdent;
1518 if (curType == array16) {
1519 sprintf(elmIndexStr, "^index_%d", (int)elmIndex++);
1520 itemIdent = String16(elmIndexStr);
1521 } else if (curType == plurals16) {
1522 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "quantity");
1523 if (itemIdentIdx >= 0) {
1524 String16 quantity16(block.getAttributeStringValue(itemIdentIdx, &len));
1525 if (quantity16 == other16) {
1526 itemIdent = quantityOther16;
1527 }
1528 else if (quantity16 == zero16) {
1529 itemIdent = quantityZero16;
1530 }
1531 else if (quantity16 == one16) {
1532 itemIdent = quantityOne16;
1533 }
1534 else if (quantity16 == two16) {
1535 itemIdent = quantityTwo16;
1536 }
1537 else if (quantity16 == few16) {
1538 itemIdent = quantityFew16;
1539 }
1540 else if (quantity16 == many16) {
1541 itemIdent = quantityMany16;
1542 }
1543 else {
1544 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1545 "Illegal 'quantity' attribute is <item> inside <plurals>\n");
1546 hasErrors = localHasErrors = true;
1547 }
1548 } else {
1549 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1550 "A 'quantity' attribute is required for <item> inside <plurals>\n");
1551 hasErrors = localHasErrors = true;
1552 }
1553 } else {
1554 ssize_t itemIdentIdx = block.indexOfAttribute(NULL, "name");
1555 if (itemIdentIdx >= 0) {
1556 itemIdent = String16(block.getAttributeStringValue(itemIdentIdx, &len));
1557 } else {
1558 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1559 "A 'name' attribute is required for <item>\n");
1560 hasErrors = localHasErrors = true;
1561 }
1562 }
1563
1564 ResXMLParser::ResXMLPosition parserPosition;
1565 block.getPosition(&parserPosition);
1566
1567 err = parseAndAddBag(bundle, in, &block, curParams, myPackage, curType,
Kenny Root15fe2cb2010-05-28 15:44:32 -07001568 ident, parentIdent, itemIdent, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001569 product, NO_PSEUDOLOCALIZATION, overwrite, outTable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 if (err == NO_ERROR) {
1571 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001572 && bundle->getPseudolocalize() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001574 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1575 PSEUDO_ACCENTED) {
1576 block.setPosition(parserPosition);
1577 err = parseAndAddBag(bundle, in, &block, pseudoParams, myPackage,
1578 curType, ident, parentIdent, itemIdent, curFormat,
1579 curIsFormatted, product, PSEUDO_ACCENTED,
1580 overwrite, outTable);
1581 }
1582 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1583 PSEUDO_BIDI) {
1584 block.setPosition(parserPosition);
1585 err = parseAndAddBag(bundle, in, &block, pseudoBidiParams, myPackage,
1586 curType, ident, parentIdent, itemIdent, curFormat,
1587 curIsFormatted, product, PSEUDO_BIDI,
1588 overwrite, outTable);
1589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 }
Anton Krumina2ef5c02014-03-12 14:46:44 -07001591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 if (err != NO_ERROR) {
1593 hasErrors = localHasErrors = true;
1594 }
1595 } else if (code == ResXMLTree::END_TAG) {
1596 if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
1597 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1598 "Found tag </%s> where </%s> is expected\n",
1599 String8(block.getElementName(&len)).string(),
1600 String8(*curTag).string());
1601 return UNKNOWN_ERROR;
1602 }
1603 break;
1604 }
1605 }
1606 } else {
1607 ResXMLParser::ResXMLPosition parserPosition;
1608 block.getPosition(&parserPosition);
1609
1610 err = parseAndAddEntry(bundle, in, &block, curParams, myPackage, curType, ident,
Kenny Root15fe2cb2010-05-28 15:44:32 -07001611 *curTag, curIsStyled, curFormat, curIsFormatted,
Anton Krumina2ef5c02014-03-12 14:46:44 -07001612 product, NO_PSEUDOLOCALIZATION, overwrite, &skippedResourceNames, outTable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613
1614 if (err < NO_ERROR) { // Why err < NO_ERROR instead of err != NO_ERROR?
1615 hasErrors = localHasErrors = true;
1616 }
1617 else if (err == NO_ERROR) {
1618 if (curIsPseudolocalizable && localeIsDefined(curParams)
Anton Krumina2ef5c02014-03-12 14:46:44 -07001619 && bundle->getPseudolocalize() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 // pseudolocalize here
Anton Krumina2ef5c02014-03-12 14:46:44 -07001621 if ((PSEUDO_ACCENTED & bundle->getPseudolocalize()) ==
1622 PSEUDO_ACCENTED) {
1623 block.setPosition(parserPosition);
1624 err = parseAndAddEntry(bundle, in, &block, pseudoParams, myPackage, curType,
1625 ident, *curTag, curIsStyled, curFormat,
1626 curIsFormatted, product,
1627 PSEUDO_ACCENTED, overwrite, &skippedResourceNames, outTable);
1628 }
1629 if ((PSEUDO_BIDI & bundle->getPseudolocalize()) ==
1630 PSEUDO_BIDI) {
1631 block.setPosition(parserPosition);
1632 err = parseAndAddEntry(bundle, in, &block, pseudoBidiParams,
1633 myPackage, curType, ident, *curTag, curIsStyled, curFormat,
1634 curIsFormatted, product,
1635 PSEUDO_BIDI, overwrite, &skippedResourceNames, outTable);
1636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 if (err != NO_ERROR) {
1638 hasErrors = localHasErrors = true;
1639 }
1640 }
1641 }
1642 }
1643
1644#if 0
1645 if (comment.size() > 0) {
1646 printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
1647 String8(curType).string(), String8(ident).string(),
1648 String8(comment).string());
1649 }
1650#endif
1651 if (!localHasErrors) {
1652 outTable->appendComment(myPackage, curType, ident, comment, false);
1653 }
1654 }
1655 else if (code == ResXMLTree::END_TAG) {
1656 if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
1657 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1658 "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
1659 return UNKNOWN_ERROR;
1660 }
1661 }
1662 else if (code == ResXMLTree::START_NAMESPACE || code == ResXMLTree::END_NAMESPACE) {
1663 }
1664 else if (code == ResXMLTree::TEXT) {
1665 if (isWhitespace(block.getText(&len))) {
1666 continue;
1667 }
1668 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
1669 "Found text \"%s\" where item tag is expected\n",
1670 String8(block.getText(&len)).string());
1671 return UNKNOWN_ERROR;
1672 }
1673 }
1674
Adam Lesinski2b8e82f2013-10-04 12:06:38 -07001675 // For every resource defined, there must be exist one variant with a product attribute
1676 // set to 'default' (or no product attribute at all).
1677 // We check to see that for every resource that was ignored because of a mismatched
1678 // product attribute, some product variant of that resource was processed.
1679 for (size_t i = 0; i < skippedResourceNames.size(); i++) {
1680 if (skippedResourceNames[i]) {
1681 const type_ident_pair_t& p = skippedResourceNames.keyAt(i);
1682 if (!outTable->hasBagOrEntry(myPackage, p.type, p.ident)) {
1683 const char* bundleProduct =
1684 (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
1685 fprintf(stderr, "In resource file %s: %s\n",
1686 in->getPrintableSource().string(),
1687 curParams.toString().string());
1688
1689 fprintf(stderr, "\t%s '%s' does not match product %s.\n"
1690 "\tYou may have forgotten to include a 'default' product variant"
1691 " of the resource.\n",
1692 String8(p.type).string(), String8(p.ident).string(),
1693 bundleProduct[0] == 0 ? "default" : bundleProduct);
1694 return UNKNOWN_ERROR;
1695 }
1696 }
1697 }
1698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1700}
1701
1702ResourceTable::ResourceTable(Bundle* bundle, const String16& assetsPackage)
1703 : mAssetsPackage(assetsPackage), mNextPackageId(1), mHaveAppPackage(false),
1704 mIsAppPackage(!bundle->getExtending()),
1705 mNumLocal(0),
1706 mBundle(bundle)
1707{
1708}
1709
1710status_t ResourceTable::addIncludedResources(Bundle* bundle, const sp<AaptAssets>& assets)
1711{
1712 status_t err = assets->buildIncludedResources(bundle);
1713 if (err != NO_ERROR) {
1714 return err;
1715 }
1716
1717 // For future reference to included resources.
1718 mAssets = assets;
1719
1720 const ResTable& incl = assets->getIncludedResources();
1721
1722 // Retrieve all the packages.
1723 const size_t N = incl.getBasePackageCount();
1724 for (size_t phase=0; phase<2; phase++) {
1725 for (size_t i=0; i<N; i++) {
1726 String16 name(incl.getBasePackageName(i));
1727 uint32_t id = incl.getBasePackageId(i);
1728 // First time through: only add base packages (id
1729 // is not 0); second time through add the other
1730 // packages.
1731 if (phase != 0) {
1732 if (id != 0) {
1733 // Skip base packages -- already one.
1734 id = 0;
1735 } else {
1736 // Assign a dynamic id.
1737 id = mNextPackageId;
1738 }
1739 } else if (id != 0) {
1740 if (id == 127) {
1741 if (mHaveAppPackage) {
Dianne Hackborna96cbb42009-05-13 15:06:13 -07001742 fprintf(stderr, "Included resources have two application packages!\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 return UNKNOWN_ERROR;
1744 }
1745 mHaveAppPackage = true;
1746 }
1747 if (mNextPackageId > id) {
1748 fprintf(stderr, "Included base package ID %d already in use!\n", id);
1749 return UNKNOWN_ERROR;
1750 }
1751 }
1752 if (id != 0) {
1753 NOISY(printf("Including package %s with ID=%d\n",
1754 String8(name).string(), id));
1755 sp<Package> p = new Package(name, id);
1756 mPackages.add(name, p);
1757 mOrderedPackages.add(p);
1758
1759 if (id >= mNextPackageId) {
1760 mNextPackageId = id+1;
1761 }
1762 }
1763 }
1764 }
1765
1766 // Every resource table always has one first entry, the bag attributes.
1767 const SourcePos unknown(String8("????"), 0);
1768 sp<Type> attr = getType(mAssetsPackage, String16("attr"), unknown);
1769
1770 return NO_ERROR;
1771}
1772
1773status_t ResourceTable::addPublic(const SourcePos& sourcePos,
1774 const String16& package,
1775 const String16& type,
1776 const String16& name,
1777 const uint32_t ident)
1778{
1779 uint32_t rid = mAssets->getIncludedResources()
1780 .identifierForName(name.string(), name.size(),
1781 type.string(), type.size(),
1782 package.string(), package.size());
1783 if (rid != 0) {
1784 sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
1785 String8(type).string(), String8(name).string(),
1786 String8(package).string());
1787 return UNKNOWN_ERROR;
1788 }
1789
1790 sp<Type> t = getType(package, type, sourcePos);
1791 if (t == NULL) {
1792 return UNKNOWN_ERROR;
1793 }
1794 return t->addPublic(sourcePos, name, ident);
1795}
1796
1797status_t ResourceTable::addEntry(const SourcePos& sourcePos,
1798 const String16& package,
1799 const String16& type,
1800 const String16& name,
1801 const String16& value,
1802 const Vector<StringPool::entry_style_span>* style,
1803 const ResTable_config* params,
1804 const bool doSetIndex,
1805 const int32_t format,
1806 const bool overwrite)
1807{
1808 // Check for adding entries in other packages... for now we do
1809 // nothing. We need to do the right thing here to support skinning.
1810 uint32_t rid = mAssets->getIncludedResources()
1811 .identifierForName(name.string(), name.size(),
1812 type.string(), type.size(),
1813 package.string(), package.size());
1814 if (rid != 0) {
1815 return NO_ERROR;
1816 }
1817
1818#if 0
1819 if (name == String16("left")) {
1820 printf("Adding entry left: file=%s, line=%d, type=%s, value=%s\n",
1821 sourcePos.file.string(), sourcePos.line, String8(type).string(),
1822 String8(value).string());
1823 }
1824#endif
Robert Greenwaltf878e2d2009-06-09 09:14:20 -07001825
1826 sp<Entry> e = getEntry(package, type, name, sourcePos, overwrite,
1827 params, doSetIndex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 if (e == NULL) {
1829 return UNKNOWN_ERROR;
1830 }
1831 status_t err = e->setItem(sourcePos, value, style, format, overwrite);
1832 if (err == NO_ERROR) {
1833 mNumLocal++;
1834 }
1835 return err;
1836}
1837
1838status_t ResourceTable::startBag(const SourcePos& sourcePos,
1839 const String16& package,
1840 const String16& type,
1841 const String16& name,
1842 const String16& bagParent,
1843 const ResTable_config* params,
Robert Greenwalt1aa81702009-06-05 15:59:15 -07001844 bool overlay,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 bool replace, bool isId)
1846{
Robert Greenwalt4b4f4a92009-04-02 16:55:50 -07001847 status_t result = NO_ERROR;
1848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 // Check for adding entries in other packages... for now we do
1850 // nothing. We need to do the right thing here to support skinning.
1851 uint32_t rid = mAssets->getIncludedResources()
1852 .identifierForName(name.string(), name.size(),
1853 type.string(), type.size(),
1854 package.string(), package.size());
1855 if (rid != 0) {
1856 return NO_ERROR;
1857 }
1858
1859#if 0
1860 if (name == String16("left")) {
1861 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1862 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1863 }
1864#endif
Xavier Ducrohet99080c72010-02-04 18:45:31 -08001865 if (overlay && !mBundle->getAutoAddOverlay() && !hasBagOrEntry(package, type, name)) {
Dianne Hackborn58c27a02009-08-13 13:36:00 -07001866 bool canAdd = false;
1867 sp<Package> p = mPackages.valueFor(package);
1868 if (p != NULL) {
1869 sp<Type> t = p->getTypes().valueFor(type);
1870 if (t != NULL) {
1871 if (t->getCanAddEntries().indexOf(name) >= 0) {
1872 canAdd = true;
1873 }
1874 }
1875 }
1876 if (!canAdd) {
1877 sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
1878 String8(name).string());
1879 return UNKNOWN_ERROR;
1880 }
Robert Greenwalt1aa81702009-06-05 15:59:15 -07001881 }
Robert Greenwaltf878e2d2009-06-09 09:14:20 -07001882 sp<Entry> e = getEntry(package, type, name, sourcePos, overlay, params);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 if (e == NULL) {
1884 return UNKNOWN_ERROR;
1885 }
1886
1887 // If a parent is explicitly specified, set it.
1888 if (bagParent.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 e->setParent(bagParent);
1890 }
Robert Greenwalt4b4f4a92009-04-02 16:55:50 -07001891
1892 if ((result = e->makeItABag(sourcePos)) != NO_ERROR) {
1893 return result;
1894 }
Robert Greenwalt9411a392009-04-03 16:44:30 -07001895
Robert Greenwalt1aa81702009-06-05 15:59:15 -07001896 if (overlay && replace) {
Robert Greenwalt9411a392009-04-03 16:44:30 -07001897 return e->emptyBag(sourcePos);
1898 }
1899 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900}
1901
1902status_t ResourceTable::addBag(const SourcePos& sourcePos,
1903 const String16& package,
1904 const String16& type,
1905 const String16& name,
1906 const String16& bagParent,
1907 const String16& bagKey,
1908 const String16& value,
1909 const Vector<StringPool::entry_style_span>* style,
1910 const ResTable_config* params,
1911 bool replace, bool isId, const int32_t format)
1912{
1913 // Check for adding entries in other packages... for now we do
1914 // nothing. We need to do the right thing here to support skinning.
1915 uint32_t rid = mAssets->getIncludedResources()
1916 .identifierForName(name.string(), name.size(),
1917 type.string(), type.size(),
1918 package.string(), package.size());
1919 if (rid != 0) {
1920 return NO_ERROR;
1921 }
1922
1923#if 0
1924 if (name == String16("left")) {
1925 printf("Adding bag left: file=%s, line=%d, type=%s\n",
1926 sourcePos.file.striing(), sourcePos.line, String8(type).string());
1927 }
1928#endif
Robert Greenwaltf878e2d2009-06-09 09:14:20 -07001929 sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 if (e == NULL) {
1931 return UNKNOWN_ERROR;
1932 }
1933
1934 // If a parent is explicitly specified, set it.
1935 if (bagParent.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 e->setParent(bagParent);
1937 }
1938
1939 const bool first = e->getBag().indexOfKey(bagKey) < 0;
1940 status_t err = e->addToBag(sourcePos, bagKey, value, style, replace, isId, format);
1941 if (err == NO_ERROR && first) {
1942 mNumLocal++;
1943 }
1944 return err;
1945}
1946
1947bool ResourceTable::hasBagOrEntry(const String16& package,
1948 const String16& type,
1949 const String16& name) const
1950{
1951 // First look for this in the included resources...
1952 uint32_t rid = mAssets->getIncludedResources()
1953 .identifierForName(name.string(), name.size(),
1954 type.string(), type.size(),
1955 package.string(), package.size());
1956 if (rid != 0) {
1957 return true;
1958 }
1959
1960 sp<Package> p = mPackages.valueFor(package);
1961 if (p != NULL) {
1962 sp<Type> t = p->getTypes().valueFor(type);
1963 if (t != NULL) {
1964 sp<ConfigList> c = t->getConfigs().valueFor(name);
1965 if (c != NULL) return true;
1966 }
1967 }
1968
1969 return false;
1970}
1971
Eric Fischer914f7e62011-09-27 16:09:41 -07001972bool ResourceTable::hasBagOrEntry(const String16& package,
1973 const String16& type,
1974 const String16& name,
1975 const ResTable_config& config) const
1976{
1977 // First look for this in the included resources...
1978 uint32_t rid = mAssets->getIncludedResources()
1979 .identifierForName(name.string(), name.size(),
1980 type.string(), type.size(),
1981 package.string(), package.size());
1982 if (rid != 0) {
1983 return true;
1984 }
1985
1986 sp<Package> p = mPackages.valueFor(package);
1987 if (p != NULL) {
1988 sp<Type> t = p->getTypes().valueFor(type);
1989 if (t != NULL) {
1990 sp<ConfigList> c = t->getConfigs().valueFor(name);
1991 if (c != NULL) {
1992 sp<Entry> e = c->getEntries().valueFor(config);
1993 if (e != NULL) {
1994 return true;
1995 }
1996 }
1997 }
1998 }
1999
2000 return false;
2001}
2002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003bool ResourceTable::hasBagOrEntry(const String16& ref,
2004 const String16* defType,
2005 const String16* defPackage)
2006{
2007 String16 package, type, name;
2008 if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
2009 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
2010 return false;
2011 }
2012 return hasBagOrEntry(package, type, name);
2013}
2014
2015bool ResourceTable::appendComment(const String16& package,
2016 const String16& type,
2017 const String16& name,
2018 const String16& comment,
2019 bool onlyIfEmpty)
2020{
2021 if (comment.size() <= 0) {
2022 return true;
2023 }
2024
2025 sp<Package> p = mPackages.valueFor(package);
2026 if (p != NULL) {
2027 sp<Type> t = p->getTypes().valueFor(type);
2028 if (t != NULL) {
2029 sp<ConfigList> c = t->getConfigs().valueFor(name);
2030 if (c != NULL) {
2031 c->appendComment(comment, onlyIfEmpty);
2032 return true;
2033 }
2034 }
2035 }
2036 return false;
2037}
2038
2039bool ResourceTable::appendTypeComment(const String16& package,
2040 const String16& type,
2041 const String16& name,
2042 const String16& comment)
2043{
2044 if (comment.size() <= 0) {
2045 return true;
2046 }
2047
2048 sp<Package> p = mPackages.valueFor(package);
2049 if (p != NULL) {
2050 sp<Type> t = p->getTypes().valueFor(type);
2051 if (t != NULL) {
2052 sp<ConfigList> c = t->getConfigs().valueFor(name);
2053 if (c != NULL) {
2054 c->appendTypeComment(comment);
2055 return true;
2056 }
2057 }
2058 }
2059 return false;
2060}
2061
Dianne Hackborn58c27a02009-08-13 13:36:00 -07002062void ResourceTable::canAddEntry(const SourcePos& pos,
2063 const String16& package, const String16& type, const String16& name)
2064{
2065 sp<Type> t = getType(package, type, pos);
2066 if (t != NULL) {
2067 t->canAddEntry(name);
2068 }
2069}
2070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071size_t ResourceTable::size() const {
2072 return mPackages.size();
2073}
2074
2075size_t ResourceTable::numLocalResources() const {
2076 return mNumLocal;
2077}
2078
2079bool ResourceTable::hasResources() const {
2080 return mNumLocal > 0;
2081}
2082
2083sp<AaptFile> ResourceTable::flatten(Bundle* bundle)
2084{
2085 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2086 status_t err = flatten(bundle, data);
2087 return err == NO_ERROR ? data : NULL;
2088}
2089
2090inline uint32_t ResourceTable::getResId(const sp<Package>& p,
2091 const sp<Type>& t,
2092 uint32_t nameId)
2093{
2094 return makeResId(p->getAssignedId(), t->getIndex(), nameId);
2095}
2096
2097uint32_t ResourceTable::getResId(const String16& package,
2098 const String16& type,
2099 const String16& name,
2100 bool onlyPublic) const
2101{
Christopher Tated8dde13a2012-11-16 15:58:08 -08002102 uint32_t id = ResourceIdCache::lookup(package, type, name, onlyPublic);
2103 if (id != 0) return id; // cache hit
2104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 sp<Package> p = mPackages.valueFor(package);
2106 if (p == NULL) return 0;
2107
2108 // First look for this in the included resources...
2109 uint32_t specFlags = 0;
2110 uint32_t rid = mAssets->getIncludedResources()
2111 .identifierForName(name.string(), name.size(),
2112 type.string(), type.size(),
2113 package.string(), package.size(),
2114 &specFlags);
2115 if (rid != 0) {
2116 if (onlyPublic) {
2117 if ((specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
2118 return 0;
2119 }
2120 }
2121
2122 if (Res_INTERNALID(rid)) {
Christopher Tated8dde13a2012-11-16 15:58:08 -08002123 return ResourceIdCache::store(package, type, name, onlyPublic, rid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124 }
Christopher Tated8dde13a2012-11-16 15:58:08 -08002125 return ResourceIdCache::store(package, type, name, onlyPublic,
2126 Res_MAKEID(p->getAssignedId()-1, Res_GETTYPE(rid), Res_GETENTRY(rid)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 }
2128
2129 sp<Type> t = p->getTypes().valueFor(type);
2130 if (t == NULL) return 0;
2131 sp<ConfigList> c = t->getConfigs().valueFor(name);
2132 if (c == NULL) return 0;
2133 int32_t ei = c->getEntryIndex();
2134 if (ei < 0) return 0;
Christopher Tated8dde13a2012-11-16 15:58:08 -08002135
2136 return ResourceIdCache::store(package, type, name, onlyPublic,
2137 getResId(p, t, ei));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138}
2139
2140uint32_t ResourceTable::getResId(const String16& ref,
2141 const String16* defType,
2142 const String16* defPackage,
2143 const char** outErrorMsg,
2144 bool onlyPublic) const
2145{
2146 String16 package, type, name;
Dianne Hackborn426431a2011-06-09 11:29:08 -07002147 bool refOnlyPublic = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 if (!ResTable::expandResourceRef(
2149 ref.string(), ref.size(), &package, &type, &name,
2150 defType, defPackage ? defPackage:&mAssetsPackage,
Dianne Hackborn426431a2011-06-09 11:29:08 -07002151 outErrorMsg, &refOnlyPublic)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 NOISY(printf("Expanding resource: ref=%s\n",
2153 String8(ref).string()));
2154 NOISY(printf("Expanding resource: defType=%s\n",
2155 defType ? String8(*defType).string() : "NULL"));
2156 NOISY(printf("Expanding resource: defPackage=%s\n",
2157 defPackage ? String8(*defPackage).string() : "NULL"));
2158 NOISY(printf("Expanding resource: ref=%s\n", String8(ref).string()));
2159 NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
2160 String8(package).string(), String8(type).string(),
2161 String8(name).string()));
2162 return 0;
2163 }
Dianne Hackborn426431a2011-06-09 11:29:08 -07002164 uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 NOISY(printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
2166 String8(package).string(), String8(type).string(),
2167 String8(name).string(), res));
2168 if (res == 0) {
2169 if (outErrorMsg)
2170 *outErrorMsg = "No resource found that matches the given name";
2171 }
2172 return res;
2173}
2174
2175bool ResourceTable::isValidResourceName(const String16& s)
2176{
2177 const char16_t* p = s.string();
2178 bool first = true;
2179 while (*p) {
2180 if ((*p >= 'a' && *p <= 'z')
2181 || (*p >= 'A' && *p <= 'Z')
2182 || *p == '_'
2183 || (!first && *p >= '0' && *p <= '9')) {
2184 first = false;
2185 p++;
2186 continue;
2187 }
2188 return false;
2189 }
2190 return true;
2191}
2192
2193bool ResourceTable::stringToValue(Res_value* outValue, StringPool* pool,
2194 const String16& str,
2195 bool preserveSpaces, bool coerceType,
2196 uint32_t attrID,
2197 const Vector<StringPool::entry_style_span>* style,
2198 String16* outStr, void* accessorCookie,
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002199 uint32_t attrType, const String8* configTypeName,
2200 const ConfigDescription* config)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201{
2202 String16 finalStr;
2203
2204 bool res = true;
2205 if (style == NULL || style->size() == 0) {
2206 // Text is not styled so it can be any type... let's figure it out.
2207 res = mAssets->getIncludedResources()
2208 .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
2209 coerceType, attrID, NULL, &mAssetsPackage, this,
2210 accessorCookie, attrType);
2211 } else {
2212 // Styled text can only be a string, and while collecting the style
2213 // information we have already processed that string!
2214 outValue->size = sizeof(Res_value);
2215 outValue->res0 = 0;
Kenny Root77456222010-03-10 11:38:05 -08002216 outValue->dataType = outValue->TYPE_STRING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 outValue->data = 0;
2218 finalStr = str;
2219 }
2220
2221 if (!res) {
2222 return false;
2223 }
2224
Kenny Root77456222010-03-10 11:38:05 -08002225 if (outValue->dataType == outValue->TYPE_STRING) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 // Should do better merging styles.
2227 if (pool) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002228 String8 configStr;
2229 if (config != NULL) {
2230 configStr = config->toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 } else {
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002232 configStr = "(null)";
2233 }
2234 NOISY(printf("Adding to pool string style #%d config %s: %s\n",
2235 style != NULL ? style->size() : 0,
2236 configStr.string(), String8(finalStr).string()));
2237 if (style != NULL && style->size() > 0) {
2238 outValue->data = pool->add(finalStr, *style, configTypeName, config);
2239 } else {
2240 outValue->data = pool->add(finalStr, true, configTypeName, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 }
2242 } else {
2243 // Caller will fill this in later.
2244 outValue->data = 0;
2245 }
2246
2247 if (outStr) {
2248 *outStr = finalStr;
2249 }
2250
2251 }
2252
2253 return true;
2254}
2255
2256uint32_t ResourceTable::getCustomResource(
2257 const String16& package, const String16& type, const String16& name) const
2258{
2259 //printf("getCustomResource: %s %s %s\n", String8(package).string(),
2260 // String8(type).string(), String8(name).string());
2261 sp<Package> p = mPackages.valueFor(package);
2262 if (p == NULL) return 0;
2263 sp<Type> t = p->getTypes().valueFor(type);
2264 if (t == NULL) return 0;
2265 sp<ConfigList> c = t->getConfigs().valueFor(name);
2266 if (c == NULL) return 0;
2267 int32_t ei = c->getEntryIndex();
2268 if (ei < 0) return 0;
2269 return getResId(p, t, ei);
2270}
2271
2272uint32_t ResourceTable::getCustomResourceWithCreation(
2273 const String16& package, const String16& type, const String16& name,
2274 const bool createIfNotFound)
2275{
2276 uint32_t resId = getCustomResource(package, type, name);
2277 if (resId != 0 || !createIfNotFound) {
2278 return resId;
2279 }
2280 String16 value("false");
2281
2282 status_t status = addEntry(mCurrentXmlPos, package, type, name, value, NULL, NULL, true);
2283 if (status == NO_ERROR) {
2284 resId = getResId(package, type, name);
2285 return resId;
2286 }
2287 return 0;
2288}
2289
2290uint32_t ResourceTable::getRemappedPackage(uint32_t origPackage) const
2291{
2292 return origPackage;
2293}
2294
2295bool ResourceTable::getAttributeType(uint32_t attrID, uint32_t* outType)
2296{
2297 //printf("getAttributeType #%08x\n", attrID);
2298 Res_value value;
2299 if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
2300 //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
2301 // String8(getEntry(attrID)->getName()).string(), value.data);
2302 *outType = value.data;
2303 return true;
2304 }
2305 return false;
2306}
2307
2308bool ResourceTable::getAttributeMin(uint32_t attrID, uint32_t* outMin)
2309{
2310 //printf("getAttributeMin #%08x\n", attrID);
2311 Res_value value;
2312 if (getItemValue(attrID, ResTable_map::ATTR_MIN, &value)) {
2313 *outMin = value.data;
2314 return true;
2315 }
2316 return false;
2317}
2318
2319bool ResourceTable::getAttributeMax(uint32_t attrID, uint32_t* outMax)
2320{
2321 //printf("getAttributeMax #%08x\n", attrID);
2322 Res_value value;
2323 if (getItemValue(attrID, ResTable_map::ATTR_MAX, &value)) {
2324 *outMax = value.data;
2325 return true;
2326 }
2327 return false;
2328}
2329
2330uint32_t ResourceTable::getAttributeL10N(uint32_t attrID)
2331{
2332 //printf("getAttributeL10N #%08x\n", attrID);
2333 Res_value value;
2334 if (getItemValue(attrID, ResTable_map::ATTR_L10N, &value)) {
2335 return value.data;
2336 }
2337 return ResTable_map::L10N_NOT_REQUIRED;
2338}
2339
2340bool ResourceTable::getLocalizationSetting()
2341{
2342 return mBundle->getRequireLocalization();
2343}
2344
2345void ResourceTable::reportError(void* accessorCookie, const char* fmt, ...)
2346{
2347 if (accessorCookie != NULL && fmt != NULL) {
2348 AccessorCookie* ac = (AccessorCookie*)accessorCookie;
2349 int retval=0;
2350 char buf[1024];
2351 va_list ap;
2352 va_start(ap, fmt);
2353 retval = vsnprintf(buf, sizeof(buf), fmt, ap);
2354 va_end(ap);
2355 ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
2356 buf, ac->attr.string(), ac->value.string());
2357 }
2358}
2359
2360bool ResourceTable::getAttributeKeys(
2361 uint32_t attrID, Vector<String16>* outKeys)
2362{
2363 sp<const Entry> e = getEntry(attrID);
2364 if (e != NULL) {
2365 const size_t N = e->getBag().size();
2366 for (size_t i=0; i<N; i++) {
2367 const String16& key = e->getBag().keyAt(i);
2368 if (key.size() > 0 && key.string()[0] != '^') {
2369 outKeys->add(key);
2370 }
2371 }
2372 return true;
2373 }
2374 return false;
2375}
2376
2377bool ResourceTable::getAttributeEnum(
2378 uint32_t attrID, const char16_t* name, size_t nameLen,
2379 Res_value* outValue)
2380{
2381 //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
2382 String16 nameStr(name, nameLen);
2383 sp<const Entry> e = getEntry(attrID);
2384 if (e != NULL) {
2385 const size_t N = e->getBag().size();
2386 for (size_t i=0; i<N; i++) {
2387 //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
2388 // String8(e->getBag().keyAt(i)).string());
2389 if (e->getBag().keyAt(i) == nameStr) {
2390 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
2391 }
2392 }
2393 }
2394 return false;
2395}
2396
2397bool ResourceTable::getAttributeFlags(
2398 uint32_t attrID, const char16_t* name, size_t nameLen,
2399 Res_value* outValue)
2400{
2401 outValue->dataType = Res_value::TYPE_INT_HEX;
2402 outValue->data = 0;
2403
2404 //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
2405 String16 nameStr(name, nameLen);
2406 sp<const Entry> e = getEntry(attrID);
2407 if (e != NULL) {
2408 const size_t N = e->getBag().size();
2409
2410 const char16_t* end = name + nameLen;
2411 const char16_t* pos = name;
Ben Gruver59eb5fd2012-03-06 19:26:22 -08002412 while (pos < end) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 const char16_t* start = pos;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 while (pos < end && *pos != '|') {
2415 pos++;
2416 }
2417
2418 String16 nameStr(start, pos-start);
2419 size_t i;
2420 for (i=0; i<N; i++) {
2421 //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
2422 // String8(e->getBag().keyAt(i)).string());
2423 if (e->getBag().keyAt(i) == nameStr) {
2424 Res_value val;
2425 bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
2426 if (!got) {
2427 return false;
2428 }
2429 //printf("Got value: 0x%08x\n", val.data);
2430 outValue->data |= val.data;
2431 break;
2432 }
2433 }
2434
2435 if (i >= N) {
2436 // Didn't find this flag identifier.
2437 return false;
2438 }
Ben Gruver59eb5fd2012-03-06 19:26:22 -08002439 pos++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 }
2441
2442 return true;
2443 }
2444 return false;
2445}
2446
2447status_t ResourceTable::assignResourceIds()
2448{
2449 const size_t N = mOrderedPackages.size();
2450 size_t pi;
2451 status_t firstError = NO_ERROR;
2452
2453 // First generate all bag attributes and assign indices.
2454 for (pi=0; pi<N; pi++) {
2455 sp<Package> p = mOrderedPackages.itemAt(pi);
2456 if (p == NULL || p->getTypes().size() == 0) {
2457 // Empty, skip!
2458 continue;
2459 }
2460
2461 status_t err = p->applyPublicTypeOrder();
2462 if (err != NO_ERROR && firstError == NO_ERROR) {
2463 firstError = err;
2464 }
2465
2466 // Generate attributes...
2467 const size_t N = p->getOrderedTypes().size();
2468 size_t ti;
2469 for (ti=0; ti<N; ti++) {
2470 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2471 if (t == NULL) {
2472 continue;
2473 }
2474 const size_t N = t->getOrderedConfigs().size();
2475 for (size_t ci=0; ci<N; ci++) {
2476 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2477 if (c == NULL) {
2478 continue;
2479 }
2480 const size_t N = c->getEntries().size();
2481 for (size_t ei=0; ei<N; ei++) {
2482 sp<Entry> e = c->getEntries().valueAt(ei);
2483 if (e == NULL) {
2484 continue;
2485 }
2486 status_t err = e->generateAttributes(this, p->getName());
2487 if (err != NO_ERROR && firstError == NO_ERROR) {
2488 firstError = err;
2489 }
2490 }
2491 }
2492 }
2493
2494 const SourcePos unknown(String8("????"), 0);
2495 sp<Type> attr = p->getType(String16("attr"), unknown);
2496
2497 // Assign indices...
2498 for (ti=0; ti<N; ti++) {
2499 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2500 if (t == NULL) {
2501 continue;
2502 }
2503 err = t->applyPublicEntryOrder();
2504 if (err != NO_ERROR && firstError == NO_ERROR) {
2505 firstError = err;
2506 }
2507
2508 const size_t N = t->getOrderedConfigs().size();
2509 t->setIndex(ti+1);
2510
2511 LOG_ALWAYS_FATAL_IF(ti == 0 && attr != t,
2512 "First type is not attr!");
2513
2514 for (size_t ei=0; ei<N; ei++) {
2515 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ei);
2516 if (c == NULL) {
2517 continue;
2518 }
2519 c->setEntryIndex(ei);
2520 }
2521 }
2522
2523 // Assign resource IDs to keys in bags...
2524 for (ti=0; ti<N; ti++) {
2525 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2526 if (t == NULL) {
2527 continue;
2528 }
2529 const size_t N = t->getOrderedConfigs().size();
2530 for (size_t ci=0; ci<N; ci++) {
2531 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2532 //printf("Ordered config #%d: %p\n", ci, c.get());
2533 const size_t N = c->getEntries().size();
2534 for (size_t ei=0; ei<N; ei++) {
2535 sp<Entry> e = c->getEntries().valueAt(ei);
2536 if (e == NULL) {
2537 continue;
2538 }
2539 status_t err = e->assignResourceIds(this, p->getName());
2540 if (err != NO_ERROR && firstError == NO_ERROR) {
2541 firstError = err;
2542 }
2543 }
2544 }
2545 }
2546 }
2547 return firstError;
2548}
2549
2550status_t ResourceTable::addSymbols(const sp<AaptSymbols>& outSymbols) {
2551 const size_t N = mOrderedPackages.size();
2552 size_t pi;
2553
2554 for (pi=0; pi<N; pi++) {
2555 sp<Package> p = mOrderedPackages.itemAt(pi);
2556 if (p->getTypes().size() == 0) {
2557 // Empty, skip!
2558 continue;
2559 }
2560
2561 const size_t N = p->getOrderedTypes().size();
2562 size_t ti;
2563
2564 for (ti=0; ti<N; ti++) {
2565 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2566 if (t == NULL) {
2567 continue;
2568 }
2569 const size_t N = t->getOrderedConfigs().size();
2570 sp<AaptSymbols> typeSymbols;
2571 typeSymbols = outSymbols->addNestedSymbol(String8(t->getName()), t->getPos());
2572 for (size_t ci=0; ci<N; ci++) {
2573 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2574 if (c == NULL) {
2575 continue;
2576 }
2577 uint32_t rid = getResId(p, t, ci);
2578 if (rid == 0) {
2579 return UNKNOWN_ERROR;
2580 }
2581 if (Res_GETPACKAGE(rid) == (size_t)(p->getAssignedId()-1)) {
2582 typeSymbols->addSymbol(String8(c->getName()), rid, c->getPos());
2583
2584 String16 comment(c->getComment());
2585 typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
Adam Lesinski2b8e82f2013-10-04 12:06:38 -07002586 //printf("Type symbol [%08x] %s comment: %s\n", rid,
2587 // String8(c->getName()).string(), String8(comment).string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 comment = c->getTypeComment();
2589 typeSymbols->appendTypeComment(String8(c->getName()), comment);
2590 } else {
2591#if 0
2592 printf("**** NO MATCH: 0x%08x vs 0x%08x\n",
2593 Res_GETPACKAGE(rid), p->getAssignedId());
2594#endif
2595 }
2596 }
2597 }
2598 }
2599 return NO_ERROR;
2600}
2601
2602
2603void
Adam Lesinskie119b222014-03-20 18:04:57 -07002604ResourceTable::addLocalization(const String16& name, const String8& locale, const SourcePos& src)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605{
Adam Lesinskie119b222014-03-20 18:04:57 -07002606 mLocalizations[name][locale] = src;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607}
2608
2609
2610/*!
2611 * Flag various sorts of localization problems. '+' indicates checks already implemented;
2612 * '-' indicates checks that will be implemented in the future.
2613 *
2614 * + A localized string for which no default-locale version exists => warning
2615 * + A string for which no version in an explicitly-requested locale exists => warning
2616 * + A localized translation of an translateable="false" string => warning
2617 * - A localized string not provided in every locale used by the table
2618 */
2619status_t
2620ResourceTable::validateLocalizations(void)
2621{
2622 status_t err = NO_ERROR;
2623 const String8 defaultLocale;
2624
2625 // For all strings...
Adam Lesinskie119b222014-03-20 18:04:57 -07002626 for (map<String16, map<String8, SourcePos> >::iterator nameIter = mLocalizations.begin();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 nameIter != mLocalizations.end();
2628 nameIter++) {
Adam Lesinskie119b222014-03-20 18:04:57 -07002629 const map<String8, SourcePos>& configSrcMap = nameIter->second;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630
2631 // Look for strings with no default localization
Adam Lesinskie119b222014-03-20 18:04:57 -07002632 if (configSrcMap.count(defaultLocale) == 0) {
2633 SourcePos().warning("string '%s' has no default translation.",
2634 String8(nameIter->first).string());
2635 if (mBundle->getVerbose()) {
2636 for (map<String8, SourcePos>::const_iterator locales = configSrcMap.begin();
2637 locales != configSrcMap.end();
2638 locales++) {
2639 locales->second.printf("locale %s found", locales->first.string());
2640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 // !!! TODO: throw an error here in some circumstances
2643 }
2644
2645 // Check that all requested localizations are present for this string
2646 if (mBundle->getConfigurations() != NULL && mBundle->getRequireLocalization()) {
2647 const char* allConfigs = mBundle->getConfigurations();
2648 const char* start = allConfigs;
2649 const char* comma;
2650
Adam Lesinskie119b222014-03-20 18:04:57 -07002651 set<String8> missingConfigs;
2652 AaptLocaleValue locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 do {
2654 String8 config;
2655 comma = strchr(start, ',');
2656 if (comma != NULL) {
2657 config.setTo(start, comma - start);
2658 start = comma + 1;
2659 } else {
2660 config.setTo(start);
2661 }
2662
Adam Lesinskie119b222014-03-20 18:04:57 -07002663 if (!locale.initFromFilterString(config)) {
2664 continue;
2665 }
2666
Anton Krumina2ef5c02014-03-12 14:46:44 -07002667 // don't bother with the pseudolocale "en_XA" or "ar_XB"
2668 if (config != "en_XA" && config != "ar_XB") {
Adam Lesinskie119b222014-03-20 18:04:57 -07002669 if (configSrcMap.find(config) == configSrcMap.end()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 // okay, no specific localization found. it's possible that we are
2671 // requiring a specific regional localization [e.g. de_DE] but there is an
2672 // available string in the generic language localization [e.g. de];
2673 // consider that string to have fulfilled the localization requirement.
2674 String8 region(config.string(), 2);
Adam Lesinskie119b222014-03-20 18:04:57 -07002675 if (configSrcMap.find(region) == configSrcMap.end() &&
2676 configSrcMap.count(defaultLocale) == 0) {
2677 missingConfigs.insert(config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 }
2679 }
2680 }
Adam Lesinskie119b222014-03-20 18:04:57 -07002681 } while (comma != NULL);
2682
2683 if (!missingConfigs.empty()) {
2684 String8 configStr;
2685 for (set<String8>::iterator iter = missingConfigs.begin();
2686 iter != missingConfigs.end();
2687 iter++) {
2688 configStr.appendFormat(" %s", iter->string());
2689 }
2690 SourcePos().warning("string '%s' is missing %u required localizations:%s",
2691 String8(nameIter->first).string(),
2692 (unsigned int)missingConfigs.size(),
2693 configStr.string());
2694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002695 }
2696 }
2697
2698 return err;
2699}
2700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701status_t ResourceTable::flatten(Bundle* bundle, const sp<AaptFile>& dest)
2702{
2703 ResourceFilter filter;
2704 status_t err = filter.parse(bundle->getConfigurations());
2705 if (err != NO_ERROR) {
2706 return err;
2707 }
2708
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002709 const ConfigDescription nullConfig;
2710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 const size_t N = mOrderedPackages.size();
2712 size_t pi;
2713
Kenny Root7c710232010-11-22 22:28:37 -08002714 const static String16 mipmap16("mipmap");
2715
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002716 bool useUTF8 = !bundle->getUTF16StringsOption();
Kenny Root1741cd42010-03-18 12:12:11 -07002717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002718 // Iterate through all data, collecting all values (strings,
2719 // references, etc).
Jeff Brown345b7eb2012-03-16 15:25:17 -07002720 StringPool valueStrings(useUTF8);
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002721 Vector<sp<Entry> > allEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 for (pi=0; pi<N; pi++) {
2723 sp<Package> p = mOrderedPackages.itemAt(pi);
2724 if (p->getTypes().size() == 0) {
2725 // Empty, skip!
2726 continue;
2727 }
2728
Jeff Brown345b7eb2012-03-16 15:25:17 -07002729 StringPool typeStrings(useUTF8);
2730 StringPool keyStrings(useUTF8);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731
2732 const size_t N = p->getOrderedTypes().size();
2733 for (size_t ti=0; ti<N; ti++) {
2734 sp<Type> t = p->getOrderedTypes().itemAt(ti);
2735 if (t == NULL) {
2736 typeStrings.add(String16("<empty>"), false);
2737 continue;
2738 }
Kenny Root7c710232010-11-22 22:28:37 -08002739 const String16 typeName(t->getName());
2740 typeStrings.add(typeName, false);
2741
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002742 // This is a hack to tweak the sorting order of the final strings,
2743 // to put stuff that is generally not language-specific first.
2744 String8 configTypeName(typeName);
2745 if (configTypeName == "drawable" || configTypeName == "layout"
2746 || configTypeName == "color" || configTypeName == "anim"
2747 || configTypeName == "interpolator" || configTypeName == "animator"
2748 || configTypeName == "xml" || configTypeName == "menu"
2749 || configTypeName == "mipmap" || configTypeName == "raw") {
2750 configTypeName = "1complex";
2751 } else {
2752 configTypeName = "2value";
2753 }
2754
Kenny Root7c710232010-11-22 22:28:37 -08002755 const bool filterable = (typeName != mipmap16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756
2757 const size_t N = t->getOrderedConfigs().size();
2758 for (size_t ci=0; ci<N; ci++) {
2759 sp<ConfigList> c = t->getOrderedConfigs().itemAt(ci);
2760 if (c == NULL) {
2761 continue;
2762 }
2763 const size_t N = c->getEntries().size();
2764 for (size_t ei=0; ei<N; ei++) {
2765 ConfigDescription config = c->getEntries().keyAt(ei);
Kenny Root7c710232010-11-22 22:28:37 -08002766 if (filterable && !filter.match(config)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 continue;
2768 }
2769 sp<Entry> e = c->getEntries().valueAt(ei);
2770 if (e == NULL) {
2771 continue;
2772 }
2773 e->setNameIndex(keyStrings.add(e->getName(), true));
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002774
2775 // If this entry has no values for other configs,
2776 // and is the default config, then it is special. Otherwise
2777 // we want to add it with the config info.
2778 ConfigDescription* valueConfig = NULL;
2779 if (N != 1 || config == nullConfig) {
2780 valueConfig = &config;
2781 }
2782
2783 status_t err = e->prepareFlatten(&valueStrings, this,
2784 &configTypeName, &config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 if (err != NO_ERROR) {
2786 return err;
2787 }
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002788 allEntries.add(e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 }
2790 }
2791 }
2792
2793 p->setTypeStrings(typeStrings.createStringBlock());
2794 p->setKeyStrings(keyStrings.createStringBlock());
2795 }
2796
Dianne Hackborn6c997a92012-01-31 11:27:43 -08002797 if (bundle->getOutputAPKFile() != NULL) {
2798 // Now we want to sort the value strings for better locality. This will
2799 // cause the positions of the strings to change, so we need to go back
2800 // through out resource entries and update them accordingly. Only need
2801 // to do this if actually writing the output file.
2802 valueStrings.sortByConfig();
2803 for (pi=0; pi<allEntries.size(); pi++) {
2804 allEntries[pi]->remapStringValue(&valueStrings);
2805 }
2806 }
2807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 ssize_t strAmt = 0;
2809
2810 // Now build the array of package chunks.
2811 Vector<sp<AaptFile> > flatPackages;
2812 for (pi=0; pi<N; pi++) {
2813 sp<Package> p = mOrderedPackages.itemAt(pi);
2814 if (p->getTypes().size() == 0) {
2815 // Empty, skip!
2816 continue;
2817 }
2818
2819 const size_t N = p->getTypeStrings().size();
2820
2821 const size_t baseSize = sizeof(ResTable_package);
2822
2823 // Start the package data.
2824 sp<AaptFile> data = new AaptFile(String8(), AaptGroupEntry(), String8());
2825 ResTable_package* header = (ResTable_package*)data->editData(baseSize);
2826 if (header == NULL) {
2827 fprintf(stderr, "ERROR: out of memory creating ResTable_package\n");
2828 return NO_MEMORY;
2829 }
2830 memset(header, 0, sizeof(*header));
2831 header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
2832 header->header.headerSize = htods(sizeof(*header));
2833 header->id = htodl(p->getAssignedId());
2834 strcpy16_htod(header->name, p->getName().string());
2835
2836 // Write the string blocks.
2837 const size_t typeStringsStart = data->getSize();
2838 sp<AaptFile> strFile = p->getTypeStringsData();
2839 ssize_t amt = data->writeData(strFile->getData(), strFile->getSize());
2840 #if PRINT_STRING_METRICS
2841 fprintf(stderr, "**** type strings: %d\n", amt);
2842 #endif
2843 strAmt += amt;
2844 if (amt < 0) {
2845 return amt;
2846 }
2847 const size_t keyStringsStart = data->getSize();
2848 strFile = p->getKeyStringsData();
2849 amt = data->writeData(strFile->getData(), strFile->getSize());
2850 #if PRINT_STRING_METRICS
2851 fprintf(stderr, "**** key strings: %d\n", amt);
2852 #endif
2853 strAmt += amt;
2854 if (amt < 0) {
2855 return amt;
2856 }
2857
2858 // Build the type chunks inside of this package.
2859 for (size_t ti=0; ti<N; ti++) {
2860 // Retrieve them in the same order as the type string block.
2861 size_t len;
2862 String16 typeName(p->getTypeStrings().stringAt(ti, &len));
2863 sp<Type> t = p->getTypes().valueFor(typeName);
2864 LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
2865 "Type name %s not found",
2866 String8(typeName).string());
2867
Kenny Root7c710232010-11-22 22:28:37 -08002868 const bool filterable = (typeName != mipmap16);
2869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 const size_t N = t != NULL ? t->getOrderedConfigs().size() : 0;
MÃ¥rten Kongstad249e3ed2012-02-08 10:22:47 +01002871
2872 // Until a non-NO_ENTRY value has been written for a resource,
2873 // that resource is invalid; validResources[i] represents
2874 // the item at t->getOrderedConfigs().itemAt(i).
2875 Vector<bool> validResources;
2876 validResources.insertAt(false, 0, N);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877
2878 // First write the typeSpec chunk, containing information about
2879 // each resource entry in this type.
2880 {
2881 const size_t typeSpecSize = sizeof(ResTable_typeSpec) + sizeof(uint32_t)*N;
2882 const size_t typeSpecStart = data->getSize();
2883 ResTable_typeSpec* tsHeader = (ResTable_typeSpec*)
2884 (((uint8_t*)data->editData(typeSpecStart+typeSpecSize)) + typeSpecStart);
2885 if (tsHeader == NULL) {
2886 fprintf(stderr, "ERROR: out of memory creating ResTable_typeSpec\n");
2887 return NO_MEMORY;
2888 }
2889 memset(tsHeader, 0, sizeof(*tsHeader));
2890 tsHeader->header.type = htods(RES_TABLE_TYPE_SPEC_TYPE);
2891 tsHeader->header.headerSize = htods(sizeof(*tsHeader));
2892 tsHeader->header.size = htodl(typeSpecSize);
2893 tsHeader->id = ti+1;
2894 tsHeader->entryCount = htodl(N);
2895
2896 uint32_t* typeSpecFlags = (uint32_t*)
2897 (((uint8_t*)data->editData())
2898 + typeSpecStart + sizeof(ResTable_typeSpec));
2899 memset(typeSpecFlags, 0, sizeof(uint32_t)*N);
Kenny Root7c710232010-11-22 22:28:37 -08002900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 for (size_t ei=0; ei<N; ei++) {
2902 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
2903 if (cl->getPublic()) {
2904 typeSpecFlags[ei] |= htodl(ResTable_typeSpec::SPEC_PUBLIC);
2905 }
2906 const size_t CN = cl->getEntries().size();
2907 for (size_t ci=0; ci<CN; ci++) {
Kenny Root7c710232010-11-22 22:28:37 -08002908 if (filterable && !filter.match(cl->getEntries().keyAt(ci))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 continue;
2910 }
2911 for (size_t cj=ci+1; cj<CN; cj++) {
Kenny Root7c710232010-11-22 22:28:37 -08002912 if (filterable && !filter.match(cl->getEntries().keyAt(cj))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 continue;
2914 }
2915 typeSpecFlags[ei] |= htodl(
2916 cl->getEntries().keyAt(ci).diff(cl->getEntries().keyAt(cj)));
2917 }
2918 }
2919 }
2920 }
2921
2922 // We need to write one type chunk for each configuration for
2923 // which we have entries in this type.
2924 const size_t NC = t->getUniqueConfigs().size();
2925
2926 const size_t typeSize = sizeof(ResTable_type) + sizeof(uint32_t)*N;
2927
2928 for (size_t ci=0; ci<NC; ci++) {
2929 ConfigDescription config = t->getUniqueConfigs().itemAt(ci);
2930
2931 NOISY(printf("Writing config %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
Dianne Hackborn69cb8752011-05-19 18:13:32 -07002932 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002933 "sw%ddp w%ddp h%ddp dir:%d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 ti+1,
2935 config.mcc, config.mnc,
2936 config.language[0] ? config.language[0] : '-',
2937 config.language[1] ? config.language[1] : '-',
2938 config.country[0] ? config.country[0] : '-',
2939 config.country[1] ? config.country[1] : '-',
2940 config.orientation,
Tobias Haamel27b28b32010-02-09 23:09:17 +01002941 config.uiMode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 config.touchscreen,
2943 config.density,
2944 config.keyboard,
2945 config.inputFlags,
2946 config.navigation,
2947 config.screenWidth,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07002948 config.screenHeight,
Dianne Hackborn69cb8752011-05-19 18:13:32 -07002949 config.smallestScreenWidthDp,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07002950 config.screenWidthDp,
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002951 config.screenHeightDp,
2952 config.layoutDirection));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953
Kenny Root7c710232010-11-22 22:28:37 -08002954 if (filterable && !filter.match(config)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 continue;
2956 }
2957
2958 const size_t typeStart = data->getSize();
2959
2960 ResTable_type* tHeader = (ResTable_type*)
2961 (((uint8_t*)data->editData(typeStart+typeSize)) + typeStart);
2962 if (tHeader == NULL) {
2963 fprintf(stderr, "ERROR: out of memory creating ResTable_type\n");
2964 return NO_MEMORY;
2965 }
2966
2967 memset(tHeader, 0, sizeof(*tHeader));
2968 tHeader->header.type = htods(RES_TABLE_TYPE_TYPE);
2969 tHeader->header.headerSize = htods(sizeof(*tHeader));
2970 tHeader->id = ti+1;
2971 tHeader->entryCount = htodl(N);
2972 tHeader->entriesStart = htodl(typeSize);
2973 tHeader->config = config;
2974 NOISY(printf("Writing type %d config: imsi:%d/%d lang:%c%c cnt:%c%c "
Dianne Hackborn69cb8752011-05-19 18:13:32 -07002975 "orien:%d ui:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002976 "sw%ddp w%ddp h%ddp dir:%d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 ti+1,
2978 tHeader->config.mcc, tHeader->config.mnc,
2979 tHeader->config.language[0] ? tHeader->config.language[0] : '-',
2980 tHeader->config.language[1] ? tHeader->config.language[1] : '-',
2981 tHeader->config.country[0] ? tHeader->config.country[0] : '-',
2982 tHeader->config.country[1] ? tHeader->config.country[1] : '-',
2983 tHeader->config.orientation,
Tobias Haamel27b28b32010-02-09 23:09:17 +01002984 tHeader->config.uiMode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 tHeader->config.touchscreen,
2986 tHeader->config.density,
2987 tHeader->config.keyboard,
2988 tHeader->config.inputFlags,
2989 tHeader->config.navigation,
2990 tHeader->config.screenWidth,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07002991 tHeader->config.screenHeight,
Dianne Hackborn69cb8752011-05-19 18:13:32 -07002992 tHeader->config.smallestScreenWidthDp,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07002993 tHeader->config.screenWidthDp,
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07002994 tHeader->config.screenHeightDp,
2995 tHeader->config.layoutDirection));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 tHeader->config.swapHtoD();
2997
2998 // Build the entries inside of this type.
2999 for (size_t ei=0; ei<N; ei++) {
3000 sp<ConfigList> cl = t->getOrderedConfigs().itemAt(ei);
3001 sp<Entry> e = cl->getEntries().valueFor(config);
3002
3003 // Set the offset for this entry in its type.
3004 uint32_t* index = (uint32_t*)
3005 (((uint8_t*)data->editData())
3006 + typeStart + sizeof(ResTable_type));
3007 if (e != NULL) {
3008 index[ei] = htodl(data->getSize()-typeStart-typeSize);
3009
3010 // Create the entry.
3011 ssize_t amt = e->flatten(bundle, data, cl->getPublic());
3012 if (amt < 0) {
3013 return amt;
3014 }
MÃ¥rten Kongstad249e3ed2012-02-08 10:22:47 +01003015 validResources.editItemAt(ei) = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 } else {
3017 index[ei] = htodl(ResTable_type::NO_ENTRY);
3018 }
3019 }
3020
3021 // Fill in the rest of the type information.
3022 tHeader = (ResTable_type*)
3023 (((uint8_t*)data->editData()) + typeStart);
3024 tHeader->header.size = htodl(data->getSize()-typeStart);
3025 }
MÃ¥rten Kongstad249e3ed2012-02-08 10:22:47 +01003026
3027 for (size_t i = 0; i < N; ++i) {
3028 if (!validResources[i]) {
3029 sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
3030 fprintf(stderr, "warning: no entries written for %s/%s\n",
3031 String8(typeName).string(), String8(c->getName()).string());
3032 }
3033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 }
3035
3036 // Fill in the rest of the package information.
3037 header = (ResTable_package*)data->editData();
3038 header->header.size = htodl(data->getSize());
3039 header->typeStrings = htodl(typeStringsStart);
3040 header->lastPublicType = htodl(p->getTypeStrings().size());
3041 header->keyStrings = htodl(keyStringsStart);
3042 header->lastPublicKey = htodl(p->getKeyStrings().size());
3043
3044 flatPackages.add(data);
3045 }
3046
3047 // And now write out the final chunks.
3048 const size_t dataStart = dest->getSize();
3049
3050 {
3051 // blah
3052 ResTable_header header;
3053 memset(&header, 0, sizeof(header));
3054 header.header.type = htods(RES_TABLE_TYPE);
3055 header.header.headerSize = htods(sizeof(header));
3056 header.packageCount = htodl(flatPackages.size());
3057 status_t err = dest->writeData(&header, sizeof(header));
3058 if (err != NO_ERROR) {
3059 fprintf(stderr, "ERROR: out of memory creating ResTable_header\n");
3060 return err;
3061 }
3062 }
3063
3064 ssize_t strStart = dest->getSize();
3065 err = valueStrings.writeStringBlock(dest);
3066 if (err != NO_ERROR) {
3067 return err;
3068 }
3069
3070 ssize_t amt = (dest->getSize()-strStart);
3071 strAmt += amt;
3072 #if PRINT_STRING_METRICS
3073 fprintf(stderr, "**** value strings: %d\n", amt);
3074 fprintf(stderr, "**** total strings: %d\n", strAmt);
3075 #endif
3076
3077 for (pi=0; pi<flatPackages.size(); pi++) {
3078 err = dest->writeData(flatPackages[pi]->getData(),
3079 flatPackages[pi]->getSize());
3080 if (err != NO_ERROR) {
3081 fprintf(stderr, "ERROR: out of memory creating package chunk for ResTable_header\n");
3082 return err;
3083 }
3084 }
3085
3086 ResTable_header* header = (ResTable_header*)
3087 (((uint8_t*)dest->getData()) + dataStart);
3088 header->header.size = htodl(dest->getSize() - dataStart);
3089
3090 NOISY(aout << "Resource table:"
3091 << HexDump(dest->getData(), dest->getSize()) << endl);
3092
3093 #if PRINT_STRING_METRICS
3094 fprintf(stderr, "**** total resource table size: %d / %d%% strings\n",
3095 dest->getSize(), (strAmt*100)/dest->getSize());
3096 #endif
3097
3098 return NO_ERROR;
3099}
3100
3101void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp)
3102{
3103 fprintf(fp,
3104 "<!-- This file contains <public> resource definitions for all\n"
3105 " resources that were generated from the source data. -->\n"
3106 "\n"
3107 "<resources>\n");
3108
3109 writePublicDefinitions(package, fp, true);
3110 writePublicDefinitions(package, fp, false);
3111
3112 fprintf(fp,
3113 "\n"
3114 "</resources>\n");
3115}
3116
3117void ResourceTable::writePublicDefinitions(const String16& package, FILE* fp, bool pub)
3118{
3119 bool didHeader = false;
3120
3121 sp<Package> pkg = mPackages.valueFor(package);
3122 if (pkg != NULL) {
3123 const size_t NT = pkg->getOrderedTypes().size();
3124 for (size_t i=0; i<NT; i++) {
3125 sp<Type> t = pkg->getOrderedTypes().itemAt(i);
3126 if (t == NULL) {
3127 continue;
3128 }
3129
3130 bool didType = false;
3131
3132 const size_t NC = t->getOrderedConfigs().size();
3133 for (size_t j=0; j<NC; j++) {
3134 sp<ConfigList> c = t->getOrderedConfigs().itemAt(j);
3135 if (c == NULL) {
3136 continue;
3137 }
3138
3139 if (c->getPublic() != pub) {
3140 continue;
3141 }
3142
3143 if (!didType) {
3144 fprintf(fp, "\n");
3145 didType = true;
3146 }
3147 if (!didHeader) {
3148 if (pub) {
3149 fprintf(fp," <!-- PUBLIC SECTION. These resources have been declared public.\n");
3150 fprintf(fp," Changes to these definitions will break binary compatibility. -->\n\n");
3151 } else {
3152 fprintf(fp," <!-- PRIVATE SECTION. These resources have not been declared public.\n");
3153 fprintf(fp," You can make them public my moving these lines into a file in res/values. -->\n\n");
3154 }
3155 didHeader = true;
3156 }
3157 if (!pub) {
3158 const size_t NE = c->getEntries().size();
3159 for (size_t k=0; k<NE; k++) {
3160 const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
3161 if (pos.file != "") {
3162 fprintf(fp," <!-- Declared at %s:%d -->\n",
3163 pos.file.string(), pos.line);
3164 }
3165 }
3166 }
3167 fprintf(fp, " <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
3168 String8(t->getName()).string(),
3169 String8(c->getName()).string(),
3170 getResId(pkg, t, c->getEntryIndex()));
3171 }
3172 }
3173 }
3174}
3175
3176ResourceTable::Item::Item(const SourcePos& _sourcePos,
3177 bool _isId,
3178 const String16& _value,
3179 const Vector<StringPool::entry_style_span>* _style,
3180 int32_t _format)
3181 : sourcePos(_sourcePos)
3182 , isId(_isId)
3183 , value(_value)
3184 , format(_format)
3185 , bagKeyId(0)
3186 , evaluating(false)
3187{
3188 if (_style) {
3189 style = *_style;
3190 }
3191}
3192
3193status_t ResourceTable::Entry::makeItABag(const SourcePos& sourcePos)
3194{
3195 if (mType == TYPE_BAG) {
3196 return NO_ERROR;
3197 }
3198 if (mType == TYPE_UNKNOWN) {
3199 mType = TYPE_BAG;
3200 return NO_ERROR;
3201 }
3202 sourcePos.error("Resource entry %s is already defined as a single item.\n"
3203 "%s:%d: Originally defined here.\n",
3204 String8(mName).string(),
3205 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3206 return UNKNOWN_ERROR;
3207}
3208
3209status_t ResourceTable::Entry::setItem(const SourcePos& sourcePos,
3210 const String16& value,
3211 const Vector<StringPool::entry_style_span>* style,
3212 int32_t format,
3213 const bool overwrite)
3214{
3215 Item item(sourcePos, false, value, style);
3216
3217 if (mType == TYPE_BAG) {
3218 const Item& item(mBag.valueAt(0));
3219 sourcePos.error("Resource entry %s is already defined as a bag.\n"
3220 "%s:%d: Originally defined here.\n",
3221 String8(mName).string(),
3222 item.sourcePos.file.string(), item.sourcePos.line);
3223 return UNKNOWN_ERROR;
3224 }
3225 if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
3226 sourcePos.error("Resource entry %s is already defined.\n"
3227 "%s:%d: Originally defined here.\n",
3228 String8(mName).string(),
3229 mItem.sourcePos.file.string(), mItem.sourcePos.line);
3230 return UNKNOWN_ERROR;
3231 }
Robert Greenwaltf878e2d2009-06-09 09:14:20 -07003232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 mType = TYPE_ITEM;
3234 mItem = item;
3235 mItemFormat = format;
3236 return NO_ERROR;
3237}
3238
3239status_t ResourceTable::Entry::addToBag(const SourcePos& sourcePos,
3240 const String16& key, const String16& value,
3241 const Vector<StringPool::entry_style_span>* style,
3242 bool replace, bool isId, int32_t format)
3243{
3244 status_t err = makeItABag(sourcePos);
3245 if (err != NO_ERROR) {
3246 return err;
3247 }
3248
3249 Item item(sourcePos, isId, value, style, format);
3250
3251 // XXX NOTE: there is an error if you try to have a bag with two keys,
3252 // one an attr and one an id, with the same name. Not something we
3253 // currently ever have to worry about.
3254 ssize_t origKey = mBag.indexOfKey(key);
3255 if (origKey >= 0) {
3256 if (!replace) {
3257 const Item& item(mBag.valueAt(origKey));
3258 sourcePos.error("Resource entry %s already has bag item %s.\n"
3259 "%s:%d: Originally defined here.\n",
3260 String8(mName).string(), String8(key).string(),
3261 item.sourcePos.file.string(), item.sourcePos.line);
3262 return UNKNOWN_ERROR;
3263 }
3264 //printf("Replacing %s with %s\n",
3265 // String8(mBag.valueFor(key).value).string(), String8(value).string());
3266 mBag.replaceValueFor(key, item);
3267 }
3268
3269 mBag.add(key, item);
3270 return NO_ERROR;
3271}
3272
Robert Greenwalt4b4f4a92009-04-02 16:55:50 -07003273status_t ResourceTable::Entry::emptyBag(const SourcePos& sourcePos)
3274{
3275 status_t err = makeItABag(sourcePos);
3276 if (err != NO_ERROR) {
3277 return err;
3278 }
3279
3280 mBag.clear();
3281 return NO_ERROR;
3282}
3283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284status_t ResourceTable::Entry::generateAttributes(ResourceTable* table,
3285 const String16& package)
3286{
3287 const String16 attr16("attr");
3288 const String16 id16("id");
3289 const size_t N = mBag.size();
3290 for (size_t i=0; i<N; i++) {
3291 const String16& key = mBag.keyAt(i);
3292 const Item& it = mBag.valueAt(i);
3293 if (it.isId) {
3294 if (!table->hasBagOrEntry(key, &id16, &package)) {
3295 String16 value("false");
3296 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
3297 id16, key, value);
3298 if (err != NO_ERROR) {
3299 return err;
3300 }
3301 }
3302 } else if (!table->hasBagOrEntry(key, &attr16, &package)) {
3303
3304#if 1
3305// fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
3306// String8(key).string());
3307// const Item& item(mBag.valueAt(i));
3308// fprintf(stderr, "Referenced from file %s line %d\n",
3309// item.sourcePos.file.string(), item.sourcePos.line);
3310// return UNKNOWN_ERROR;
3311#else
3312 char numberStr[16];
3313 sprintf(numberStr, "%d", ResTable_map::TYPE_ANY);
3314 status_t err = table->addBag(SourcePos("<generated>", 0), package,
3315 attr16, key, String16(""),
3316 String16("^type"),
3317 String16(numberStr), NULL, NULL);
3318 if (err != NO_ERROR) {
3319 return err;
3320 }
3321#endif
3322 }
3323 }
3324 return NO_ERROR;
3325}
3326
3327status_t ResourceTable::Entry::assignResourceIds(ResourceTable* table,
3328 const String16& package)
3329{
3330 bool hasErrors = false;
3331
3332 if (mType == TYPE_BAG) {
3333 const char* errorMsg;
3334 const String16 style16("style");
3335 const String16 attr16("attr");
3336 const String16 id16("id");
3337 mParentId = 0;
3338 if (mParent.size() > 0) {
Dianne Hackbornf795e9a2011-06-09 16:17:53 -07003339 mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 if (mParentId == 0) {
3341 mPos.error("Error retrieving parent for item: %s '%s'.\n",
3342 errorMsg, String8(mParent).string());
3343 hasErrors = true;
3344 }
3345 }
3346 const size_t N = mBag.size();
3347 for (size_t i=0; i<N; i++) {
3348 const String16& key = mBag.keyAt(i);
3349 Item& it = mBag.editValueAt(i);
3350 it.bagKeyId = table->getResId(key,
Dianne Hackbornf795e9a2011-06-09 16:17:53 -07003351 it.isId ? &id16 : &attr16, NULL, &errorMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
3353 if (it.bagKeyId == 0) {
3354 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
3355 String8(it.isId ? id16 : attr16).string(),
3356 String8(key).string());
3357 hasErrors = true;
3358 }
3359 }
3360 }
3361 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
3362}
3363
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003364status_t ResourceTable::Entry::prepareFlatten(StringPool* strings, ResourceTable* table,
3365 const String8* configTypeName, const ConfigDescription* config)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366{
3367 if (mType == TYPE_ITEM) {
3368 Item& it = mItem;
3369 AccessorCookie ac(it.sourcePos, String8(mName), String8(it.value));
3370 if (!table->stringToValue(&it.parsedValue, strings,
3371 it.value, false, true, 0,
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003372 &it.style, NULL, &ac, mItemFormat,
3373 configTypeName, config)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 return UNKNOWN_ERROR;
3375 }
3376 } else if (mType == TYPE_BAG) {
3377 const size_t N = mBag.size();
3378 for (size_t i=0; i<N; i++) {
3379 const String16& key = mBag.keyAt(i);
3380 Item& it = mBag.editValueAt(i);
3381 AccessorCookie ac(it.sourcePos, String8(key), String8(it.value));
3382 if (!table->stringToValue(&it.parsedValue, strings,
3383 it.value, false, true, it.bagKeyId,
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003384 &it.style, NULL, &ac, it.format,
3385 configTypeName, config)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 return UNKNOWN_ERROR;
3387 }
3388 }
3389 } else {
3390 mPos.error("Error: entry %s is not a single item or a bag.\n",
3391 String8(mName).string());
3392 return UNKNOWN_ERROR;
3393 }
3394 return NO_ERROR;
3395}
3396
Dianne Hackborn6c997a92012-01-31 11:27:43 -08003397status_t ResourceTable::Entry::remapStringValue(StringPool* strings)
3398{
3399 if (mType == TYPE_ITEM) {
3400 Item& it = mItem;
3401 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3402 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3403 }
3404 } else if (mType == TYPE_BAG) {
3405 const size_t N = mBag.size();
3406 for (size_t i=0; i<N; i++) {
3407 Item& it = mBag.editValueAt(i);
3408 if (it.parsedValue.dataType == Res_value::TYPE_STRING) {
3409 it.parsedValue.data = strings->mapOriginalPosToNewPos(it.parsedValue.data);
3410 }
3411 }
3412 } else {
3413 mPos.error("Error: entry %s is not a single item or a bag.\n",
3414 String8(mName).string());
3415 return UNKNOWN_ERROR;
3416 }
3417 return NO_ERROR;
3418}
3419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420ssize_t ResourceTable::Entry::flatten(Bundle* bundle, const sp<AaptFile>& data, bool isPublic)
3421{
3422 size_t amt = 0;
3423 ResTable_entry header;
3424 memset(&header, 0, sizeof(header));
3425 header.size = htods(sizeof(header));
3426 const type ty = this != NULL ? mType : TYPE_ITEM;
3427 if (this != NULL) {
3428 if (ty == TYPE_BAG) {
3429 header.flags |= htods(header.FLAG_COMPLEX);
3430 }
3431 if (isPublic) {
3432 header.flags |= htods(header.FLAG_PUBLIC);
3433 }
3434 header.key.index = htodl(mNameIndex);
3435 }
3436 if (ty != TYPE_BAG) {
3437 status_t err = data->writeData(&header, sizeof(header));
3438 if (err != NO_ERROR) {
3439 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3440 return err;
3441 }
3442
3443 const Item& it = mItem;
3444 Res_value par;
3445 memset(&par, 0, sizeof(par));
3446 par.size = htods(it.parsedValue.size);
3447 par.dataType = it.parsedValue.dataType;
3448 par.res0 = it.parsedValue.res0;
3449 par.data = htodl(it.parsedValue.data);
3450 #if 0
3451 printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
3452 String8(mName).string(), it.parsedValue.dataType,
3453 it.parsedValue.data, par.res0);
3454 #endif
3455 err = data->writeData(&par, it.parsedValue.size);
3456 if (err != NO_ERROR) {
3457 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3458 return err;
3459 }
3460 amt += it.parsedValue.size;
3461 } else {
3462 size_t N = mBag.size();
3463 size_t i;
3464 // Create correct ordering of items.
3465 KeyedVector<uint32_t, const Item*> items;
3466 for (i=0; i<N; i++) {
3467 const Item& it = mBag.valueAt(i);
3468 items.add(it.bagKeyId, &it);
3469 }
3470 N = items.size();
3471
3472 ResTable_map_entry mapHeader;
3473 memcpy(&mapHeader, &header, sizeof(header));
3474 mapHeader.size = htods(sizeof(mapHeader));
3475 mapHeader.parent.ident = htodl(mParentId);
3476 mapHeader.count = htodl(N);
3477 status_t err = data->writeData(&mapHeader, sizeof(mapHeader));
3478 if (err != NO_ERROR) {
3479 fprintf(stderr, "ERROR: out of memory creating ResTable_entry\n");
3480 return err;
3481 }
3482
3483 for (i=0; i<N; i++) {
3484 const Item& it = *items.valueAt(i);
3485 ResTable_map map;
3486 map.name.ident = htodl(it.bagKeyId);
3487 map.value.size = htods(it.parsedValue.size);
3488 map.value.dataType = it.parsedValue.dataType;
3489 map.value.res0 = it.parsedValue.res0;
3490 map.value.data = htodl(it.parsedValue.data);
3491 err = data->writeData(&map, sizeof(map));
3492 if (err != NO_ERROR) {
3493 fprintf(stderr, "ERROR: out of memory creating Res_value\n");
3494 return err;
3495 }
3496 amt += sizeof(map);
3497 }
3498 }
3499 return amt;
3500}
3501
3502void ResourceTable::ConfigList::appendComment(const String16& comment,
3503 bool onlyIfEmpty)
3504{
3505 if (comment.size() <= 0) {
3506 return;
3507 }
3508 if (onlyIfEmpty && mComment.size() > 0) {
3509 return;
3510 }
3511 if (mComment.size() > 0) {
3512 mComment.append(String16("\n"));
3513 }
3514 mComment.append(comment);
3515}
3516
3517void ResourceTable::ConfigList::appendTypeComment(const String16& comment)
3518{
3519 if (comment.size() <= 0) {
3520 return;
3521 }
3522 if (mTypeComment.size() > 0) {
3523 mTypeComment.append(String16("\n"));
3524 }
3525 mTypeComment.append(comment);
3526}
3527
3528status_t ResourceTable::Type::addPublic(const SourcePos& sourcePos,
3529 const String16& name,
3530 const uint32_t ident)
3531{
3532 #if 0
3533 int32_t entryIdx = Res_GETENTRY(ident);
3534 if (entryIdx < 0) {
3535 sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
3536 String8(mName).string(), String8(name).string(), ident);
3537 return UNKNOWN_ERROR;
3538 }
3539 #endif
3540
3541 int32_t typeIdx = Res_GETTYPE(ident);
3542 if (typeIdx >= 0) {
3543 typeIdx++;
3544 if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
3545 sourcePos.error("Public resource %s/%s has conflicting type codes for its"
3546 " public identifiers (0x%x vs 0x%x).\n",
3547 String8(mName).string(), String8(name).string(),
3548 mPublicIndex, typeIdx);
3549 return UNKNOWN_ERROR;
3550 }
3551 mPublicIndex = typeIdx;
3552 }
3553
3554 if (mFirstPublicSourcePos == NULL) {
3555 mFirstPublicSourcePos = new SourcePos(sourcePos);
3556 }
3557
3558 if (mPublic.indexOfKey(name) < 0) {
3559 mPublic.add(name, Public(sourcePos, String16(), ident));
3560 } else {
3561 Public& p = mPublic.editValueFor(name);
3562 if (p.ident != ident) {
3563 sourcePos.error("Public resource %s/%s has conflicting public identifiers"
3564 " (0x%08x vs 0x%08x).\n"
3565 "%s:%d: Originally defined here.\n",
3566 String8(mName).string(), String8(name).string(), p.ident, ident,
3567 p.sourcePos.file.string(), p.sourcePos.line);
3568 return UNKNOWN_ERROR;
3569 }
3570 }
3571
3572 return NO_ERROR;
3573}
3574
Dianne Hackborn58c27a02009-08-13 13:36:00 -07003575void ResourceTable::Type::canAddEntry(const String16& name)
3576{
3577 mCanAddEntries.add(name);
3578}
3579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580sp<ResourceTable::Entry> ResourceTable::Type::getEntry(const String16& entry,
3581 const SourcePos& sourcePos,
3582 const ResTable_config* config,
Robert Greenwaltf878e2d2009-06-09 09:14:20 -07003583 bool doSetIndex,
Xavier Ducrohet99080c72010-02-04 18:45:31 -08003584 bool overlay,
3585 bool autoAddOverlay)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586{
3587 int pos = -1;
3588 sp<ConfigList> c = mConfigs.valueFor(entry);
3589 if (c == NULL) {
Xavier Ducrohet99080c72010-02-04 18:45:31 -08003590 if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
Dianne Hackborn58c27a02009-08-13 13:36:00 -07003591 sourcePos.error("Resource at %s appears in overlay but not"
3592 " in the base package; use <add-resource> to add.\n",
3593 String8(entry).string());
Robert Greenwaltf878e2d2009-06-09 09:14:20 -07003594 return NULL;
3595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 c = new ConfigList(entry, sourcePos);
3597 mConfigs.add(entry, c);
3598 pos = (int)mOrderedConfigs.size();
3599 mOrderedConfigs.add(c);
3600 if (doSetIndex) {
3601 c->setEntryIndex(pos);
3602 }
3603 }
3604
3605 ConfigDescription cdesc;
3606 if (config) cdesc = *config;
3607
3608 sp<Entry> e = c->getEntries().valueFor(cdesc);
3609 if (e == NULL) {
3610 if (config != NULL) {
3611 NOISY(printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
Dianne Hackborn69cb8752011-05-19 18:13:32 -07003612 "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07003613 "sw%ddp w%ddp h%ddp dir:%d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 sourcePos.file.string(), sourcePos.line,
3615 config->mcc, config->mnc,
3616 config->language[0] ? config->language[0] : '-',
3617 config->language[1] ? config->language[1] : '-',
3618 config->country[0] ? config->country[0] : '-',
3619 config->country[1] ? config->country[1] : '-',
3620 config->orientation,
3621 config->touchscreen,
3622 config->density,
3623 config->keyboard,
3624 config->inputFlags,
3625 config->navigation,
3626 config->screenWidth,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07003627 config->screenHeight,
Dianne Hackborn69cb8752011-05-19 18:13:32 -07003628 config->smallestScreenWidthDp,
Dianne Hackbornebff8f92011-05-12 18:07:47 -07003629 config->screenWidthDp,
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07003630 config->screenHeightDp,
3631 config->layoutDirection));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 } else {
3633 NOISY(printf("New entry at %s:%d: NULL config\n",
3634 sourcePos.file.string(), sourcePos.line));
3635 }
3636 e = new Entry(entry, sourcePos);
3637 c->addEntry(cdesc, e);
3638 /*
3639 if (doSetIndex) {
3640 if (pos < 0) {
3641 for (pos=0; pos<(int)mOrderedConfigs.size(); pos++) {
3642 if (mOrderedConfigs[pos] == c) {
3643 break;
3644 }
3645 }
3646 if (pos >= (int)mOrderedConfigs.size()) {
3647 sourcePos.error("Internal error: config not found in mOrderedConfigs when adding entry");
3648 return NULL;
3649 }
3650 }
3651 e->setEntryIndex(pos);
3652 }
3653 */
3654 }
3655
3656 mUniqueConfigs.add(cdesc);
3657
3658 return e;
3659}
3660
3661status_t ResourceTable::Type::applyPublicEntryOrder()
3662{
3663 size_t N = mOrderedConfigs.size();
3664 Vector<sp<ConfigList> > origOrder(mOrderedConfigs);
3665 bool hasError = false;
3666
3667 size_t i;
3668 for (i=0; i<N; i++) {
3669 mOrderedConfigs.replaceAt(NULL, i);
3670 }
3671
3672 const size_t NP = mPublic.size();
3673 //printf("Ordering %d configs from %d public defs\n", N, NP);
3674 size_t j;
3675 for (j=0; j<NP; j++) {
3676 const String16& name = mPublic.keyAt(j);
3677 const Public& p = mPublic.valueAt(j);
3678 int32_t idx = Res_GETENTRY(p.ident);
3679 //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
3680 // String8(mName).string(), String8(name).string(), p.ident, N);
3681 bool found = false;
3682 for (i=0; i<N; i++) {
3683 sp<ConfigList> e = origOrder.itemAt(i);
3684 //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
3685 if (e->getName() == name) {
3686 if (idx >= (int32_t)mOrderedConfigs.size()) {
3687 p.sourcePos.error("Public entry identifier 0x%x entry index "
3688 "is larger than available symbols (index %d, total symbols %d).\n",
3689 p.ident, idx, mOrderedConfigs.size());
3690 hasError = true;
3691 } else if (mOrderedConfigs.itemAt(idx) == NULL) {
3692 e->setPublic(true);
3693 e->setPublicSourcePos(p.sourcePos);
3694 mOrderedConfigs.replaceAt(e, idx);
3695 origOrder.removeAt(i);
3696 N--;
3697 found = true;
3698 break;
3699 } else {
3700 sp<ConfigList> oe = mOrderedConfigs.itemAt(idx);
3701
3702 p.sourcePos.error("Multiple entry names declared for public entry"
3703 " identifier 0x%x in type %s (%s vs %s).\n"
3704 "%s:%d: Originally defined here.",
3705 idx+1, String8(mName).string(),
3706 String8(oe->getName()).string(),
3707 String8(name).string(),
3708 oe->getPublicSourcePos().file.string(),
3709 oe->getPublicSourcePos().line);
3710 hasError = true;
3711 }
3712 }
3713 }
3714
3715 if (!found) {
3716 p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
3717 String8(mName).string(), String8(name).string());
3718 hasError = true;
3719 }
3720 }
3721
3722 //printf("Copying back in %d non-public configs, have %d\n", N, origOrder.size());
3723
3724 if (N != origOrder.size()) {
3725 printf("Internal error: remaining private symbol count mismatch\n");
3726 N = origOrder.size();
3727 }
3728
3729 j = 0;
3730 for (i=0; i<N; i++) {
3731 sp<ConfigList> e = origOrder.itemAt(i);
3732 // There will always be enough room for the remaining entries.
3733 while (mOrderedConfigs.itemAt(j) != NULL) {
3734 j++;
3735 }
3736 mOrderedConfigs.replaceAt(e, j);
3737 j++;
3738 }
3739
3740 return hasError ? UNKNOWN_ERROR : NO_ERROR;
3741}
3742
3743ResourceTable::Package::Package(const String16& name, ssize_t includedId)
3744 : mName(name), mIncludedId(includedId),
3745 mTypeStringsMapping(0xffffffff),
3746 mKeyStringsMapping(0xffffffff)
3747{
3748}
3749
3750sp<ResourceTable::Type> ResourceTable::Package::getType(const String16& type,
3751 const SourcePos& sourcePos,
3752 bool doSetIndex)
3753{
3754 sp<Type> t = mTypes.valueFor(type);
3755 if (t == NULL) {
3756 t = new Type(type, sourcePos);
3757 mTypes.add(type, t);
3758 mOrderedTypes.add(t);
3759 if (doSetIndex) {
3760 // For some reason the type's index is set to one plus the index
3761 // in the mOrderedTypes list, rather than just the index.
3762 t->setIndex(mOrderedTypes.size());
3763 }
3764 }
3765 return t;
3766}
3767
3768status_t ResourceTable::Package::setTypeStrings(const sp<AaptFile>& data)
3769{
3770 mTypeStringsData = data;
3771 status_t err = setStrings(data, &mTypeStrings, &mTypeStringsMapping);
3772 if (err != NO_ERROR) {
3773 fprintf(stderr, "ERROR: Type string data is corrupt!\n");
3774 }
3775 return err;
3776}
3777
3778status_t ResourceTable::Package::setKeyStrings(const sp<AaptFile>& data)
3779{
3780 mKeyStringsData = data;
3781 status_t err = setStrings(data, &mKeyStrings, &mKeyStringsMapping);
3782 if (err != NO_ERROR) {
3783 fprintf(stderr, "ERROR: Key string data is corrupt!\n");
3784 }
3785 return err;
3786}
3787
3788status_t ResourceTable::Package::setStrings(const sp<AaptFile>& data,
3789 ResStringPool* strings,
3790 DefaultKeyedVector<String16, uint32_t>* mappings)
3791{
3792 if (data->getData() == NULL) {
3793 return UNKNOWN_ERROR;
3794 }
3795
3796 NOISY(aout << "Setting restable string pool: "
3797 << HexDump(data->getData(), data->getSize()) << endl);
3798
3799 status_t err = strings->setTo(data->getData(), data->getSize());
3800 if (err == NO_ERROR) {
3801 const size_t N = strings->size();
3802 for (size_t i=0; i<N; i++) {
3803 size_t len;
3804 mappings->add(String16(strings->stringAt(i, &len)), i);
3805 }
3806 }
3807 return err;
3808}
3809
3810status_t ResourceTable::Package::applyPublicTypeOrder()
3811{
3812 size_t N = mOrderedTypes.size();
3813 Vector<sp<Type> > origOrder(mOrderedTypes);
3814
3815 size_t i;
3816 for (i=0; i<N; i++) {
3817 mOrderedTypes.replaceAt(NULL, i);
3818 }
3819
3820 for (i=0; i<N; i++) {
3821 sp<Type> t = origOrder.itemAt(i);
3822 int32_t idx = t->getPublicIndex();
3823 if (idx > 0) {
3824 idx--;
3825 while (idx >= (int32_t)mOrderedTypes.size()) {
3826 mOrderedTypes.add();
3827 }
3828 if (mOrderedTypes.itemAt(idx) != NULL) {
3829 sp<Type> ot = mOrderedTypes.itemAt(idx);
3830 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
3831 " identifier 0x%x (%s vs %s).\n"
3832 "%s:%d: Originally defined here.",
3833 idx, String8(ot->getName()).string(),
3834 String8(t->getName()).string(),
3835 ot->getFirstPublicSourcePos().file.string(),
3836 ot->getFirstPublicSourcePos().line);
3837 return UNKNOWN_ERROR;
3838 }
3839 mOrderedTypes.replaceAt(t, idx);
3840 origOrder.removeAt(i);
3841 i--;
3842 N--;
3843 }
3844 }
3845
3846 size_t j=0;
3847 for (i=0; i<N; i++) {
3848 sp<Type> t = origOrder.itemAt(i);
3849 // There will always be enough room for the remaining types.
3850 while (mOrderedTypes.itemAt(j) != NULL) {
3851 j++;
3852 }
3853 mOrderedTypes.replaceAt(t, j);
3854 }
3855
3856 return NO_ERROR;
3857}
3858
3859sp<ResourceTable::Package> ResourceTable::getPackage(const String16& package)
3860{
3861 sp<Package> p = mPackages.valueFor(package);
3862 if (p == NULL) {
MÃ¥rten Kongstadc761d8b2012-02-07 19:12:45 +01003863 if (mIsAppPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 if (mHaveAppPackage) {
3865 fprintf(stderr, "Adding multiple application package resources; only one is allowed.\n"
3866 "Use -x to create extended resources.\n");
3867 return NULL;
3868 }
3869 mHaveAppPackage = true;
3870 p = new Package(package, 127);
3871 } else {
3872 p = new Package(package, mNextPackageId);
3873 }
3874 //printf("*** NEW PACKAGE: \"%s\" id=%d\n",
3875 // String8(package).string(), p->getAssignedId());
3876 mPackages.add(package, p);
3877 mOrderedPackages.add(p);
3878 mNextPackageId++;
3879 }
3880 return p;
3881}
3882
3883sp<ResourceTable::Type> ResourceTable::getType(const String16& package,
3884 const String16& type,
3885 const SourcePos& sourcePos,
3886 bool doSetIndex)
3887{
3888 sp<Package> p = getPackage(package);
3889 if (p == NULL) {
3890 return NULL;
3891 }
3892 return p->getType(type, sourcePos, doSetIndex);
3893}
3894
3895sp<ResourceTable::Entry> ResourceTable::getEntry(const String16& package,
3896 const String16& type,
3897 const String16& name,
3898 const SourcePos& sourcePos,
Robert Greenwaltf878e2d2009-06-09 09:14:20 -07003899 bool overlay,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 const ResTable_config* config,
3901 bool doSetIndex)
3902{
3903 sp<Type> t = getType(package, type, sourcePos, doSetIndex);
3904 if (t == NULL) {
3905 return NULL;
3906 }
Xavier Ducrohet99080c72010-02-04 18:45:31 -08003907 return t->getEntry(name, sourcePos, config, doSetIndex, overlay, mBundle->getAutoAddOverlay());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908}
3909
3910sp<const ResourceTable::Entry> ResourceTable::getEntry(uint32_t resID,
3911 const ResTable_config* config) const
3912{
3913 int pid = Res_GETPACKAGE(resID)+1;
3914 const size_t N = mOrderedPackages.size();
3915 size_t i;
3916 sp<Package> p;
3917 for (i=0; i<N; i++) {
3918 sp<Package> check = mOrderedPackages[i];
3919 if (check->getAssignedId() == pid) {
3920 p = check;
3921 break;
3922 }
3923
3924 }
3925 if (p == NULL) {
Marco Nelissendd931862009-07-13 13:02:33 -07003926 fprintf(stderr, "warning: Package not found for resource #%08x\n", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 return NULL;
3928 }
3929
3930 int tid = Res_GETTYPE(resID);
3931 if (tid < 0 || tid >= (int)p->getOrderedTypes().size()) {
Marco Nelissendd931862009-07-13 13:02:33 -07003932 fprintf(stderr, "warning: Type not found for resource #%08x\n", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 return NULL;
3934 }
3935 sp<Type> t = p->getOrderedTypes()[tid];
3936
3937 int eid = Res_GETENTRY(resID);
3938 if (eid < 0 || eid >= (int)t->getOrderedConfigs().size()) {
Marco Nelissendd931862009-07-13 13:02:33 -07003939 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 return NULL;
3941 }
3942
3943 sp<ConfigList> c = t->getOrderedConfigs()[eid];
3944 if (c == NULL) {
Marco Nelissendd931862009-07-13 13:02:33 -07003945 fprintf(stderr, "warning: Entry not found for resource #%08x\n", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 return NULL;
3947 }
3948
3949 ConfigDescription cdesc;
3950 if (config) cdesc = *config;
3951 sp<Entry> e = c->getEntries().valueFor(cdesc);
3952 if (c == NULL) {
Marco Nelissendd931862009-07-13 13:02:33 -07003953 fprintf(stderr, "warning: Entry configuration not found for resource #%08x\n", resID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 return NULL;
3955 }
3956
3957 return e;
3958}
3959
3960const ResourceTable::Item* ResourceTable::getItem(uint32_t resID, uint32_t attrID) const
3961{
3962 sp<const Entry> e = getEntry(resID);
3963 if (e == NULL) {
3964 return NULL;
3965 }
3966
3967 const size_t N = e->getBag().size();
3968 for (size_t i=0; i<N; i++) {
3969 const Item& it = e->getBag().valueAt(i);
3970 if (it.bagKeyId == 0) {
Marco Nelissendd931862009-07-13 13:02:33 -07003971 fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 String8(e->getName()).string(),
3973 String8(e->getBag().keyAt(i)).string());
3974 }
3975 if (it.bagKeyId == attrID) {
3976 return &it;
3977 }
3978 }
3979
3980 return NULL;
3981}
3982
3983bool ResourceTable::getItemValue(
3984 uint32_t resID, uint32_t attrID, Res_value* outValue)
3985{
3986 const Item* item = getItem(resID, attrID);
3987
3988 bool res = false;
3989 if (item != NULL) {
3990 if (item->evaluating) {
3991 sp<const Entry> e = getEntry(resID);
3992 const size_t N = e->getBag().size();
3993 size_t i;
3994 for (i=0; i<N; i++) {
3995 if (&e->getBag().valueAt(i) == item) {
3996 break;
3997 }
3998 }
Marco Nelissendd931862009-07-13 13:02:33 -07003999 fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 String8(e->getName()).string(),
4001 String8(e->getBag().keyAt(i)).string());
4002 return false;
4003 }
4004 item->evaluating = true;
4005 res = stringToValue(outValue, NULL, item->value, false, false, item->bagKeyId);
4006 NOISY(
4007 if (res) {
4008 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
4009 resID, attrID, String8(getEntry(resID)->getName()).string(),
4010 outValue->dataType, outValue->data);
4011 } else {
4012 printf("getItemValue of #%08x[#%08x]: failed\n",
4013 resID, attrID);
4014 }
4015 );
4016 item->evaluating = false;
4017 }
4018 return res;
4019}