2 // Copyright 2006 The Android Open Source Project
4 // Build resource files from raw assets.
7 #include "AaptAssets.h"
8 #include "StringPool.h"
10 #include "ResourceTable.h"
15 // ==========================================================================
16 // ==========================================================================
17 // ==========================================================================
29 status_t
parsePackage(const sp
<AaptGroup
>& grp
);
32 // ==========================================================================
33 // ==========================================================================
34 // ==========================================================================
36 static String8
parseResourceName(const String8
& leaf
)
38 const char* firstDot
= strchr(leaf
.string(), '.');
39 const char* str
= leaf
.string();
42 return String8(str
, firstDot
-str
);
48 ResourceTypeSet::ResourceTypeSet()
50 KeyedVector
<String8
,sp
<AaptGroup
> >()
54 class ResourceDirIterator
57 ResourceDirIterator(const sp
<ResourceTypeSet
>& set
, const String8
& resType
)
58 : mResType(resType
), mSet(set
), mSetPos(0), mGroupPos(0)
62 inline const sp
<AaptGroup
>& getGroup() const { return mGroup
; }
63 inline const sp
<AaptFile
>& getFile() const { return mFile
; }
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
; }
80 // Try to get next file in this current group.
81 if (mGroup
!= NULL
&& mGroupPos
< mGroup
->getFiles().size()) {
83 file
= group
->getFiles().valueAt(mGroupPos
++);
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) {
91 file
= group
->getFiles().valueAt(0);
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 ui=%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
, mParams
.uiMode
,
111 mParams
.density
, mParams
.touchscreen
, mParams
.keyboard
,
112 mParams
.inputFlags
, mParams
.navigation
));
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
;
123 NOISY(printf("file name=%s\n", mBaseName
.string()));
132 const sp
<ResourceTypeSet
> mSet
;
135 sp
<AaptGroup
> mGroup
;
142 ResTable_config mParams
;
145 // ==========================================================================
146 // ==========================================================================
147 // ==========================================================================
149 bool isValidResourceType(const String8
& type
)
151 return type
== "anim" || type
== "drawable" || type
== "layout"
152 || type
== "values" || type
== "xml" || type
== "raw"
153 || type
== "color" || type
== "menu";
156 static sp
<AaptFile
> getResourceFile(const sp
<AaptAssets
>& assets
, bool makeIfNecessary
=true)
158 sp
<AaptGroup
> group
= assets
->getFiles().valueFor(String8("resources.arsc"));
161 file
= group
->getFiles().valueFor(AaptGroupEntry());
167 if (!makeIfNecessary
) {
170 return assets
->addFile(String8("resources.arsc"), AaptGroupEntry(), String8(),
174 static status_t
parsePackage(Bundle
* bundle
, const sp
<AaptAssets
>& assets
,
175 const sp
<AaptGroup
>& grp
)
177 if (grp
->getFiles().size() != 1) {
178 fprintf(stderr
, "warning: Multiple AndroidManifest.xml files found, using %s\n",
179 grp
->getFiles().valueAt(0)->getPrintableSource().string());
182 sp
<AaptFile
> file
= grp
->getFiles().valueAt(0);
185 status_t err
= parseXMLResource(file
, &block
);
186 if (err
!= NO_ERROR
) {
189 //printXMLBlock(&block);
191 ResXMLTree::event_code_t code
;
192 while ((code
=block
.next()) != ResXMLTree::START_TAG
193 && code
!= ResXMLTree::END_DOCUMENT
194 && code
!= ResXMLTree::BAD_DOCUMENT
) {
198 if (code
!= ResXMLTree::START_TAG
) {
199 fprintf(stderr
, "%s:%d: No start tag found\n",
200 file
->getPrintableSource().string(), block
.getLineNumber());
201 return UNKNOWN_ERROR
;
203 if (strcmp16(block
.getElementName(&len
), String16("manifest").string()) != 0) {
204 fprintf(stderr
, "%s:%d: Invalid start tag %s, expected <manifest>\n",
205 file
->getPrintableSource().string(), block
.getLineNumber(),
206 String8(block
.getElementName(&len
)).string());
207 return UNKNOWN_ERROR
;
210 ssize_t nameIndex
= block
.indexOfAttribute(NULL
, "package");
212 fprintf(stderr
, "%s:%d: <manifest> does not have package attribute.\n",
213 file
->getPrintableSource().string(), block
.getLineNumber());
214 return UNKNOWN_ERROR
;
217 assets
->setPackage(String8(block
.getAttributeStringValue(nameIndex
, &len
)));
219 String16
uses_sdk16("uses-sdk");
220 while ((code
=block
.next()) != ResXMLTree::END_DOCUMENT
221 && code
!= ResXMLTree::BAD_DOCUMENT
) {
222 if (code
== ResXMLTree::START_TAG
) {
223 if (strcmp16(block
.getElementName(&len
), uses_sdk16
.string()) == 0) {
224 ssize_t minSdkIndex
= block
.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE
,
226 if (minSdkIndex
>= 0) {
227 const uint16_t* minSdk16
= block
.getAttributeStringValue(minSdkIndex
, &len
);
228 const char* minSdk8
= strdup(String8(minSdk16
).string());
229 bundle
->setMinSdkVersion(minSdk8
);
238 // ==========================================================================
239 // ==========================================================================
240 // ==========================================================================
242 static status_t
makeFileResources(Bundle
* bundle
, const sp
<AaptAssets
>& assets
,
243 ResourceTable
* table
,
244 const sp
<ResourceTypeSet
>& set
,
247 String8
type8(resType
);
248 String16
type16(resType
);
250 bool hasErrors
= false;
252 ResourceDirIterator
it(set
, String8(resType
));
254 while ((res
=it
.next()) == NO_ERROR
) {
255 if (bundle
->getVerbose()) {
256 printf(" (new resource id %s from %s)\n",
257 it
.getBaseName().string(), it
.getFile()->getPrintableSource().string());
259 String16
baseName(it
.getBaseName());
260 const char16_t* str
= baseName
.string();
261 const char16_t* const end
= str
+ baseName
.size();
263 if (!((*str
>= 'a' && *str
<= 'z')
264 || (*str
>= '0' && *str
<= '9')
265 || *str
== '_' || *str
== '.')) {
266 fprintf(stderr
, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
267 it
.getPath().string());
272 String8 resPath
= it
.getPath();
273 resPath
.convertToResPath();
274 table
->addEntry(SourcePos(it
.getPath(), 0), String16(assets
->getPackage()),
280 assets
->addResource(it
.getLeafName(), resPath
, it
.getFile(), type8
);
283 return hasErrors
? UNKNOWN_ERROR
: NO_ERROR
;
286 static status_t
preProcessImages(Bundle
* bundle
, const sp
<AaptAssets
>& assets
,
287 const sp
<ResourceTypeSet
>& set
)
289 ResourceDirIterator
it(set
, String8("drawable"));
290 Vector
<sp
<AaptFile
> > newNameFiles
;
291 Vector
<String8
> newNamePaths
;
292 bool hasErrors
= false;
294 while ((res
=it
.next()) == NO_ERROR
) {
295 res
= preProcessImage(bundle
, assets
, it
.getFile(), NULL
);
296 if (res
< NO_ERROR
) {
301 return (hasErrors
|| (res
< NO_ERROR
)) ? UNKNOWN_ERROR
: NO_ERROR
;
304 status_t
postProcessImages(const sp
<AaptAssets
>& assets
,
305 ResourceTable
* table
,
306 const sp
<ResourceTypeSet
>& set
)
308 ResourceDirIterator
it(set
, String8("drawable"));
309 bool hasErrors
= false;
311 while ((res
=it
.next()) == NO_ERROR
) {
312 res
= postProcessImage(assets
, table
, it
.getFile());
313 if (res
< NO_ERROR
) {
318 return (hasErrors
|| (res
< NO_ERROR
)) ? UNKNOWN_ERROR
: NO_ERROR
;
321 static void collect_files(const sp
<AaptDir
>& dir
,
322 KeyedVector
<String8
, sp
<ResourceTypeSet
> >* resources
)
324 const DefaultKeyedVector
<String8
, sp
<AaptGroup
> >& groups
= dir
->getFiles();
325 int N
= groups
.size();
326 for (int i
=0; i
<N
; i
++) {
327 String8 leafName
= groups
.keyAt(i
);
328 const sp
<AaptGroup
>& group
= groups
.valueAt(i
);
330 const DefaultKeyedVector
<AaptGroupEntry
, sp
<AaptFile
> >& files
333 if (files
.size() == 0) {
337 String8 resType
= files
.valueAt(0)->getResourceType();
339 ssize_t index
= resources
->indexOfKey(resType
);
342 sp
<ResourceTypeSet
> set
= new ResourceTypeSet();
343 set
->add(leafName
, group
);
344 resources
->add(resType
, set
);
346 sp
<ResourceTypeSet
> set
= resources
->valueAt(index
);
347 index
= set
->indexOfKey(leafName
);
349 set
->add(leafName
, group
);
351 sp
<AaptGroup
> existingGroup
= set
->valueAt(index
);
352 int M
= files
.size();
353 for (int j
=0; j
<M
; j
++) {
354 existingGroup
->addFile(files
.valueAt(j
));
361 static void collect_files(const sp
<AaptAssets
>& ass
,
362 KeyedVector
<String8
, sp
<ResourceTypeSet
> >* resources
)
364 const Vector
<sp
<AaptDir
> >& dirs
= ass
->resDirs();
367 for (int i
=0; i
<N
; i
++) {
368 sp
<AaptDir
> d
= dirs
.itemAt(i
);
369 collect_files(d
, resources
);
371 // don't try to include the res dir
372 ass
->removeDir(d
->getLeaf());
379 ATTR_LEADING_SPACES
= -3,
380 ATTR_TRAILING_SPACES
= -4
382 static int validateAttr(const String8
& path
, const ResXMLParser
& parser
,
383 const char* ns
, const char* attr
, const char* validChars
, bool required
)
387 ssize_t index
= parser
.indexOfAttribute(ns
, attr
);
389 if (index
>= 0 && (str
=parser
.getAttributeStringValue(index
, &len
)) != NULL
) {
391 for (size_t i
=0; i
<len
; i
++) {
393 const char* p
= validChars
;
403 fprintf(stderr
, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
404 path
.string(), parser
.getLineNumber(),
405 String8(parser
.getElementName(&len
)).string(), attr
, (char)str
[i
]);
411 fprintf(stderr
, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
412 path
.string(), parser
.getLineNumber(),
413 String8(parser
.getElementName(&len
)).string(), attr
);
414 return ATTR_LEADING_SPACES
;
416 if (str
[len
-1] == ' ') {
417 fprintf(stderr
, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
418 path
.string(), parser
.getLineNumber(),
419 String8(parser
.getElementName(&len
)).string(), attr
);
420 return ATTR_TRAILING_SPACES
;
425 fprintf(stderr
, "%s:%d: Tag <%s> missing required attribute %s.\n",
426 path
.string(), parser
.getLineNumber(),
427 String8(parser
.getElementName(&len
)).string(), attr
);
428 return ATTR_NOT_FOUND
;
433 static void checkForIds(const String8
& path
, ResXMLParser
& parser
)
435 ResXMLTree::event_code_t code
;
436 while ((code
=parser
.next()) != ResXMLTree::END_DOCUMENT
437 && code
> ResXMLTree::BAD_DOCUMENT
) {
438 if (code
== ResXMLTree::START_TAG
) {
439 ssize_t index
= parser
.indexOfAttribute(NULL
, "id");
441 fprintf(stderr
, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
442 path
.string(), parser
.getLineNumber());
448 static bool applyFileOverlay(Bundle
*bundle
,
449 const sp
<AaptAssets
>& assets
,
450 const sp
<ResourceTypeSet
>& baseSet
,
453 if (bundle
->getVerbose()) {
454 printf("applyFileOverlay for %s\n", resType
);
457 // Replace any base level files in this category with any found from the overlay
458 // Also add any found only in the overlay.
459 sp
<AaptAssets
> overlay
= assets
->getOverlay();
460 String8
resTypeString(resType
);
462 // work through the linked list of overlays
463 while (overlay
.get()) {
464 KeyedVector
<String8
, sp
<ResourceTypeSet
> >* overlayRes
= overlay
->getResources();
466 // get the overlay resources of the requested type
467 ssize_t index
= overlayRes
->indexOfKey(resTypeString
);
469 sp
<ResourceTypeSet
> overlaySet
= overlayRes
->valueAt(index
);
471 // for each of the resources, check for a match in the previously built
472 // non-overlay "baseset".
473 size_t overlayCount
= overlaySet
->size();
474 for (size_t overlayIndex
=0; overlayIndex
<overlayCount
; overlayIndex
++) {
475 if (bundle
->getVerbose()) {
476 printf("trying overlaySet Key=%s\n",overlaySet
->keyAt(overlayIndex
).string());
478 size_t baseIndex
= baseSet
->indexOfKey(overlaySet
->keyAt(overlayIndex
));
479 if (baseIndex
< UNKNOWN_ERROR
) {
480 // look for same flavor. For a given file (strings.xml, for example)
481 // there may be a locale specific or other flavors - we want to match
483 sp
<AaptGroup
> overlayGroup
= overlaySet
->valueAt(overlayIndex
);
484 sp
<AaptGroup
> baseGroup
= baseSet
->valueAt(baseIndex
);
486 DefaultKeyedVector
<AaptGroupEntry
, sp
<AaptFile
> > overlayFiles
=
487 overlayGroup
->getFiles();
488 if (bundle
->getVerbose()) {
489 DefaultKeyedVector
<AaptGroupEntry
, sp
<AaptFile
> > baseFiles
=
490 baseGroup
->getFiles();
491 for (size_t i
=0; i
< baseFiles
.size(); i
++) {
492 printf("baseFile %ld has flavor %s\n", i
,
493 baseFiles
.keyAt(i
).toString().string());
495 for (size_t i
=0; i
< overlayFiles
.size(); i
++) {
496 printf("overlayFile %ld has flavor %s\n", i
,
497 overlayFiles
.keyAt(i
).toString().string());
501 size_t overlayGroupSize
= overlayFiles
.size();
502 for (size_t overlayGroupIndex
= 0;
503 overlayGroupIndex
<overlayGroupSize
;
504 overlayGroupIndex
++) {
505 size_t baseFileIndex
=
506 baseGroup
->getFiles().indexOfKey(overlayFiles
.
507 keyAt(overlayGroupIndex
));
508 if(baseFileIndex
< UNKNOWN_ERROR
) {
509 if (bundle
->getVerbose()) {
510 printf("found a match (%ld) for overlay file %s, for flavor %s\n",
512 overlayGroup
->getLeaf().string(),
513 overlayFiles
.keyAt(overlayGroupIndex
).toString().string());
515 baseGroup
->removeFile(baseFileIndex
);
517 // didn't find a match fall through and add it..
519 baseGroup
->addFile(overlayFiles
.valueAt(overlayGroupIndex
));
520 assets
->addGroupEntry(overlayFiles
.keyAt(overlayGroupIndex
));
523 // this group doesn't exist (a file that's only in the overlay)
524 baseSet
->add(overlaySet
->keyAt(overlayIndex
),
525 overlaySet
->valueAt(overlayIndex
));
526 // make sure all flavors are defined in the resources.
527 sp
<AaptGroup
> overlayGroup
= overlaySet
->valueAt(overlayIndex
);
528 DefaultKeyedVector
<AaptGroupEntry
, sp
<AaptFile
> > overlayFiles
=
529 overlayGroup
->getFiles();
530 size_t overlayGroupSize
= overlayFiles
.size();
531 for (size_t overlayGroupIndex
= 0;
532 overlayGroupIndex
<overlayGroupSize
;
533 overlayGroupIndex
++) {
534 assets
->addGroupEntry(overlayFiles
.keyAt(overlayGroupIndex
));
538 // this overlay didn't have resources for this type
541 overlay
= overlay
->getOverlay();
546 void addTagAttribute(const sp
<XMLNode
>& node
, const char* ns8
,
547 const char* attr8
, const char* value
)
553 const String16
ns(ns8
);
554 const String16
attr(attr8
);
556 if (node
->getAttribute(ns
, attr
) != NULL
) {
557 fprintf(stderr
, "Warning: AndroidManifest.xml already defines %s (in %s)\n",
558 String8(attr
).string(), String8(ns
).string());
562 node
->addAttribute(ns
, attr
, String16(value
));
565 static void fullyQualifyClassName(const String8
& package
, sp
<XMLNode
> node
,
566 const String16
& attrName
) {
567 XMLNode::attribute_entry
* attr
= node
->editAttribute(
568 String16("http://schemas.android.com/apk/res/android"), attrName
);
570 String8
name(attr
->string
);
572 // asdf --> package.asdf
573 // .asdf .a.b --> package.asdf package.a.b
574 // asdf.adsf --> asdf.asdf
576 const char* p
= name
.string();
577 const char* q
= strchr(p
, '.');
579 className
+= package
;
581 } else if (q
== NULL
) {
582 className
+= package
;
588 NOISY(printf("Qualifying class '%s' to '%s'", name
.string(), className
.string()));
589 attr
->string
.setTo(String16(className
));
593 status_t
massageManifest(Bundle
* bundle
, sp
<XMLNode
> root
)
595 root
= root
->searchElement(String16(), String16("manifest"));
597 fprintf(stderr
, "No <manifest> tag.\n");
598 return UNKNOWN_ERROR
;
601 addTagAttribute(root
, RESOURCES_ANDROID_NAMESPACE
, "versionCode",
602 bundle
->getVersionCode());
603 addTagAttribute(root
, RESOURCES_ANDROID_NAMESPACE
, "versionName",
604 bundle
->getVersionName());
606 if (bundle
->getMinSdkVersion() != NULL
607 || bundle
->getTargetSdkVersion() != NULL
608 || bundle
->getMaxSdkVersion() != NULL
) {
609 sp
<XMLNode
> vers
= root
->getChildElement(String16(), String16("uses-sdk"));
611 vers
= XMLNode::newElement(root
->getFilename(), String16(), String16("uses-sdk"));
612 root
->insertChildAt(vers
, 0);
615 addTagAttribute(vers
, RESOURCES_ANDROID_NAMESPACE
, "minSdkVersion",
616 bundle
->getMinSdkVersion());
617 addTagAttribute(vers
, RESOURCES_ANDROID_NAMESPACE
, "targetSdkVersion",
618 bundle
->getTargetSdkVersion());
619 addTagAttribute(vers
, RESOURCES_ANDROID_NAMESPACE
, "maxSdkVersion",
620 bundle
->getMaxSdkVersion());
623 // Deal with manifest package name overrides
624 const char* manifestPackageNameOverride
= bundle
->getManifestPackageNameOverride();
625 if (manifestPackageNameOverride
!= NULL
) {
626 // Update the actual package name
627 XMLNode::attribute_entry
* attr
= root
->editAttribute(String16(), String16("package"));
629 fprintf(stderr
, "package name is required with --rename-manifest-package.\n");
630 return UNKNOWN_ERROR
;
632 String8
origPackage(attr
->string
);
633 attr
->string
.setTo(String16(manifestPackageNameOverride
));
634 NOISY(printf("Overriding package '%s' to be '%s'\n", origPackage
.string(), manifestPackageNameOverride
));
636 // Make class names fully qualified
637 sp
<XMLNode
> application
= root
->getChildElement(String16(), String16("application"));
638 if (application
!= NULL
) {
639 fullyQualifyClassName(origPackage
, application
, String16("name"));
640 fullyQualifyClassName(origPackage
, application
, String16("backupAgent"));
642 Vector
<sp
<XMLNode
> >& children
= const_cast<Vector
<sp
<XMLNode
> >&>(application
->getChildren());
643 for (size_t i
= 0; i
< children
.size(); i
++) {
644 sp
<XMLNode
> child
= children
.editItemAt(i
);
645 String8
tag(child
->getElementName());
646 if (tag
== "activity" || tag
== "service" || tag
== "receiver" || tag
== "provider") {
647 fullyQualifyClassName(origPackage
, child
, String16("name"));
648 } else if (tag
== "activity-alias") {
649 fullyQualifyClassName(origPackage
, child
, String16("name"));
650 fullyQualifyClassName(origPackage
, child
, String16("targetActivity"));
656 // Deal with manifest package name overrides
657 const char* instrumentationPackageNameOverride
= bundle
->getInstrumentationPackageNameOverride();
658 if (instrumentationPackageNameOverride
!= NULL
) {
659 // Fix up instrumentation targets.
660 Vector
<sp
<XMLNode
> >& children
= const_cast<Vector
<sp
<XMLNode
> >&>(root
->getChildren());
661 for (size_t i
= 0; i
< children
.size(); i
++) {
662 sp
<XMLNode
> child
= children
.editItemAt(i
);
663 String8
tag(child
->getElementName());
664 if (tag
== "instrumentation") {
665 XMLNode::attribute_entry
* attr
= child
->editAttribute(
666 String16("http://schemas.android.com/apk/res/android"), String16("targetPackage"));
668 attr
->string
.setTo(String16(instrumentationPackageNameOverride
));
677 #define ASSIGN_IT(n) \
679 ssize_t index = resources->indexOfKey(String8(#n)); \
681 n ## s = resources->valueAt(index); \
685 status_t
buildResources(Bundle
* bundle
, const sp
<AaptAssets
>& assets
)
687 // First, look for a package file to parse. This is required to
688 // be able to generate the resource information.
689 sp
<AaptGroup
> androidManifestFile
=
690 assets
->getFiles().valueFor(String8("AndroidManifest.xml"));
691 if (androidManifestFile
== NULL
) {
692 fprintf(stderr
, "ERROR: No AndroidManifest.xml file found.\n");
693 return UNKNOWN_ERROR
;
696 status_t err
= parsePackage(bundle
, assets
, androidManifestFile
);
697 if (err
!= NO_ERROR
) {
701 NOISY(printf("Creating resources for package %s\n",
702 assets
->getPackage().string()));
704 ResourceTable
table(bundle
, String16(assets
->getPackage()));
705 err
= table
.addIncludedResources(bundle
, assets
);
706 if (err
!= NO_ERROR
) {
710 NOISY(printf("Found %d included resource packages\n", (int)table
.size()));
712 // Standard flags for compiled XML and optional UTF-8 encoding
713 int xmlFlags
= XML_COMPILE_STANDARD_RESOURCE
;
714 if (bundle
->getUTF8()) {
715 xmlFlags
|= XML_COMPILE_UTF8
;
718 // --------------------------------------------------------------
719 // First, gather all resource information.
720 // --------------------------------------------------------------
722 // resType -> leafName -> group
723 KeyedVector
<String8
, sp
<ResourceTypeSet
> > *resources
=
724 new KeyedVector
<String8
, sp
<ResourceTypeSet
> >;
725 collect_files(assets
, resources
);
727 sp
<ResourceTypeSet
> drawables
;
728 sp
<ResourceTypeSet
> layouts
;
729 sp
<ResourceTypeSet
> anims
;
730 sp
<ResourceTypeSet
> xmls
;
731 sp
<ResourceTypeSet
> raws
;
732 sp
<ResourceTypeSet
> colors
;
733 sp
<ResourceTypeSet
> menus
;
743 assets
->setResources(resources
);
744 // now go through any resource overlays and collect their files
745 sp
<AaptAssets
> current
= assets
->getOverlay();
746 while(current
.get()) {
747 KeyedVector
<String8
, sp
<ResourceTypeSet
> > *resources
=
748 new KeyedVector
<String8
, sp
<ResourceTypeSet
> >;
749 current
->setResources(resources
);
750 collect_files(current
, resources
);
751 current
= current
->getOverlay();
753 // apply the overlay files to the base set
754 if (!applyFileOverlay(bundle
, assets
, drawables
, "drawable") ||
755 !applyFileOverlay(bundle
, assets
, layouts
, "layout") ||
756 !applyFileOverlay(bundle
, assets
, anims
, "anim") ||
757 !applyFileOverlay(bundle
, assets
, xmls
, "xml") ||
758 !applyFileOverlay(bundle
, assets
, raws
, "raw") ||
759 !applyFileOverlay(bundle
, assets
, colors
, "color") ||
760 !applyFileOverlay(bundle
, assets
, menus
, "menu")) {
761 return UNKNOWN_ERROR
;
764 bool hasErrors
= false;
766 if (drawables
!= NULL
) {
767 err
= preProcessImages(bundle
, assets
, drawables
);
768 if (err
== NO_ERROR
) {
769 err
= makeFileResources(bundle
, assets
, &table
, drawables
, "drawable");
770 if (err
!= NO_ERROR
) {
778 if (layouts
!= NULL
) {
779 err
= makeFileResources(bundle
, assets
, &table
, layouts
, "layout");
780 if (err
!= NO_ERROR
) {
786 err
= makeFileResources(bundle
, assets
, &table
, anims
, "anim");
787 if (err
!= NO_ERROR
) {
793 err
= makeFileResources(bundle
, assets
, &table
, xmls
, "xml");
794 if (err
!= NO_ERROR
) {
800 err
= makeFileResources(bundle
, assets
, &table
, raws
, "raw");
801 if (err
!= NO_ERROR
) {
808 while(current
.get()) {
809 KeyedVector
<String8
, sp
<ResourceTypeSet
> > *resources
=
810 current
->getResources();
812 ssize_t index
= resources
->indexOfKey(String8("values"));
814 ResourceDirIterator
it(resources
->valueAt(index
), String8("values"));
816 while ((res
=it
.next()) == NO_ERROR
) {
817 sp
<AaptFile
> file
= it
.getFile();
818 res
= compileResourceFile(bundle
, assets
, file
, it
.getParams(),
819 (current
!=assets
), &table
);
820 if (res
!= NO_ERROR
) {
825 current
= current
->getOverlay();
828 if (colors
!= NULL
) {
829 err
= makeFileResources(bundle
, assets
, &table
, colors
, "color");
830 if (err
!= NO_ERROR
) {
836 err
= makeFileResources(bundle
, assets
, &table
, menus
, "menu");
837 if (err
!= NO_ERROR
) {
842 // --------------------------------------------------------------------
843 // Assignment of resource IDs and initial generation of resource table.
844 // --------------------------------------------------------------------
846 if (table
.hasResources()) {
847 sp
<AaptFile
> resFile(getResourceFile(assets
));
848 if (resFile
== NULL
) {
849 fprintf(stderr
, "Error: unable to generate entry for resource data\n");
850 return UNKNOWN_ERROR
;
853 err
= table
.assignResourceIds();
854 if (err
< NO_ERROR
) {
859 // --------------------------------------------------------------
860 // Finally, we can now we can compile XML files, which may reference
862 // --------------------------------------------------------------
864 if (layouts
!= NULL
) {
865 ResourceDirIterator
it(layouts
, String8("layout"));
866 while ((err
=it
.next()) == NO_ERROR
) {
867 String8 src
= it
.getFile()->getPrintableSource();
868 err
= compileXmlFile(assets
, it
.getFile(), &table
, xmlFlags
);
869 if (err
== NO_ERROR
) {
871 block
.setTo(it
.getFile()->getData(), it
.getFile()->getSize(), true);
872 checkForIds(src
, block
);
878 if (err
< NO_ERROR
) {
885 ResourceDirIterator
it(anims
, String8("anim"));
886 while ((err
=it
.next()) == NO_ERROR
) {
887 err
= compileXmlFile(assets
, it
.getFile(), &table
, xmlFlags
);
888 if (err
!= NO_ERROR
) {
893 if (err
< NO_ERROR
) {
900 ResourceDirIterator
it(xmls
, String8("xml"));
901 while ((err
=it
.next()) == NO_ERROR
) {
902 err
= compileXmlFile(assets
, it
.getFile(), &table
, xmlFlags
);
903 if (err
!= NO_ERROR
) {
908 if (err
< NO_ERROR
) {
914 if (drawables
!= NULL
) {
915 err
= postProcessImages(assets
, &table
, drawables
);
916 if (err
!= NO_ERROR
) {
921 if (colors
!= NULL
) {
922 ResourceDirIterator
it(colors
, String8("color"));
923 while ((err
=it
.next()) == NO_ERROR
) {
924 err
= compileXmlFile(assets
, it
.getFile(), &table
, xmlFlags
);
925 if (err
!= NO_ERROR
) {
930 if (err
< NO_ERROR
) {
937 ResourceDirIterator
it(menus
, String8("menu"));
938 while ((err
=it
.next()) == NO_ERROR
) {
939 String8 src
= it
.getFile()->getPrintableSource();
940 err
= compileXmlFile(assets
, it
.getFile(), &table
, xmlFlags
);
941 if (err
!= NO_ERROR
) {
945 block
.setTo(it
.getFile()->getData(), it
.getFile()->getSize(), true);
946 checkForIds(src
, block
);
949 if (err
< NO_ERROR
) {
955 const sp
<AaptFile
> manifestFile(androidManifestFile
->getFiles().valueAt(0));
956 String8
manifestPath(manifestFile
->getPrintableSource());
958 // Perform a basic validation of the manifest file. This time we
959 // parse it with the comments intact, so that we can use them to
960 // generate java docs... so we are not going to write this one
961 // back out to the final manifest data.
962 err
= compileXmlFile(assets
, manifestFile
, &table
,
963 XML_COMPILE_ASSIGN_ATTRIBUTE_IDS
964 | XML_COMPILE_STRIP_WHITESPACE
| XML_COMPILE_STRIP_RAW_VALUES
);
965 if (err
< NO_ERROR
) {
969 block
.setTo(manifestFile
->getData(), manifestFile
->getSize(), true);
970 String16
manifest16("manifest");
971 String16
permission16("permission");
972 String16
permission_group16("permission-group");
973 String16
uses_permission16("uses-permission");
974 String16
instrumentation16("instrumentation");
975 String16
application16("application");
976 String16
provider16("provider");
977 String16
service16("service");
978 String16
receiver16("receiver");
979 String16
activity16("activity");
980 String16
action16("action");
981 String16
category16("category");
982 String16
data16("scheme");
983 const char* packageIdentChars
= "abcdefghijklmnopqrstuvwxyz"
984 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789";
985 const char* packageIdentCharsWithTheStupid
= "abcdefghijklmnopqrstuvwxyz"
986 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
987 const char* classIdentChars
= "abcdefghijklmnopqrstuvwxyz"
988 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789$";
989 const char* processIdentChars
= "abcdefghijklmnopqrstuvwxyz"
990 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:";
991 const char* authoritiesIdentChars
= "abcdefghijklmnopqrstuvwxyz"
992 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-:;";
993 const char* typeIdentChars
= "abcdefghijklmnopqrstuvwxyz"
994 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789:-/*+";
995 const char* schemeIdentChars
= "abcdefghijklmnopqrstuvwxyz"
996 "ABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789-";
997 ResXMLTree::event_code_t code
;
998 sp
<AaptSymbols
> permissionSymbols
;
999 sp
<AaptSymbols
> permissionGroupSymbols
;
1000 while ((code
=block
.next()) != ResXMLTree::END_DOCUMENT
1001 && code
> ResXMLTree::BAD_DOCUMENT
) {
1002 if (code
== ResXMLTree::START_TAG
) {
1004 if (block
.getElementNamespace(&len
) != NULL
) {
1007 if (strcmp16(block
.getElementName(&len
), manifest16
.string()) == 0) {
1008 if (validateAttr(manifestPath
, block
, NULL
, "package",
1009 packageIdentChars
, true) != ATTR_OKAY
) {
1012 } else if (strcmp16(block
.getElementName(&len
), permission16
.string()) == 0
1013 || strcmp16(block
.getElementName(&len
), permission_group16
.string()) == 0) {
1014 const bool isGroup
= strcmp16(block
.getElementName(&len
),
1015 permission_group16
.string()) == 0;
1016 if (validateAttr(manifestPath
, block
, RESOURCES_ANDROID_NAMESPACE
, "name",
1017 isGroup
? packageIdentCharsWithTheStupid
1018 : packageIdentChars
, true) != ATTR_OKAY
) {
1021 SourcePos
srcPos(manifestPath
, block
.getLineNumber());
1022 sp
<AaptSymbols
> syms
;
1024 syms
= permissionSymbols
;
1026 sp
<AaptSymbols
> symbols
=
1027 assets
->getSymbolsFor(String8("Manifest"));
1028 syms
= permissionSymbols
= symbols
->addNestedSymbol(
1029 String8("permission"), srcPos
);
1032 syms
= permissionGroupSymbols
;
1034 sp
<AaptSymbols
> symbols
=
1035 assets
->getSymbolsFor(String8("Manifest"));
1036 syms
= permissionGroupSymbols
= symbols
->addNestedSymbol(
1037 String8("permission_group"), srcPos
);
1041 ssize_t index
= block
.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE
, "name");
1042 const uint16_t* id
= block
.getAttributeStringValue(index
, &len
);
1044 fprintf(stderr
, "%s:%d: missing name attribute in element <%s>.\n",
1045 manifestPath
.string(), block
.getLineNumber(),
1046 String8(block
.getElementName(&len
)).string());
1051 char* p
= idStr
.lockBuffer(idStr
.size());
1052 char* e
= p
+ idStr
.size();
1053 bool begins_with_digit
= true; // init to true so an empty string fails
1056 if (*e
>= '0' && *e
<= '9') {
1057 begins_with_digit
= true;
1060 if ((*e
>= 'a' && *e
<= 'z') ||
1061 (*e
>= 'A' && *e
<= 'Z') ||
1063 begins_with_digit
= false;
1066 if (isGroup
&& (*e
== '-')) {
1068 begins_with_digit
= false;
1074 idStr
.unlockBuffer();
1075 // verify that we stopped because we hit a period or
1076 // the beginning of the string, and that the
1077 // identifier didn't begin with a digit.
1078 if (begins_with_digit
|| (e
!= p
&& *(e
-1) != '.')) {
1080 "%s:%d: Permission name <%s> is not a valid Java symbol\n",
1081 manifestPath
.string(), block
.getLineNumber(), idStr
.string());
1084 syms
->addStringSymbol(String8(e
), idStr
, srcPos
);
1085 const uint16_t* cmt
= block
.getComment(&len
);
1086 if (cmt
!= NULL
&& *cmt
!= 0) {
1087 //printf("Comment of %s: %s\n", String8(e).string(),
1088 // String8(cmt).string());
1089 syms
->appendComment(String8(e
), String16(cmt
), srcPos
);
1091 //printf("No comment for %s\n", String8(e).string());
1093 syms
->makeSymbolPublic(String8(e
), srcPos
);
1094 } else if (strcmp16(block
.getElementName(&len
), uses_permission16
.string()) == 0) {
1095 if (validateAttr(manifestPath
, block
, RESOURCES_ANDROID_NAMESPACE
, "name",
1096 packageIdentChars
, true) != ATTR_OKAY
) {
1099 } else if (strcmp16(block
.getElementName(&len
), instrumentation16
.string()) == 0) {
1100 if (validateAttr(manifestPath
, block
, RESOURCES_ANDROID_NAMESPACE
, "name",
1101 classIdentChars
, true) != ATTR_OKAY
) {
1104 if (validateAttr(manifestPath
, block
,
1105 RESOURCES_ANDROID_NAMESPACE
, "targetPackage",
1106 packageIdentChars
, true) != ATTR_OKAY
) {
1109 } else if (strcmp16(block
.getElementName(&len
), application16
.string()) == 0) {
1110 if (validateAttr(manifestPath
, block
, RESOURCES_ANDROID_NAMESPACE
, "name",
1111 classIdentChars
, false) != ATTR_OKAY
) {
1114 if (validateAttr(manifestPath
, block
,
1115 RESOURCES_ANDROID_NAMESPACE
, "permission",
1116 packageIdentChars
, false) != ATTR_OKAY
) {
1119 if (validateAttr(manifestPath
, block
,
1120 RESOURCES_ANDROID_NAMESPACE
, "process",
1121 processIdentChars
, false) != ATTR_OKAY
) {
1124 if (validateAttr(manifestPath
, block
,
1125 RESOURCES_ANDROID_NAMESPACE
, "taskAffinity",
1126 processIdentChars
, false) != ATTR_OKAY
) {
1129 } else if (strcmp16(block
.getElementName(&len
), provider16
.string()) == 0) {
1130 if (validateAttr(manifestPath
, block
, RESOURCES_ANDROID_NAMESPACE
, "name",
1131 classIdentChars
, true) != ATTR_OKAY
) {
1134 if (validateAttr(manifestPath
, block
,
1135 RESOURCES_ANDROID_NAMESPACE
, "authorities",
1136 authoritiesIdentChars
, true) != ATTR_OKAY
) {
1139 if (validateAttr(manifestPath
, block
,
1140 RESOURCES_ANDROID_NAMESPACE
, "permission",
1141 packageIdentChars
, false) != ATTR_OKAY
) {
1144 if (validateAttr(manifestPath
, block
,
1145 RESOURCES_ANDROID_NAMESPACE
, "process",
1146 processIdentChars
, false) != ATTR_OKAY
) {
1149 } else if (strcmp16(block
.getElementName(&len
), service16
.string()) == 0
1150 || strcmp16(block
.getElementName(&len
), receiver16
.string()) == 0
1151 || strcmp16(block
.getElementName(&len
), activity16
.string()) == 0) {
1152 if (validateAttr(manifestPath
, block
, RESOURCES_ANDROID_NAMESPACE
, "name",
1153 classIdentChars
, true) != ATTR_OKAY
) {
1156 if (validateAttr(manifestPath
, block
,
1157 RESOURCES_ANDROID_NAMESPACE
, "permission",
1158 packageIdentChars
, false) != ATTR_OKAY
) {
1161 if (validateAttr(manifestPath
, block
,
1162 RESOURCES_ANDROID_NAMESPACE
, "process",
1163 processIdentChars
, false) != ATTR_OKAY
) {
1166 if (validateAttr(manifestPath
, block
,
1167 RESOURCES_ANDROID_NAMESPACE
, "taskAffinity",
1168 processIdentChars
, false) != ATTR_OKAY
) {
1171 } else if (strcmp16(block
.getElementName(&len
), action16
.string()) == 0
1172 || strcmp16(block
.getElementName(&len
), category16
.string()) == 0) {
1173 if (validateAttr(manifestPath
, block
,
1174 RESOURCES_ANDROID_NAMESPACE
, "name",
1175 packageIdentChars
, true) != ATTR_OKAY
) {
1178 } else if (strcmp16(block
.getElementName(&len
), data16
.string()) == 0) {
1179 if (validateAttr(manifestPath
, block
,
1180 RESOURCES_ANDROID_NAMESPACE
, "mimeType",
1181 typeIdentChars
, true) != ATTR_OKAY
) {
1184 if (validateAttr(manifestPath
, block
,
1185 RESOURCES_ANDROID_NAMESPACE
, "scheme",
1186 schemeIdentChars
, true) != ATTR_OKAY
) {
1193 if (table
.validateLocalizations()) {
1198 return UNKNOWN_ERROR
;
1201 // Generate final compiled manifest file.
1202 manifestFile
->clearData();
1203 sp
<XMLNode
> manifestTree
= XMLNode::parse(manifestFile
);
1204 if (manifestTree
== NULL
) {
1205 return UNKNOWN_ERROR
;
1207 err
= massageManifest(bundle
, manifestTree
);
1208 if (err
< NO_ERROR
) {
1211 err
= compileXmlFile(assets
, manifestTree
, manifestFile
, &table
);
1212 if (err
< NO_ERROR
) {
1217 //printXMLBlock(&block);
1219 // --------------------------------------------------------------
1220 // Generate the final resource table.
1221 // Re-flatten because we may have added new resource IDs
1222 // --------------------------------------------------------------
1224 if (table
.hasResources()) {
1225 sp
<AaptSymbols
> symbols
= assets
->getSymbolsFor(String8("R"));
1226 err
= table
.addSymbols(symbols
);
1227 if (err
< NO_ERROR
) {
1231 sp
<AaptFile
> resFile(getResourceFile(assets
));
1232 if (resFile
== NULL
) {
1233 fprintf(stderr
, "Error: unable to generate entry for resource data\n");
1234 return UNKNOWN_ERROR
;
1237 err
= table
.flatten(bundle
, resFile
);
1238 if (err
< NO_ERROR
) {
1242 if (bundle
->getPublicOutputFile()) {
1243 FILE* fp
= fopen(bundle
->getPublicOutputFile(), "w+");
1245 fprintf(stderr
, "ERROR: Unable to open public definitions output file %s: %s\n",
1246 (const char*)bundle
->getPublicOutputFile(), strerror(errno
));
1247 return UNKNOWN_ERROR
;
1249 if (bundle
->getVerbose()) {
1250 printf(" Writing public definitions to %s.\n", bundle
->getPublicOutputFile());
1252 table
.writePublicDefinitions(String16(assets
->getPackage()), fp
);
1258 rt
.add(resFile
->getData(), resFile
->getSize(), NULL
);
1259 printf("Generated resources:\n");
1263 // These resources are now considered to be a part of the included
1264 // resources, for others to reference.
1265 err
= assets
->addIncludedResources(resFile
);
1266 if (err
< NO_ERROR
) {
1267 fprintf(stderr
, "ERROR: Unable to parse generated resources, aborting.\n");
1274 static const char* getIndentSpace(int indent
)
1276 static const char whitespace
[] =
1279 return whitespace
+ sizeof(whitespace
) - 1 - indent
*4;
1282 static status_t
fixupSymbol(String16
* inoutSymbol
)
1284 inoutSymbol
->replaceAll('.', '_');
1285 inoutSymbol
->replaceAll(':', '_');
1289 static String16
getAttributeComment(const sp
<AaptAssets
>& assets
,
1290 const String8
& name
,
1291 String16
* outTypeComment
= NULL
)
1293 sp
<AaptSymbols
> asym
= assets
->getSymbolsFor(String8("R"));
1295 //printf("Got R symbols!\n");
1296 asym
= asym
->getNestedSymbols().valueFor(String8("attr"));
1298 //printf("Got attrs symbols! comment %s=%s\n",
1299 // name.string(), String8(asym->getComment(name)).string());
1300 if (outTypeComment
!= NULL
) {
1301 *outTypeComment
= asym
->getTypeComment(name
);
1303 return asym
->getComment(name
);
1309 static status_t
writeLayoutClasses(
1310 FILE* fp
, const sp
<AaptAssets
>& assets
,
1311 const sp
<AaptSymbols
>& symbols
, int indent
, bool includePrivate
)
1313 const char* indentStr
= getIndentSpace(indent
);
1314 if (!includePrivate
) {
1315 fprintf(fp
, "%s/** @doconly */\n", indentStr
);
1317 fprintf(fp
, "%spublic static final class styleable {\n", indentStr
);
1320 String16
attr16("attr");
1321 String16
package16(assets
->getPackage());
1323 indentStr
= getIndentSpace(indent
);
1324 bool hasErrors
= false;
1327 size_t N
= symbols
->getNestedSymbols().size();
1328 for (i
=0; i
<N
; i
++) {
1329 sp
<AaptSymbols
> nsymbols
= symbols
->getNestedSymbols().valueAt(i
);
1330 String16
nclassName16(symbols
->getNestedSymbols().keyAt(i
));
1331 String8
realClassName(nclassName16
);
1332 if (fixupSymbol(&nclassName16
) != NO_ERROR
) {
1335 String8
nclassName(nclassName16
);
1337 SortedVector
<uint32_t> idents
;
1338 Vector
<uint32_t> origOrder
;
1339 Vector
<bool> publicFlags
;
1342 size_t NA
= nsymbols
->getSymbols().size();
1343 for (a
=0; a
<NA
; a
++) {
1344 const AaptSymbolEntry
& sym(nsymbols
->getSymbols().valueAt(a
));
1345 int32_t code
= sym
.typeCode
== AaptSymbolEntry::TYPE_INT32
1347 bool isPublic
= true;
1349 String16
name16(sym
.name
);
1350 uint32_t typeSpecFlags
;
1351 code
= assets
->getIncludedResources().identifierForName(
1352 name16
.string(), name16
.size(),
1353 attr16
.string(), attr16
.size(),
1354 package16
.string(), package16
.size(), &typeSpecFlags
);
1356 fprintf(stderr
, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
1357 nclassName
.string(), sym
.name
.string());
1360 isPublic
= (typeSpecFlags
&ResTable_typeSpec::SPEC_PUBLIC
) != 0;
1363 origOrder
.add(code
);
1364 publicFlags
.add(isPublic
);
1369 bool deprecated
= false;
1371 String16 comment
= symbols
->getComment(realClassName
);
1372 fprintf(fp
, "%s/** ", indentStr
);
1373 if (comment
.size() > 0) {
1374 String8
cmt(comment
);
1375 fprintf(fp
, "%s\n", cmt
.string());
1376 if (strstr(cmt
.string(), "@deprecated") != NULL
) {
1380 fprintf(fp
, "Attributes that can be used with a %s.\n", nclassName
.string());
1382 bool hasTable
= false;
1383 for (a
=0; a
<NA
; a
++) {
1384 ssize_t pos
= idents
.indexOf(origOrder
.itemAt(a
));
1389 "%s <p>Includes the following attributes:</p>\n"
1391 "%s <colgroup align=\"left\" />\n"
1392 "%s <colgroup align=\"left\" />\n"
1393 "%s <tr><th>Attribute</th><th>Description</th></tr>\n",
1400 const AaptSymbolEntry
& sym
= nsymbols
->getSymbols().valueAt(a
);
1401 if (!publicFlags
.itemAt(a
) && !includePrivate
) {
1404 String8
name8(sym
.name
);
1405 String16
comment(sym
.comment
);
1406 if (comment
.size() <= 0) {
1407 comment
= getAttributeComment(assets
, name8
);
1409 if (comment
.size() > 0) {
1410 const char16_t* p
= comment
.string();
1411 while (*p
!= 0 && *p
!= '.') {
1413 while (*p
!= 0 && *p
!= '}') {
1423 comment
= String16(comment
.string(), p
-comment
.string());
1425 String16
name(name8
);
1427 fprintf(fp
, "%s <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
1428 indentStr
, nclassName
.string(),
1429 String8(name
).string(),
1430 assets
->getPackage().string(),
1431 String8(name
).string(),
1432 String8(comment
).string());
1436 fprintf(fp
, "%s </table>\n", indentStr
);
1438 for (a
=0; a
<NA
; a
++) {
1439 ssize_t pos
= idents
.indexOf(origOrder
.itemAt(a
));
1441 const AaptSymbolEntry
& sym
= nsymbols
->getSymbols().valueAt(a
);
1442 if (!publicFlags
.itemAt(a
) && !includePrivate
) {
1445 String16
name(sym
.name
);
1447 fprintf(fp
, "%s @see #%s_%s\n",
1448 indentStr
, nclassName
.string(),
1449 String8(name
).string());
1452 fprintf(fp
, "%s */\n", getIndentSpace(indent
));
1455 fprintf(fp
, "%s@Deprecated\n", indentStr
);
1459 "%spublic static final int[] %s = {\n"
1461 indentStr
, nclassName
.string(),
1462 getIndentSpace(indent
+1));
1464 for (a
=0; a
<NA
; a
++) {
1467 fprintf(fp
, ",\n%s", getIndentSpace(indent
+1));
1472 fprintf(fp
, "0x%08x", idents
[a
]);
1475 fprintf(fp
, "\n%s};\n", indentStr
);
1477 for (a
=0; a
<NA
; a
++) {
1478 ssize_t pos
= idents
.indexOf(origOrder
.itemAt(a
));
1480 const AaptSymbolEntry
& sym
= nsymbols
->getSymbols().valueAt(a
);
1481 if (!publicFlags
.itemAt(a
) && !includePrivate
) {
1484 String8
name8(sym
.name
);
1485 String16
comment(sym
.comment
);
1486 String16 typeComment
;
1487 if (comment
.size() <= 0) {
1488 comment
= getAttributeComment(assets
, name8
, &typeComment
);
1490 getAttributeComment(assets
, name8
, &typeComment
);
1492 String16
name(name8
);
1493 if (fixupSymbol(&name
) != NO_ERROR
) {
1497 uint32_t typeSpecFlags
= 0;
1498 String16
name16(sym
.name
);
1499 assets
->getIncludedResources().identifierForName(
1500 name16
.string(), name16
.size(),
1501 attr16
.string(), attr16
.size(),
1502 package16
.string(), package16
.size(), &typeSpecFlags
);
1503 //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
1504 // String8(attr16).string(), String8(name16).string(), typeSpecFlags);
1505 const bool pub
= (typeSpecFlags
&ResTable_typeSpec::SPEC_PUBLIC
) != 0;
1507 bool deprecated
= false;
1509 fprintf(fp
, "%s/**\n", indentStr
);
1510 if (comment
.size() > 0) {
1511 String8
cmt(comment
);
1512 fprintf(fp
, "%s <p>\n%s @attr description\n", indentStr
, indentStr
);
1513 fprintf(fp
, "%s %s\n", indentStr
, cmt
.string());
1514 if (strstr(cmt
.string(), "@deprecated") != NULL
) {
1519 "%s <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
1520 "%s attribute's value can be found in the {@link #%s} array.\n",
1522 pub
? assets
->getPackage().string()
1523 : assets
->getSymbolsPrivatePackage().string(),
1524 String8(name
).string(),
1525 indentStr
, nclassName
.string());
1527 if (typeComment
.size() > 0) {
1528 String8
cmt(typeComment
);
1529 fprintf(fp
, "\n\n%s %s\n", indentStr
, cmt
.string());
1530 if (strstr(cmt
.string(), "@deprecated") != NULL
) {
1534 if (comment
.size() > 0) {
1537 "%s <p>This corresponds to the global attribute"
1538 "%s resource symbol {@link %s.R.attr#%s}.\n",
1539 indentStr
, indentStr
,
1540 assets
->getPackage().string(),
1541 String8(name
).string());
1544 "%s <p>This is a private symbol.\n", indentStr
);
1547 fprintf(fp
, "%s @attr name %s:%s\n", indentStr
,
1548 "android", String8(name
).string());
1549 fprintf(fp
, "%s*/\n", indentStr
);
1551 fprintf(fp
, "%s@Deprecated\n", indentStr
);
1554 "%spublic static final int %s_%s = %d;\n",
1555 indentStr
, nclassName
.string(),
1556 String8(name
).string(), (int)pos
);
1562 fprintf(fp
, "%s};\n", getIndentSpace(indent
));
1563 return hasErrors
? UNKNOWN_ERROR
: NO_ERROR
;
1566 static status_t
writeSymbolClass(
1567 FILE* fp
, const sp
<AaptAssets
>& assets
, bool includePrivate
,
1568 const sp
<AaptSymbols
>& symbols
, const String8
& className
, int indent
)
1570 fprintf(fp
, "%spublic %sfinal class %s {\n",
1571 getIndentSpace(indent
),
1572 indent
!= 0 ? "static " : "", className
.string());
1576 status_t err
= NO_ERROR
;
1578 size_t N
= symbols
->getSymbols().size();
1579 for (i
=0; i
<N
; i
++) {
1580 const AaptSymbolEntry
& sym
= symbols
->getSymbols().valueAt(i
);
1581 if (sym
.typeCode
!= AaptSymbolEntry::TYPE_INT32
) {
1584 if (!includePrivate
&& !sym
.isPublic
) {
1587 String16
name(sym
.name
);
1588 String8
realName(name
);
1589 if (fixupSymbol(&name
) != NO_ERROR
) {
1590 return UNKNOWN_ERROR
;
1592 String16
comment(sym
.comment
);
1593 bool haveComment
= false;
1594 bool deprecated
= false;
1595 if (comment
.size() > 0) {
1597 String8
cmt(comment
);
1600 getIndentSpace(indent
), cmt
.string());
1601 if (strstr(cmt
.string(), "@deprecated") != NULL
) {
1604 } else if (sym
.isPublic
&& !includePrivate
) {
1605 sym
.sourcePos
.warning("No comment for public symbol %s:%s/%s",
1606 assets
->getPackage().string(), className
.string(),
1607 String8(sym
.name
).string());
1609 String16
typeComment(sym
.typeComment
);
1610 if (typeComment
.size() > 0) {
1611 String8
cmt(typeComment
);
1615 "%s/** %s\n", getIndentSpace(indent
), cmt
.string());
1618 "%s %s\n", getIndentSpace(indent
), cmt
.string());
1620 if (strstr(cmt
.string(), "@deprecated") != NULL
) {
1625 fprintf(fp
,"%s */\n", getIndentSpace(indent
));
1628 fprintf(fp
, "%s@Deprecated\n", getIndentSpace(indent
));
1630 fprintf(fp
, "%spublic static final int %s=0x%08x;\n",
1631 getIndentSpace(indent
),
1632 String8(name
).string(), (int)sym
.int32Val
);
1635 for (i
=0; i
<N
; i
++) {
1636 const AaptSymbolEntry
& sym
= symbols
->getSymbols().valueAt(i
);
1637 if (sym
.typeCode
!= AaptSymbolEntry::TYPE_STRING
) {
1640 if (!includePrivate
&& !sym
.isPublic
) {
1643 String16
name(sym
.name
);
1644 if (fixupSymbol(&name
) != NO_ERROR
) {
1645 return UNKNOWN_ERROR
;
1647 String16
comment(sym
.comment
);
1648 bool deprecated
= false;
1649 if (comment
.size() > 0) {
1650 String8
cmt(comment
);
1654 getIndentSpace(indent
), cmt
.string(),
1655 getIndentSpace(indent
));
1656 if (strstr(cmt
.string(), "@deprecated") != NULL
) {
1659 } else if (sym
.isPublic
&& !includePrivate
) {
1660 sym
.sourcePos
.warning("No comment for public symbol %s:%s/%s",
1661 assets
->getPackage().string(), className
.string(),
1662 String8(sym
.name
).string());
1665 fprintf(fp
, "%s@Deprecated\n", getIndentSpace(indent
));
1667 fprintf(fp
, "%spublic static final String %s=\"%s\";\n",
1668 getIndentSpace(indent
),
1669 String8(name
).string(), sym
.stringVal
.string());
1672 sp
<AaptSymbols
> styleableSymbols
;
1674 N
= symbols
->getNestedSymbols().size();
1675 for (i
=0; i
<N
; i
++) {
1676 sp
<AaptSymbols
> nsymbols
= symbols
->getNestedSymbols().valueAt(i
);
1677 String8
nclassName(symbols
->getNestedSymbols().keyAt(i
));
1678 if (nclassName
== "styleable") {
1679 styleableSymbols
= nsymbols
;
1681 err
= writeSymbolClass(fp
, assets
, includePrivate
, nsymbols
, nclassName
, indent
);
1683 if (err
!= NO_ERROR
) {
1688 if (styleableSymbols
!= NULL
) {
1689 err
= writeLayoutClasses(fp
, assets
, styleableSymbols
, indent
, includePrivate
);
1690 if (err
!= NO_ERROR
) {
1696 fprintf(fp
, "%s}\n", getIndentSpace(indent
));
1700 status_t
writeResourceSymbols(Bundle
* bundle
, const sp
<AaptAssets
>& assets
,
1701 const String8
& package
, bool includePrivate
)
1703 if (!bundle
->getRClassDir()) {
1707 const size_t N
= assets
->getSymbols().size();
1708 for (size_t i
=0; i
<N
; i
++) {
1709 sp
<AaptSymbols
> symbols
= assets
->getSymbols().valueAt(i
);
1710 String8
className(assets
->getSymbols().keyAt(i
));
1711 String8
dest(bundle
->getRClassDir());
1712 if (bundle
->getMakePackageDirs()) {
1713 String8
pkg(package
);
1714 const char* last
= pkg
.string();
1715 const char* s
= last
-1;
1718 if (s
> last
&& (*s
== '.' || *s
== 0)) {
1719 String8
part(last
, s
-last
);
1720 dest
.appendPath(part
);
1721 #ifdef HAVE_MS_C_RUNTIME
1722 _mkdir(dest
.string());
1724 mkdir(dest
.string(), S_IRUSR
|S_IWUSR
|S_IXUSR
|S_IRGRP
|S_IXGRP
);
1730 dest
.appendPath(className
);
1731 dest
.append(".java");
1732 FILE* fp
= fopen(dest
.string(), "w+");
1734 fprintf(stderr
, "ERROR: Unable to open class file %s: %s\n",
1735 dest
.string(), strerror(errno
));
1736 return UNKNOWN_ERROR
;
1738 if (bundle
->getVerbose()) {
1739 printf(" Writing symbols for class %s.\n", className
.string());
1743 "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n"
1745 " * This class was automatically generated by the\n"
1746 " * aapt tool from the resource data it found. It\n"
1747 " * should not be modified by hand.\n"
1750 "package %s;\n\n", package
.string());
1752 status_t err
= writeSymbolClass(fp
, assets
, includePrivate
, symbols
, className
, 0);
1753 if (err
!= NO_ERROR
) {
1764 class ProguardKeepSet
1767 // { rule --> { file locations } }
1768 KeyedVector
<String8
, SortedVector
<String8
> > rules
;
1770 void add(const String8
& rule
, const String8
& where
);
1773 void ProguardKeepSet::add(const String8
& rule
, const String8
& where
)
1775 ssize_t index
= rules
.indexOfKey(rule
);
1777 index
= rules
.add(rule
, SortedVector
<String8
>());
1779 rules
.editValueAt(index
).add(where
);
1783 addProguardKeepRule(ProguardKeepSet
* keep
, const String8
& inClassName
,
1784 const char* pkg
, const String8
& srcName
, int line
)
1786 String8
className(inClassName
);
1788 // asdf --> package.asdf
1789 // .asdf .a.b --> package.asdf package.a.b
1790 // asdf.adsf --> asdf.asdf
1791 const char* p
= className
.string();
1792 const char* q
= strchr(p
, '.');
1795 className
.append(inClassName
);
1796 } else if (q
== NULL
) {
1798 className
.append(".");
1799 className
.append(inClassName
);
1803 String8
rule("-keep class ");
1805 rule
+= " { <init>(...); }";
1807 String8
location("view ");
1808 location
+= srcName
;
1810 sprintf(lineno
, ":%d", line
);
1813 keep
->add(rule
, location
);
1817 writeProguardForAndroidManifest(ProguardKeepSet
* keep
, const sp
<AaptAssets
>& assets
)
1822 ResXMLTree::event_code_t code
;
1824 bool inApplication
= false;
1826 sp
<AaptGroup
> assGroup
;
1827 sp
<AaptFile
> assFile
;
1830 // First, look for a package file to parse. This is required to
1831 // be able to generate the resource information.
1832 assGroup
= assets
->getFiles().valueFor(String8("AndroidManifest.xml"));
1833 if (assGroup
== NULL
) {
1834 fprintf(stderr
, "ERROR: No AndroidManifest.xml file found.\n");
1838 if (assGroup
->getFiles().size() != 1) {
1839 fprintf(stderr
, "warning: Multiple AndroidManifest.xml files found, using %s\n",
1840 assGroup
->getFiles().valueAt(0)->getPrintableSource().string());
1843 assFile
= assGroup
->getFiles().valueAt(0);
1845 err
= parseXMLResource(assFile
, &tree
);
1846 if (err
!= NO_ERROR
) {
1852 while ((code
=tree
.next()) != ResXMLTree::END_DOCUMENT
&& code
!= ResXMLTree::BAD_DOCUMENT
) {
1853 if (code
== ResXMLTree::END_TAG
) {
1854 if (/* name == "Application" && */ depth
== 2) {
1855 inApplication
= false;
1860 if (code
!= ResXMLTree::START_TAG
) {
1864 String8
tag(tree
.getElementName(&len
));
1865 // printf("Depth %d tag %s\n", depth, tag.string());
1866 bool keepTag
= false;
1868 if (tag
!= "manifest") {
1869 fprintf(stderr
, "ERROR: manifest does not start with <manifest> tag\n");
1872 pkg
= getAttribute(tree
, NULL
, "package", NULL
);
1873 } else if (depth
== 2) {
1874 if (tag
== "application") {
1875 inApplication
= true;
1878 String8 agent
= getAttribute(tree
, "http://schemas.android.com/apk/res/android",
1879 "backupAgent", &error
);
1880 if (agent
.length() > 0) {
1881 addProguardKeepRule(keep
, agent
, pkg
.string(),
1882 assFile
->getPrintableSource(), tree
.getLineNumber());
1884 } else if (tag
== "instrumentation") {
1888 if (!keepTag
&& inApplication
&& depth
== 3) {
1889 if (tag
== "activity" || tag
== "service" || tag
== "receiver" || tag
== "provider") {
1894 String8 name
= getAttribute(tree
, "http://schemas.android.com/apk/res/android",
1897 fprintf(stderr
, "ERROR: %s\n", error
.string());
1900 if (name
.length() > 0) {
1901 addProguardKeepRule(keep
, name
, pkg
.string(),
1902 assFile
->getPrintableSource(), tree
.getLineNumber());
1911 writeProguardForXml(ProguardKeepSet
* keep
, const sp
<AaptFile
>& layoutFile
,
1912 const char* startTag
, const char* altTag
)
1917 ResXMLTree::event_code_t code
;
1919 err
= parseXMLResource(layoutFile
, &tree
);
1920 if (err
!= NO_ERROR
) {
1926 if (startTag
!= NULL
) {
1927 bool haveStart
= false;
1928 while ((code
=tree
.next()) != ResXMLTree::END_DOCUMENT
&& code
!= ResXMLTree::BAD_DOCUMENT
) {
1929 if (code
!= ResXMLTree::START_TAG
) {
1932 String8
tag(tree
.getElementName(&len
));
1933 if (tag
== startTag
) {
1943 while ((code
=tree
.next()) != ResXMLTree::END_DOCUMENT
&& code
!= ResXMLTree::BAD_DOCUMENT
) {
1944 if (code
!= ResXMLTree::START_TAG
) {
1947 String8
tag(tree
.getElementName(&len
));
1949 // If there is no '.', we'll assume that it's one of the built in names.
1950 if (strchr(tag
.string(), '.')) {
1951 addProguardKeepRule(keep
, tag
, NULL
,
1952 layoutFile
->getPrintableSource(), tree
.getLineNumber());
1953 } else if (altTag
!= NULL
&& tag
== altTag
) {
1954 ssize_t classIndex
= tree
.indexOfAttribute(NULL
, "class");
1955 if (classIndex
< 0) {
1956 fprintf(stderr
, "%s:%d: <view> does not have class attribute.\n",
1957 layoutFile
->getPrintableSource().string(), tree
.getLineNumber());
1960 addProguardKeepRule(keep
,
1961 String8(tree
.getAttributeStringValue(classIndex
, &len
)), NULL
,
1962 layoutFile
->getPrintableSource(), tree
.getLineNumber());
1971 writeProguardForLayouts(ProguardKeepSet
* keep
, const sp
<AaptAssets
>& assets
)
1974 const Vector
<sp
<AaptDir
> >& dirs
= assets
->resDirs();
1975 const size_t K
= dirs
.size();
1976 for (size_t k
=0; k
<K
; k
++) {
1977 const sp
<AaptDir
>& d
= dirs
.itemAt(k
);
1978 const String8
& dirName
= d
->getLeaf();
1979 const char* startTag
= NULL
;
1980 const char* altTag
= NULL
;
1981 if ((dirName
== String8("layout")) || (strncmp(dirName
.string(), "layout-", 7) == 0)) {
1983 } else if ((dirName
== String8("xml")) || (strncmp(dirName
.string(), "xml-", 4) == 0)) {
1984 startTag
= "PreferenceScreen";
1989 const KeyedVector
<String8
,sp
<AaptGroup
> > groups
= d
->getFiles();
1990 const size_t N
= groups
.size();
1991 for (size_t i
=0; i
<N
; i
++) {
1992 const sp
<AaptGroup
>& group
= groups
.valueAt(i
);
1993 const DefaultKeyedVector
<AaptGroupEntry
, sp
<AaptFile
> >& files
= group
->getFiles();
1994 const size_t M
= files
.size();
1995 for (size_t j
=0; j
<M
; j
++) {
1996 err
= writeProguardForXml(keep
, files
.valueAt(j
), startTag
, altTag
);
2007 writeProguardFile(Bundle
* bundle
, const sp
<AaptAssets
>& assets
)
2011 if (!bundle
->getProguardFile()) {
2015 ProguardKeepSet keep
;
2017 err
= writeProguardForAndroidManifest(&keep
, assets
);
2022 err
= writeProguardForLayouts(&keep
, assets
);
2027 FILE* fp
= fopen(bundle
->getProguardFile(), "w+");
2029 fprintf(stderr
, "ERROR: Unable to open class file %s: %s\n",
2030 bundle
->getProguardFile(), strerror(errno
));
2031 return UNKNOWN_ERROR
;
2034 const KeyedVector
<String8
, SortedVector
<String8
> >& rules
= keep
.rules
;
2035 const size_t N
= rules
.size();
2036 for (size_t i
=0; i
<N
; i
++) {
2037 const SortedVector
<String8
>& locations
= rules
.valueAt(i
);
2038 const size_t M
= locations
.size();
2039 for (size_t j
=0; j
<M
; j
++) {
2040 fprintf(fp
, "# %s\n", locations
.itemAt(j
).string());
2042 fprintf(fp
, "%s\n\n", rules
.keyAt(i
).string());