/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "NameMangler.h" #include "Resource.h" #include "ResourceTable.h" #include "ResourceValues.h" #include "ValueVisitor.h" #include "java/AnnotationProcessor.h" #include "java/ClassDefinitionWriter.h" #include "java/JavaClassGenerator.h" #include "util/StringPiece.h" #include #include #include #include #include namespace aapt { JavaClassGenerator::JavaClassGenerator(ResourceTable* table, JavaClassGeneratorOptions options) : mTable(table), mOptions(options) { } static void generateHeader(const StringPiece16& packageNameToGenerate, std::ostream* out) { *out << "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n" " *\n" " * This class was automatically generated by the\n" " * aapt tool from the resource data it found. It\n" " * should not be modified by hand.\n" " */\n\n" "package " << packageNameToGenerate << ";\n\n"; } static const std::set sJavaIdentifiers = { u"abstract", u"assert", u"boolean", u"break", u"byte", u"case", u"catch", u"char", u"class", u"const", u"continue", u"default", u"do", u"double", u"else", u"enum", u"extends", u"final", u"finally", u"float", u"for", u"goto", u"if", u"implements", u"import", u"instanceof", u"int", u"interface", u"long", u"native", u"new", u"package", u"private", u"protected", u"public", u"return", u"short", u"static", u"strictfp", u"super", u"switch", u"synchronized", u"this", u"throw", u"throws", u"transient", u"try", u"void", u"volatile", u"while", u"true", u"false", u"null" }; static bool isValidSymbol(const StringPiece16& symbol) { return sJavaIdentifiers.find(symbol) == sJavaIdentifiers.end(); } /* * Java symbols can not contain . or -, but those are valid in a resource name. * Replace those with '_'. */ static std::u16string transform(const StringPiece16& symbol) { std::u16string output = symbol.toString(); for (char16_t& c : output) { if (c == u'.' || c == u'-') { c = u'_'; } } return output; } bool JavaClassGenerator::skipSymbol(SymbolState state) { switch (mOptions.types) { case JavaClassGeneratorOptions::SymbolTypes::kAll: return false; case JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate: return state == SymbolState::kUndefined; case JavaClassGeneratorOptions::SymbolTypes::kPublic: return state != SymbolState::kPublic; } return true; } void JavaClassGenerator::writeStyleableEntryForClass(ClassDefinitionWriter* outClassDef, AnnotationProcessor* processor, const StringPiece16& packageNameToGenerate, const std::u16string& entryName, const Styleable* styleable) { // This must be sorted by resource ID. std::vector> sortedAttributes; sortedAttributes.reserve(styleable->entries.size()); for (const auto& attr : styleable->entries) { // If we are not encoding final attributes, the styleable entry may have no ID // if we are building a static library. assert((!mOptions.useFinal || attr.id) && "no ID set for Styleable entry"); assert(attr.name && "no name set for Styleable entry"); sortedAttributes.emplace_back(attr.id ? attr.id.value() : ResourceId(0), attr.name.value()); } std::sort(sortedAttributes.begin(), sortedAttributes.end()); auto accessorFunc = [](const std::pair& a) -> ResourceId { return a.first; }; // First we emit the array containing the IDs of each attribute. outClassDef->addArrayMember(transform(entryName), processor, sortedAttributes.begin(), sortedAttributes.end(), accessorFunc); // Now we emit the indices into the array. size_t attrCount = sortedAttributes.size(); for (size_t i = 0; i < attrCount; i++) { std::stringstream name; name << transform(entryName); // We may reference IDs from other packages, so prefix the entry name with // the package. const ResourceNameRef& itemName = sortedAttributes[i].second; if (!itemName.package.empty() && packageNameToGenerate != itemName.package) { name << "_" << transform(itemName.package); } name << "_" << transform(itemName.entry); outClassDef->addIntMember(name.str(), nullptr, i); } } static void addAttributeFormatDoc(AnnotationProcessor* processor, Attribute* attr) { const uint32_t typeMask = attr->typeMask; if (typeMask & android::ResTable_map::TYPE_REFERENCE) { processor->appendComment( "

