blob: 41ee88b4451c1bc90162a62f4b5883262c32cd25 [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
13#define NOISY(x) // x
14
15// ==========================================================================
16// ==========================================================================
17// ==========================================================================
18
19class PackageInfo
20{
21public:
22 PackageInfo()
23 {
24 }
25 ~PackageInfo()
26 {
27 }
28
29 status_t parsePackage(const sp<AaptGroup>& grp);
30};
31
32// ==========================================================================
33// ==========================================================================
34// ==========================================================================
35
36static String8 parseResourceName(const String8& leaf)
37{
38 const char* firstDot = strchr(leaf.string(), '.');
39 const char* str = leaf.string();
40
41 if (firstDot) {
42 return String8(str, firstDot-str);
43 } else {
44 return String8(str);
45 }
46}
47
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048ResourceTypeSet::ResourceTypeSet()
49 :RefBase(),
50 KeyedVector<String8,sp<AaptGroup> >()
51{
52}
53
54class ResourceDirIterator
55{
56public:
57 ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType)
58 : mResType(resType), mSet(set), mSetPos(0), mGroupPos(0)
59 {
60 }
61
62 inline const sp<AaptGroup>& getGroup() const { return mGroup; }
63 inline const sp<AaptFile>& getFile() const { return mFile; }
64
65 inline const String8& getBaseName() const { return mBaseName; }
66 inline const String8& getLeafName() const { return mLeafName; }
67 inline String8 getPath() const { return mPath; }
68 inline const ResTable_config& getParams() const { return mParams; }
69
70 enum {
71 EOD = 1
72 };
73
74 ssize_t next()
75 {
76 while (true) {
77 sp<AaptGroup> group;
78 sp<AaptFile> file;
79
80 // Try to get next file in this current group.
81 if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) {
82 group = mGroup;
83 file = group->getFiles().valueAt(mGroupPos++);
84
85 // Try to get the next group/file in this directory
86 } else if (mSetPos < mSet->size()) {
87 mGroup = group = mSet->valueAt(mSetPos++);
88 if (group->getFiles().size() < 1) {
89 continue;
90 }
91 file = group->getFiles().valueAt(0);
92 mGroupPos = 1;
93
94 // All done!
95 } else {
96 return EOD;
97 }
98
99 mFile = file;
100
101 String8 leaf(group->getLeaf());
102 mLeafName = String8(leaf);
103 mParams = file->getGroupEntry().toParams();
104 NOISY(printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d density=%d touch=%d key=%d inp=%d nav=%d\n",
105 group->getPath().string(), mParams.mcc, mParams.mnc,
106 mParams.language[0] ? mParams.language[0] : '-',
107 mParams.language[1] ? mParams.language[1] : '-',
108 mParams.country[0] ? mParams.country[0] : '-',
109 mParams.country[1] ? mParams.country[1] : '-',
110 mParams.orientation,
111 mParams.density, mParams.touchscreen, mParams.keyboard,
112 mParams.inputFlags, mParams.navigation));
113 mPath = "res";
114 mPath.appendPath(file->getGroupEntry().toDirName(mResType));
115 mPath.appendPath(leaf);
116 mBaseName = parseResourceName(leaf);
117 if (mBaseName == "") {
118 fprintf(stderr, "Error: malformed resource filename %s\n",
119 file->getPrintableSource().string());
120 return UNKNOWN_ERROR;
121 }
122
123 NOISY(printf("file name=%s\n", mBaseName.string()));
124
125 return NO_ERROR;
126 }
127 }
128
129private:
130 String8 mResType;
131
132 const sp<ResourceTypeSet> mSet;
133 size_t mSetPos;
134
135 sp<AaptGroup> mGroup;
136 size_t mGroupPos;
137
138 sp<AaptFile> mFile;
139 String8 mBaseName;
140 String8 mLeafName;
141 String8 mPath;
142 ResTable_config mParams;
143};
144
145// ==========================================================================
146// ==========================================================================
147// ==========================================================================
148
149bool isValidResourceType(const String8& type)
150{
151 return type == "anim" || type == "drawable" || type == "layout"
152 || type == "values" || type == "xml" || type == "raw"
153 || type == "color" || type == "menu";
154}
155
156static sp<AaptFile> getResourceFile(const sp<AaptAssets>& assets, bool makeIfNecessary=true)
157{
158 sp<AaptGroup> group = assets->getFiles().valueFor(String8("resources.arsc"));
159 sp<AaptFile> file;
160 if (group != NULL) {
161 file = group->getFiles().valueFor(AaptGroupEntry());
162 if (file != NULL) {
163 return file;
164 }
165 }
166
167 if (!makeIfNecessary) {
168 return NULL;
169 }
170 return assets->addFile(String8("resources.arsc"), AaptGroupEntry(), String8(),
171 NULL, String8());
172}
173
174static status_t parsePackage(const sp<AaptAssets>& assets, const sp<AaptGroup>& grp)
175{
176 if (grp->getFiles().size() != 1) {
Marco Nelissendd931862009-07-13 13:02:33 -0700177 fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 grp->getFiles().valueAt(0)->getPrintableSource().string());
179 }
180
181 sp<AaptFile> file = grp->getFiles().valueAt(0);
182
183 ResXMLTree block;
184 status_t err = parseXMLResource(file, &block);
185 if (err != NO_ERROR) {
186 return err;
187 }
188 //printXMLBlock(&block);
189
190 ResXMLTree::event_code_t code;
191 while ((code=block.next()) != ResXMLTree::START_TAG
192 && code != ResXMLTree::END_DOCUMENT
193 && code != ResXMLTree::BAD_DOCUMENT) {
194 }
195
196 size_t len;
197 if (code != ResXMLTree::START_TAG) {
198 fprintf(stderr, "%s:%d: No start tag found\n",
199 file->getPrintableSource().string(), block.getLineNumber());
200 return UNKNOWN_ERROR;
201 }
202 if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) {
203 fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
204 file->getPrintableSource().string(), block.getLineNumber(),
205 String8(block.getElementName(&len)).string());
206 return UNKNOWN_ERROR;
207 }
208
209 ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
210 if (nameIndex < 0) {
211 fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
212 file->getPrintableSource().string(), block.getLineNumber());
213 return UNKNOWN_ERROR;
214 }
215
216 assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len)));
217
218 return NO_ERROR;
219}
220
221// ==========================================================================
222// ==========================================================================
223// ==========================================================================
224
225static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
226 ResourceTable* table,
227 const sp<ResourceTypeSet>& set,
228 const char* resType)
229{
230 String8 type8(resType);
231 String16 type16(resType);
232
233 bool hasErrors = false;
234
235 ResourceDirIterator it(set, String8(resType));
236 ssize_t res;
237 while ((res=it.next()) == NO_ERROR) {
238 if (bundle->getVerbose()) {
239 printf(" (new resource id %s from %s)\n",
240 it.getBaseName().string(), it.getFile()->getPrintableSource().string());
241 }
242 String16 baseName(it.getBaseName());
243 const char16_t* str = baseName.string();
244 const char16_t* const end = str + baseName.size();
245 while (str < end) {
246 if (!((*str >= 'a' && *str <= 'z')
247 || (*str >= '0' && *str <= '9')
248 || *str == '_' || *str == '.')) {
249 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
250 it.getPath().string());
251 hasErrors = true;
252 }
253 str++;
254 }
255 String8 resPath = it.getPath();
256 resPath.convertToResPath();
257 table->addEntry(SourcePos(it.getPath(), 0), String16(assets->getPackage()),
258 type16,
259 baseName,
260 String16(resPath),
261 NULL,
262 &it.getParams());
263 assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
264 }
265
266 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
267}
268
269static status_t preProcessImages(Bundle* bundle, const sp<AaptAssets>& assets,
270 const sp<ResourceTypeSet>& set)
271{
272 ResourceDirIterator it(set, String8("drawable"));
273 Vector<sp<AaptFile> > newNameFiles;
274 Vector<String8> newNamePaths;
275 ssize_t res;
276 while ((res=it.next()) == NO_ERROR) {
277 res = preProcessImage(bundle, assets, it.getFile(), NULL);
278 if (res != NO_ERROR) {
279 return res;
280 }
281 }
282
283 return NO_ERROR;
284}
285
286status_t postProcessImages(const sp<AaptAssets>& assets,
287 ResourceTable* table,
288 const sp<ResourceTypeSet>& set)
289{
290 ResourceDirIterator it(set, String8("drawable"));
291 ssize_t res;
292 while ((res=it.next()) == NO_ERROR) {
293 res = postProcessImage(assets, table, it.getFile());
294 if (res != NO_ERROR) {
295 return res;
296 }
297 }
298
299 return res < NO_ERROR ? res : (status_t)NO_ERROR;
300}
301
302static void collect_files(const sp<AaptDir>& dir,
303 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
304{
305 const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles();
306 int N = groups.size();
307 for (int i=0; i<N; i++) {
308 String8 leafName = groups.keyAt(i);
309 const sp<AaptGroup>& group = groups.valueAt(i);
310
311 const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files
312 = group->getFiles();
313
314 if (files.size() == 0) {
315 continue;
316 }
317
318 String8 resType = files.valueAt(0)->getResourceType();
319
320 ssize_t index = resources->indexOfKey(resType);
321
322 if (index < 0) {
323 sp<ResourceTypeSet> set = new ResourceTypeSet();
324 set->add(leafName, group);
325 resources->add(resType, set);
326 } else {
327 sp<ResourceTypeSet> set = resources->valueAt(index);
328 index = set->indexOfKey(leafName);
329 if (index < 0) {
330 set->add(leafName, group);
331 } else {
332 sp<AaptGroup> existingGroup = set->valueAt(index);
333 int M = files.size();
334 for (int j=0; j<M; j++) {
335 existingGroup->addFile(files.valueAt(j));
336 }
337 }
338 }
339 }
340}
341
342static void collect_files(const sp<AaptAssets>& ass,
343 KeyedVector<String8, sp<ResourceTypeSet> >* resources)
344{
345 const Vector<sp<AaptDir> >& dirs = ass->resDirs();
346 int N = dirs.size();
347
348 for (int i=0; i<N; i++) {
349 sp<AaptDir> d = dirs.itemAt(i);
350 collect_files(d, resources);
351
352 // don't try to include the res dir
353 ass->removeDir(d->getLeaf());
354 }
355}
356
357enum {
358 ATTR_OKAY = -1,
359 ATTR_NOT_FOUND = -2,
360 ATTR_LEADING_SPACES = -3,
361 ATTR_TRAILING_SPACES = -4
362};
363static int validateAttr(const String8& path, const ResXMLParser& parser,
364 const char* ns, const char* attr, const char* validChars, bool required)
365{
366 size_t len;
367
368 ssize_t index = parser.indexOfAttribute(ns, attr);
369 const uint16_t* str;
370 if (index >= 0 && (str=parser.getAttributeStringValue(index, &len)) != NULL) {
371 if (validChars) {
372 for (size_t i=0; i<len; i++) {
373 uint16_t c = str[i];
374 const char* p = validChars;
375 bool okay = false;
376 while (*p) {
377 if (c == *p) {
378 okay = true;
379 break;
380 }
381 p++;
382 }
383 if (!okay) {
384 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
385 path.string(), parser.getLineNumber(),
386 String8(parser.getElementName(&len)).string(), attr, (char)str[i]);
387 return (int)i;
388 }
389 }
390 }
391 if (*str == ' ') {
392 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
393 path.string(), parser.getLineNumber(),
394 String8(parser.getElementName(&len)).string(), attr);
395 return ATTR_LEADING_SPACES;
396 }
397 if (str[len-1] == ' ') {
398 fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
399 path.string(), parser.getLineNumber(),
400 String8(parser.getElementName(&len)).string(), attr);
401 return ATTR_TRAILING_SPACES;
402 }
403 return ATTR_OKAY;
404 }
405 if (required) {
406 fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
407 path.string(), parser.getLineNumber(),
408 String8(parser.getElementName(&len)).string(), attr);
409 return ATTR_NOT_FOUND;
410 }
411 return ATTR_OKAY;
412}
413
414static void checkForIds(const String8& path, ResXMLParser& parser)
415{
416 ResXMLTree::event_code_t code;
417 while ((code=parser.next()) != ResXMLTree::END_DOCUMENT
418 && code > ResXMLTree::BAD_DOCUMENT) {
419 if (code == ResXMLTree::START_TAG) {
420 ssize_t index = parser.indexOfAttribute(NULL, "id");
421 if (index >= 0) {
Marco Nelissendd931862009-07-13 13:02:33 -0700422 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 -0800423 path.string(), parser.getLineNumber());
424 }
425 }
426 }
427}
428
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700429static bool applyFileOverlay(const sp<AaptAssets>& assets,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 const sp<ResourceTypeSet>& baseSet,
431 const char *resType)
432{
433 // Replace any base level files in this category with any found from the overlay
434 // Also add any found only in the overlay.
435 sp<AaptAssets> overlay = assets->getOverlay();
436 String8 resTypeString(resType);
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 // work through the linked list of overlays
439 while (overlay.get()) {
440 KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources();
441
442 // get the overlay resources of the requested type
443 ssize_t index = overlayRes->indexOfKey(resTypeString);
444 if (index >= 0) {
445 sp<ResourceTypeSet> overlaySet = overlayRes->valueAt(index);
446
447 // for each of the resources, check for a match in the previously built
448 // non-overlay "baseset".
449 size_t overlayCount = overlaySet->size();
450 for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
451 size_t baseIndex = baseSet->indexOfKey(overlaySet->keyAt(overlayIndex));
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700452 if (baseIndex < UNKNOWN_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 // look for same flavor. For a given file (strings.xml, for example)
454 // there may be a locale specific or other flavors - we want to match
455 // the same flavor.
456 sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
457 sp<AaptGroup> baseGroup = baseSet->valueAt(baseIndex);
458
459 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles =
460 baseGroup->getFiles();
461 DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
462 overlayGroup->getFiles();
463 size_t overlayGroupSize = overlayFiles.size();
464 for (size_t overlayGroupIndex = 0;
465 overlayGroupIndex<overlayGroupSize;
466 overlayGroupIndex++) {
467 size_t baseFileIndex =
468 baseFiles.indexOfKey(overlayFiles.keyAt(overlayGroupIndex));
469 if(baseFileIndex < UNKNOWN_ERROR) {
470 baseGroup->removeFile(baseFileIndex);
471 } else {
472 // didn't find a match fall through and add it..
473 }
474 baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
475 }
476 } else {
477 // this group doesn't exist (a file that's only in the overlay)
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700478 fprintf(stderr, "aapt: error: "
479 "*** Resource file '%s' exists only in an overlay\n",
480 overlaySet->keyAt(overlayIndex).string());
481 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 }
483 }
484 // this overlay didn't have resources for this type
485 }
486 // try next overlay
487 overlay = overlay->getOverlay();
488 }
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700489 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490}
491
Dianne Hackborn62da8462009-05-13 15:06:13 -0700492void addTagAttribute(const sp<XMLNode>& node, const char* ns8,
493 const char* attr8, const char* value)
494{
495 if (value == NULL) {
496 return;
497 }
498
499 const String16 ns(ns8);
500 const String16 attr(attr8);
501
502 if (node->getAttribute(ns, attr) != NULL) {
503 fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s)\n",
504 String8(attr).string(), String8(ns).string());
505 return;
506 }
507
508 node->addAttribute(ns, attr, String16(value));
509}
510
511status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
512{
513 root = root->searchElement(String16(), String16("manifest"));
514 if (root == NULL) {
515 fprintf(stderr, "No <manifest> tag.\n");
516 return UNKNOWN_ERROR;
517 }
518
519 addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
520 bundle->getVersionCode());
521 addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
522 bundle->getVersionName());
523
524 if (bundle->getMinSdkVersion() != NULL
525 || bundle->getTargetSdkVersion() != NULL
526 || bundle->getMaxSdkVersion() != NULL) {
527 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
528 if (vers == NULL) {
529 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
530 root->insertChildAt(vers, 0);
531 }
532
533 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
534 bundle->getMinSdkVersion());
535 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
536 bundle->getTargetSdkVersion());
537 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
538 bundle->getMaxSdkVersion());
539 }
540
541 return NO_ERROR;
542}
543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544#define ASSIGN_IT(n) \
545 do { \
546 ssize_t index = resources->indexOfKey(String8(#n)); \
547 if (index >= 0) { \
548 n ## s = resources->valueAt(index); \
549 } \
550 } while (0)
551
552status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets)
553{
554 // First, look for a package file to parse. This is required to
555 // be able to generate the resource information.
556 sp<AaptGroup> androidManifestFile =
557 assets->getFiles().valueFor(String8("AndroidManifest.xml"));
558 if (androidManifestFile == NULL) {
559 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
560 return UNKNOWN_ERROR;
561 }
562
563 status_t err = parsePackage(assets, androidManifestFile);
564 if (err != NO_ERROR) {
565 return err;
566 }
567
568 NOISY(printf("Creating resources for package %s\n",
569 assets->getPackage().string()));
570
571 ResourceTable table(bundle, String16(assets->getPackage()));
572 err = table.addIncludedResources(bundle, assets);
573 if (err != NO_ERROR) {
574 return err;
575 }
576
577 NOISY(printf("Found %d included resource packages\n", (int)table.size()));
578
579 // --------------------------------------------------------------
580 // First, gather all resource information.
581 // --------------------------------------------------------------
582
583 // resType -> leafName -> group
584 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
585 new KeyedVector<String8, sp<ResourceTypeSet> >;
586 collect_files(assets, resources);
587
588 sp<ResourceTypeSet> drawables;
589 sp<ResourceTypeSet> layouts;
590 sp<ResourceTypeSet> anims;
591 sp<ResourceTypeSet> xmls;
592 sp<ResourceTypeSet> raws;
593 sp<ResourceTypeSet> colors;
594 sp<ResourceTypeSet> menus;
595
596 ASSIGN_IT(drawable);
597 ASSIGN_IT(layout);
598 ASSIGN_IT(anim);
599 ASSIGN_IT(xml);
600 ASSIGN_IT(raw);
601 ASSIGN_IT(color);
602 ASSIGN_IT(menu);
603
604 assets->setResources(resources);
605 // now go through any resource overlays and collect their files
606 sp<AaptAssets> current = assets->getOverlay();
607 while(current.get()) {
608 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
609 new KeyedVector<String8, sp<ResourceTypeSet> >;
610 current->setResources(resources);
611 collect_files(current, resources);
612 current = current->getOverlay();
613 }
614 // apply the overlay files to the base set
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700615 if (!applyFileOverlay(assets, drawables, "drawable") ||
616 !applyFileOverlay(assets, layouts, "layout") ||
617 !applyFileOverlay(assets, anims, "anim") ||
618 !applyFileOverlay(assets, xmls, "xml") ||
619 !applyFileOverlay(assets, raws, "raw") ||
620 !applyFileOverlay(assets, colors, "color") ||
621 !applyFileOverlay(assets, menus, "menu")) {
622 return UNKNOWN_ERROR;
623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624
625 bool hasErrors = false;
626
627 if (drawables != NULL) {
628 err = preProcessImages(bundle, assets, drawables);
629 if (err == NO_ERROR) {
630 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
631 if (err != NO_ERROR) {
632 hasErrors = true;
633 }
634 } else {
635 hasErrors = true;
636 }
637 }
638
639 if (layouts != NULL) {
640 err = makeFileResources(bundle, assets, &table, layouts, "layout");
641 if (err != NO_ERROR) {
642 hasErrors = true;
643 }
644 }
645
646 if (anims != NULL) {
647 err = makeFileResources(bundle, assets, &table, anims, "anim");
648 if (err != NO_ERROR) {
649 hasErrors = true;
650 }
651 }
652
653 if (xmls != NULL) {
654 err = makeFileResources(bundle, assets, &table, xmls, "xml");
655 if (err != NO_ERROR) {
656 hasErrors = true;
657 }
658 }
659
660 if (raws != NULL) {
661 err = makeFileResources(bundle, assets, &table, raws, "raw");
662 if (err != NO_ERROR) {
663 hasErrors = true;
664 }
665 }
666
667 // compile resources
668 current = assets;
669 while(current.get()) {
670 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
671 current->getResources();
672
673 ssize_t index = resources->indexOfKey(String8("values"));
674 if (index >= 0) {
675 ResourceDirIterator it(resources->valueAt(index), String8("values"));
676 ssize_t res;
677 while ((res=it.next()) == NO_ERROR) {
678 sp<AaptFile> file = it.getFile();
679 res = compileResourceFile(bundle, assets, file, it.getParams(),
680 (current!=assets), &table);
681 if (res != NO_ERROR) {
682 hasErrors = true;
683 }
684 }
685 }
686 current = current->getOverlay();
687 }
688
689 if (colors != NULL) {
690 err = makeFileResources(bundle, assets, &table, colors, "color");
691 if (err != NO_ERROR) {
692 hasErrors = true;
693 }
694 }
695
696 if (menus != NULL) {
697 err = makeFileResources(bundle, assets, &table, menus, "menu");
698 if (err != NO_ERROR) {
699 hasErrors = true;
700 }
701 }
702
703 // --------------------------------------------------------------------
704 // Assignment of resource IDs and initial generation of resource table.
705 // --------------------------------------------------------------------
706
707 if (table.hasResources()) {
708 sp<AaptFile> resFile(getResourceFile(assets));
709 if (resFile == NULL) {
710 fprintf(stderr, "Error: unable to generate entry for resource data\n");
711 return UNKNOWN_ERROR;
712 }
713
714 err = table.assignResourceIds();
715 if (err < NO_ERROR) {
716 return err;
717 }
718 }
719
720 // --------------------------------------------------------------
721 // Finally, we can now we can compile XML files, which may reference
722 // resources.
723 // --------------------------------------------------------------
724
725 if (layouts != NULL) {
726 ResourceDirIterator it(layouts, String8("layout"));
727 while ((err=it.next()) == NO_ERROR) {
728 String8 src = it.getFile()->getPrintableSource();
729 err = compileXmlFile(assets, it.getFile(), &table);
730 if (err == NO_ERROR) {
731 ResXMLTree block;
732 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
733 checkForIds(src, block);
734 } else {
735 hasErrors = true;
736 }
737 }
738
739 if (err < NO_ERROR) {
740 hasErrors = true;
741 }
742 err = NO_ERROR;
743 }
744
745 if (anims != NULL) {
746 ResourceDirIterator it(anims, String8("anim"));
747 while ((err=it.next()) == NO_ERROR) {
748 err = compileXmlFile(assets, it.getFile(), &table);
749 if (err != NO_ERROR) {
750 hasErrors = true;
751 }
752 }
753
754 if (err < NO_ERROR) {
755 hasErrors = true;
756 }
757 err = NO_ERROR;
758 }
759
760 if (xmls != NULL) {
761 ResourceDirIterator it(xmls, String8("xml"));
762 while ((err=it.next()) == NO_ERROR) {
763 err = compileXmlFile(assets, it.getFile(), &table);
764 if (err != NO_ERROR) {
765 hasErrors = true;
766 }
767 }
768
769 if (err < NO_ERROR) {
770 hasErrors = true;
771 }
772 err = NO_ERROR;
773 }
774
775 if (drawables != NULL) {
776 err = postProcessImages(assets, &table, drawables);
777 if (err != NO_ERROR) {
778 hasErrors = true;
779 }
780 }
781
782 if (colors != NULL) {
783 ResourceDirIterator it(colors, String8("color"));
784 while ((err=it.next()) == NO_ERROR) {
785 err = compileXmlFile(assets, it.getFile(), &table);
786 if (err != NO_ERROR) {
787 hasErrors = true;
788 }
789 }
790
791 if (err < NO_ERROR) {
792 hasErrors = true;
793 }
794 err = NO_ERROR;
795 }
796
797 if (menus != NULL) {
798 ResourceDirIterator it(menus, String8("menu"));
799 while ((err=it.next()) == NO_ERROR) {
800 String8 src = it.getFile()->getPrintableSource();
801 err = compileXmlFile(assets, it.getFile(), &table);
802 if (err != NO_ERROR) {
803 hasErrors = true;
804 }
805 ResXMLTree block;
806 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
807 checkForIds(src, block);
808 }
809
810 if (err < NO_ERROR) {
811 hasErrors = true;
812 }
813 err = NO_ERROR;
814 }
815
816 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
817 String8 manifestPath(manifestFile->getPrintableSource());
818
819 // Perform a basic validation of the manifest file. This time we
820 // parse it with the comments intact, so that we can use them to
821 // generate java docs... so we are not going to write this one
822 // back out to the final manifest data.
823 err = compileXmlFile(assets, manifestFile, &table,
824 XML_COMPILE_ASSIGN_ATTRIBUTE_IDS
825 | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES);
826 if (err < NO_ERROR) {
827 return err;
828 }
829 ResXMLTree block;
830 block.setTo(manifestFile->getData(), manifestFile->getSize(), true);
831 String16 manifest16("manifest");
832 String16 permission16("permission");
833 String16 permission_group16("permission-group");
834 String16 uses_permission16("uses-permission");
835 String16 instrumentation16("instrumentation");
836 String16 application16("application");
837 String16 provider16("provider");
838 String16 service16("service");
839 String16 receiver16("receiver");
840 String16 activity16("activity");
841 String16 action16("action");
842 String16 category16("category");
843 String16 data16("scheme");
844 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
845 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
846 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
847 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
848 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
849 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
850 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
851 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
852 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
853 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
854 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
855 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
856 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
857 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
858 ResXMLTree::event_code_t code;
859 sp<AaptSymbols> permissionSymbols;
860 sp<AaptSymbols> permissionGroupSymbols;
861 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
862 && code > ResXMLTree::BAD_DOCUMENT) {
863 if (code == ResXMLTree::START_TAG) {
864 size_t len;
865 if (block.getElementNamespace(&len) != NULL) {
866 continue;
867 }
868 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
869 if (validateAttr(manifestPath, block, NULL, "package",
870 packageIdentChars, true) != ATTR_OKAY) {
871 hasErrors = true;
872 }
873 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
874 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
875 const bool isGroup = strcmp16(block.getElementName(&len),
876 permission_group16.string()) == 0;
877 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
878 isGroup ? packageIdentCharsWithTheStupid
879 : packageIdentChars, true) != ATTR_OKAY) {
880 hasErrors = true;
881 }
882 SourcePos srcPos(manifestPath, block.getLineNumber());
883 sp<AaptSymbols> syms;
884 if (!isGroup) {
885 syms = permissionSymbols;
886 if (syms == NULL) {
887 sp<AaptSymbols> symbols =
888 assets->getSymbolsFor(String8("Manifest"));
889 syms = permissionSymbols = symbols->addNestedSymbol(
890 String8("permission"), srcPos);
891 }
892 } else {
893 syms = permissionGroupSymbols;
894 if (syms == NULL) {
895 sp<AaptSymbols> symbols =
896 assets->getSymbolsFor(String8("Manifest"));
897 syms = permissionGroupSymbols = symbols->addNestedSymbol(
898 String8("permission_group"), srcPos);
899 }
900 }
901 size_t len;
902 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
903 const uint16_t* id = block.getAttributeStringValue(index, &len);
904 if (id == NULL) {
905 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
906 manifestPath.string(), block.getLineNumber(),
907 String8(block.getElementName(&len)).string());
908 hasErrors = true;
909 break;
910 }
911 String8 idStr(id);
912 char* p = idStr.lockBuffer(idStr.size());
913 char* e = p + idStr.size();
914 bool begins_with_digit = true; // init to true so an empty string fails
915 while (e > p) {
916 e--;
917 if (*e >= '0' && *e <= '9') {
918 begins_with_digit = true;
919 continue;
920 }
921 if ((*e >= 'a' && *e <= 'z') ||
922 (*e >= 'A' && *e <= 'Z') ||
923 (*e == '_')) {
924 begins_with_digit = false;
925 continue;
926 }
927 if (isGroup && (*e == '-')) {
928 *e = '_';
929 begins_with_digit = false;
930 continue;
931 }
932 e++;
933 break;
934 }
935 idStr.unlockBuffer();
936 // verify that we stopped because we hit a period or
937 // the beginning of the string, and that the
938 // identifier didn't begin with a digit.
939 if (begins_with_digit || (e != p && *(e-1) != '.')) {
940 fprintf(stderr,
941 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
942 manifestPath.string(), block.getLineNumber(), idStr.string());
943 hasErrors = true;
944 }
945 syms->addStringSymbol(String8(e), idStr, srcPos);
946 const uint16_t* cmt = block.getComment(&len);
947 if (cmt != NULL && *cmt != 0) {
948 //printf("Comment of %s: %s\n", String8(e).string(),
949 // String8(cmt).string());
950 syms->appendComment(String8(e), String16(cmt), srcPos);
951 } else {
952 //printf("No comment for %s\n", String8(e).string());
953 }
954 syms->makeSymbolPublic(String8(e), srcPos);
955 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
956 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
957 packageIdentChars, true) != ATTR_OKAY) {
958 hasErrors = true;
959 }
960 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
961 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
962 classIdentChars, true) != ATTR_OKAY) {
963 hasErrors = true;
964 }
965 if (validateAttr(manifestPath, block,
966 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
967 packageIdentChars, true) != ATTR_OKAY) {
968 hasErrors = true;
969 }
970 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
971 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
972 classIdentChars, false) != ATTR_OKAY) {
973 hasErrors = true;
974 }
975 if (validateAttr(manifestPath, block,
976 RESOURCES_ANDROID_NAMESPACE, "permission",
977 packageIdentChars, false) != ATTR_OKAY) {
978 hasErrors = true;
979 }
980 if (validateAttr(manifestPath, block,
981 RESOURCES_ANDROID_NAMESPACE, "process",
982 processIdentChars, false) != ATTR_OKAY) {
983 hasErrors = true;
984 }
985 if (validateAttr(manifestPath, block,
986 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
987 processIdentChars, false) != ATTR_OKAY) {
988 hasErrors = true;
989 }
990 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
991 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
992 classIdentChars, true) != ATTR_OKAY) {
993 hasErrors = true;
994 }
995 if (validateAttr(manifestPath, block,
996 RESOURCES_ANDROID_NAMESPACE, "authorities",
997 authoritiesIdentChars, true) != ATTR_OKAY) {
998 hasErrors = true;
999 }
1000 if (validateAttr(manifestPath, block,
1001 RESOURCES_ANDROID_NAMESPACE, "permission",
1002 packageIdentChars, false) != ATTR_OKAY) {
1003 hasErrors = true;
1004 }
1005 if (validateAttr(manifestPath, block,
1006 RESOURCES_ANDROID_NAMESPACE, "process",
1007 processIdentChars, false) != ATTR_OKAY) {
1008 hasErrors = true;
1009 }
1010 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1011 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1012 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1013 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
1014 classIdentChars, true) != ATTR_OKAY) {
1015 hasErrors = true;
1016 }
1017 if (validateAttr(manifestPath, block,
1018 RESOURCES_ANDROID_NAMESPACE, "permission",
1019 packageIdentChars, false) != ATTR_OKAY) {
1020 hasErrors = true;
1021 }
1022 if (validateAttr(manifestPath, block,
1023 RESOURCES_ANDROID_NAMESPACE, "process",
1024 processIdentChars, false) != ATTR_OKAY) {
1025 hasErrors = true;
1026 }
1027 if (validateAttr(manifestPath, block,
1028 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1029 processIdentChars, false) != ATTR_OKAY) {
1030 hasErrors = true;
1031 }
1032 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1033 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
1034 if (validateAttr(manifestPath, block,
1035 RESOURCES_ANDROID_NAMESPACE, "name",
1036 packageIdentChars, true) != ATTR_OKAY) {
1037 hasErrors = true;
1038 }
1039 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
1040 if (validateAttr(manifestPath, block,
1041 RESOURCES_ANDROID_NAMESPACE, "mimeType",
1042 typeIdentChars, true) != ATTR_OKAY) {
1043 hasErrors = true;
1044 }
1045 if (validateAttr(manifestPath, block,
1046 RESOURCES_ANDROID_NAMESPACE, "scheme",
1047 schemeIdentChars, true) != ATTR_OKAY) {
1048 hasErrors = true;
1049 }
1050 }
1051 }
1052 }
1053
1054 if (table.validateLocalizations()) {
1055 hasErrors = true;
1056 }
1057
1058 if (hasErrors) {
1059 return UNKNOWN_ERROR;
1060 }
1061
1062 // Generate final compiled manifest file.
1063 manifestFile->clearData();
Dianne Hackborn62da8462009-05-13 15:06:13 -07001064 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1065 if (manifestTree == NULL) {
1066 return UNKNOWN_ERROR;
1067 }
1068 err = massageManifest(bundle, manifestTree);
1069 if (err < NO_ERROR) {
1070 return err;
1071 }
1072 err = compileXmlFile(assets, manifestTree, manifestFile, &table);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 if (err < NO_ERROR) {
1074 return err;
1075 }
1076
1077 //block.restart();
1078 //printXMLBlock(&block);
1079
1080 // --------------------------------------------------------------
1081 // Generate the final resource table.
1082 // Re-flatten because we may have added new resource IDs
1083 // --------------------------------------------------------------
1084
1085 if (table.hasResources()) {
1086 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1087 err = table.addSymbols(symbols);
1088 if (err < NO_ERROR) {
1089 return err;
1090 }
1091
1092 sp<AaptFile> resFile(getResourceFile(assets));
1093 if (resFile == NULL) {
1094 fprintf(stderr, "Error: unable to generate entry for resource data\n");
1095 return UNKNOWN_ERROR;
1096 }
1097
1098 err = table.flatten(bundle, resFile);
1099 if (err < NO_ERROR) {
1100 return err;
1101 }
1102
1103 if (bundle->getPublicOutputFile()) {
1104 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1105 if (fp == NULL) {
1106 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1107 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1108 return UNKNOWN_ERROR;
1109 }
1110 if (bundle->getVerbose()) {
1111 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1112 }
1113 table.writePublicDefinitions(String16(assets->getPackage()), fp);
Marco Nelissen6a1fade2009-04-20 16:16:01 -07001114 fclose(fp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116
1117 NOISY(
1118 ResTable rt;
1119 rt.add(resFile->getData(), resFile->getSize(), NULL);
1120 printf("Generated resources:\n");
1121 rt.print();
1122 )
1123
1124 // These resources are now considered to be a part of the included
1125 // resources, for others to reference.
1126 err = assets->addIncludedResources(resFile);
1127 if (err < NO_ERROR) {
1128 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
1129 return err;
1130 }
1131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 return err;
1133}
1134
1135static const char* getIndentSpace(int indent)
1136{
1137static const char whitespace[] =
1138" ";
1139
1140 return whitespace + sizeof(whitespace) - 1 - indent*4;
1141}
1142
1143static status_t fixupSymbol(String16* inoutSymbol)
1144{
1145 inoutSymbol->replaceAll('.', '_');
1146 inoutSymbol->replaceAll(':', '_');
1147 return NO_ERROR;
1148}
1149
1150static String16 getAttributeComment(const sp<AaptAssets>& assets,
1151 const String8& name,
1152 String16* outTypeComment = NULL)
1153{
1154 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
1155 if (asym != NULL) {
1156 //printf("Got R symbols!\n");
1157 asym = asym->getNestedSymbols().valueFor(String8("attr"));
1158 if (asym != NULL) {
1159 //printf("Got attrs symbols! comment %s=%s\n",
1160 // name.string(), String8(asym->getComment(name)).string());
1161 if (outTypeComment != NULL) {
1162 *outTypeComment = asym->getTypeComment(name);
1163 }
1164 return asym->getComment(name);
1165 }
1166 }
1167 return String16();
1168}
1169
1170static status_t writeLayoutClasses(
1171 FILE* fp, const sp<AaptAssets>& assets,
1172 const sp<AaptSymbols>& symbols, int indent, bool includePrivate)
1173{
1174 const char* indentStr = getIndentSpace(indent);
1175 if (!includePrivate) {
1176 fprintf(fp, "%s/** @doconly */\n", indentStr);
1177 }
1178 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
1179 indent++;
1180
1181 String16 attr16("attr");
1182 String16 package16(assets->getPackage());
1183
1184 indentStr = getIndentSpace(indent);
1185 bool hasErrors = false;
1186
1187 size_t i;
1188 size_t N = symbols->getNestedSymbols().size();
1189 for (i=0; i<N; i++) {
1190 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1191 String16 nclassName16(symbols->getNestedSymbols().keyAt(i));
1192 String8 realClassName(nclassName16);
1193 if (fixupSymbol(&nclassName16) != NO_ERROR) {
1194 hasErrors = true;
1195 }
1196 String8 nclassName(nclassName16);
1197
1198 SortedVector<uint32_t> idents;
1199 Vector<uint32_t> origOrder;
1200 Vector<bool> publicFlags;
1201
1202 size_t a;
1203 size_t NA = nsymbols->getSymbols().size();
1204 for (a=0; a<NA; a++) {
1205 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1206 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1207 ? sym.int32Val : 0;
1208 bool isPublic = true;
1209 if (code == 0) {
1210 String16 name16(sym.name);
1211 uint32_t typeSpecFlags;
1212 code = assets->getIncludedResources().identifierForName(
1213 name16.string(), name16.size(),
1214 attr16.string(), attr16.size(),
1215 package16.string(), package16.size(), &typeSpecFlags);
1216 if (code == 0) {
1217 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1218 nclassName.string(), sym.name.string());
1219 hasErrors = true;
1220 }
1221 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1222 }
1223 idents.add(code);
1224 origOrder.add(code);
1225 publicFlags.add(isPublic);
1226 }
1227
1228 NA = idents.size();
1229
1230 String16 comment = symbols->getComment(realClassName);
1231 fprintf(fp, "%s/** ", indentStr);
1232 if (comment.size() > 0) {
1233 fprintf(fp, "%s\n", String8(comment).string());
1234 } else {
1235 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
1236 }
1237 bool hasTable = false;
1238 for (a=0; a<NA; a++) {
1239 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1240 if (pos >= 0) {
1241 if (!hasTable) {
1242 hasTable = true;
1243 fprintf(fp,
1244 "%s <p>Includes the following attributes:</p>\n"
1245 "%s <table border=\"2\" width=\"85%%\" align=\"center\" frame=\"hsides\" rules=\"all\" cellpadding=\"5\">\n"
1246 "%s <colgroup align=\"left\" />\n"
1247 "%s <colgroup align=\"left\" />\n"
1248 "%s <tr><th>Attribute<th>Summary</tr>\n",
1249 indentStr,
1250 indentStr,
1251 indentStr,
1252 indentStr,
1253 indentStr);
1254 }
1255 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1256 if (!publicFlags.itemAt(a) && !includePrivate) {
1257 continue;
1258 }
1259 String8 name8(sym.name);
1260 String16 comment(sym.comment);
1261 if (comment.size() <= 0) {
1262 comment = getAttributeComment(assets, name8);
1263 }
1264 if (comment.size() > 0) {
1265 const char16_t* p = comment.string();
1266 while (*p != 0 && *p != '.') {
1267 if (*p == '{') {
1268 while (*p != 0 && *p != '}') {
1269 p++;
1270 }
1271 } else {
1272 p++;
1273 }
1274 }
1275 if (*p == '.') {
1276 p++;
1277 }
1278 comment = String16(comment.string(), p-comment.string());
1279 }
1280 String16 name(name8);
1281 fixupSymbol(&name);
1282 fprintf(fp, "%s <tr><th><code>{@link #%s_%s %s:%s}</code><td>%s</tr>\n",
1283 indentStr, nclassName.string(),
1284 String8(name).string(),
1285 assets->getPackage().string(),
1286 String8(name).string(),
1287 String8(comment).string());
1288 }
1289 }
1290 if (hasTable) {
1291 fprintf(fp, "%s </table>\n", indentStr);
1292 }
1293 for (a=0; a<NA; a++) {
1294 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1295 if (pos >= 0) {
1296 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1297 if (!publicFlags.itemAt(a) && !includePrivate) {
1298 continue;
1299 }
1300 String16 name(sym.name);
1301 fixupSymbol(&name);
1302 fprintf(fp, "%s @see #%s_%s\n",
1303 indentStr, nclassName.string(),
1304 String8(name).string());
1305 }
1306 }
1307 fprintf(fp, "%s */\n", getIndentSpace(indent));
1308
1309 fprintf(fp,
1310 "%spublic static final int[] %s = {\n"
1311 "%s",
1312 indentStr, nclassName.string(),
1313 getIndentSpace(indent+1));
1314
1315 for (a=0; a<NA; a++) {
1316 if (a != 0) {
1317 if ((a&3) == 0) {
1318 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
1319 } else {
1320 fprintf(fp, ", ");
1321 }
1322 }
1323 fprintf(fp, "0x%08x", idents[a]);
1324 }
1325
1326 fprintf(fp, "\n%s};\n", indentStr);
1327
1328 for (a=0; a<NA; a++) {
1329 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1330 if (pos >= 0) {
1331 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1332 if (!publicFlags.itemAt(a) && !includePrivate) {
1333 continue;
1334 }
1335 String8 name8(sym.name);
1336 String16 comment(sym.comment);
1337 String16 typeComment;
1338 if (comment.size() <= 0) {
1339 comment = getAttributeComment(assets, name8, &typeComment);
1340 } else {
1341 getAttributeComment(assets, name8, &typeComment);
1342 }
1343 String16 name(name8);
1344 if (fixupSymbol(&name) != NO_ERROR) {
1345 hasErrors = true;
1346 }
1347
1348 uint32_t typeSpecFlags = 0;
1349 String16 name16(sym.name);
1350 assets->getIncludedResources().identifierForName(
1351 name16.string(), name16.size(),
1352 attr16.string(), attr16.size(),
1353 package16.string(), package16.size(), &typeSpecFlags);
1354 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1355 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1356 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1357
1358 fprintf(fp, "%s/**\n", indentStr);
1359 if (comment.size() > 0) {
1360 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
1361 fprintf(fp, "%s %s\n", indentStr, String8(comment).string());
1362 } else {
1363 fprintf(fp,
1364 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
1365 "%s attribute's value can be found in the {@link #%s} array.\n",
1366 indentStr,
1367 pub ? assets->getPackage().string()
1368 : assets->getSymbolsPrivatePackage().string(),
1369 String8(name).string(),
1370 indentStr, nclassName.string());
1371 }
1372 if (typeComment.size() > 0) {
1373 fprintf(fp, "\n\n%s %s\n", indentStr, String8(typeComment).string());
1374 }
1375 if (comment.size() > 0) {
1376 if (pub) {
1377 fprintf(fp,
1378 "%s <p>This corresponds to the global attribute"
1379 "%s resource symbol {@link %s.R.attr#%s}.\n",
1380 indentStr, indentStr,
1381 assets->getPackage().string(),
1382 String8(name).string());
1383 } else {
1384 fprintf(fp,
1385 "%s <p>This is a private symbol.\n", indentStr);
1386 }
1387 }
1388 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
1389 "android", String8(name).string());
1390 fprintf(fp, "%s*/\n", indentStr);
1391 fprintf(fp,
1392 "%spublic static final int %s_%s = %d;\n",
1393 indentStr, nclassName.string(),
1394 String8(name).string(), (int)pos);
1395 }
1396 }
1397 }
1398
1399 indent--;
1400 fprintf(fp, "%s};\n", getIndentSpace(indent));
1401 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1402}
1403
1404static status_t writeSymbolClass(
1405 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
1406 const sp<AaptSymbols>& symbols, const String8& className, int indent)
1407{
1408 fprintf(fp, "%spublic %sfinal class %s {\n",
1409 getIndentSpace(indent),
1410 indent != 0 ? "static " : "", className.string());
1411 indent++;
1412
1413 size_t i;
1414 status_t err = NO_ERROR;
1415
1416 size_t N = symbols->getSymbols().size();
1417 for (i=0; i<N; i++) {
1418 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
1419 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
1420 continue;
1421 }
1422 if (!includePrivate && !sym.isPublic) {
1423 continue;
1424 }
1425 String16 name(sym.name);
1426 String8 realName(name);
1427 if (fixupSymbol(&name) != NO_ERROR) {
1428 return UNKNOWN_ERROR;
1429 }
1430 String16 comment(sym.comment);
1431 bool haveComment = false;
1432 if (comment.size() > 0) {
1433 haveComment = true;
1434 fprintf(fp,
1435 "%s/** %s\n",
1436 getIndentSpace(indent), String8(comment).string());
1437 } else if (sym.isPublic && !includePrivate) {
1438 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
1439 assets->getPackage().string(), className.string(),
1440 String8(sym.name).string());
1441 }
1442 String16 typeComment(sym.typeComment);
1443 if (typeComment.size() > 0) {
1444 if (!haveComment) {
1445 haveComment = true;
1446 fprintf(fp,
1447 "%s/** %s\n",
1448 getIndentSpace(indent), String8(typeComment).string());
1449 } else {
1450 fprintf(fp,
1451 "%s %s\n",
1452 getIndentSpace(indent), String8(typeComment).string());
1453 }
1454 }
1455 if (haveComment) {
1456 fprintf(fp,"%s */\n", getIndentSpace(indent));
1457 }
1458 fprintf(fp, "%spublic static final int %s=0x%08x;\n",
1459 getIndentSpace(indent),
1460 String8(name).string(), (int)sym.int32Val);
1461 }
1462
1463 for (i=0; i<N; i++) {
1464 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
1465 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
1466 continue;
1467 }
1468 if (!includePrivate && !sym.isPublic) {
1469 continue;
1470 }
1471 String16 name(sym.name);
1472 if (fixupSymbol(&name) != NO_ERROR) {
1473 return UNKNOWN_ERROR;
1474 }
1475 String16 comment(sym.comment);
1476 if (comment.size() > 0) {
1477 fprintf(fp,
1478 "%s/** %s\n"
1479 "%s */\n",
1480 getIndentSpace(indent), String8(comment).string(),
1481 getIndentSpace(indent));
1482 } else if (sym.isPublic && !includePrivate) {
1483 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
1484 assets->getPackage().string(), className.string(),
1485 String8(sym.name).string());
1486 }
1487 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
1488 getIndentSpace(indent),
1489 String8(name).string(), sym.stringVal.string());
1490 }
1491
1492 sp<AaptSymbols> styleableSymbols;
1493
1494 N = symbols->getNestedSymbols().size();
1495 for (i=0; i<N; i++) {
1496 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1497 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
1498 if (nclassName == "styleable") {
1499 styleableSymbols = nsymbols;
1500 } else {
1501 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName, indent);
1502 }
1503 if (err != NO_ERROR) {
1504 return err;
1505 }
1506 }
1507
1508 if (styleableSymbols != NULL) {
1509 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate);
1510 if (err != NO_ERROR) {
1511 return err;
1512 }
1513 }
1514
1515 indent--;
1516 fprintf(fp, "%s}\n", getIndentSpace(indent));
1517 return NO_ERROR;
1518}
1519
1520status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
1521 const String8& package, bool includePrivate)
1522{
1523 if (!bundle->getRClassDir()) {
1524 return NO_ERROR;
1525 }
1526
1527 const size_t N = assets->getSymbols().size();
1528 for (size_t i=0; i<N; i++) {
1529 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
1530 String8 className(assets->getSymbols().keyAt(i));
1531 String8 dest(bundle->getRClassDir());
1532 if (bundle->getMakePackageDirs()) {
1533 String8 pkg(package);
1534 const char* last = pkg.string();
1535 const char* s = last-1;
1536 do {
1537 s++;
1538 if (s > last && (*s == '.' || *s == 0)) {
1539 String8 part(last, s-last);
1540 dest.appendPath(part);
1541#ifdef HAVE_MS_C_RUNTIME
1542 _mkdir(dest.string());
1543#else
1544 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
1545#endif
1546 last = s+1;
1547 }
1548 } while (*s);
1549 }
1550 dest.appendPath(className);
1551 dest.append(".java");
1552 FILE* fp = fopen(dest.string(), "w+");
1553 if (fp == NULL) {
1554 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
1555 dest.string(), strerror(errno));
1556 return UNKNOWN_ERROR;
1557 }
1558 if (bundle->getVerbose()) {
1559 printf(" Writing symbols for class %s.\n", className.string());
1560 }
1561
1562 fprintf(fp,
1563 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
1564 " *\n"
1565 " * This class was automatically generated by the\n"
1566 " * aapt tool from the resource data it found. It\n"
1567 " * should not be modified by hand.\n"
1568 " */\n"
1569 "\n"
1570 "package %s;\n\n", package.string());
1571
1572 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols, className, 0);
1573 if (err != NO_ERROR) {
1574 return err;
1575 }
1576 fclose(fp);
1577 }
1578
1579 return NO_ERROR;
1580}