blob: 44aaa43eb73ec8e1325a7ec6c24f1c22a05a1202 [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#include "Main.h"
7#include "AaptAssets.h"
8#include "StringPool.h"
9#include "XMLNode.h"
10#include "ResourceTable.h"
11#include "Images.h"
12
Josiah Gaskin8a39da82011-06-06 17:00:35 -070013#include "CrunchCache.h"
14#include "FileFinder.h"
15#include "CacheUpdater.h"
16
Jeff Brownc0f73662012-03-16 22:17:41 -070017#include <utils/WorkQueue.h>
18
Raphaelf51125d2011-10-27 17:01:31 -070019#if HAVE_PRINTF_ZD
20# define ZD "%zd"
21# define ZD_TYPE ssize_t
22#else
23# define ZD "%ld"
24# define ZD_TYPE long
25#endif
26
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027#define NOISY(x) // x
28
Jeff Brownc0f73662012-03-16 22:17:41 -070029// Number of threads to use for preprocessing images.
30static const size_t MAX_THREADS = 4;
31
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032// ==========================================================================
33// ==========================================================================
34// ==========================================================================
35
36class PackageInfo
37{
38public:
39 PackageInfo()
40 {
41 }
42 ~PackageInfo()
43 {
44 }
45
46 status_t parsePackage(const sp<AaptGroup>& grp);
47};
48
49// ==========================================================================
50// ==========================================================================
51// ==========================================================================
52
53static String8 parseResourceName(const String8& leaf)
54{
55 const char* firstDot = strchr(leaf.string(), '.');
56 const char* str = leaf.string();
57
58 if (firstDot) {
59 return String8(str, firstDot-str);
60 } else {
61 return String8(str);
62 }
63}
64
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065ResourceTypeSet::ResourceTypeSet()
66 :RefBase(),
67 KeyedVector<String8,sp<AaptGroup> >()
68{
69}
70
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -070071FilePathStore::FilePathStore()
72 :RefBase(),
73 Vector<String8>()
74{
75}
76
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077class ResourceDirIterator
78{
79public:
80 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType)
81 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0)
82 {
83 }
84
85 inline const sp<AaptGroup>& getGroup() const { return mGroup; }
86 inline const sp<AaptFile>& getFile() const { return mFile; }
87
88 inline const String8& getBaseName() const { return mBaseName; }
89 inline const String8& getLeafName() const { return mLeafName; }
90 inline String8 getPath() const { return mPath; }
91 inline const ResTable_config& getParams() const { return mParams; }
92
93 enum {
94 EOD = 1
95 };
96
97 ssize_t next()
98 {
99 while (true) {
100 sp<AaptGroup> group;
101 sp<AaptFile> file;
102
103 // Try to get next file in this current group.
104 if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) {
105 group = mGroup;
106 file = group->getFiles().valueAt(mGroupPos++);
107
108 // Try to get the next group/file in this directory
109 } else if (mSetPos < mSet->size()) {
110 mGroup = group = mSet->valueAt(mSetPos++);
111 if (group->getFiles().size() < 1) {
112 continue;
113 }
114 file = group->getFiles().valueAt(0);
115 mGroupPos = 1;
116
117 // All done!
118 } else {
119 return EOD;
120 }
121
122 mFile = file;
123
124 String8 leaf(group->getLeaf());
125 mLeafName = String8(leaf);
126 mParams = file->getGroupEntry().toParams();
Tobias Haamel27b28b32010-02-09 23:09:17 +0100127 NOISY(printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d ui=%d density=%d touch=%d key=%d inp=%d nav=%d\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 group->getPath().string(), mParams.mcc, mParams.mnc,
129 mParams.language[0] ? mParams.language[0] : '-',
130 mParams.language[1] ? mParams.language[1] : '-',
131 mParams.country[0] ? mParams.country[0] : '-',
132 mParams.country[1] ? mParams.country[1] : '-',
Tobias Haamel27b28b32010-02-09 23:09:17 +0100133 mParams.orientation, mParams.uiMode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 mParams.density, mParams.touchscreen, mParams.keyboard,
135 mParams.inputFlags, mParams.navigation));
136 mPath = "res";
137 mPath.appendPath(file->getGroupEntry().toDirName(mResType));
138 mPath.appendPath(leaf);
139 mBaseName = parseResourceName(leaf);
140 if (mBaseName == "") {
141 fprintf(stderr, "Error: malformed resource filename %s\n",
142 file->getPrintableSource().string());
143 return UNKNOWN_ERROR;
144 }
145
146 NOISY(printf("file name=%s\n", mBaseName.string()));
147
148 return NO_ERROR;
149 }
150 }
151
152private:
153 String8 mResType;
154
155 const sp<ResourceTypeSet> mSet;
156 size_t mSetPos;
157
158 sp<AaptGroup> mGroup;
159 size_t mGroupPos;
160
161 sp<AaptFile> mFile;
162 String8 mBaseName;
163 String8 mLeafName;
164 String8 mPath;
165 ResTable_config mParams;
166};
167
168// ==========================================================================
169// ==========================================================================
170// ==========================================================================
171
172bool isValidResourceType(const String8& type)
173{
Dianne Hackbornf31161a2011-01-04 21:02:48 -0800174 return type == "anim" || type == "animator" || type == "interpolator"
175 || type == "drawable" || type == "layout"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 || type == "values" || type == "xml" || type == "raw"
Kenny Root7c710232010-11-22 22:28:37 -0800177 || type == "color" || type == "menu" || type == "mipmap";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178}
179
180static sp<AaptFile> getResourceFile(const sp<AaptAssets>& assets, bool makeIfNecessary=true)
181{
182 sp<AaptGroup> group = assets->getFiles().valueFor(String8("resources.arsc"));
183 sp<AaptFile> file;
184 if (group != NULL) {
185 file = group->getFiles().valueFor(AaptGroupEntry());
186 if (file != NULL) {
187 return file;
188 }
189 }
190
191 if (!makeIfNecessary) {
192 return NULL;
193 }
194 return assets->addFile(String8("resources.arsc"), AaptGroupEntry(), String8(),
195 NULL, String8());
196}
197
Kenny Rootb5ef7ee2009-12-10 13:52:53 -0800198static status_t parsePackage(Bundle* bundle, const sp<AaptAssets>& assets,
199 const sp<AaptGroup>& grp)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200{
201 if (grp->getFiles().size() != 1) {
Marco Nelissendd931862009-07-13 13:02:33 -0700202 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 grp->getFiles().valueAt(0)->getPrintableSource().string());
204 }
205
206 sp<AaptFile> file = grp->getFiles().valueAt(0);
207
208 ResXMLTree block;
209 status_t err = parseXMLResource(file, &block);
210 if (err != NO_ERROR) {
211 return err;
212 }
213 //printXMLBlock(&block);
214
215 ResXMLTree::event_code_t code;
216 while ((code=block.next()) != ResXMLTree::START_TAG
217 && code != ResXMLTree::END_DOCUMENT
218 && code != ResXMLTree::BAD_DOCUMENT) {
219 }
220
221 size_t len;
222 if (code != ResXMLTree::START_TAG) {
223 fprintf(stderr, "%s:%d: No start tag found\n",
224 file->getPrintableSource().string(), block.getLineNumber());
225 return UNKNOWN_ERROR;
226 }
227 if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) {
228 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
229 file->getPrintableSource().string(), block.getLineNumber(),
230 String8(block.getElementName(&len)).string());
231 return UNKNOWN_ERROR;
232 }
233
234 ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
235 if (nameIndex < 0) {
236 fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
237 file->getPrintableSource().string(), block.getLineNumber());
238 return UNKNOWN_ERROR;
239 }
240
241 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len)));
242
Kenny Rootb5ef7ee2009-12-10 13:52:53 -0800243 String16 uses_sdk16("uses-sdk");
244 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
245 && code != ResXMLTree::BAD_DOCUMENT) {
246 if (code == ResXMLTree::START_TAG) {
247 if (strcmp16(block.getElementName(&len), uses_sdk16.string()) == 0) {
Kenny Root5a8ec762010-02-24 20:00:03 -0800248 ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE,
Kenny Rootb5ef7ee2009-12-10 13:52:53 -0800249 "minSdkVersion");
250 if (minSdkIndex >= 0) {
Kenny Root7ff20e32010-02-24 23:49:59 -0800251 const uint16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len);
252 const char* minSdk8 = strdup(String8(minSdk16).string());
Kenny Root1741cd42010-03-18 12:12:11 -0700253 bundle->setManifestMinSdkVersion(minSdk8);
Kenny Rootb5ef7ee2009-12-10 13:52:53 -0800254 }
255 }
256 }
257 }
258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 return NO_ERROR;
260}
261
262// ==========================================================================
263// ==========================================================================
264// ==========================================================================
265
266static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
267 ResourceTable* table,
268 const sp<ResourceTypeSet>& set,
269 const char* resType)
270{
271 String8 type8(resType);
272 String16 type16(resType);
273
274 bool hasErrors = false;
275
276 ResourceDirIterator it(set, String8(resType));
277 ssize_t res;
278 while ((res=it.next()) == NO_ERROR) {
279 if (bundle->getVerbose()) {
280 printf(" (new resource id %s from %s)\n",
281 it.getBaseName().string(), it.getFile()->getPrintableSource().string());
282 }
283 String16 baseName(it.getBaseName());
284 const char16_t* str = baseName.string();
285 const char16_t* const end = str + baseName.size();
286 while (str < end) {
287 if (!((*str >= 'a' && *str <= 'z')
288 || (*str >= '0' && *str <= '9')
289 || *str == '_' || *str == '.')) {
290 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
291 it.getPath().string());
292 hasErrors = true;
293 }
294 str++;
295 }
296 String8 resPath = it.getPath();
297 resPath.convertToResPath();
298 table->addEntry(SourcePos(it.getPath(), 0), String16(assets->getPackage()),
299 type16,
300 baseName,
301 String16(resPath),
302 NULL,
303 &it.getParams());
304 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
305 }
306
307 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
308}
309
Jeff Brownc0f73662012-03-16 22:17:41 -0700310class PreProcessImageWorkUnit : public WorkQueue::WorkUnit {
311public:
312 PreProcessImageWorkUnit(const Bundle* bundle, const sp<AaptAssets>& assets,
313 const sp<AaptFile>& file, volatile bool* hasErrors) :
314 mBundle(bundle), mAssets(assets), mFile(file), mHasErrors(hasErrors) {
315 }
316
317 virtual bool run() {
318 status_t status = preProcessImage(mBundle, mAssets, mFile, NULL);
319 if (status) {
320 *mHasErrors = true;
321 }
322 return true; // continue even if there are errors
323 }
324
325private:
326 const Bundle* mBundle;
327 sp<AaptAssets> mAssets;
328 sp<AaptFile> mFile;
329 volatile bool* mHasErrors;
330};
331
332static status_t preProcessImages(const Bundle* bundle, const sp<AaptAssets>& assets,
Kenny Root7c710232010-11-22 22:28:37 -0800333 const sp<ResourceTypeSet>& set, const char* type)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334{
Jeff Brownc0f73662012-03-16 22:17:41 -0700335 volatile bool hasErrors = false;
Josiah Gaskin8a39da82011-06-06 17:00:35 -0700336 ssize_t res = NO_ERROR;
337 if (bundle->getUseCrunchCache() == false) {
Jeff Brownc0f73662012-03-16 22:17:41 -0700338 WorkQueue wq(MAX_THREADS, false);
Xavier Ducrohet84be06e2011-07-20 17:45:11 -0700339 ResourceDirIterator it(set, String8(type));
Josiah Gaskin8a39da82011-06-06 17:00:35 -0700340 while ((res=it.next()) == NO_ERROR) {
Jeff Brownc0f73662012-03-16 22:17:41 -0700341 PreProcessImageWorkUnit* w = new PreProcessImageWorkUnit(
342 bundle, assets, it.getFile(), &hasErrors);
343 status_t status = wq.schedule(w);
344 if (status) {
345 fprintf(stderr, "preProcessImages failed: schedule() returned %d\n", status);
Josiah Gaskin8a39da82011-06-06 17:00:35 -0700346 hasErrors = true;
Jeff Brownc0f73662012-03-16 22:17:41 -0700347 delete w;
348 break;
Josiah Gaskin8a39da82011-06-06 17:00:35 -0700349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 }
Jeff Brownc0f73662012-03-16 22:17:41 -0700351 status_t status = wq.finish();
352 if (status) {
353 fprintf(stderr, "preProcessImages failed: finish() returned %d\n", status);
354 hasErrors = true;
355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 }
Daniel Sandler3547f852009-08-14 13:47:30 -0700357 return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358}
359
360status_t postProcessImages(const sp<AaptAssets>& assets,
361 ResourceTable* table,
362 const sp<ResourceTypeSet>& set)
363{
364 ResourceDirIterator it(set, String8("drawable"));
Daniel Sandler3547f852009-08-14 13:47:30 -0700365 bool hasErrors = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 ssize_t res;
367 while ((res=it.next()) == NO_ERROR) {
368 res = postProcessImage(assets, table, it.getFile());
Daniel Sandler3547f852009-08-14 13:47:30 -0700369 if (res < NO_ERROR) {
370 hasErrors = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 }
372 }
373
Daniel Sandler3547f852009-08-14 13:47:30 -0700374 return (hasErrors || (res < NO_ERROR)) ? UNKNOWN_ERROR : NO_ERROR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375}
376
377static void collect_files(const sp<AaptDir>& dir,
378 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
379{
380 const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles();
381 int N = groups.size();
382 for (int i=0; i<N; i++) {
383 String8 leafName = groups.keyAt(i);
384 const sp<AaptGroup>& group = groups.valueAt(i);
385
386 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files
387 = group->getFiles();
388
389 if (files.size() == 0) {
390 continue;
391 }
392
393 String8 resType = files.valueAt(0)->getResourceType();
394
395 ssize_t index = resources->indexOfKey(resType);
396
397 if (index < 0) {
398 sp<ResourceTypeSet> set = new ResourceTypeSet();
Dianne Hackborne6b68032011-10-13 16:26:02 -0700399 NOISY(printf("Creating new resource type set for leaf %s with group %s (%p)\n",
400 leafName.string(), group->getPath().string(), group.get()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 set->add(leafName, group);
402 resources->add(resType, set);
403 } else {
404 sp<ResourceTypeSet> set = resources->valueAt(index);
405 index = set->indexOfKey(leafName);
406 if (index < 0) {
Dianne Hackborne6b68032011-10-13 16:26:02 -0700407 NOISY(printf("Adding to resource type set for leaf %s group %s (%p)\n",
408 leafName.string(), group->getPath().string(), group.get()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 set->add(leafName, group);
410 } else {
411 sp<AaptGroup> existingGroup = set->valueAt(index);
Dianne Hackborne6b68032011-10-13 16:26:02 -0700412 NOISY(printf("Extending to resource type set for leaf %s group %s (%p)\n",
413 leafName.string(), group->getPath().string(), group.get()));
414 for (size_t j=0; j<files.size(); j++) {
415 NOISY(printf("Adding file %s in group %s resType %s\n",
416 files.valueAt(j)->getSourceFile().string(),
417 files.keyAt(j).toDirName(String8()).string(),
418 resType.string()));
419 status_t err = existingGroup->addFile(files.valueAt(j));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 }
421 }
422 }
423 }
424}
425
426static void collect_files(const sp<AaptAssets>& ass,
427 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
428{
429 const Vector<sp<AaptDir> >& dirs = ass->resDirs();
430 int N = dirs.size();
431
432 for (int i=0; i<N; i++) {
433 sp<AaptDir> d = dirs.itemAt(i);
Dianne Hackborne6b68032011-10-13 16:26:02 -0700434 NOISY(printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(),
435 d->getLeaf().string()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436 collect_files(d, resources);
437
438 // don't try to include the res dir
Dianne Hackborne6b68032011-10-13 16:26:02 -0700439 NOISY(printf("Removing dir leaf %s\n", d->getLeaf().string()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 ass->removeDir(d->getLeaf());
441 }
442}
443
444enum {
445 ATTR_OKAY = -1,
446 ATTR_NOT_FOUND = -2,
447 ATTR_LEADING_SPACES = -3,
448 ATTR_TRAILING_SPACES = -4
449};
Dianne Hackborncf244ad2010-03-09 15:00:30 -0800450static int validateAttr(const String8& path, const ResTable& table,
451 const ResXMLParser& parser,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 const char* ns, const char* attr, const char* validChars, bool required)
453{
454 size_t len;
455
456 ssize_t index = parser.indexOfAttribute(ns, attr);
457 const uint16_t* str;
Dianne Hackborncf244ad2010-03-09 15:00:30 -0800458 Res_value value;
459 if (index >= 0 && parser.getAttributeValue(index, &value) >= 0) {
460 const ResStringPool* pool = &parser.getStrings();
461 if (value.dataType == Res_value::TYPE_REFERENCE) {
462 uint32_t specFlags = 0;
463 int strIdx;
464 if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) {
465 fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n",
466 path.string(), parser.getLineNumber(),
467 String8(parser.getElementName(&len)).string(), attr,
468 value.data);
469 return ATTR_NOT_FOUND;
470 }
471
472 pool = table.getTableStringBlock(strIdx);
473 #if 0
474 if (pool != NULL) {
475 str = pool->stringAt(value.data, &len);
476 }
477 printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr,
478 specFlags, strIdx, str != NULL ? String8(str).string() : "???");
479 #endif
480 if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) {
481 fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n",
482 path.string(), parser.getLineNumber(),
483 String8(parser.getElementName(&len)).string(), attr,
484 specFlags);
485 return ATTR_NOT_FOUND;
486 }
487 }
488 if (value.dataType == Res_value::TYPE_STRING) {
489 if (pool == NULL) {
490 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n",
491 path.string(), parser.getLineNumber(),
492 String8(parser.getElementName(&len)).string(), attr);
493 return ATTR_NOT_FOUND;
494 }
495 if ((str=pool->stringAt(value.data, &len)) == NULL) {
496 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
497 path.string(), parser.getLineNumber(),
498 String8(parser.getElementName(&len)).string(), attr);
499 return ATTR_NOT_FOUND;
500 }
501 } else {
502 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
503 path.string(), parser.getLineNumber(),
504 String8(parser.getElementName(&len)).string(), attr,
505 value.dataType);
506 return ATTR_NOT_FOUND;
507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 if (validChars) {
509 for (size_t i=0; i<len; i++) {
510 uint16_t c = str[i];
511 const char* p = validChars;
512 bool okay = false;
513 while (*p) {
514 if (c == *p) {
515 okay = true;
516 break;
517 }
518 p++;
519 }
520 if (!okay) {
521 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
522 path.string(), parser.getLineNumber(),
523 String8(parser.getElementName(&len)).string(), attr, (char)str[i]);
524 return (int)i;
525 }
526 }
527 }
528 if (*str == ' ') {
529 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
530 path.string(), parser.getLineNumber(),
531 String8(parser.getElementName(&len)).string(), attr);
532 return ATTR_LEADING_SPACES;
533 }
534 if (str[len-1] == ' ') {
535 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
536 path.string(), parser.getLineNumber(),
537 String8(parser.getElementName(&len)).string(), attr);
538 return ATTR_TRAILING_SPACES;
539 }
540 return ATTR_OKAY;
541 }
542 if (required) {
543 fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
544 path.string(), parser.getLineNumber(),
545 String8(parser.getElementName(&len)).string(), attr);
546 return ATTR_NOT_FOUND;
547 }
548 return ATTR_OKAY;
549}
550
551static void checkForIds(const String8& path, ResXMLParser& parser)
552{
553 ResXMLTree::event_code_t code;
554 while ((code=parser.next()) != ResXMLTree::END_DOCUMENT
555 && code > ResXMLTree::BAD_DOCUMENT) {
556 if (code == ResXMLTree::START_TAG) {
557 ssize_t index = parser.indexOfAttribute(NULL, "id");
558 if (index >= 0) {
Marco Nelissendd931862009-07-13 13:02:33 -0700559 fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 path.string(), parser.getLineNumber());
561 }
562 }
563 }
564}
565
Robert Greenwalt832528f2009-08-31 14:48:20 -0700566static bool applyFileOverlay(Bundle *bundle,
567 const sp<AaptAssets>& assets,
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800568 sp<ResourceTypeSet> *baseSet,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 const char *resType)
570{
Robert Greenwalt832528f2009-08-31 14:48:20 -0700571 if (bundle->getVerbose()) {
572 printf("applyFileOverlay for %s\n", resType);
573 }
574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 // Replace any base level files in this category with any found from the overlay
576 // Also add any found only in the overlay.
577 sp<AaptAssets> overlay = assets->getOverlay();
578 String8 resTypeString(resType);
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 // work through the linked list of overlays
581 while (overlay.get()) {
582 KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources();
583
584 // get the overlay resources of the requested type
585 ssize_t index = overlayRes->indexOfKey(resTypeString);
586 if (index >= 0) {
587 sp<ResourceTypeSet> overlaySet = overlayRes->valueAt(index);
588
589 // for each of the resources, check for a match in the previously built
590 // non-overlay "baseset".
591 size_t overlayCount = overlaySet->size();
592 for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
Robert Greenwalt832528f2009-08-31 14:48:20 -0700593 if (bundle->getVerbose()) {
594 printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).string());
595 }
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800596 size_t baseIndex = UNKNOWN_ERROR;
597 if (baseSet->get() != NULL) {
598 baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
599 }
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700600 if (baseIndex < UNKNOWN_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 // look for same flavor. For a given file (strings.xml, for example)
602 // there may be a locale specific or other flavors - we want to match
603 // the same flavor.
604 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800605 sp<AaptGroup> baseGroup = (*baseSet)->valueAt(baseIndex);
Robert Greenwalt832528f2009-08-31 14:48:20 -0700606
607 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 overlayGroup->getFiles();
Robert Greenwalt832528f2009-08-31 14:48:20 -0700609 if (bundle->getVerbose()) {
610 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles =
611 baseGroup->getFiles();
612 for (size_t i=0; i < baseFiles.size(); i++) {
Raphaelf51125d2011-10-27 17:01:31 -0700613 printf("baseFile " ZD " has flavor %s\n", (ZD_TYPE) i,
Robert Greenwalt832528f2009-08-31 14:48:20 -0700614 baseFiles.keyAt(i).toString().string());
615 }
616 for (size_t i=0; i < overlayFiles.size(); i++) {
Raphaelf51125d2011-10-27 17:01:31 -0700617 printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i,
Robert Greenwalt832528f2009-08-31 14:48:20 -0700618 overlayFiles.keyAt(i).toString().string());
619 }
620 }
621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 size_t overlayGroupSize = overlayFiles.size();
Robert Greenwalt832528f2009-08-31 14:48:20 -0700623 for (size_t overlayGroupIndex = 0;
624 overlayGroupIndex<overlayGroupSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 overlayGroupIndex++) {
Robert Greenwalt832528f2009-08-31 14:48:20 -0700626 size_t baseFileIndex =
627 baseGroup->getFiles().indexOfKey(overlayFiles.
628 keyAt(overlayGroupIndex));
Dianne Hackborne6b68032011-10-13 16:26:02 -0700629 if (baseFileIndex < UNKNOWN_ERROR) {
Robert Greenwalt832528f2009-08-31 14:48:20 -0700630 if (bundle->getVerbose()) {
Raphaelf51125d2011-10-27 17:01:31 -0700631 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
632 (ZD_TYPE) baseFileIndex,
Robert Greenwalt832528f2009-08-31 14:48:20 -0700633 overlayGroup->getLeaf().string(),
634 overlayFiles.keyAt(overlayGroupIndex).toString().string());
635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 baseGroup->removeFile(baseFileIndex);
637 } else {
638 // didn't find a match fall through and add it..
Dianne Hackborne6b68032011-10-13 16:26:02 -0700639 if (true || bundle->getVerbose()) {
640 printf("nothing matches overlay file %s, for flavor %s\n",
641 overlayGroup->getLeaf().string(),
642 overlayFiles.keyAt(overlayGroupIndex).toString().string());
643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 }
645 baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
Dianne Hackborn64551b22009-08-15 00:00:33 -0700646 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 }
648 } else {
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800649 if (baseSet->get() == NULL) {
650 *baseSet = new ResourceTypeSet();
651 assets->getResources()->add(String8(resType), *baseSet);
652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 // this group doesn't exist (a file that's only in the overlay)
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800654 (*baseSet)->add(overlaySet->keyAt(overlayIndex),
Dianne Hackborn58c27a02009-08-13 13:36:00 -0700655 overlaySet->valueAt(overlayIndex));
Dianne Hackborn64551b22009-08-15 00:00:33 -0700656 // make sure all flavors are defined in the resources.
657 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
Robert Greenwalt832528f2009-08-31 14:48:20 -0700658 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
Dianne Hackborn64551b22009-08-15 00:00:33 -0700659 overlayGroup->getFiles();
660 size_t overlayGroupSize = overlayFiles.size();
Robert Greenwalt832528f2009-08-31 14:48:20 -0700661 for (size_t overlayGroupIndex = 0;
662 overlayGroupIndex<overlayGroupSize;
Dianne Hackborn64551b22009-08-15 00:00:33 -0700663 overlayGroupIndex++) {
664 assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666 }
667 }
668 // this overlay didn't have resources for this type
669 }
670 // try next overlay
671 overlay = overlay->getOverlay();
672 }
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700673 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674}
675
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700676/*
677 * Inserts an attribute in a given node, only if the attribute does not
678 * exist.
679 * If errorOnFailedInsert is true, and the attribute already exists, returns false.
680 * Returns true otherwise, even if the attribute already exists.
681 */
682bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
683 const char* attr8, const char* value, bool errorOnFailedInsert)
Dianne Hackborn62da8462009-05-13 15:06:13 -0700684{
685 if (value == NULL) {
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700686 return true;
Dianne Hackborn62da8462009-05-13 15:06:13 -0700687 }
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700688
Dianne Hackborn62da8462009-05-13 15:06:13 -0700689 const String16 ns(ns8);
690 const String16 attr(attr8);
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700691
Dianne Hackborn62da8462009-05-13 15:06:13 -0700692 if (node->getAttribute(ns, attr) != NULL) {
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700693 if (errorOnFailedInsert) {
694 fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
695 " cannot insert new value %s.\n",
696 String8(attr).string(), String8(ns).string(), value);
697 return false;
698 }
699
Kenny Rooted983092010-03-18 14:14:49 -0700700 fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s);"
701 " using existing value in manifest.\n",
Dianne Hackborn62da8462009-05-13 15:06:13 -0700702 String8(attr).string(), String8(ns).string());
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700703
704 // don't stop the build.
705 return true;
Dianne Hackborn62da8462009-05-13 15:06:13 -0700706 }
707
708 node->addAttribute(ns, attr, String16(value));
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700709 return true;
Dianne Hackborn62da8462009-05-13 15:06:13 -0700710}
711
Dianne Hackbornef05e072010-03-01 17:43:39 -0800712static void fullyQualifyClassName(const String8& package, sp<XMLNode> node,
713 const String16& attrName) {
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600714 XMLNode::attribute_entry* attr = node->editAttribute(
Dianne Hackbornef05e072010-03-01 17:43:39 -0800715 String16("http://schemas.android.com/apk/res/android"), attrName);
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600716 if (attr != NULL) {
717 String8 name(attr->string);
718
719 // asdf --> package.asdf
720 // .asdf .a.b --> package.asdf package.a.b
721 // asdf.adsf --> asdf.asdf
722 String8 className;
723 const char* p = name.string();
724 const char* q = strchr(p, '.');
725 if (p == q) {
726 className += package;
727 className += name;
728 } else if (q == NULL) {
729 className += package;
730 className += ".";
731 className += name;
732 } else {
733 className += name;
734 }
735 NOISY(printf("Qualifying class '%s' to '%s'", name.string(), className.string()));
736 attr->string.setTo(String16(className));
737 }
738}
739
Dianne Hackborn62da8462009-05-13 15:06:13 -0700740status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
741{
742 root = root->searchElement(String16(), String16("manifest"));
743 if (root == NULL) {
744 fprintf(stderr, "No <manifest> tag.\n");
745 return UNKNOWN_ERROR;
746 }
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700747
748 bool errorOnFailedInsert = bundle->getErrorOnFailedInsert();
749
750 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
751 bundle->getVersionCode(), errorOnFailedInsert)) {
752 return UNKNOWN_ERROR;
753 }
754 if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
755 bundle->getVersionName(), errorOnFailedInsert)) {
756 return UNKNOWN_ERROR;
757 }
Dianne Hackborn62da8462009-05-13 15:06:13 -0700758
759 if (bundle->getMinSdkVersion() != NULL
760 || bundle->getTargetSdkVersion() != NULL
761 || bundle->getMaxSdkVersion() != NULL) {
762 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
763 if (vers == NULL) {
764 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
765 root->insertChildAt(vers, 0);
766 }
767
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700768 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
769 bundle->getMinSdkVersion(), errorOnFailedInsert)) {
770 return UNKNOWN_ERROR;
771 }
772 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
773 bundle->getTargetSdkVersion(), errorOnFailedInsert)) {
774 return UNKNOWN_ERROR;
775 }
776 if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
777 bundle->getMaxSdkVersion(), errorOnFailedInsert)) {
778 return UNKNOWN_ERROR;
779 }
Dianne Hackborn62da8462009-05-13 15:06:13 -0700780 }
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600781
Xavier Ducrohet6487b092010-08-31 10:45:31 -0700782 if (bundle->getDebugMode()) {
783 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
784 if (application != NULL) {
Xavier Ducrohet7714a242012-09-05 17:49:21 -0700785 if (!addTagAttribute(application, RESOURCES_ANDROID_NAMESPACE, "debuggable", "true",
786 errorOnFailedInsert)) {
787 return UNKNOWN_ERROR;
788 }
Xavier Ducrohet6487b092010-08-31 10:45:31 -0700789 }
790 }
791
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600792 // Deal with manifest package name overrides
793 const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
794 if (manifestPackageNameOverride != NULL) {
795 // Update the actual package name
796 XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package"));
797 if (attr == NULL) {
798 fprintf(stderr, "package name is required with --rename-manifest-package.\n");
799 return UNKNOWN_ERROR;
800 }
801 String8 origPackage(attr->string);
802 attr->string.setTo(String16(manifestPackageNameOverride));
803 NOISY(printf("Overriding package '%s' to be '%s'\n", origPackage.string(), manifestPackageNameOverride));
804
805 // Make class names fully qualified
806 sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
807 if (application != NULL) {
Dianne Hackbornef05e072010-03-01 17:43:39 -0800808 fullyQualifyClassName(origPackage, application, String16("name"));
Dianne Hackbornb0381ef2010-03-03 13:36:35 -0800809 fullyQualifyClassName(origPackage, application, String16("backupAgent"));
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600810
811 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
812 for (size_t i = 0; i < children.size(); i++) {
813 sp<XMLNode> child = children.editItemAt(i);
814 String8 tag(child->getElementName());
815 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
Dianne Hackbornef05e072010-03-01 17:43:39 -0800816 fullyQualifyClassName(origPackage, child, String16("name"));
817 } else if (tag == "activity-alias") {
818 fullyQualifyClassName(origPackage, child, String16("name"));
819 fullyQualifyClassName(origPackage, child, String16("targetActivity"));
Jeff Hamilton2fee0ed2010-01-06 15:46:38 -0600820 }
821 }
822 }
823 }
824
Dianne Hackbornef05e072010-03-01 17:43:39 -0800825 // Deal with manifest package name overrides
826 const char* instrumentationPackageNameOverride = bundle->getInstrumentationPackageNameOverride();
827 if (instrumentationPackageNameOverride != NULL) {
828 // Fix up instrumentation targets.
829 Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(root->getChildren());
830 for (size_t i = 0; i < children.size(); i++) {
831 sp<XMLNode> child = children.editItemAt(i);
832 String8 tag(child->getElementName());
833 if (tag == "instrumentation") {
834 XMLNode::attribute_entry* attr = child->editAttribute(
835 String16("http://schemas.android.com/apk/res/android"), String16("targetPackage"));
836 if (attr != NULL) {
837 attr->string.setTo(String16(instrumentationPackageNameOverride));
838 }
839 }
840 }
841 }
842
Dianne Hackborn62da8462009-05-13 15:06:13 -0700843 return NO_ERROR;
844}
845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846#define ASSIGN_IT(n) \
847 do { \
848 ssize_t index = resources->indexOfKey(String8(#n)); \
849 if (index >= 0) { \
850 n ## s = resources->valueAt(index); \
851 } \
852 } while (0)
853
Josiah Gaskin8a39da82011-06-06 17:00:35 -0700854status_t updatePreProcessedCache(Bundle* bundle)
855{
856 #if BENCHMARK
857 fprintf(stdout, "BENCHMARK: Starting PNG PreProcessing \n");
858 long startPNGTime = clock();
859 #endif /* BENCHMARK */
860
861 String8 source(bundle->getResourceSourceDirs()[0]);
862 String8 dest(bundle->getCrunchedOutputDir());
863
864 FileFinder* ff = new SystemFileFinder();
865 CrunchCache cc(source,dest,ff);
866
867 CacheUpdater* cu = new SystemCacheUpdater(bundle);
868 size_t numFiles = cc.crunch(cu);
869
870 if (bundle->getVerbose())
871 fprintf(stdout, "Crunched %d PNG files to update cache\n", (int)numFiles);
872
873 delete ff;
874 delete cu;
875
876 #if BENCHMARK
877 fprintf(stdout, "BENCHMARK: End PNG PreProcessing. Time Elapsed: %f ms \n"
878 ,(clock() - startPNGTime)/1000.0);
879 #endif /* BENCHMARK */
880 return 0;
881}
882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets)
884{
885 // First, look for a package file to parse. This is required to
886 // be able to generate the resource information.
887 sp<AaptGroup> androidManifestFile =
888 assets->getFiles().valueFor(String8("AndroidManifest.xml"));
889 if (androidManifestFile == NULL) {
890 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
891 return UNKNOWN_ERROR;
892 }
893
Kenny Rootb5ef7ee2009-12-10 13:52:53 -0800894 status_t err = parsePackage(bundle, assets, androidManifestFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 if (err != NO_ERROR) {
896 return err;
897 }
898
899 NOISY(printf("Creating resources for package %s\n",
900 assets->getPackage().string()));
901
902 ResourceTable table(bundle, String16(assets->getPackage()));
903 err = table.addIncludedResources(bundle, assets);
904 if (err != NO_ERROR) {
905 return err;
906 }
907
908 NOISY(printf("Found %d included resource packages\n", (int)table.size()));
909
Kenny Root19138462009-12-04 09:38:48 -0800910 // Standard flags for compiled XML and optional UTF-8 encoding
911 int xmlFlags = XML_COMPILE_STANDARD_RESOURCE;
Kenny Root1741cd42010-03-18 12:12:11 -0700912
913 /* Only enable UTF-8 if the caller of aapt didn't specifically
914 * request UTF-16 encoding and the parameters of this package
915 * allow UTF-8 to be used.
916 */
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800917 if (!bundle->getUTF16StringsOption()) {
Kenny Root19138462009-12-04 09:38:48 -0800918 xmlFlags |= XML_COMPILE_UTF8;
919 }
920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 // --------------------------------------------------------------
922 // First, gather all resource information.
923 // --------------------------------------------------------------
924
925 // resType -> leafName -> group
926 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
927 new KeyedVector<String8, sp<ResourceTypeSet> >;
928 collect_files(assets, resources);
929
930 sp<ResourceTypeSet> drawables;
931 sp<ResourceTypeSet> layouts;
932 sp<ResourceTypeSet> anims;
Dianne Hackbornf31161a2011-01-04 21:02:48 -0800933 sp<ResourceTypeSet> animators;
934 sp<ResourceTypeSet> interpolators;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 sp<ResourceTypeSet> xmls;
936 sp<ResourceTypeSet> raws;
937 sp<ResourceTypeSet> colors;
938 sp<ResourceTypeSet> menus;
Kenny Root7c710232010-11-22 22:28:37 -0800939 sp<ResourceTypeSet> mipmaps;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940
941 ASSIGN_IT(drawable);
942 ASSIGN_IT(layout);
943 ASSIGN_IT(anim);
Dianne Hackbornf31161a2011-01-04 21:02:48 -0800944 ASSIGN_IT(animator);
945 ASSIGN_IT(interpolator);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 ASSIGN_IT(xml);
947 ASSIGN_IT(raw);
948 ASSIGN_IT(color);
949 ASSIGN_IT(menu);
Kenny Root7c710232010-11-22 22:28:37 -0800950 ASSIGN_IT(mipmap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951
952 assets->setResources(resources);
953 // now go through any resource overlays and collect their files
954 sp<AaptAssets> current = assets->getOverlay();
955 while(current.get()) {
956 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
957 new KeyedVector<String8, sp<ResourceTypeSet> >;
958 current->setResources(resources);
959 collect_files(current, resources);
960 current = current->getOverlay();
961 }
962 // apply the overlay files to the base set
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800963 if (!applyFileOverlay(bundle, assets, &drawables, "drawable") ||
964 !applyFileOverlay(bundle, assets, &layouts, "layout") ||
965 !applyFileOverlay(bundle, assets, &anims, "anim") ||
Dianne Hackbornf31161a2011-01-04 21:02:48 -0800966 !applyFileOverlay(bundle, assets, &animators, "animator") ||
967 !applyFileOverlay(bundle, assets, &interpolators, "interpolator") ||
Xavier Ducrohet83f4c092010-03-04 15:21:59 -0800968 !applyFileOverlay(bundle, assets, &xmls, "xml") ||
969 !applyFileOverlay(bundle, assets, &raws, "raw") ||
970 !applyFileOverlay(bundle, assets, &colors, "color") ||
Kenny Root7c710232010-11-22 22:28:37 -0800971 !applyFileOverlay(bundle, assets, &menus, "menu") ||
972 !applyFileOverlay(bundle, assets, &mipmaps, "mipmap")) {
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700973 return UNKNOWN_ERROR;
974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975
976 bool hasErrors = false;
977
978 if (drawables != NULL) {
Anthony Newnam578a57f2010-09-01 12:06:04 -0500979 if (bundle->getOutputAPKFile() != NULL) {
Kenny Root7c710232010-11-22 22:28:37 -0800980 err = preProcessImages(bundle, assets, drawables, "drawable");
Anthony Newnam578a57f2010-09-01 12:06:04 -0500981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 if (err == NO_ERROR) {
983 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
984 if (err != NO_ERROR) {
985 hasErrors = true;
986 }
987 } else {
988 hasErrors = true;
989 }
990 }
991
Kenny Root7c710232010-11-22 22:28:37 -0800992 if (mipmaps != NULL) {
993 if (bundle->getOutputAPKFile() != NULL) {
994 err = preProcessImages(bundle, assets, mipmaps, "mipmap");
995 }
996 if (err == NO_ERROR) {
997 err = makeFileResources(bundle, assets, &table, mipmaps, "mipmap");
998 if (err != NO_ERROR) {
999 hasErrors = true;
1000 }
1001 } else {
1002 hasErrors = true;
1003 }
1004 }
1005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 if (layouts != NULL) {
1007 err = makeFileResources(bundle, assets, &table, layouts, "layout");
1008 if (err != NO_ERROR) {
1009 hasErrors = true;
1010 }
1011 }
1012
1013 if (anims != NULL) {
1014 err = makeFileResources(bundle, assets, &table, anims, "anim");
1015 if (err != NO_ERROR) {
1016 hasErrors = true;
1017 }
1018 }
1019
Dianne Hackbornf31161a2011-01-04 21:02:48 -08001020 if (animators != NULL) {
1021 err = makeFileResources(bundle, assets, &table, animators, "animator");
1022 if (err != NO_ERROR) {
1023 hasErrors = true;
1024 }
1025 }
1026
1027 if (interpolators != NULL) {
1028 err = makeFileResources(bundle, assets, &table, interpolators, "interpolator");
1029 if (err != NO_ERROR) {
1030 hasErrors = true;
1031 }
1032 }
1033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 if (xmls != NULL) {
1035 err = makeFileResources(bundle, assets, &table, xmls, "xml");
1036 if (err != NO_ERROR) {
1037 hasErrors = true;
1038 }
1039 }
1040
1041 if (raws != NULL) {
1042 err = makeFileResources(bundle, assets, &table, raws, "raw");
1043 if (err != NO_ERROR) {
1044 hasErrors = true;
1045 }
1046 }
1047
1048 // compile resources
1049 current = assets;
1050 while(current.get()) {
1051 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
1052 current->getResources();
1053
1054 ssize_t index = resources->indexOfKey(String8("values"));
1055 if (index >= 0) {
1056 ResourceDirIterator it(resources->valueAt(index), String8("values"));
1057 ssize_t res;
1058 while ((res=it.next()) == NO_ERROR) {
1059 sp<AaptFile> file = it.getFile();
1060 res = compileResourceFile(bundle, assets, file, it.getParams(),
1061 (current!=assets), &table);
1062 if (res != NO_ERROR) {
1063 hasErrors = true;
1064 }
1065 }
1066 }
1067 current = current->getOverlay();
1068 }
1069
1070 if (colors != NULL) {
1071 err = makeFileResources(bundle, assets, &table, colors, "color");
1072 if (err != NO_ERROR) {
1073 hasErrors = true;
1074 }
1075 }
1076
1077 if (menus != NULL) {
1078 err = makeFileResources(bundle, assets, &table, menus, "menu");
1079 if (err != NO_ERROR) {
1080 hasErrors = true;
1081 }
1082 }
1083
1084 // --------------------------------------------------------------------
1085 // Assignment of resource IDs and initial generation of resource table.
1086 // --------------------------------------------------------------------
1087
1088 if (table.hasResources()) {
1089 sp<AaptFile> resFile(getResourceFile(assets));
1090 if (resFile == NULL) {
1091 fprintf(stderr, "Error: unable to generate entry for resource data\n");
1092 return UNKNOWN_ERROR;
1093 }
1094
1095 err = table.assignResourceIds();
1096 if (err < NO_ERROR) {
1097 return err;
1098 }
1099 }
1100
1101 // --------------------------------------------------------------
1102 // Finally, we can now we can compile XML files, which may reference
1103 // resources.
1104 // --------------------------------------------------------------
1105
1106 if (layouts != NULL) {
1107 ResourceDirIterator it(layouts, String8("layout"));
1108 while ((err=it.next()) == NO_ERROR) {
1109 String8 src = it.getFile()->getPrintableSource();
Kenny Root19138462009-12-04 09:38:48 -08001110 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 if (err == NO_ERROR) {
1112 ResXMLTree block;
1113 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1114 checkForIds(src, block);
1115 } else {
1116 hasErrors = true;
1117 }
1118 }
1119
1120 if (err < NO_ERROR) {
1121 hasErrors = true;
1122 }
1123 err = NO_ERROR;
1124 }
1125
1126 if (anims != NULL) {
1127 ResourceDirIterator it(anims, String8("anim"));
1128 while ((err=it.next()) == NO_ERROR) {
Kenny Root19138462009-12-04 09:38:48 -08001129 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 if (err != NO_ERROR) {
1131 hasErrors = true;
1132 }
1133 }
1134
1135 if (err < NO_ERROR) {
1136 hasErrors = true;
1137 }
1138 err = NO_ERROR;
1139 }
1140
Dianne Hackbornf31161a2011-01-04 21:02:48 -08001141 if (animators != NULL) {
1142 ResourceDirIterator it(animators, String8("animator"));
1143 while ((err=it.next()) == NO_ERROR) {
1144 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1145 if (err != NO_ERROR) {
1146 hasErrors = true;
1147 }
1148 }
1149
1150 if (err < NO_ERROR) {
1151 hasErrors = true;
1152 }
1153 err = NO_ERROR;
1154 }
1155
1156 if (interpolators != NULL) {
1157 ResourceDirIterator it(interpolators, String8("interpolator"));
1158 while ((err=it.next()) == NO_ERROR) {
1159 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
1160 if (err != NO_ERROR) {
1161 hasErrors = true;
1162 }
1163 }
1164
1165 if (err < NO_ERROR) {
1166 hasErrors = true;
1167 }
1168 err = NO_ERROR;
1169 }
1170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 if (xmls != NULL) {
1172 ResourceDirIterator it(xmls, String8("xml"));
1173 while ((err=it.next()) == NO_ERROR) {
Kenny Root19138462009-12-04 09:38:48 -08001174 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 if (err != NO_ERROR) {
1176 hasErrors = true;
1177 }
1178 }
1179
1180 if (err < NO_ERROR) {
1181 hasErrors = true;
1182 }
1183 err = NO_ERROR;
1184 }
1185
1186 if (drawables != NULL) {
1187 err = postProcessImages(assets, &table, drawables);
1188 if (err != NO_ERROR) {
1189 hasErrors = true;
1190 }
1191 }
1192
1193 if (colors != NULL) {
1194 ResourceDirIterator it(colors, String8("color"));
1195 while ((err=it.next()) == NO_ERROR) {
Kenny Root19138462009-12-04 09:38:48 -08001196 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 if (err != NO_ERROR) {
1198 hasErrors = true;
1199 }
1200 }
1201
1202 if (err < NO_ERROR) {
1203 hasErrors = true;
1204 }
1205 err = NO_ERROR;
1206 }
1207
1208 if (menus != NULL) {
1209 ResourceDirIterator it(menus, String8("menu"));
1210 while ((err=it.next()) == NO_ERROR) {
1211 String8 src = it.getFile()->getPrintableSource();
Kenny Root19138462009-12-04 09:38:48 -08001212 err = compileXmlFile(assets, it.getFile(), &table, xmlFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 if (err != NO_ERROR) {
1214 hasErrors = true;
1215 }
1216 ResXMLTree block;
1217 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
1218 checkForIds(src, block);
1219 }
1220
1221 if (err < NO_ERROR) {
1222 hasErrors = true;
1223 }
1224 err = NO_ERROR;
1225 }
1226
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001227 if (table.validateLocalizations()) {
1228 hasErrors = true;
1229 }
1230
1231 if (hasErrors) {
1232 return UNKNOWN_ERROR;
1233 }
1234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
1236 String8 manifestPath(manifestFile->getPrintableSource());
1237
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001238 // Generate final compiled manifest file.
1239 manifestFile->clearData();
1240 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1241 if (manifestTree == NULL) {
1242 return UNKNOWN_ERROR;
1243 }
1244 err = massageManifest(bundle, manifestTree);
1245 if (err < NO_ERROR) {
1246 return err;
1247 }
1248 err = compileXmlFile(assets, manifestTree, manifestFile, &table);
1249 if (err < NO_ERROR) {
1250 return err;
1251 }
1252
1253 //block.restart();
1254 //printXMLBlock(&block);
1255
1256 // --------------------------------------------------------------
1257 // Generate the final resource table.
1258 // Re-flatten because we may have added new resource IDs
1259 // --------------------------------------------------------------
1260
1261 ResTable finalResTable;
1262 sp<AaptFile> resFile;
1263
1264 if (table.hasResources()) {
1265 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1266 err = table.addSymbols(symbols);
1267 if (err < NO_ERROR) {
1268 return err;
1269 }
1270
1271 resFile = getResourceFile(assets);
1272 if (resFile == NULL) {
1273 fprintf(stderr, "Error: unable to generate entry for resource data\n");
1274 return UNKNOWN_ERROR;
1275 }
1276
1277 err = table.flatten(bundle, resFile);
1278 if (err < NO_ERROR) {
1279 return err;
1280 }
1281
1282 if (bundle->getPublicOutputFile()) {
1283 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1284 if (fp == NULL) {
1285 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1286 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1287 return UNKNOWN_ERROR;
1288 }
1289 if (bundle->getVerbose()) {
1290 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1291 }
1292 table.writePublicDefinitions(String16(assets->getPackage()), fp);
1293 fclose(fp);
1294 }
1295
1296 // Read resources back in,
1297 finalResTable.add(resFile->getData(), resFile->getSize(), NULL);
1298
1299#if 0
1300 NOISY(
1301 printf("Generated resources:\n");
1302 finalResTable.print();
1303 )
1304#endif
1305 }
1306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 // Perform a basic validation of the manifest file. This time we
1308 // parse it with the comments intact, so that we can use them to
1309 // generate java docs... so we are not going to write this one
1310 // back out to the final manifest data.
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001311 sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
1312 manifestFile->getGroupEntry(),
1313 manifestFile->getResourceType());
1314 err = compileXmlFile(assets, manifestFile,
1315 outManifestFile, &table,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 XML_COMPILE_ASSIGN_ATTRIBUTE_IDS
1317 | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES);
1318 if (err < NO_ERROR) {
1319 return err;
1320 }
1321 ResXMLTree block;
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001322 block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 String16 manifest16("manifest");
1324 String16 permission16("permission");
1325 String16 permission_group16("permission-group");
1326 String16 uses_permission16("uses-permission");
1327 String16 instrumentation16("instrumentation");
1328 String16 application16("application");
1329 String16 provider16("provider");
1330 String16 service16("service");
1331 String16 receiver16("receiver");
1332 String16 activity16("activity");
1333 String16 action16("action");
1334 String16 category16("category");
1335 String16 data16("scheme");
1336 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
1337 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
1338 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
1339 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1340 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
1341 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
1342 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
1343 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
1344 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
1345 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
1346 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1347 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
1348 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
1349 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
1350 ResXMLTree::event_code_t code;
1351 sp<AaptSymbols> permissionSymbols;
1352 sp<AaptSymbols> permissionGroupSymbols;
1353 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
1354 && code > ResXMLTree::BAD_DOCUMENT) {
1355 if (code == ResXMLTree::START_TAG) {
1356 size_t len;
1357 if (block.getElementNamespace(&len) != NULL) {
1358 continue;
1359 }
1360 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001361 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 packageIdentChars, true) != ATTR_OKAY) {
1363 hasErrors = true;
1364 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001365 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1366 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
1367 hasErrors = true;
1368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
1370 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
1371 const bool isGroup = strcmp16(block.getElementName(&len),
1372 permission_group16.string()) == 0;
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001373 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1374 "name", isGroup ? packageIdentCharsWithTheStupid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 : packageIdentChars, true) != ATTR_OKAY) {
1376 hasErrors = true;
1377 }
1378 SourcePos srcPos(manifestPath, block.getLineNumber());
1379 sp<AaptSymbols> syms;
1380 if (!isGroup) {
1381 syms = permissionSymbols;
1382 if (syms == NULL) {
1383 sp<AaptSymbols> symbols =
1384 assets->getSymbolsFor(String8("Manifest"));
1385 syms = permissionSymbols = symbols->addNestedSymbol(
1386 String8("permission"), srcPos);
1387 }
1388 } else {
1389 syms = permissionGroupSymbols;
1390 if (syms == NULL) {
1391 sp<AaptSymbols> symbols =
1392 assets->getSymbolsFor(String8("Manifest"));
1393 syms = permissionGroupSymbols = symbols->addNestedSymbol(
1394 String8("permission_group"), srcPos);
1395 }
1396 }
1397 size_t len;
1398 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
1399 const uint16_t* id = block.getAttributeStringValue(index, &len);
1400 if (id == NULL) {
1401 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
1402 manifestPath.string(), block.getLineNumber(),
1403 String8(block.getElementName(&len)).string());
1404 hasErrors = true;
1405 break;
1406 }
1407 String8 idStr(id);
1408 char* p = idStr.lockBuffer(idStr.size());
1409 char* e = p + idStr.size();
1410 bool begins_with_digit = true; // init to true so an empty string fails
1411 while (e > p) {
1412 e--;
1413 if (*e >= '0' && *e <= '9') {
1414 begins_with_digit = true;
1415 continue;
1416 }
1417 if ((*e >= 'a' && *e <= 'z') ||
1418 (*e >= 'A' && *e <= 'Z') ||
1419 (*e == '_')) {
1420 begins_with_digit = false;
1421 continue;
1422 }
1423 if (isGroup && (*e == '-')) {
1424 *e = '_';
1425 begins_with_digit = false;
1426 continue;
1427 }
1428 e++;
1429 break;
1430 }
1431 idStr.unlockBuffer();
1432 // verify that we stopped because we hit a period or
1433 // the beginning of the string, and that the
1434 // identifier didn't begin with a digit.
1435 if (begins_with_digit || (e != p && *(e-1) != '.')) {
1436 fprintf(stderr,
1437 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1438 manifestPath.string(), block.getLineNumber(), idStr.string());
1439 hasErrors = true;
1440 }
1441 syms->addStringSymbol(String8(e), idStr, srcPos);
1442 const uint16_t* cmt = block.getComment(&len);
1443 if (cmt != NULL && *cmt != 0) {
1444 //printf("Comment of %s: %s\n", String8(e).string(),
1445 // String8(cmt).string());
1446 syms->appendComment(String8(e), String16(cmt), srcPos);
1447 } else {
1448 //printf("No comment for %s\n", String8(e).string());
1449 }
1450 syms->makeSymbolPublic(String8(e), srcPos);
1451 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001452 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1453 "name", packageIdentChars, true) != ATTR_OKAY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 hasErrors = true;
1455 }
1456 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001457 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1458 "name", classIdentChars, true) != ATTR_OKAY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 hasErrors = true;
1460 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001461 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
1463 packageIdentChars, true) != ATTR_OKAY) {
1464 hasErrors = true;
1465 }
1466 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001467 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1468 "name", classIdentChars, false) != ATTR_OKAY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 hasErrors = true;
1470 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001471 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 RESOURCES_ANDROID_NAMESPACE, "permission",
1473 packageIdentChars, false) != ATTR_OKAY) {
1474 hasErrors = true;
1475 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001476 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 RESOURCES_ANDROID_NAMESPACE, "process",
1478 processIdentChars, false) != ATTR_OKAY) {
1479 hasErrors = true;
1480 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001481 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1483 processIdentChars, false) != ATTR_OKAY) {
1484 hasErrors = true;
1485 }
1486 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001487 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1488 "name", classIdentChars, true) != ATTR_OKAY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 hasErrors = true;
1490 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001491 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 RESOURCES_ANDROID_NAMESPACE, "authorities",
1493 authoritiesIdentChars, true) != ATTR_OKAY) {
1494 hasErrors = true;
1495 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001496 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 RESOURCES_ANDROID_NAMESPACE, "permission",
1498 packageIdentChars, false) != ATTR_OKAY) {
1499 hasErrors = true;
1500 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001501 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 RESOURCES_ANDROID_NAMESPACE, "process",
1503 processIdentChars, false) != ATTR_OKAY) {
1504 hasErrors = true;
1505 }
1506 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1507 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1508 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001509 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
1510 "name", classIdentChars, true) != ATTR_OKAY) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 hasErrors = true;
1512 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001513 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 RESOURCES_ANDROID_NAMESPACE, "permission",
1515 packageIdentChars, false) != ATTR_OKAY) {
1516 hasErrors = true;
1517 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001518 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 RESOURCES_ANDROID_NAMESPACE, "process",
1520 processIdentChars, false) != ATTR_OKAY) {
1521 hasErrors = true;
1522 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001523 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1525 processIdentChars, false) != ATTR_OKAY) {
1526 hasErrors = true;
1527 }
1528 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1529 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001530 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 RESOURCES_ANDROID_NAMESPACE, "name",
1532 packageIdentChars, true) != ATTR_OKAY) {
1533 hasErrors = true;
1534 }
1535 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001536 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 RESOURCES_ANDROID_NAMESPACE, "mimeType",
1538 typeIdentChars, true) != ATTR_OKAY) {
1539 hasErrors = true;
1540 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001541 if (validateAttr(manifestPath, finalResTable, block,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 RESOURCES_ANDROID_NAMESPACE, "scheme",
1543 schemeIdentChars, true) != ATTR_OKAY) {
1544 hasErrors = true;
1545 }
1546 }
1547 }
1548 }
1549
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001550 if (resFile != NULL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 // These resources are now considered to be a part of the included
1552 // resources, for others to reference.
1553 err = assets->addIncludedResources(resFile);
1554 if (err < NO_ERROR) {
1555 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
1556 return err;
1557 }
1558 }
Dianne Hackborncf244ad2010-03-09 15:00:30 -08001559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 return err;
1561}
1562
1563static const char* getIndentSpace(int indent)
1564{
1565static const char whitespace[] =
1566" ";
1567
1568 return whitespace + sizeof(whitespace) - 1 - indent*4;
1569}
1570
1571static status_t fixupSymbol(String16* inoutSymbol)
1572{
1573 inoutSymbol->replaceAll('.', '_');
1574 inoutSymbol->replaceAll(':', '_');
1575 return NO_ERROR;
1576}
1577
1578static String16 getAttributeComment(const sp<AaptAssets>& assets,
1579 const String8& name,
1580 String16* outTypeComment = NULL)
1581{
1582 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
1583 if (asym != NULL) {
1584 //printf("Got R symbols!\n");
1585 asym = asym->getNestedSymbols().valueFor(String8("attr"));
1586 if (asym != NULL) {
1587 //printf("Got attrs symbols! comment %s=%s\n",
1588 // name.string(), String8(asym->getComment(name)).string());
1589 if (outTypeComment != NULL) {
1590 *outTypeComment = asym->getTypeComment(name);
1591 }
1592 return asym->getComment(name);
1593 }
1594 }
1595 return String16();
1596}
1597
1598static status_t writeLayoutClasses(
1599 FILE* fp, const sp<AaptAssets>& assets,
Xavier Ducrohet8730f462013-04-12 16:00:49 -07001600 const sp<AaptSymbols>& symbols, int indent, bool includePrivate, bool nonConstantId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601{
1602 const char* indentStr = getIndentSpace(indent);
1603 if (!includePrivate) {
1604 fprintf(fp, "%s/** @doconly */\n", indentStr);
1605 }
1606 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
1607 indent++;
1608
1609 String16 attr16("attr");
1610 String16 package16(assets->getPackage());
1611
1612 indentStr = getIndentSpace(indent);
1613 bool hasErrors = false;
1614
Xavier Ducrohet8730f462013-04-12 16:00:49 -07001615 const char * id_array_format = nonConstantId ?
1616 "%spublic static int[] %s = {\n%s" :
1617 "%spublic static final int[] %s = {\n%s";
1618
1619 const char * id_array_index_format = nonConstantId ?
1620 "%spublic static int %s_%s = %d;\n" :
1621 "%spublic static final int %s_%s = %d;\n";
1622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 size_t i;
1624 size_t N = symbols->getNestedSymbols().size();
1625 for (i=0; i<N; i++) {
1626 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1627 String16 nclassName16(symbols->getNestedSymbols().keyAt(i));
1628 String8 realClassName(nclassName16);
1629 if (fixupSymbol(&nclassName16) != NO_ERROR) {
1630 hasErrors = true;
1631 }
1632 String8 nclassName(nclassName16);
1633
1634 SortedVector<uint32_t> idents;
1635 Vector<uint32_t> origOrder;
1636 Vector<bool> publicFlags;
1637
1638 size_t a;
1639 size_t NA = nsymbols->getSymbols().size();
1640 for (a=0; a<NA; a++) {
1641 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1642 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1643 ? sym.int32Val : 0;
1644 bool isPublic = true;
1645 if (code == 0) {
1646 String16 name16(sym.name);
1647 uint32_t typeSpecFlags;
1648 code = assets->getIncludedResources().identifierForName(
1649 name16.string(), name16.size(),
1650 attr16.string(), attr16.size(),
1651 package16.string(), package16.size(), &typeSpecFlags);
1652 if (code == 0) {
1653 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1654 nclassName.string(), sym.name.string());
1655 hasErrors = true;
1656 }
1657 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1658 }
1659 idents.add(code);
1660 origOrder.add(code);
1661 publicFlags.add(isPublic);
1662 }
1663
1664 NA = idents.size();
1665
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001666 bool deprecated = false;
1667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 String16 comment = symbols->getComment(realClassName);
1669 fprintf(fp, "%s/** ", indentStr);
1670 if (comment.size() > 0) {
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001671 String8 cmt(comment);
1672 fprintf(fp, "%s\n", cmt.string());
1673 if (strstr(cmt.string(), "@deprecated") != NULL) {
1674 deprecated = true;
1675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 } else {
1677 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
1678 }
1679 bool hasTable = false;
1680 for (a=0; a<NA; a++) {
1681 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1682 if (pos >= 0) {
1683 if (!hasTable) {
1684 hasTable = true;
1685 fprintf(fp,
1686 "%s <p>Includes the following attributes:</p>\n"
Dirk Dougherty59ad2752009-11-03 15:33:37 -08001687 "%s <table>\n"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 "%s <colgroup align=\"left\" />\n"
1689 "%s <colgroup align=\"left\" />\n"
Dirk Dougherty59ad2752009-11-03 15:33:37 -08001690 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 indentStr,
1692 indentStr,
1693 indentStr,
1694 indentStr,
1695 indentStr);
1696 }
1697 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1698 if (!publicFlags.itemAt(a) && !includePrivate) {
1699 continue;
1700 }
1701 String8 name8(sym.name);
1702 String16 comment(sym.comment);
1703 if (comment.size() <= 0) {
1704 comment = getAttributeComment(assets, name8);
1705 }
1706 if (comment.size() > 0) {
1707 const char16_t* p = comment.string();
1708 while (*p != 0 && *p != '.') {
1709 if (*p == '{') {
1710 while (*p != 0 && *p != '}') {
1711 p++;
1712 }
1713 } else {
1714 p++;
1715 }
1716 }
1717 if (*p == '.') {
1718 p++;
1719 }
1720 comment = String16(comment.string(), p-comment.string());
1721 }
1722 String16 name(name8);
1723 fixupSymbol(&name);
Dirk Dougherty59ad2752009-11-03 15:33:37 -08001724 fprintf(fp, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 indentStr, nclassName.string(),
1726 String8(name).string(),
1727 assets->getPackage().string(),
1728 String8(name).string(),
1729 String8(comment).string());
1730 }
1731 }
1732 if (hasTable) {
1733 fprintf(fp, "%s </table>\n", indentStr);
1734 }
1735 for (a=0; a<NA; a++) {
1736 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1737 if (pos >= 0) {
1738 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1739 if (!publicFlags.itemAt(a) && !includePrivate) {
1740 continue;
1741 }
1742 String16 name(sym.name);
1743 fixupSymbol(&name);
1744 fprintf(fp, "%s @see #%s_%s\n",
1745 indentStr, nclassName.string(),
1746 String8(name).string());
1747 }
1748 }
1749 fprintf(fp, "%s */\n", getIndentSpace(indent));
1750
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001751 if (deprecated) {
1752 fprintf(fp, "%s@Deprecated\n", indentStr);
1753 }
1754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 fprintf(fp,
Xavier Ducrohet8730f462013-04-12 16:00:49 -07001756 id_array_format,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 indentStr, nclassName.string(),
1758 getIndentSpace(indent+1));
1759
1760 for (a=0; a<NA; a++) {
1761 if (a != 0) {
1762 if ((a&3) == 0) {
1763 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
1764 } else {
1765 fprintf(fp, ", ");
1766 }
1767 }
1768 fprintf(fp, "0x%08x", idents[a]);
1769 }
1770
1771 fprintf(fp, "\n%s};\n", indentStr);
1772
1773 for (a=0; a<NA; a++) {
1774 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1775 if (pos >= 0) {
1776 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1777 if (!publicFlags.itemAt(a) && !includePrivate) {
1778 continue;
1779 }
1780 String8 name8(sym.name);
1781 String16 comment(sym.comment);
1782 String16 typeComment;
1783 if (comment.size() <= 0) {
1784 comment = getAttributeComment(assets, name8, &typeComment);
1785 } else {
1786 getAttributeComment(assets, name8, &typeComment);
1787 }
1788 String16 name(name8);
1789 if (fixupSymbol(&name) != NO_ERROR) {
1790 hasErrors = true;
1791 }
1792
1793 uint32_t typeSpecFlags = 0;
1794 String16 name16(sym.name);
1795 assets->getIncludedResources().identifierForName(
1796 name16.string(), name16.size(),
1797 attr16.string(), attr16.size(),
1798 package16.string(), package16.size(), &typeSpecFlags);
1799 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1800 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1801 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001802
1803 bool deprecated = false;
1804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 fprintf(fp, "%s/**\n", indentStr);
1806 if (comment.size() > 0) {
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001807 String8 cmt(comment);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001809 fprintf(fp, "%s %s\n", indentStr, cmt.string());
1810 if (strstr(cmt.string(), "@deprecated") != NULL) {
1811 deprecated = true;
1812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 } else {
1814 fprintf(fp,
1815 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
1816 "%s attribute's value can be found in the {@link #%s} array.\n",
1817 indentStr,
1818 pub ? assets->getPackage().string()
1819 : assets->getSymbolsPrivatePackage().string(),
1820 String8(name).string(),
1821 indentStr, nclassName.string());
1822 }
1823 if (typeComment.size() > 0) {
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001824 String8 cmt(typeComment);
1825 fprintf(fp, "\n\n%s %s\n", indentStr, cmt.string());
1826 if (strstr(cmt.string(), "@deprecated") != NULL) {
1827 deprecated = true;
1828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830 if (comment.size() > 0) {
1831 if (pub) {
1832 fprintf(fp,
1833 "%s <p>This corresponds to the global attribute"
1834 "%s resource symbol {@link %s.R.attr#%s}.\n",
1835 indentStr, indentStr,
1836 assets->getPackage().string(),
1837 String8(name).string());
1838 } else {
1839 fprintf(fp,
1840 "%s <p>This is a private symbol.\n", indentStr);
1841 }
1842 }
1843 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
1844 "android", String8(name).string());
1845 fprintf(fp, "%s*/\n", indentStr);
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001846 if (deprecated) {
1847 fprintf(fp, "%s@Deprecated\n", indentStr);
1848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 fprintf(fp,
Xavier Ducrohet8730f462013-04-12 16:00:49 -07001850 id_array_index_format,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 indentStr, nclassName.string(),
1852 String8(name).string(), (int)pos);
1853 }
1854 }
1855 }
1856
1857 indent--;
1858 fprintf(fp, "%s};\n", getIndentSpace(indent));
1859 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1860}
1861
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07001862static status_t writeTextLayoutClasses(
1863 FILE* fp, const sp<AaptAssets>& assets,
1864 const sp<AaptSymbols>& symbols, bool includePrivate)
1865{
1866 String16 attr16("attr");
1867 String16 package16(assets->getPackage());
1868
1869 bool hasErrors = false;
1870
1871 size_t i;
1872 size_t N = symbols->getNestedSymbols().size();
1873 for (i=0; i<N; i++) {
1874 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1875 String16 nclassName16(symbols->getNestedSymbols().keyAt(i));
1876 String8 realClassName(nclassName16);
1877 if (fixupSymbol(&nclassName16) != NO_ERROR) {
1878 hasErrors = true;
1879 }
1880 String8 nclassName(nclassName16);
1881
1882 SortedVector<uint32_t> idents;
1883 Vector<uint32_t> origOrder;
1884 Vector<bool> publicFlags;
1885
1886 size_t a;
1887 size_t NA = nsymbols->getSymbols().size();
1888 for (a=0; a<NA; a++) {
1889 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1890 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1891 ? sym.int32Val : 0;
1892 bool isPublic = true;
1893 if (code == 0) {
1894 String16 name16(sym.name);
1895 uint32_t typeSpecFlags;
1896 code = assets->getIncludedResources().identifierForName(
1897 name16.string(), name16.size(),
1898 attr16.string(), attr16.size(),
1899 package16.string(), package16.size(), &typeSpecFlags);
1900 if (code == 0) {
1901 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1902 nclassName.string(), sym.name.string());
1903 hasErrors = true;
1904 }
1905 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1906 }
1907 idents.add(code);
1908 origOrder.add(code);
1909 publicFlags.add(isPublic);
1910 }
1911
1912 NA = idents.size();
1913
1914 fprintf(fp, "int[] styleable %s {", nclassName.string());
1915
1916 for (a=0; a<NA; a++) {
1917 if (a != 0) {
1918 fprintf(fp, ",");
1919 }
1920 fprintf(fp, " 0x%08x", idents[a]);
1921 }
1922
1923 fprintf(fp, " }\n");
1924
1925 for (a=0; a<NA; a++) {
1926 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1927 if (pos >= 0) {
1928 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1929 if (!publicFlags.itemAt(a) && !includePrivate) {
1930 continue;
1931 }
1932 String8 name8(sym.name);
1933 String16 comment(sym.comment);
1934 String16 typeComment;
1935 if (comment.size() <= 0) {
1936 comment = getAttributeComment(assets, name8, &typeComment);
1937 } else {
1938 getAttributeComment(assets, name8, &typeComment);
1939 }
1940 String16 name(name8);
1941 if (fixupSymbol(&name) != NO_ERROR) {
1942 hasErrors = true;
1943 }
1944
1945 uint32_t typeSpecFlags = 0;
1946 String16 name16(sym.name);
1947 assets->getIncludedResources().identifierForName(
1948 name16.string(), name16.size(),
1949 attr16.string(), attr16.size(),
1950 package16.string(), package16.size(), &typeSpecFlags);
1951 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1952 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1953 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1954
1955 fprintf(fp,
Xavier Ducrohetd1604742012-09-26 10:11:54 -07001956 "int styleable %s_%s %d\n",
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07001957 nclassName.string(),
1958 String8(name).string(), (int)pos);
1959 }
1960 }
1961 }
1962
1963 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1964}
1965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966static status_t writeSymbolClass(
1967 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
Xavier Ducrohetd06c1af2011-02-14 16:58:00 -08001968 const sp<AaptSymbols>& symbols, const String8& className, int indent,
1969 bool nonConstantId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970{
1971 fprintf(fp, "%spublic %sfinal class %s {\n",
1972 getIndentSpace(indent),
1973 indent != 0 ? "static " : "", className.string());
1974 indent++;
1975
1976 size_t i;
1977 status_t err = NO_ERROR;
1978
Xavier Ducrohetd06c1af2011-02-14 16:58:00 -08001979 const char * id_format = nonConstantId ?
1980 "%spublic static int %s=0x%08x;\n" :
1981 "%spublic static final int %s=0x%08x;\n";
1982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 size_t N = symbols->getSymbols().size();
1984 for (i=0; i<N; i++) {
1985 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
1986 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
1987 continue;
1988 }
Dianne Hackborn1644c6d72012-02-06 15:33:21 -08001989 if (!assets->isJavaSymbol(sym, includePrivate)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 continue;
1991 }
1992 String16 name(sym.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 if (fixupSymbol(&name) != NO_ERROR) {
1994 return UNKNOWN_ERROR;
1995 }
1996 String16 comment(sym.comment);
1997 bool haveComment = false;
Dianne Hackborn4a51c202009-08-21 15:14:02 -07001998 bool deprecated = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 if (comment.size() > 0) {
2000 haveComment = true;
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002001 String8 cmt(comment);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 fprintf(fp,
2003 "%s/** %s\n",
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002004 getIndentSpace(indent), cmt.string());
2005 if (strstr(cmt.string(), "@deprecated") != NULL) {
2006 deprecated = true;
2007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 } else if (sym.isPublic && !includePrivate) {
2009 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
2010 assets->getPackage().string(), className.string(),
2011 String8(sym.name).string());
2012 }
2013 String16 typeComment(sym.typeComment);
2014 if (typeComment.size() > 0) {
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002015 String8 cmt(typeComment);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 if (!haveComment) {
2017 haveComment = true;
2018 fprintf(fp,
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002019 "%s/** %s\n", getIndentSpace(indent), cmt.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 } else {
2021 fprintf(fp,
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002022 "%s %s\n", getIndentSpace(indent), cmt.string());
2023 }
2024 if (strstr(cmt.string(), "@deprecated") != NULL) {
2025 deprecated = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 }
2027 }
2028 if (haveComment) {
2029 fprintf(fp,"%s */\n", getIndentSpace(indent));
2030 }
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002031 if (deprecated) {
2032 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
2033 }
Xavier Ducrohetd06c1af2011-02-14 16:58:00 -08002034 fprintf(fp, id_format,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 getIndentSpace(indent),
2036 String8(name).string(), (int)sym.int32Val);
2037 }
2038
2039 for (i=0; i<N; i++) {
2040 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2041 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
2042 continue;
2043 }
Dianne Hackborn1644c6d72012-02-06 15:33:21 -08002044 if (!assets->isJavaSymbol(sym, includePrivate)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 continue;
2046 }
2047 String16 name(sym.name);
2048 if (fixupSymbol(&name) != NO_ERROR) {
2049 return UNKNOWN_ERROR;
2050 }
2051 String16 comment(sym.comment);
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002052 bool deprecated = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 if (comment.size() > 0) {
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002054 String8 cmt(comment);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 fprintf(fp,
2056 "%s/** %s\n"
2057 "%s */\n",
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002058 getIndentSpace(indent), cmt.string(),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 getIndentSpace(indent));
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002060 if (strstr(cmt.string(), "@deprecated") != NULL) {
2061 deprecated = true;
2062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 } else if (sym.isPublic && !includePrivate) {
2064 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
2065 assets->getPackage().string(), className.string(),
2066 String8(sym.name).string());
2067 }
Dianne Hackborn4a51c202009-08-21 15:14:02 -07002068 if (deprecated) {
2069 fprintf(fp, "%s@Deprecated\n", getIndentSpace(indent));
2070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
2072 getIndentSpace(indent),
2073 String8(name).string(), sym.stringVal.string());
2074 }
2075
2076 sp<AaptSymbols> styleableSymbols;
2077
2078 N = symbols->getNestedSymbols().size();
2079 for (i=0; i<N; i++) {
2080 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2081 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2082 if (nclassName == "styleable") {
2083 styleableSymbols = nsymbols;
2084 } else {
Xavier Ducrohetd06c1af2011-02-14 16:58:00 -08002085 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName, indent, nonConstantId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 }
2087 if (err != NO_ERROR) {
2088 return err;
2089 }
2090 }
2091
2092 if (styleableSymbols != NULL) {
Xavier Ducrohet8730f462013-04-12 16:00:49 -07002093 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate, nonConstantId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 if (err != NO_ERROR) {
2095 return err;
2096 }
2097 }
2098
2099 indent--;
2100 fprintf(fp, "%s}\n", getIndentSpace(indent));
2101 return NO_ERROR;
2102}
2103
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002104static status_t writeTextSymbolClass(
2105 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
2106 const sp<AaptSymbols>& symbols, const String8& className)
2107{
2108 size_t i;
2109 status_t err = NO_ERROR;
2110
2111 size_t N = symbols->getSymbols().size();
2112 for (i=0; i<N; i++) {
2113 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
2114 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
2115 continue;
2116 }
2117
2118 if (!assets->isJavaSymbol(sym, includePrivate)) {
2119 continue;
2120 }
2121
2122 String16 name(sym.name);
2123 if (fixupSymbol(&name) != NO_ERROR) {
2124 return UNKNOWN_ERROR;
2125 }
2126
2127 fprintf(fp, "int %s %s 0x%08x\n",
2128 className.string(),
2129 String8(name).string(), (int)sym.int32Val);
2130 }
2131
2132 N = symbols->getNestedSymbols().size();
2133 for (i=0; i<N; i++) {
2134 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
2135 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
2136 if (nclassName == "styleable") {
2137 err = writeTextLayoutClasses(fp, assets, nsymbols, includePrivate);
2138 } else {
2139 err = writeTextSymbolClass(fp, assets, includePrivate, nsymbols, nclassName);
2140 }
2141 if (err != NO_ERROR) {
2142 return err;
2143 }
2144 }
2145
2146 return NO_ERROR;
2147}
2148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
2150 const String8& package, bool includePrivate)
2151{
2152 if (!bundle->getRClassDir()) {
2153 return NO_ERROR;
2154 }
2155
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002156 const char* textSymbolsDest = bundle->getOutputTextSymbols();
2157
2158 String8 R("R");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 const size_t N = assets->getSymbols().size();
2160 for (size_t i=0; i<N; i++) {
2161 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
2162 String8 className(assets->getSymbols().keyAt(i));
2163 String8 dest(bundle->getRClassDir());
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 if (bundle->getMakePackageDirs()) {
2166 String8 pkg(package);
2167 const char* last = pkg.string();
2168 const char* s = last-1;
2169 do {
2170 s++;
2171 if (s > last && (*s == '.' || *s == 0)) {
2172 String8 part(last, s-last);
2173 dest.appendPath(part);
2174#ifdef HAVE_MS_C_RUNTIME
2175 _mkdir(dest.string());
2176#else
2177 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
2178#endif
2179 last = s+1;
2180 }
2181 } while (*s);
2182 }
2183 dest.appendPath(className);
2184 dest.append(".java");
2185 FILE* fp = fopen(dest.string(), "w+");
2186 if (fp == NULL) {
2187 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2188 dest.string(), strerror(errno));
2189 return UNKNOWN_ERROR;
2190 }
2191 if (bundle->getVerbose()) {
2192 printf(" Writing symbols for class %s.\n", className.string());
2193 }
2194
2195 fprintf(fp,
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002196 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
2197 " *\n"
2198 " * This class was automatically generated by the\n"
2199 " * aapt tool from the resource data it found. It\n"
2200 " * should not be modified by hand.\n"
2201 " */\n"
2202 "\n"
2203 "package %s;\n\n", package.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204
Dianne Hackborn1644c6d72012-02-06 15:33:21 -08002205 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
2206 className, 0, bundle->getNonConstantId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 if (err != NO_ERROR) {
2208 return err;
2209 }
2210 fclose(fp);
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002211
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002212 if (textSymbolsDest != NULL && R == className) {
2213 String8 textDest(textSymbolsDest);
2214 textDest.appendPath(className);
2215 textDest.append(".txt");
2216
2217 FILE* fp = fopen(textDest.string(), "w+");
2218 if (fp == NULL) {
2219 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
2220 textDest.string(), strerror(errno));
2221 return UNKNOWN_ERROR;
2222 }
2223 if (bundle->getVerbose()) {
2224 printf(" Writing text symbols for class %s.\n", className.string());
2225 }
2226
2227 status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
2228 className);
2229 if (err != NO_ERROR) {
2230 return err;
2231 }
2232 fclose(fp);
2233 }
2234
Josiah Gaskinb711f3f2011-08-15 18:33:44 -07002235 // If we were asked to generate a dependency file, we'll go ahead and add this R.java
2236 // as a target in the dependency file right next to it.
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002237 if (bundle->getGenDependencies() && R == className) {
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002238 // Add this R.java to the dependency file
2239 String8 dependencyFile(bundle->getRClassDir());
Josiah Gaskinb711f3f2011-08-15 18:33:44 -07002240 dependencyFile.appendPath("R.java.d");
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002241
Xavier Ducrohetf5de6502012-09-11 14:45:22 -07002242 FILE *fp = fopen(dependencyFile.string(), "a");
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002243 fprintf(fp,"%s \\\n", dest.string());
2244 fclose(fp);
2245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 }
2247
2248 return NO_ERROR;
2249}
Joe Onorato1553c822009-08-30 13:36:22 -07002250
2251
Joe Onorato1553c822009-08-30 13:36:22 -07002252class ProguardKeepSet
2253{
2254public:
2255 // { rule --> { file locations } }
2256 KeyedVector<String8, SortedVector<String8> > rules;
2257
2258 void add(const String8& rule, const String8& where);
2259};
2260
2261void ProguardKeepSet::add(const String8& rule, const String8& where)
2262{
2263 ssize_t index = rules.indexOfKey(rule);
2264 if (index < 0) {
2265 index = rules.add(rule, SortedVector<String8>());
2266 }
2267 rules.editValueAt(index).add(where);
2268}
2269
Dianne Hackbornb0381ef2010-03-03 13:36:35 -08002270void
2271addProguardKeepRule(ProguardKeepSet* keep, const String8& inClassName,
2272 const char* pkg, const String8& srcName, int line)
2273{
2274 String8 className(inClassName);
2275 if (pkg != NULL) {
2276 // asdf --> package.asdf
2277 // .asdf .a.b --> package.asdf package.a.b
2278 // asdf.adsf --> asdf.asdf
2279 const char* p = className.string();
2280 const char* q = strchr(p, '.');
2281 if (p == q) {
2282 className = pkg;
2283 className.append(inClassName);
2284 } else if (q == NULL) {
2285 className = pkg;
2286 className.append(".");
2287 className.append(inClassName);
2288 }
2289 }
Ying Wang561a9182010-08-13 13:56:07 -07002290
Dianne Hackbornb0381ef2010-03-03 13:36:35 -08002291 String8 rule("-keep class ");
2292 rule += className;
2293 rule += " { <init>(...); }";
2294
2295 String8 location("view ");
2296 location += srcName;
2297 char lineno[20];
2298 sprintf(lineno, ":%d", line);
2299 location += lineno;
2300
2301 keep->add(rule, location);
2302}
2303
Dianne Hackborn92751972012-05-18 19:22:14 -07002304void
2305addProguardKeepMethodRule(ProguardKeepSet* keep, const String8& memberName,
2306 const char* pkg, const String8& srcName, int line)
2307{
2308 String8 rule("-keepclassmembers class * { *** ");
2309 rule += memberName;
2310 rule += "(...); }";
2311
2312 String8 location("onClick ");
2313 location += srcName;
2314 char lineno[20];
2315 sprintf(lineno, ":%d", line);
2316 location += lineno;
2317
2318 keep->add(rule, location);
2319}
2320
Joe Onorato1553c822009-08-30 13:36:22 -07002321status_t
2322writeProguardForAndroidManifest(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
2323{
2324 status_t err;
2325 ResXMLTree tree;
2326 size_t len;
2327 ResXMLTree::event_code_t code;
2328 int depth = 0;
2329 bool inApplication = false;
2330 String8 error;
2331 sp<AaptGroup> assGroup;
2332 sp<AaptFile> assFile;
2333 String8 pkg;
2334
2335 // First, look for a package file to parse. This is required to
2336 // be able to generate the resource information.
2337 assGroup = assets->getFiles().valueFor(String8("AndroidManifest.xml"));
2338 if (assGroup == NULL) {
2339 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
2340 return -1;
2341 }
2342
2343 if (assGroup->getFiles().size() != 1) {
2344 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
2345 assGroup->getFiles().valueAt(0)->getPrintableSource().string());
2346 }
2347
2348 assFile = assGroup->getFiles().valueAt(0);
2349
2350 err = parseXMLResource(assFile, &tree);
2351 if (err != NO_ERROR) {
2352 return err;
2353 }
2354
2355 tree.restart();
2356
2357 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2358 if (code == ResXMLTree::END_TAG) {
2359 if (/* name == "Application" && */ depth == 2) {
2360 inApplication = false;
2361 }
2362 depth--;
2363 continue;
2364 }
2365 if (code != ResXMLTree::START_TAG) {
2366 continue;
2367 }
2368 depth++;
2369 String8 tag(tree.getElementName(&len));
2370 // printf("Depth %d tag %s\n", depth, tag.string());
Ying Wang46f4b982010-01-13 14:18:11 -08002371 bool keepTag = false;
Joe Onorato1553c822009-08-30 13:36:22 -07002372 if (depth == 1) {
2373 if (tag != "manifest") {
2374 fprintf(stderr, "ERROR: manifest does not start with <manifest> tag\n");
2375 return -1;
2376 }
2377 pkg = getAttribute(tree, NULL, "package", NULL);
Ying Wang46f4b982010-01-13 14:18:11 -08002378 } else if (depth == 2) {
2379 if (tag == "application") {
2380 inApplication = true;
2381 keepTag = true;
Ying Wang561a9182010-08-13 13:56:07 -07002382
Dianne Hackbornb0381ef2010-03-03 13:36:35 -08002383 String8 agent = getAttribute(tree, "http://schemas.android.com/apk/res/android",
2384 "backupAgent", &error);
2385 if (agent.length() > 0) {
2386 addProguardKeepRule(keep, agent, pkg.string(),
2387 assFile->getPrintableSource(), tree.getLineNumber());
2388 }
Ying Wang46f4b982010-01-13 14:18:11 -08002389 } else if (tag == "instrumentation") {
2390 keepTag = true;
2391 }
Joe Onorato1553c822009-08-30 13:36:22 -07002392 }
Ying Wang46f4b982010-01-13 14:18:11 -08002393 if (!keepTag && inApplication && depth == 3) {
2394 if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
2395 keepTag = true;
2396 }
2397 }
2398 if (keepTag) {
2399 String8 name = getAttribute(tree, "http://schemas.android.com/apk/res/android",
2400 "name", &error);
2401 if (error != "") {
2402 fprintf(stderr, "ERROR: %s\n", error.string());
2403 return -1;
2404 }
2405 if (name.length() > 0) {
Dianne Hackbornb0381ef2010-03-03 13:36:35 -08002406 addProguardKeepRule(keep, name, pkg.string(),
2407 assFile->getPrintableSource(), tree.getLineNumber());
Joe Onorato1553c822009-08-30 13:36:22 -07002408 }
2409 }
2410 }
2411
2412 return NO_ERROR;
2413}
2414
Ying Wang561a9182010-08-13 13:56:07 -07002415struct NamespaceAttributePair {
2416 const char* ns;
2417 const char* attr;
2418
2419 NamespaceAttributePair(const char* n, const char* a) : ns(n), attr(a) {}
2420 NamespaceAttributePair() : ns(NULL), attr(NULL) {}
2421};
2422
Joe Onorato1553c822009-08-30 13:36:22 -07002423status_t
Dianne Hackbornabd03652010-03-02 14:56:51 -08002424writeProguardForXml(ProguardKeepSet* keep, const sp<AaptFile>& layoutFile,
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002425 const char* startTag, const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs)
Joe Onorato1553c822009-08-30 13:36:22 -07002426{
2427 status_t err;
2428 ResXMLTree tree;
2429 size_t len;
2430 ResXMLTree::event_code_t code;
2431
2432 err = parseXMLResource(layoutFile, &tree);
2433 if (err != NO_ERROR) {
2434 return err;
2435 }
2436
2437 tree.restart();
2438
Dianne Hackbornabd03652010-03-02 14:56:51 -08002439 if (startTag != NULL) {
2440 bool haveStart = false;
2441 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2442 if (code != ResXMLTree::START_TAG) {
2443 continue;
2444 }
2445 String8 tag(tree.getElementName(&len));
2446 if (tag == startTag) {
2447 haveStart = true;
2448 }
2449 break;
2450 }
2451 if (!haveStart) {
2452 return NO_ERROR;
2453 }
2454 }
Ying Wang561a9182010-08-13 13:56:07 -07002455
Joe Onorato1553c822009-08-30 13:36:22 -07002456 while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
2457 if (code != ResXMLTree::START_TAG) {
2458 continue;
2459 }
2460 String8 tag(tree.getElementName(&len));
2461
2462 // If there is no '.', we'll assume that it's one of the built in names.
2463 if (strchr(tag.string(), '.')) {
Dianne Hackbornb0381ef2010-03-03 13:36:35 -08002464 addProguardKeepRule(keep, tag, NULL,
Dianne Hackbornabd03652010-03-02 14:56:51 -08002465 layoutFile->getPrintableSource(), tree.getLineNumber());
Ying Wang561a9182010-08-13 13:56:07 -07002466 } else if (tagAttrPairs != NULL) {
2467 ssize_t tagIndex = tagAttrPairs->indexOfKey(tag);
2468 if (tagIndex >= 0) {
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002469 const Vector<NamespaceAttributePair>& nsAttrVector = tagAttrPairs->valueAt(tagIndex);
2470 for (size_t i = 0; i < nsAttrVector.size(); i++) {
2471 const NamespaceAttributePair& nsAttr = nsAttrVector[i];
2472
2473 ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
2474 if (attrIndex < 0) {
2475 // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
2476 // layoutFile->getPrintableSource().string(), tree.getLineNumber(),
2477 // tag.string(), nsAttr.ns, nsAttr.attr);
2478 } else {
2479 size_t len;
2480 addProguardKeepRule(keep,
2481 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
2482 layoutFile->getPrintableSource(), tree.getLineNumber());
2483 }
Ying Wang561a9182010-08-13 13:56:07 -07002484 }
Dianne Hackbornabd03652010-03-02 14:56:51 -08002485 }
Joe Onorato1553c822009-08-30 13:36:22 -07002486 }
Dianne Hackborn92751972012-05-18 19:22:14 -07002487 ssize_t attrIndex = tree.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "onClick");
2488 if (attrIndex >= 0) {
2489 size_t len;
2490 addProguardKeepMethodRule(keep,
2491 String8(tree.getAttributeStringValue(attrIndex, &len)), NULL,
2492 layoutFile->getPrintableSource(), tree.getLineNumber());
2493 }
Joe Onorato1553c822009-08-30 13:36:22 -07002494 }
2495
2496 return NO_ERROR;
2497}
2498
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002499static void addTagAttrPair(KeyedVector<String8, Vector<NamespaceAttributePair> >* dest,
Ying Wang561a9182010-08-13 13:56:07 -07002500 const char* tag, const char* ns, const char* attr) {
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002501 String8 tagStr(tag);
2502 ssize_t index = dest->indexOfKey(tagStr);
2503
2504 if (index < 0) {
2505 Vector<NamespaceAttributePair> vector;
2506 vector.add(NamespaceAttributePair(ns, attr));
2507 dest->add(tagStr, vector);
2508 } else {
2509 dest->editValueAt(index).add(NamespaceAttributePair(ns, attr));
2510 }
Ying Wang561a9182010-08-13 13:56:07 -07002511}
2512
Joe Onorato1553c822009-08-30 13:36:22 -07002513status_t
2514writeProguardForLayouts(ProguardKeepSet* keep, const sp<AaptAssets>& assets)
2515{
2516 status_t err;
Ying Wang561a9182010-08-13 13:56:07 -07002517
2518 // tag:attribute pairs that should be checked in layout files.
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002519 KeyedVector<String8, Vector<NamespaceAttributePair> > kLayoutTagAttrPairs;
Ying Wang561a9182010-08-13 13:56:07 -07002520 addTagAttrPair(&kLayoutTagAttrPairs, "view", NULL, "class");
Dianne Hackborn8a44bb22010-08-19 12:56:10 -07002521 addTagAttrPair(&kLayoutTagAttrPairs, "fragment", NULL, "class");
Ying Wang561a9182010-08-13 13:56:07 -07002522 addTagAttrPair(&kLayoutTagAttrPairs, "fragment", RESOURCES_ANDROID_NAMESPACE, "name");
2523
2524 // tag:attribute pairs that should be checked in xml files.
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002525 KeyedVector<String8, Vector<NamespaceAttributePair> > kXmlTagAttrPairs;
Ying Wang561a9182010-08-13 13:56:07 -07002526 addTagAttrPair(&kXmlTagAttrPairs, "PreferenceScreen", RESOURCES_ANDROID_NAMESPACE, "fragment");
Dianne Hackborn8a44bb22010-08-19 12:56:10 -07002527 addTagAttrPair(&kXmlTagAttrPairs, "header", RESOURCES_ANDROID_NAMESPACE, "fragment");
Ying Wang561a9182010-08-13 13:56:07 -07002528
Ying Wangc1112962010-01-20 22:12:46 -08002529 const Vector<sp<AaptDir> >& dirs = assets->resDirs();
2530 const size_t K = dirs.size();
2531 for (size_t k=0; k<K; k++) {
2532 const sp<AaptDir>& d = dirs.itemAt(k);
2533 const String8& dirName = d->getLeaf();
Dianne Hackbornabd03652010-03-02 14:56:51 -08002534 const char* startTag = NULL;
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002535 const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
Dianne Hackbornabd03652010-03-02 14:56:51 -08002536 if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
Ying Wang561a9182010-08-13 13:56:07 -07002537 tagAttrPairs = &kLayoutTagAttrPairs;
Dianne Hackbornabd03652010-03-02 14:56:51 -08002538 } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
2539 startTag = "PreferenceScreen";
Ying Wang561a9182010-08-13 13:56:07 -07002540 tagAttrPairs = &kXmlTagAttrPairs;
Dianne Hackborn92751972012-05-18 19:22:14 -07002541 } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) {
2542 startTag = "menu";
2543 tagAttrPairs = NULL;
Dianne Hackbornabd03652010-03-02 14:56:51 -08002544 } else {
Ying Wangc1112962010-01-20 22:12:46 -08002545 continue;
2546 }
Ying Wang561a9182010-08-13 13:56:07 -07002547
Ying Wangc1112962010-01-20 22:12:46 -08002548 const KeyedVector<String8,sp<AaptGroup> > groups = d->getFiles();
Joe Onorato1553c822009-08-30 13:36:22 -07002549 const size_t N = groups.size();
2550 for (size_t i=0; i<N; i++) {
2551 const sp<AaptGroup>& group = groups.valueAt(i);
2552 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files = group->getFiles();
2553 const size_t M = files.size();
2554 for (size_t j=0; j<M; j++) {
Ying Wang561a9182010-08-13 13:56:07 -07002555 err = writeProguardForXml(keep, files.valueAt(j), startTag, tagAttrPairs);
Joe Onorato1553c822009-08-30 13:36:22 -07002556 if (err < 0) {
2557 return err;
2558 }
2559 }
2560 }
2561 }
Ying Wang45ccfa52011-06-20 15:41:08 -07002562 // Handle the overlays
2563 sp<AaptAssets> overlay = assets->getOverlay();
2564 if (overlay.get()) {
2565 return writeProguardForLayouts(keep, overlay);
2566 }
Xavier Ducrohet095cd2e2012-07-18 18:06:09 -07002567
Joe Onorato1553c822009-08-30 13:36:22 -07002568 return NO_ERROR;
2569}
2570
2571status_t
2572writeProguardFile(Bundle* bundle, const sp<AaptAssets>& assets)
2573{
2574 status_t err = -1;
2575
2576 if (!bundle->getProguardFile()) {
2577 return NO_ERROR;
2578 }
2579
2580 ProguardKeepSet keep;
2581
2582 err = writeProguardForAndroidManifest(&keep, assets);
2583 if (err < 0) {
2584 return err;
2585 }
2586
2587 err = writeProguardForLayouts(&keep, assets);
2588 if (err < 0) {
2589 return err;
2590 }
2591
2592 FILE* fp = fopen(bundle->getProguardFile(), "w+");
2593 if (fp == NULL) {
2594 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
2595 bundle->getProguardFile(), strerror(errno));
2596 return UNKNOWN_ERROR;
2597 }
2598
2599 const KeyedVector<String8, SortedVector<String8> >& rules = keep.rules;
2600 const size_t N = rules.size();
2601 for (size_t i=0; i<N; i++) {
2602 const SortedVector<String8>& locations = rules.valueAt(i);
2603 const size_t M = locations.size();
2604 for (size_t j=0; j<M; j++) {
2605 fprintf(fp, "# %s\n", locations.itemAt(j).string());
2606 }
2607 fprintf(fp, "%s\n\n", rules.keyAt(i).string());
2608 }
2609 fclose(fp);
2610
2611 return err;
2612}
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002613
Josiah Gaskin03589cc2011-06-27 16:26:02 -07002614// Loops through the string paths and writes them to the file pointer
2615// Each file path is written on its own line with a terminating backslash.
2616status_t writePathsToFile(const sp<FilePathStore>& files, FILE* fp)
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002617{
2618 status_t deps = -1;
Josiah Gaskin9bf34ca2011-06-14 13:57:09 -07002619 for (size_t file_i = 0; file_i < files->size(); ++file_i) {
2620 // Add the full file path to the dependency file
2621 fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
2622 deps++;
2623 }
2624 return deps;
Xavier Ducrohet91398682011-07-19 10:18:28 -07002625}
Josiah Gaskin03589cc2011-06-27 16:26:02 -07002626
2627status_t
2628writeDependencyPreReqs(Bundle* bundle, const sp<AaptAssets>& assets, FILE* fp, bool includeRaw)
2629{
2630 status_t deps = -1;
2631 deps += writePathsToFile(assets->getFullResPaths(), fp);
2632 if (includeRaw) {
2633 deps += writePathsToFile(assets->getFullAssetPaths(), fp);
2634 }
2635 return deps;
2636}