May be a reference to another resource, in the form\n" "\"@[+][package:]type/name\" or a theme\n" "attribute in the form\n" "\"?[package:]type/name\"."); } if (typeMask & android::ResTable_map::TYPE_STRING) { processor->appendComment( "

May be a string value, using '\\\\;' to escape characters such as\n" "'\\\\n' or '\\\\uxxxx' for a unicode character;"); } if (typeMask & android::ResTable_map::TYPE_INTEGER) { processor->appendComment("

May be an integer value, such as \"100\"."); } if (typeMask & android::ResTable_map::TYPE_BOOLEAN) { processor->appendComment( "

May be a boolean value, such as \"true\" or\n" "\"false\"."); } if (typeMask & android::ResTable_map::TYPE_COLOR) { processor->appendComment( "

May be a color value, in the form of \"#rgb\",\n" "\"#argb\", \"#rrggbb#aarrggbb\"."); } if (typeMask & android::ResTable_map::TYPE_FLOAT) { processor->appendComment( "

May be a floating point value, such as \"1.2\"."); } if (typeMask & android::ResTable_map::TYPE_DIMENSION) { processor->appendComment( "

May be a dimension value, which is a floating point number appended with a\n" "unit such as \"14.5sp\".\n" "Available units are: px (pixels), dp (density-independent pixels),\n" "sp (scaled pixels based on preferred font size), in (inches), and\n" "mm (millimeters)."); } if (typeMask & android::ResTable_map::TYPE_FRACTION) { processor->appendComment( "

May be a fractional value, which is a floating point number appended with\n" "either % or %p, such as \"14.5%\".\n" "The % suffix always means a percentage of the base size;\n" "the optional %p suffix provides a size relative to some parent container."); } if (typeMask & (android::ResTable_map::TYPE_FLAGS | android::ResTable_map::TYPE_ENUM)) { if (typeMask & android::ResTable_map::TYPE_FLAGS) { processor->appendComment( "

Must be one or more (separated by '|') of the following " "constant values.

"); } else { processor->appendComment("

Must be one of the following constant values.

"); } processor->appendComment("\n\n" "\n" "\n" "\n"); for (const Attribute::Symbol& symbol : attr->symbols) { std::stringstream line; line << "" << "" << ""; processor->appendComment(line.str()); } processor->appendComment("
ConstantValueDescription
" << symbol.symbol.name.value().entry << "" << std::hex << symbol.value << std::dec << "" << util::trimWhitespace(symbol.symbol.getComment()) << "
"); } } bool JavaClassGenerator::writeEntriesForClass(ClassDefinitionWriter* outClassDef, const StringPiece16& packageNameToGenerate, const ResourceTablePackage* package, const ResourceTableType* type) { for (const auto& entry : type->entries) { if (skipSymbol(entry->symbolStatus.state)) { continue; } ResourceId id(package->id.value(), type->id.value(), entry->id.value()); assert(id.isValid()); std::u16string unmangledPackage; std::u16string unmangledName = entry->name; if (NameMangler::unmangle(&unmangledName, &unmangledPackage)) { // The entry name was mangled, and we successfully unmangled it. // Check that we want to emit this symbol. if (package->name != unmangledPackage) { // Skip the entry if it doesn't belong to the package we're writing. continue; } } else if (packageNameToGenerate != package->name) { // We are processing a mangled package name, // but this is a non-mangled resource. continue; } if (!isValidSymbol(unmangledName)) { ResourceNameRef resourceName(packageNameToGenerate, type->type, unmangledName); std::stringstream err; err << "invalid symbol name '" << resourceName << "'"; mError = err.str(); return false; } // Build the comments and annotations for this entry. AnnotationProcessor processor; if (entry->symbolStatus.state != SymbolState::kUndefined) { processor.appendComment(entry->symbolStatus.comment); } for (const auto& configValue : entry->values) { processor.appendComment(configValue->value->getComment()); } // If this is an Attribute, append the format Javadoc. if (!entry->values.empty()) { if (Attribute* attr = valueCast(entry->values.front()->value.get())) { // We list out the available values for the given attribute. addAttributeFormatDoc(&processor, attr); } } if (type->type == ResourceType::kStyleable) { assert(!entry->values.empty()); const Styleable* styleable = static_cast( entry->values.front()->value.get()); writeStyleableEntryForClass(outClassDef, &processor, packageNameToGenerate, unmangledName, styleable); } else { outClassDef->addResourceMember(transform(unmangledName), &processor, id); } } return true; } bool JavaClassGenerator::generate(const StringPiece16& packageNameToGenerate, std::ostream* out) { return generate(packageNameToGenerate, packageNameToGenerate, out); } bool JavaClassGenerator::generate(const StringPiece16& packageNameToGenerate, const StringPiece16& outPackageName, std::ostream* out) { generateHeader(outPackageName, out); *out << "public final class R {\n"; for (const auto& package : mTable->packages) { for (const auto& type : package->types) { if (type->type == ResourceType::kAttrPrivate) { continue; } ClassDefinitionWriterOptions classOptions; classOptions.useFinalQualifier = mOptions.useFinal; classOptions.forceCreationIfEmpty = (mOptions.types == JavaClassGeneratorOptions::SymbolTypes::kPublic); ClassDefinitionWriter classDef(toString(type->type), classOptions); bool result = writeEntriesForClass(&classDef, packageNameToGenerate, package.get(), type.get()); if (!result) { return false; } if (type->type == ResourceType::kAttr) { // Also include private attributes in this same class. ResourceTableType* privType = package->findType(ResourceType::kAttrPrivate); if (privType) { result = writeEntriesForClass(&classDef, packageNameToGenerate, package.get(), privType); if (!result) { return false; } } } AnnotationProcessor processor; if (type->type == ResourceType::kStyleable && mOptions.types == JavaClassGeneratorOptions::SymbolTypes::kPublic) { // When generating a public R class, we don't want Styleable to be part of the API. // It is only emitted for documentation purposes. processor.appendComment("@doconly"); } classDef.writeToStream(out, " ", &processor); } } *out << "}\n"; out->flush(); return true; } } // namespace aapt