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