diff options
Diffstat (limited to 'tools/aapt2/java/JavaClassGenerator.cpp')
-rw-r--r-- | tools/aapt2/java/JavaClassGenerator.cpp | 336 |
1 files changed, 336 insertions, 0 deletions
diff --git a/tools/aapt2/java/JavaClassGenerator.cpp b/tools/aapt2/java/JavaClassGenerator.cpp new file mode 100644 index 000000000000..dfd2ef6f5372 --- /dev/null +++ b/tools/aapt2/java/JavaClassGenerator.cpp @@ -0,0 +1,336 @@ +/* + * 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 <algorithm> +#include <ostream> +#include <set> +#include <sstream> +#include <tuple> + +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<StringPiece16> 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<std::pair<ResourceId, ResourceNameRef>> 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( + "<p>May be a reference to another resource, in the form\n" + "\"<code>@[+][<i>package</i>:]<i>type</i>/<i>name</i></code>\" or a theme\n" + "attribute in the form\n" + "\"<code>?[<i>package</i>:]<i>type</i>/<i>name</i></code>\"."); + } + + if (typeMask & android::ResTable_map::TYPE_STRING) { + processor->appendComment( + "<p>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("<p>May be an integer value, such as \"<code>100</code>\"."); + } + + if (typeMask & android::ResTable_map::TYPE_BOOLEAN) { + processor->appendComment( + "<p>May be a boolean value, such as \"<code>true</code>\" or\n" + "\"<code>false</code>\"."); + } + + if (typeMask & android::ResTable_map::TYPE_COLOR) { + processor->appendComment( + "<p>May be a color value, in the form of \"<code>#<i>rgb</i></code>\",\n" + "\"<code>#<i>argb</i></code>\", \"<code>#<i>rrggbb</i></code\", or \n" + "\"<code>#<i>aarrggbb</i></code>\"."); + } + + if (typeMask & android::ResTable_map::TYPE_FLOAT) { + processor->appendComment( + "<p>May be a floating point value, such as \"<code>1.2</code>\"."); + } + + if (typeMask & android::ResTable_map::TYPE_DIMENSION) { + processor->appendComment( + "<p>May be a dimension value, which is a floating point number appended with a\n" + "unit such as \"<code>14.5sp</code>\".\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( + "<p>May be a fractional value, which is a floating point number appended with\n" + "either % or %p, such as \"<code>14.5%</code>\".\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( + "<p>Must be one or more (separated by '|') of the following " + "constant values.</p>"); + } else { + processor->appendComment("<p>Must be one of the following constant values.</p>"); + } + + processor->appendComment("<table>\n<colgroup align=\"left\" />\n" + "<colgroup align=\"left\" />\n" + "<colgroup align=\"left\" />\n" + "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n"); + for (const Attribute::Symbol& symbol : attr->symbols) { + std::stringstream line; + line << "<tr><td>" << symbol.symbol.name.value().entry << "</td>" + << "<td>" << std::hex << symbol.value << std::dec << "</td>" + << "<td>" << util::trimWhitespace(symbol.symbol.getComment()) << "</td></tr>"; + processor->appendComment(line.str()); + } + processor->appendComment("</table>"); + } +} + +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<const Styleable*>( + 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<Attribute>(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 |