/* * 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/JavaClassGenerator.h" #include "util/StringPiece.h" #include #include #include #include #include namespace aapt { // The number of attributes to emit per line in a Styleable array. constexpr size_t kAttribsPerLine = 4; 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::generateStyleable(const StringPiece16& packageNameToGenerate, const std::u16string& entryName, const Styleable* styleable, std::ostream* out) { const StringPiece finalModifier = mOptions.useFinal ? " final" : ""; // 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()); // First we emit the array containing the IDs of each attribute. *out << " " << "public static final int[] " << transform(entryName) << " = {"; const size_t attrCount = sortedAttributes.size(); for (size_t i = 0; i < attrCount; i++) { if (i % kAttribsPerLine == 0) { *out << "\n "; } *out << sortedAttributes[i].first; if (i != attrCount - 1) { *out << ", "; } } *out << "\n };\n"; // Now we emit the indices into the array. for (size_t i = 0; i < attrCount; i++) { *out << " " << "public static" << finalModifier << " int " << 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) { *out << "_" << transform(itemName.package); } *out << "_" << transform(itemName.entry) << " = " << i << ";\n"; } } 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::generateType(const StringPiece16& packageNameToGenerate, const ResourceTablePackage* package, const ResourceTableType* type, std::ostream* out) { const StringPiece finalModifier = mOptions.useFinal ? " final" : ""; std::u16string unmangledPackage; std::u16string unmangledName; 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()); 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; } if (type->type == ResourceType::kStyleable) { assert(!entry->values.empty()); generateStyleable(packageNameToGenerate, unmangledName, static_cast( entry->values.front().value.get()), out); } else { 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 (!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); } } std::string comment = processor.buildComment(); if (!comment.empty()) { *out << comment << "\n"; } std::string annotations = processor.buildAnnotations(); if (!annotations.empty()) { *out << annotations << "\n"; } *out << " " << "public static" << finalModifier << " int " << transform(unmangledName) << " = " << id << ";\n"; } } 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) { StringPiece16 typeStr; if (type->type == ResourceType::kAttrPrivate) { typeStr = toString(ResourceType::kAttr); } else { typeStr = toString(type->type); } *out << " public static final class " << typeStr << " {\n"; if (!generateType(packageNameToGenerate, package.get(), type.get(), out)) { return false; } *out << " }\n"; } } *out << "}\n"; out->flush(); return true; } } // namespace aapt