blob: 9d2ed1044b3eb30e4d57104dc165ee8aa9be342a [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)
Dianne Hackborn58c27a02009-08-13 13:36:00 -0700478 baseSet->add(overlaySet->keyAt(overlayIndex),
479 overlaySet->valueAt(overlayIndex));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 }
481 }
482 // this overlay didn't have resources for this type
483 }
484 // try next overlay
485 overlay = overlay->getOverlay();
486 }
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700487 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488}
489
Dianne Hackborn62da8462009-05-13 15:06:13 -0700490void addTagAttribute(const sp<XMLNode>& node, const char* ns8,
491 const char* attr8, const char* value)
492{
493 if (value == NULL) {
494 return;
495 }
496
497 const String16 ns(ns8);
498 const String16 attr(attr8);
499
500 if (node->getAttribute(ns, attr) != NULL) {
501 fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s)\n",
502 String8(attr).string(), String8(ns).string());
503 return;
504 }
505
506 node->addAttribute(ns, attr, String16(value));
507}
508
509status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
510{
511 root = root->searchElement(String16(), String16("manifest"));
512 if (root == NULL) {
513 fprintf(stderr, "No <manifest> tag.\n");
514 return UNKNOWN_ERROR;
515 }
516
517 addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
518 bundle->getVersionCode());
519 addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
520 bundle->getVersionName());
521
522 if (bundle->getMinSdkVersion() != NULL
523 || bundle->getTargetSdkVersion() != NULL
524 || bundle->getMaxSdkVersion() != NULL) {
525 sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
526 if (vers == NULL) {
527 vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
528 root->insertChildAt(vers, 0);
529 }
530
531 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
532 bundle->getMinSdkVersion());
533 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
534 bundle->getTargetSdkVersion());
535 addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
536 bundle->getMaxSdkVersion());
537 }
538
539 return NO_ERROR;
540}
541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542#define ASSIGN_IT(n) \
543 do { \
544 ssize_t index = resources->indexOfKey(String8(#n)); \
545 if (index >= 0) { \
546 n ## s = resources->valueAt(index); \
547 } \
548 } while (0)
549
550status_t buildResources(Bundle* bundle, const sp<AaptAssets>& assets)
551{
552 // First, look for a package file to parse. This is required to
553 // be able to generate the resource information.
554 sp<AaptGroup> androidManifestFile =
555 assets->getFiles().valueFor(String8("AndroidManifest.xml"));
556 if (androidManifestFile == NULL) {
557 fprintf(stderr, "ERROR: No AndroidManifest.xml file found.\n");
558 return UNKNOWN_ERROR;
559 }
560
561 status_t err = parsePackage(assets, androidManifestFile);
562 if (err != NO_ERROR) {
563 return err;
564 }
565
566 NOISY(printf("Creating resources for package %s\n",
567 assets->getPackage().string()));
568
569 ResourceTable table(bundle, String16(assets->getPackage()));
570 err = table.addIncludedResources(bundle, assets);
571 if (err != NO_ERROR) {
572 return err;
573 }
574
575 NOISY(printf("Found %d included resource packages\n", (int)table.size()));
576
577 // --------------------------------------------------------------
578 // First, gather all resource information.
579 // --------------------------------------------------------------
580
581 // resType -> leafName -> group
582 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
583 new KeyedVector<String8, sp<ResourceTypeSet> >;
584 collect_files(assets, resources);
585
586 sp<ResourceTypeSet> drawables;
587 sp<ResourceTypeSet> layouts;
588 sp<ResourceTypeSet> anims;
589 sp<ResourceTypeSet> xmls;
590 sp<ResourceTypeSet> raws;
591 sp<ResourceTypeSet> colors;
592 sp<ResourceTypeSet> menus;
593
594 ASSIGN_IT(drawable);
595 ASSIGN_IT(layout);
596 ASSIGN_IT(anim);
597 ASSIGN_IT(xml);
598 ASSIGN_IT(raw);
599 ASSIGN_IT(color);
600 ASSIGN_IT(menu);
601
602 assets->setResources(resources);
603 // now go through any resource overlays and collect their files
604 sp<AaptAssets> current = assets->getOverlay();
605 while(current.get()) {
606 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
607 new KeyedVector<String8, sp<ResourceTypeSet> >;
608 current->setResources(resources);
609 collect_files(current, resources);
610 current = current->getOverlay();
611 }
612 // apply the overlay files to the base set
Robert Greenwaltfa5c7e12009-06-05 18:53:26 -0700613 if (!applyFileOverlay(assets, drawables, "drawable") ||
614 !applyFileOverlay(assets, layouts, "layout") ||
615 !applyFileOverlay(assets, anims, "anim") ||
616 !applyFileOverlay(assets, xmls, "xml") ||
617 !applyFileOverlay(assets, raws, "raw") ||
618 !applyFileOverlay(assets, colors, "color") ||
619 !applyFileOverlay(assets, menus, "menu")) {
620 return UNKNOWN_ERROR;
621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622
623 bool hasErrors = false;
624
625 if (drawables != NULL) {
626 err = preProcessImages(bundle, assets, drawables);
627 if (err == NO_ERROR) {
628 err = makeFileResources(bundle, assets, &table, drawables, "drawable");
629 if (err != NO_ERROR) {
630 hasErrors = true;
631 }
632 } else {
633 hasErrors = true;
634 }
635 }
636
637 if (layouts != NULL) {
638 err = makeFileResources(bundle, assets, &table, layouts, "layout");
639 if (err != NO_ERROR) {
640 hasErrors = true;
641 }
642 }
643
644 if (anims != NULL) {
645 err = makeFileResources(bundle, assets, &table, anims, "anim");
646 if (err != NO_ERROR) {
647 hasErrors = true;
648 }
649 }
650
651 if (xmls != NULL) {
652 err = makeFileResources(bundle, assets, &table, xmls, "xml");
653 if (err != NO_ERROR) {
654 hasErrors = true;
655 }
656 }
657
658 if (raws != NULL) {
659 err = makeFileResources(bundle, assets, &table, raws, "raw");
660 if (err != NO_ERROR) {
661 hasErrors = true;
662 }
663 }
664
665 // compile resources
666 current = assets;
667 while(current.get()) {
668 KeyedVector<String8, sp<ResourceTypeSet> > *resources =
669 current->getResources();
670
671 ssize_t index = resources->indexOfKey(String8("values"));
672 if (index >= 0) {
673 ResourceDirIterator it(resources->valueAt(index), String8("values"));
674 ssize_t res;
675 while ((res=it.next()) == NO_ERROR) {
676 sp<AaptFile> file = it.getFile();
677 res = compileResourceFile(bundle, assets, file, it.getParams(),
678 (current!=assets), &table);
679 if (res != NO_ERROR) {
680 hasErrors = true;
681 }
682 }
683 }
684 current = current->getOverlay();
685 }
686
687 if (colors != NULL) {
688 err = makeFileResources(bundle, assets, &table, colors, "color");
689 if (err != NO_ERROR) {
690 hasErrors = true;
691 }
692 }
693
694 if (menus != NULL) {
695 err = makeFileResources(bundle, assets, &table, menus, "menu");
696 if (err != NO_ERROR) {
697 hasErrors = true;
698 }
699 }
700
701 // --------------------------------------------------------------------
702 // Assignment of resource IDs and initial generation of resource table.
703 // --------------------------------------------------------------------
704
705 if (table.hasResources()) {
706 sp<AaptFile> resFile(getResourceFile(assets));
707 if (resFile == NULL) {
708 fprintf(stderr, "Error: unable to generate entry for resource data\n");
709 return UNKNOWN_ERROR;
710 }
711
712 err = table.assignResourceIds();
713 if (err < NO_ERROR) {
714 return err;
715 }
716 }
717
718 // --------------------------------------------------------------
719 // Finally, we can now we can compile XML files, which may reference
720 // resources.
721 // --------------------------------------------------------------
722
723 if (layouts != NULL) {
724 ResourceDirIterator it(layouts, String8("layout"));
725 while ((err=it.next()) == NO_ERROR) {
726 String8 src = it.getFile()->getPrintableSource();
727 err = compileXmlFile(assets, it.getFile(), &table);
728 if (err == NO_ERROR) {
729 ResXMLTree block;
730 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
731 checkForIds(src, block);
732 } else {
733 hasErrors = true;
734 }
735 }
736
737 if (err < NO_ERROR) {
738 hasErrors = true;
739 }
740 err = NO_ERROR;
741 }
742
743 if (anims != NULL) {
744 ResourceDirIterator it(anims, String8("anim"));
745 while ((err=it.next()) == NO_ERROR) {
746 err = compileXmlFile(assets, it.getFile(), &table);
747 if (err != NO_ERROR) {
748 hasErrors = true;
749 }
750 }
751
752 if (err < NO_ERROR) {
753 hasErrors = true;
754 }
755 err = NO_ERROR;
756 }
757
758 if (xmls != NULL) {
759 ResourceDirIterator it(xmls, String8("xml"));
760 while ((err=it.next()) == NO_ERROR) {
761 err = compileXmlFile(assets, it.getFile(), &table);
762 if (err != NO_ERROR) {
763 hasErrors = true;
764 }
765 }
766
767 if (err < NO_ERROR) {
768 hasErrors = true;
769 }
770 err = NO_ERROR;
771 }
772
773 if (drawables != NULL) {
774 err = postProcessImages(assets, &table, drawables);
775 if (err != NO_ERROR) {
776 hasErrors = true;
777 }
778 }
779
780 if (colors != NULL) {
781 ResourceDirIterator it(colors, String8("color"));
782 while ((err=it.next()) == NO_ERROR) {
783 err = compileXmlFile(assets, it.getFile(), &table);
784 if (err != NO_ERROR) {
785 hasErrors = true;
786 }
787 }
788
789 if (err < NO_ERROR) {
790 hasErrors = true;
791 }
792 err = NO_ERROR;
793 }
794
795 if (menus != NULL) {
796 ResourceDirIterator it(menus, String8("menu"));
797 while ((err=it.next()) == NO_ERROR) {
798 String8 src = it.getFile()->getPrintableSource();
799 err = compileXmlFile(assets, it.getFile(), &table);
800 if (err != NO_ERROR) {
801 hasErrors = true;
802 }
803 ResXMLTree block;
804 block.setTo(it.getFile()->getData(), it.getFile()->getSize(), true);
805 checkForIds(src, block);
806 }
807
808 if (err < NO_ERROR) {
809 hasErrors = true;
810 }
811 err = NO_ERROR;
812 }
813
814 const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
815 String8 manifestPath(manifestFile->getPrintableSource());
816
817 // Perform a basic validation of the manifest file. This time we
818 // parse it with the comments intact, so that we can use them to
819 // generate java docs... so we are not going to write this one
820 // back out to the final manifest data.
821 err = compileXmlFile(assets, manifestFile, &table,
822 XML_COMPILE_ASSIGN_ATTRIBUTE_IDS
823 | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES);
824 if (err < NO_ERROR) {
825 return err;
826 }
827 ResXMLTree block;
828 block.setTo(manifestFile->getData(), manifestFile->getSize(), true);
829 String16 manifest16("manifest");
830 String16 permission16("permission");
831 String16 permission_group16("permission-group");
832 String16 uses_permission16("uses-permission");
833 String16 instrumentation16("instrumentation");
834 String16 application16("application");
835 String16 provider16("provider");
836 String16 service16("service");
837 String16 receiver16("receiver");
838 String16 activity16("activity");
839 String16 action16("action");
840 String16 category16("category");
841 String16 data16("scheme");
842 const char* packageIdentChars = "abcdefghijklmnopqrstuvwxyz"
843 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
844 const char* packageIdentCharsWithTheStupid = "abcdefghijklmnopqrstuvwxyz"
845 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
846 const char* classIdentChars = "abcdefghijklmnopqrstuvwxyz"
847 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
848 const char* processIdentChars = "abcdefghijklmnopqrstuvwxyz"
849 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
850 const char* authoritiesIdentChars = "abcdefghijklmnopqrstuvwxyz"
851 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
852 const char* typeIdentChars = "abcdefghijklmnopqrstuvwxyz"
853 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
854 const char* schemeIdentChars = "abcdefghijklmnopqrstuvwxyz"
855 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
856 ResXMLTree::event_code_t code;
857 sp<AaptSymbols> permissionSymbols;
858 sp<AaptSymbols> permissionGroupSymbols;
859 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
860 && code > ResXMLTree::BAD_DOCUMENT) {
861 if (code == ResXMLTree::START_TAG) {
862 size_t len;
863 if (block.getElementNamespace(&len) != NULL) {
864 continue;
865 }
866 if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
867 if (validateAttr(manifestPath, block, NULL, "package",
868 packageIdentChars, true) != ATTR_OKAY) {
869 hasErrors = true;
870 }
871 } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
872 || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
873 const bool isGroup = strcmp16(block.getElementName(&len),
874 permission_group16.string()) == 0;
875 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
876 isGroup ? packageIdentCharsWithTheStupid
877 : packageIdentChars, true) != ATTR_OKAY) {
878 hasErrors = true;
879 }
880 SourcePos srcPos(manifestPath, block.getLineNumber());
881 sp<AaptSymbols> syms;
882 if (!isGroup) {
883 syms = permissionSymbols;
884 if (syms == NULL) {
885 sp<AaptSymbols> symbols =
886 assets->getSymbolsFor(String8("Manifest"));
887 syms = permissionSymbols = symbols->addNestedSymbol(
888 String8("permission"), srcPos);
889 }
890 } else {
891 syms = permissionGroupSymbols;
892 if (syms == NULL) {
893 sp<AaptSymbols> symbols =
894 assets->getSymbolsFor(String8("Manifest"));
895 syms = permissionGroupSymbols = symbols->addNestedSymbol(
896 String8("permission_group"), srcPos);
897 }
898 }
899 size_t len;
900 ssize_t index = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "name");
901 const uint16_t* id = block.getAttributeStringValue(index, &len);
902 if (id == NULL) {
903 fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n",
904 manifestPath.string(), block.getLineNumber(),
905 String8(block.getElementName(&len)).string());
906 hasErrors = true;
907 break;
908 }
909 String8 idStr(id);
910 char* p = idStr.lockBuffer(idStr.size());
911 char* e = p + idStr.size();
912 bool begins_with_digit = true; // init to true so an empty string fails
913 while (e > p) {
914 e--;
915 if (*e >= '0' && *e <= '9') {
916 begins_with_digit = true;
917 continue;
918 }
919 if ((*e >= 'a' && *e <= 'z') ||
920 (*e >= 'A' && *e <= 'Z') ||
921 (*e == '_')) {
922 begins_with_digit = false;
923 continue;
924 }
925 if (isGroup && (*e == '-')) {
926 *e = '_';
927 begins_with_digit = false;
928 continue;
929 }
930 e++;
931 break;
932 }
933 idStr.unlockBuffer();
934 // verify that we stopped because we hit a period or
935 // the beginning of the string, and that the
936 // identifier didn't begin with a digit.
937 if (begins_with_digit || (e != p && *(e-1) != '.')) {
938 fprintf(stderr,
939 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
940 manifestPath.string(), block.getLineNumber(), idStr.string());
941 hasErrors = true;
942 }
943 syms->addStringSymbol(String8(e), idStr, srcPos);
944 const uint16_t* cmt = block.getComment(&len);
945 if (cmt != NULL && *cmt != 0) {
946 //printf("Comment of %s: %s\n", String8(e).string(),
947 // String8(cmt).string());
948 syms->appendComment(String8(e), String16(cmt), srcPos);
949 } else {
950 //printf("No comment for %s\n", String8(e).string());
951 }
952 syms->makeSymbolPublic(String8(e), srcPos);
953 } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
954 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
955 packageIdentChars, true) != ATTR_OKAY) {
956 hasErrors = true;
957 }
958 } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
959 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
960 classIdentChars, true) != ATTR_OKAY) {
961 hasErrors = true;
962 }
963 if (validateAttr(manifestPath, block,
964 RESOURCES_ANDROID_NAMESPACE, "targetPackage",
965 packageIdentChars, true) != ATTR_OKAY) {
966 hasErrors = true;
967 }
968 } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
969 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
970 classIdentChars, false) != ATTR_OKAY) {
971 hasErrors = true;
972 }
973 if (validateAttr(manifestPath, block,
974 RESOURCES_ANDROID_NAMESPACE, "permission",
975 packageIdentChars, false) != ATTR_OKAY) {
976 hasErrors = true;
977 }
978 if (validateAttr(manifestPath, block,
979 RESOURCES_ANDROID_NAMESPACE, "process",
980 processIdentChars, false) != ATTR_OKAY) {
981 hasErrors = true;
982 }
983 if (validateAttr(manifestPath, block,
984 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
985 processIdentChars, false) != ATTR_OKAY) {
986 hasErrors = true;
987 }
988 } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
989 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
990 classIdentChars, true) != ATTR_OKAY) {
991 hasErrors = true;
992 }
993 if (validateAttr(manifestPath, block,
994 RESOURCES_ANDROID_NAMESPACE, "authorities",
995 authoritiesIdentChars, true) != ATTR_OKAY) {
996 hasErrors = true;
997 }
998 if (validateAttr(manifestPath, block,
999 RESOURCES_ANDROID_NAMESPACE, "permission",
1000 packageIdentChars, false) != ATTR_OKAY) {
1001 hasErrors = true;
1002 }
1003 if (validateAttr(manifestPath, block,
1004 RESOURCES_ANDROID_NAMESPACE, "process",
1005 processIdentChars, false) != ATTR_OKAY) {
1006 hasErrors = true;
1007 }
1008 } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
1009 || strcmp16(block.getElementName(&len), receiver16.string()) == 0
1010 || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
1011 if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
1012 classIdentChars, true) != ATTR_OKAY) {
1013 hasErrors = true;
1014 }
1015 if (validateAttr(manifestPath, block,
1016 RESOURCES_ANDROID_NAMESPACE, "permission",
1017 packageIdentChars, false) != ATTR_OKAY) {
1018 hasErrors = true;
1019 }
1020 if (validateAttr(manifestPath, block,
1021 RESOURCES_ANDROID_NAMESPACE, "process",
1022 processIdentChars, false) != ATTR_OKAY) {
1023 hasErrors = true;
1024 }
1025 if (validateAttr(manifestPath, block,
1026 RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
1027 processIdentChars, false) != ATTR_OKAY) {
1028 hasErrors = true;
1029 }
1030 } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
1031 || strcmp16(block.getElementName(&len), category16.string()) == 0) {
1032 if (validateAttr(manifestPath, block,
1033 RESOURCES_ANDROID_NAMESPACE, "name",
1034 packageIdentChars, true) != ATTR_OKAY) {
1035 hasErrors = true;
1036 }
1037 } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
1038 if (validateAttr(manifestPath, block,
1039 RESOURCES_ANDROID_NAMESPACE, "mimeType",
1040 typeIdentChars, true) != ATTR_OKAY) {
1041 hasErrors = true;
1042 }
1043 if (validateAttr(manifestPath, block,
1044 RESOURCES_ANDROID_NAMESPACE, "scheme",
1045 schemeIdentChars, true) != ATTR_OKAY) {
1046 hasErrors = true;
1047 }
1048 }
1049 }
1050 }
1051
1052 if (table.validateLocalizations()) {
1053 hasErrors = true;
1054 }
1055
1056 if (hasErrors) {
1057 return UNKNOWN_ERROR;
1058 }
1059
1060 // Generate final compiled manifest file.
1061 manifestFile->clearData();
Dianne Hackborn62da8462009-05-13 15:06:13 -07001062 sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
1063 if (manifestTree == NULL) {
1064 return UNKNOWN_ERROR;
1065 }
1066 err = massageManifest(bundle, manifestTree);
1067 if (err < NO_ERROR) {
1068 return err;
1069 }
1070 err = compileXmlFile(assets, manifestTree, manifestFile, &table);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 if (err < NO_ERROR) {
1072 return err;
1073 }
1074
1075 //block.restart();
1076 //printXMLBlock(&block);
1077
1078 // --------------------------------------------------------------
1079 // Generate the final resource table.
1080 // Re-flatten because we may have added new resource IDs
1081 // --------------------------------------------------------------
1082
1083 if (table.hasResources()) {
1084 sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
1085 err = table.addSymbols(symbols);
1086 if (err < NO_ERROR) {
1087 return err;
1088 }
1089
1090 sp<AaptFile> resFile(getResourceFile(assets));
1091 if (resFile == NULL) {
1092 fprintf(stderr, "Error: unable to generate entry for resource data\n");
1093 return UNKNOWN_ERROR;
1094 }
1095
1096 err = table.flatten(bundle, resFile);
1097 if (err < NO_ERROR) {
1098 return err;
1099 }
1100
1101 if (bundle->getPublicOutputFile()) {
1102 FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
1103 if (fp == NULL) {
1104 fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
1105 (const char*)bundle->getPublicOutputFile(), strerror(errno));
1106 return UNKNOWN_ERROR;
1107 }
1108 if (bundle->getVerbose()) {
1109 printf(" Writing public definitions to %s.\n", bundle->getPublicOutputFile());
1110 }
1111 table.writePublicDefinitions(String16(assets->getPackage()), fp);
Marco Nelissen6a1fade2009-04-20 16:16:01 -07001112 fclose(fp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 }
1114
1115 NOISY(
1116 ResTable rt;
1117 rt.add(resFile->getData(), resFile->getSize(), NULL);
1118 printf("Generated resources:\n");
1119 rt.print();
1120 )
1121
1122 // These resources are now considered to be a part of the included
1123 // resources, for others to reference.
1124 err = assets->addIncludedResources(resFile);
1125 if (err < NO_ERROR) {
1126 fprintf(stderr, "ERROR: Unable to parse generated resources, aborting.\n");
1127 return err;
1128 }
1129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 return err;
1131}
1132
1133static const char* getIndentSpace(int indent)
1134{
1135static const char whitespace[] =
1136" ";
1137
1138 return whitespace + sizeof(whitespace) - 1 - indent*4;
1139}
1140
1141static status_t fixupSymbol(String16* inoutSymbol)
1142{
1143 inoutSymbol->replaceAll('.', '_');
1144 inoutSymbol->replaceAll(':', '_');
1145 return NO_ERROR;
1146}
1147
1148static String16 getAttributeComment(const sp<AaptAssets>& assets,
1149 const String8& name,
1150 String16* outTypeComment = NULL)
1151{
1152 sp<AaptSymbols> asym = assets->getSymbolsFor(String8("R"));
1153 if (asym != NULL) {
1154 //printf("Got R symbols!\n");
1155 asym = asym->getNestedSymbols().valueFor(String8("attr"));
1156 if (asym != NULL) {
1157 //printf("Got attrs symbols! comment %s=%s\n",
1158 // name.string(), String8(asym->getComment(name)).string());
1159 if (outTypeComment != NULL) {
1160 *outTypeComment = asym->getTypeComment(name);
1161 }
1162 return asym->getComment(name);
1163 }
1164 }
1165 return String16();
1166}
1167
1168static status_t writeLayoutClasses(
1169 FILE* fp, const sp<AaptAssets>& assets,
1170 const sp<AaptSymbols>& symbols, int indent, bool includePrivate)
1171{
1172 const char* indentStr = getIndentSpace(indent);
1173 if (!includePrivate) {
1174 fprintf(fp, "%s/** @doconly */\n", indentStr);
1175 }
1176 fprintf(fp, "%spublic static final class styleable {\n", indentStr);
1177 indent++;
1178
1179 String16 attr16("attr");
1180 String16 package16(assets->getPackage());
1181
1182 indentStr = getIndentSpace(indent);
1183 bool hasErrors = false;
1184
1185 size_t i;
1186 size_t N = symbols->getNestedSymbols().size();
1187 for (i=0; i<N; i++) {
1188 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1189 String16 nclassName16(symbols->getNestedSymbols().keyAt(i));
1190 String8 realClassName(nclassName16);
1191 if (fixupSymbol(&nclassName16) != NO_ERROR) {
1192 hasErrors = true;
1193 }
1194 String8 nclassName(nclassName16);
1195
1196 SortedVector<uint32_t> idents;
1197 Vector<uint32_t> origOrder;
1198 Vector<bool> publicFlags;
1199
1200 size_t a;
1201 size_t NA = nsymbols->getSymbols().size();
1202 for (a=0; a<NA; a++) {
1203 const AaptSymbolEntry& sym(nsymbols->getSymbols().valueAt(a));
1204 int32_t code = sym.typeCode == AaptSymbolEntry::TYPE_INT32
1205 ? sym.int32Val : 0;
1206 bool isPublic = true;
1207 if (code == 0) {
1208 String16 name16(sym.name);
1209 uint32_t typeSpecFlags;
1210 code = assets->getIncludedResources().identifierForName(
1211 name16.string(), name16.size(),
1212 attr16.string(), attr16.size(),
1213 package16.string(), package16.size(), &typeSpecFlags);
1214 if (code == 0) {
1215 fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1216 nclassName.string(), sym.name.string());
1217 hasErrors = true;
1218 }
1219 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1220 }
1221 idents.add(code);
1222 origOrder.add(code);
1223 publicFlags.add(isPublic);
1224 }
1225
1226 NA = idents.size();
1227
1228 String16 comment = symbols->getComment(realClassName);
1229 fprintf(fp, "%s/** ", indentStr);
1230 if (comment.size() > 0) {
1231 fprintf(fp, "%s\n", String8(comment).string());
1232 } else {
1233 fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
1234 }
1235 bool hasTable = false;
1236 for (a=0; a<NA; a++) {
1237 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1238 if (pos >= 0) {
1239 if (!hasTable) {
1240 hasTable = true;
1241 fprintf(fp,
1242 "%s <p>Includes the following attributes:</p>\n"
1243 "%s <table border=\"2\" width=\"85%%\" align=\"center\" frame=\"hsides\" rules=\"all\" cellpadding=\"5\">\n"
1244 "%s <colgroup align=\"left\" />\n"
1245 "%s <colgroup align=\"left\" />\n"
1246 "%s <tr><th>Attribute<th>Summary</tr>\n",
1247 indentStr,
1248 indentStr,
1249 indentStr,
1250 indentStr,
1251 indentStr);
1252 }
1253 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1254 if (!publicFlags.itemAt(a) && !includePrivate) {
1255 continue;
1256 }
1257 String8 name8(sym.name);
1258 String16 comment(sym.comment);
1259 if (comment.size() <= 0) {
1260 comment = getAttributeComment(assets, name8);
1261 }
1262 if (comment.size() > 0) {
1263 const char16_t* p = comment.string();
1264 while (*p != 0 && *p != '.') {
1265 if (*p == '{') {
1266 while (*p != 0 && *p != '}') {
1267 p++;
1268 }
1269 } else {
1270 p++;
1271 }
1272 }
1273 if (*p == '.') {
1274 p++;
1275 }
1276 comment = String16(comment.string(), p-comment.string());
1277 }
1278 String16 name(name8);
1279 fixupSymbol(&name);
1280 fprintf(fp, "%s <tr><th><code>{@link #%s_%s %s:%s}</code><td>%s</tr>\n",
1281 indentStr, nclassName.string(),
1282 String8(name).string(),
1283 assets->getPackage().string(),
1284 String8(name).string(),
1285 String8(comment).string());
1286 }
1287 }
1288 if (hasTable) {
1289 fprintf(fp, "%s </table>\n", indentStr);
1290 }
1291 for (a=0; a<NA; a++) {
1292 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1293 if (pos >= 0) {
1294 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1295 if (!publicFlags.itemAt(a) && !includePrivate) {
1296 continue;
1297 }
1298 String16 name(sym.name);
1299 fixupSymbol(&name);
1300 fprintf(fp, "%s @see #%s_%s\n",
1301 indentStr, nclassName.string(),
1302 String8(name).string());
1303 }
1304 }
1305 fprintf(fp, "%s */\n", getIndentSpace(indent));
1306
1307 fprintf(fp,
1308 "%spublic static final int[] %s = {\n"
1309 "%s",
1310 indentStr, nclassName.string(),
1311 getIndentSpace(indent+1));
1312
1313 for (a=0; a<NA; a++) {
1314 if (a != 0) {
1315 if ((a&3) == 0) {
1316 fprintf(fp, ",\n%s", getIndentSpace(indent+1));
1317 } else {
1318 fprintf(fp, ", ");
1319 }
1320 }
1321 fprintf(fp, "0x%08x", idents[a]);
1322 }
1323
1324 fprintf(fp, "\n%s};\n", indentStr);
1325
1326 for (a=0; a<NA; a++) {
1327 ssize_t pos = idents.indexOf(origOrder.itemAt(a));
1328 if (pos >= 0) {
1329 const AaptSymbolEntry& sym = nsymbols->getSymbols().valueAt(a);
1330 if (!publicFlags.itemAt(a) && !includePrivate) {
1331 continue;
1332 }
1333 String8 name8(sym.name);
1334 String16 comment(sym.comment);
1335 String16 typeComment;
1336 if (comment.size() <= 0) {
1337 comment = getAttributeComment(assets, name8, &typeComment);
1338 } else {
1339 getAttributeComment(assets, name8, &typeComment);
1340 }
1341 String16 name(name8);
1342 if (fixupSymbol(&name) != NO_ERROR) {
1343 hasErrors = true;
1344 }
1345
1346 uint32_t typeSpecFlags = 0;
1347 String16 name16(sym.name);
1348 assets->getIncludedResources().identifierForName(
1349 name16.string(), name16.size(),
1350 attr16.string(), attr16.size(),
1351 package16.string(), package16.size(), &typeSpecFlags);
1352 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1353 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1354 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
1355
1356 fprintf(fp, "%s/**\n", indentStr);
1357 if (comment.size() > 0) {
1358 fprintf(fp, "%s <p>\n%s @attr description\n", indentStr, indentStr);
1359 fprintf(fp, "%s %s\n", indentStr, String8(comment).string());
1360 } else {
1361 fprintf(fp,
1362 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
1363 "%s attribute's value can be found in the {@link #%s} array.\n",
1364 indentStr,
1365 pub ? assets->getPackage().string()
1366 : assets->getSymbolsPrivatePackage().string(),
1367 String8(name).string(),
1368 indentStr, nclassName.string());
1369 }
1370 if (typeComment.size() > 0) {
1371 fprintf(fp, "\n\n%s %s\n", indentStr, String8(typeComment).string());
1372 }
1373 if (comment.size() > 0) {
1374 if (pub) {
1375 fprintf(fp,
1376 "%s <p>This corresponds to the global attribute"
1377 "%s resource symbol {@link %s.R.attr#%s}.\n",
1378 indentStr, indentStr,
1379 assets->getPackage().string(),
1380 String8(name).string());
1381 } else {
1382 fprintf(fp,
1383 "%s <p>This is a private symbol.\n", indentStr);
1384 }
1385 }
1386 fprintf(fp, "%s @attr name %s:%s\n", indentStr,
1387 "android", String8(name).string());
1388 fprintf(fp, "%s*/\n", indentStr);
1389 fprintf(fp,
1390 "%spublic static final int %s_%s = %d;\n",
1391 indentStr, nclassName.string(),
1392 String8(name).string(), (int)pos);
1393 }
1394 }
1395 }
1396
1397 indent--;
1398 fprintf(fp, "%s};\n", getIndentSpace(indent));
1399 return hasErrors ? UNKNOWN_ERROR : NO_ERROR;
1400}
1401
1402static status_t writeSymbolClass(
1403 FILE* fp, const sp<AaptAssets>& assets, bool includePrivate,
1404 const sp<AaptSymbols>& symbols, const String8& className, int indent)
1405{
1406 fprintf(fp, "%spublic %sfinal class %s {\n",
1407 getIndentSpace(indent),
1408 indent != 0 ? "static " : "", className.string());
1409 indent++;
1410
1411 size_t i;
1412 status_t err = NO_ERROR;
1413
1414 size_t N = symbols->getSymbols().size();
1415 for (i=0; i<N; i++) {
1416 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
1417 if (sym.typeCode != AaptSymbolEntry::TYPE_INT32) {
1418 continue;
1419 }
1420 if (!includePrivate && !sym.isPublic) {
1421 continue;
1422 }
1423 String16 name(sym.name);
1424 String8 realName(name);
1425 if (fixupSymbol(&name) != NO_ERROR) {
1426 return UNKNOWN_ERROR;
1427 }
1428 String16 comment(sym.comment);
1429 bool haveComment = false;
1430 if (comment.size() > 0) {
1431 haveComment = true;
1432 fprintf(fp,
1433 "%s/** %s\n",
1434 getIndentSpace(indent), String8(comment).string());
1435 } else if (sym.isPublic && !includePrivate) {
1436 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
1437 assets->getPackage().string(), className.string(),
1438 String8(sym.name).string());
1439 }
1440 String16 typeComment(sym.typeComment);
1441 if (typeComment.size() > 0) {
1442 if (!haveComment) {
1443 haveComment = true;
1444 fprintf(fp,
1445 "%s/** %s\n",
1446 getIndentSpace(indent), String8(typeComment).string());
1447 } else {
1448 fprintf(fp,
1449 "%s %s\n",
1450 getIndentSpace(indent), String8(typeComment).string());
1451 }
1452 }
1453 if (haveComment) {
1454 fprintf(fp,"%s */\n", getIndentSpace(indent));
1455 }
1456 fprintf(fp, "%spublic static final int %s=0x%08x;\n",
1457 getIndentSpace(indent),
1458 String8(name).string(), (int)sym.int32Val);
1459 }
1460
1461 for (i=0; i<N; i++) {
1462 const AaptSymbolEntry& sym = symbols->getSymbols().valueAt(i);
1463 if (sym.typeCode != AaptSymbolEntry::TYPE_STRING) {
1464 continue;
1465 }
1466 if (!includePrivate && !sym.isPublic) {
1467 continue;
1468 }
1469 String16 name(sym.name);
1470 if (fixupSymbol(&name) != NO_ERROR) {
1471 return UNKNOWN_ERROR;
1472 }
1473 String16 comment(sym.comment);
1474 if (comment.size() > 0) {
1475 fprintf(fp,
1476 "%s/** %s\n"
1477 "%s */\n",
1478 getIndentSpace(indent), String8(comment).string(),
1479 getIndentSpace(indent));
1480 } else if (sym.isPublic && !includePrivate) {
1481 sym.sourcePos.warning("No comment for public symbol %s:%s/%s",
1482 assets->getPackage().string(), className.string(),
1483 String8(sym.name).string());
1484 }
1485 fprintf(fp, "%spublic static final String %s=\"%s\";\n",
1486 getIndentSpace(indent),
1487 String8(name).string(), sym.stringVal.string());
1488 }
1489
1490 sp<AaptSymbols> styleableSymbols;
1491
1492 N = symbols->getNestedSymbols().size();
1493 for (i=0; i<N; i++) {
1494 sp<AaptSymbols> nsymbols = symbols->getNestedSymbols().valueAt(i);
1495 String8 nclassName(symbols->getNestedSymbols().keyAt(i));
1496 if (nclassName == "styleable") {
1497 styleableSymbols = nsymbols;
1498 } else {
1499 err = writeSymbolClass(fp, assets, includePrivate, nsymbols, nclassName, indent);
1500 }
1501 if (err != NO_ERROR) {
1502 return err;
1503 }
1504 }
1505
1506 if (styleableSymbols != NULL) {
1507 err = writeLayoutClasses(fp, assets, styleableSymbols, indent, includePrivate);
1508 if (err != NO_ERROR) {
1509 return err;
1510 }
1511 }
1512
1513 indent--;
1514 fprintf(fp, "%s}\n", getIndentSpace(indent));
1515 return NO_ERROR;
1516}
1517
1518status_t writeResourceSymbols(Bundle* bundle, const sp<AaptAssets>& assets,
1519 const String8& package, bool includePrivate)
1520{
1521 if (!bundle->getRClassDir()) {
1522 return NO_ERROR;
1523 }
1524
1525 const size_t N = assets->getSymbols().size();
1526 for (size_t i=0; i<N; i++) {
1527 sp<AaptSymbols> symbols = assets->getSymbols().valueAt(i);
1528 String8 className(assets->getSymbols().keyAt(i));
1529 String8 dest(bundle->getRClassDir());
1530 if (bundle->getMakePackageDirs()) {
1531 String8 pkg(package);
1532 const char* last = pkg.string();
1533 const char* s = last-1;
1534 do {
1535 s++;
1536 if (s > last && (*s == '.' || *s == 0)) {
1537 String8 part(last, s-last);
1538 dest.appendPath(part);
1539#ifdef HAVE_MS_C_RUNTIME
1540 _mkdir(dest.string());
1541#else
1542 mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
1543#endif
1544 last = s+1;
1545 }
1546 } while (*s);
1547 }
1548 dest.appendPath(className);
1549 dest.append(".java");
1550 FILE* fp = fopen(dest.string(), "w+");
1551 if (fp == NULL) {
1552 fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
1553 dest.string(), strerror(errno));
1554 return UNKNOWN_ERROR;
1555 }
1556 if (bundle->getVerbose()) {
1557 printf(" Writing symbols for class %s.\n", className.string());
1558 }
1559
1560 fprintf(fp,
1561 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
1562 " *\n"
1563 " * This class was automatically generated by the\n"
1564 " * aapt tool from the resource data it found. It\n"
1565 " * should not be modified by hand.\n"
1566 " */\n"
1567 "\n"
1568 "package %s;\n\n", package.string());
1569
1570 status_t err = writeSymbolClass(fp, assets, includePrivate, symbols, className, 0);
1571 if (err != NO_ERROR) {
1572 return err;
1573 }
1574 fclose(fp);
1575 }
1576
1577 return NO_ERROR;
1578}