1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "java/JavaClassGenerator.h"
18
19 #include <algorithm>
20 #include <ostream>
21 #include <set>
22 #include <sstream>
23 #include <tuple>
24
25 #include "android-base/errors.h"
26 #include "android-base/logging.h"
27 #include "android-base/stringprintf.h"
28 #include "androidfw/StringPiece.h"
29
30 #include "NameMangler.h"
31 #include "Resource.h"
32 #include "ResourceTable.h"
33 #include "ResourceValues.h"
34 #include "SdkConstants.h"
35 #include "ValueVisitor.h"
36 #include "java/AnnotationProcessor.h"
37 #include "java/ClassDefinition.h"
38 #include "process/SymbolTable.h"
39
40 using ::aapt::io::OutputStream;
41 using ::aapt::text::Printer;
42 using ::android::StringPiece;
43 using ::android::base::StringPrintf;
44
45 namespace aapt {
46
47 static const std::set<StringPiece> sJavaIdentifiers = {
48 "abstract", "assert", "boolean", "break", "byte",
49 "case", "catch", "char", "class", "const",
50 "continue", "default", "do", "double", "else",
51 "enum", "extends", "final", "finally", "float",
52 "for", "goto", "if", "implements", "import",
53 "instanceof", "int", "interface", "long", "native",
54 "new", "package", "private", "protected", "public",
55 "return", "short", "static", "strictfp", "super",
56 "switch", "synchronized", "this", "throw", "throws",
57 "transient", "try", "void", "volatile", "while",
58 "true", "false", "null"};
59
IsValidSymbol(const StringPiece & symbol)60 static bool IsValidSymbol(const StringPiece& symbol) {
61 return sJavaIdentifiers.find(symbol) == sJavaIdentifiers.end();
62 }
63
64 // Java symbols can not contain . or -, but those are valid in a resource name.
65 // Replace those with '_'.
TransformToFieldName(const StringPiece & symbol)66 std::string JavaClassGenerator::TransformToFieldName(const StringPiece& symbol) {
67 std::string output = symbol.to_string();
68 for (char& c : output) {
69 if (c == '.' || c == '-') {
70 c = '_';
71 }
72 }
73 return output;
74 }
75
76 // Transforms an attribute in a styleable to the Java field name:
77 //
78 // <declare-styleable name="Foo">
79 // <attr name="android:bar" />
80 // <attr name="bar" />
81 // </declare-styleable>
82 //
83 // Foo_android_bar
84 // Foo_bar
TransformNestedAttr(const ResourceNameRef & attr_name,const std::string & styleable_class_name,const StringPiece & package_name_to_generate)85 static std::string TransformNestedAttr(const ResourceNameRef& attr_name,
86 const std::string& styleable_class_name,
87 const StringPiece& package_name_to_generate) {
88 std::string output = styleable_class_name;
89
90 // We may reference IDs from other packages, so prefix the entry name with
91 // the package.
92 if (!attr_name.package.empty() &&
93 package_name_to_generate != attr_name.package) {
94 output += "_" + JavaClassGenerator::TransformToFieldName(attr_name.package);
95 }
96 output += "_" + JavaClassGenerator::TransformToFieldName(attr_name.entry);
97 return output;
98 }
99
AddAttributeFormatDoc(AnnotationProcessor * processor,Attribute * attr)100 static void AddAttributeFormatDoc(AnnotationProcessor* processor, Attribute* attr) {
101 const uint32_t type_mask = attr->type_mask;
102 if (type_mask & android::ResTable_map::TYPE_REFERENCE) {
103 processor->AppendComment(
104 "<p>May be a reference to another resource, in the form\n"
105 "\"<code>@[+][<i>package</i>:]<i>type</i>/<i>name</i></code>\" or a "
106 "theme\n"
107 "attribute in the form\n"
108 "\"<code>?[<i>package</i>:]<i>type</i>/<i>name</i></code>\".");
109 }
110
111 if (type_mask & android::ResTable_map::TYPE_STRING) {
112 processor->AppendComment(
113 "<p>May be a string value, using '\\\\;' to escape characters such as\n"
114 "'\\\\n' or '\\\\uxxxx' for a unicode character;");
115 }
116
117 if (type_mask & android::ResTable_map::TYPE_INTEGER) {
118 processor->AppendComment(
119 "<p>May be an integer value, such as \"<code>100</code>\".");
120 }
121
122 if (type_mask & android::ResTable_map::TYPE_BOOLEAN) {
123 processor->AppendComment(
124 "<p>May be a boolean value, such as \"<code>true</code>\" or\n"
125 "\"<code>false</code>\".");
126 }
127
128 if (type_mask & android::ResTable_map::TYPE_COLOR) {
129 processor->AppendComment(
130 "<p>May be a color value, in the form of "
131 "\"<code>#<i>rgb</i></code>\",\n"
132 "\"<code>#<i>argb</i></code>\", \"<code>#<i>rrggbb</i></code>\", or \n"
133 "\"<code>#<i>aarrggbb</i></code>\".");
134 }
135
136 if (type_mask & android::ResTable_map::TYPE_FLOAT) {
137 processor->AppendComment(
138 "<p>May be a floating point value, such as \"<code>1.2</code>\".");
139 }
140
141 if (type_mask & android::ResTable_map::TYPE_DIMENSION) {
142 processor->AppendComment(
143 "<p>May be a dimension value, which is a floating point number "
144 "appended with a\n"
145 "unit such as \"<code>14.5sp</code>\".\n"
146 "Available units are: px (pixels), dp (density-independent pixels),\n"
147 "sp (scaled pixels based on preferred font size), in (inches), and\n"
148 "mm (millimeters).");
149 }
150
151 if (type_mask & android::ResTable_map::TYPE_FRACTION) {
152 processor->AppendComment(
153 "<p>May be a fractional value, which is a floating point number "
154 "appended with\n"
155 "either % or %p, such as \"<code>14.5%</code>\".\n"
156 "The % suffix always means a percentage of the base size;\n"
157 "the optional %p suffix provides a size relative to some parent "
158 "container.");
159 }
160
161 if (type_mask &
162 (android::ResTable_map::TYPE_FLAGS | android::ResTable_map::TYPE_ENUM)) {
163 if (type_mask & android::ResTable_map::TYPE_FLAGS) {
164 processor->AppendComment(
165 "<p>Must be one or more (separated by '|') of the following "
166 "constant values.</p>");
167 } else {
168 processor->AppendComment(
169 "<p>Must be one of the following constant values.</p>");
170 }
171
172 processor->AppendComment(
173 "<table>\n<colgroup align=\"left\" />\n"
174 "<colgroup align=\"left\" />\n"
175 "<colgroup align=\"left\" />\n"
176 "<tr><th>Constant</th><th>Value</th><th>Description</th></tr>\n");
177 for (const Attribute::Symbol& symbol : attr->symbols) {
178 std::stringstream line;
179 line << "<tr><td>" << symbol.symbol.name.value().entry << "</td>"
180 << "<td>" << std::hex << symbol.value << std::dec << "</td>"
181 << "<td>" << util::TrimWhitespace(symbol.symbol.GetComment())
182 << "</td></tr>";
183 processor->AppendComment(line.str());
184 }
185 processor->AppendComment("</table>");
186 }
187 }
188
JavaClassGenerator(IAaptContext * context,ResourceTable * table,const JavaClassGeneratorOptions & options)189 JavaClassGenerator::JavaClassGenerator(IAaptContext* context,
190 ResourceTable* table,
191 const JavaClassGeneratorOptions& options)
192 : context_(context), table_(table), options_(options) {}
193
SkipSymbol(Visibility::Level level)194 bool JavaClassGenerator::SkipSymbol(Visibility::Level level) {
195 switch (options_.types) {
196 case JavaClassGeneratorOptions::SymbolTypes::kAll:
197 return false;
198 case JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate:
199 return level == Visibility::Level::kUndefined;
200 case JavaClassGeneratorOptions::SymbolTypes::kPublic:
201 return level != Visibility::Level::kPublic;
202 }
203 return true;
204 }
205
206 // Whether or not to skip writing this symbol.
SkipSymbol(const Maybe<SymbolTable::Symbol> & symbol)207 bool JavaClassGenerator::SkipSymbol(const Maybe<SymbolTable::Symbol>& symbol) {
208 return !symbol || (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic &&
209 !symbol.value().is_public);
210 }
211
212 struct StyleableAttr {
213 const Reference* attr_ref = nullptr;
214 std::string field_name;
215 Maybe<SymbolTable::Symbol> symbol;
216 };
217
operator <(const StyleableAttr & lhs,const StyleableAttr & rhs)218 static bool operator<(const StyleableAttr& lhs, const StyleableAttr& rhs) {
219 const ResourceId lhs_id = lhs.attr_ref->id.value_or_default(ResourceId(0));
220 const ResourceId rhs_id = rhs.attr_ref->id.value_or_default(ResourceId(0));
221 if (lhs_id < rhs_id) {
222 return true;
223 } else if (lhs_id > rhs_id) {
224 return false;
225 } else {
226 return lhs.attr_ref->name.value() < rhs.attr_ref->name.value();
227 }
228 }
229
ProcessStyleable(const ResourceNameRef & name,const ResourceId & id,const Styleable & styleable,const StringPiece & package_name_to_generate,ClassDefinition * out_class_def,MethodDefinition * out_rewrite_method,Printer * r_txt_printer)230 void JavaClassGenerator::ProcessStyleable(const ResourceNameRef& name, const ResourceId& id,
231 const Styleable& styleable,
232 const StringPiece& package_name_to_generate,
233 ClassDefinition* out_class_def,
234 MethodDefinition* out_rewrite_method,
235 Printer* r_txt_printer) {
236 const std::string array_field_name = TransformToFieldName(name.entry);
237 std::unique_ptr<ResourceArrayMember> array_def =
238 util::make_unique<ResourceArrayMember>(array_field_name);
239
240 // The array must be sorted by resource ID.
241 std::vector<StyleableAttr> sorted_attributes;
242 sorted_attributes.reserve(styleable.entries.size());
243 for (const auto& attr : styleable.entries) {
244 // If we are not encoding final attributes, the styleable entry may have no
245 // ID if we are building a static library.
246 CHECK(!options_.use_final || attr.id) << "no ID set for Styleable entry";
247 CHECK(bool(attr.name)) << "no name set for Styleable entry";
248
249 // We will need the unmangled, transformed name in the comments and the field,
250 // so create it once and cache it in this StyleableAttr data structure.
251 StyleableAttr styleable_attr;
252 styleable_attr.attr_ref = &attr;
253
254 // The field name for this attribute is prefixed by the name of this styleable and
255 // the package it comes from.
256 styleable_attr.field_name =
257 TransformNestedAttr(attr.name.value(), array_field_name, package_name_to_generate);
258
259 Reference ref = attr;
260 if (attr.name.value().package.empty()) {
261
262 // If the resource does not have a package name, set the package to the unmangled package name
263 // of the styleable declaration because attributes without package names would have been
264 // declared in the same package as the styleable.
265 ref.name = ResourceName(package_name_to_generate, ref.name.value().type,
266 ref.name.value().entry);
267 }
268
269 // Look up the symbol so that we can write out in the comments what are possible legal values
270 // for this attribute.
271 const SymbolTable::Symbol* symbol = context_->GetExternalSymbols()->FindByReference(ref);
272
273 if (symbol && symbol->attribute) {
274 // Copy the symbol data structure because the returned instance can be destroyed.
275 styleable_attr.symbol = *symbol;
276 }
277 sorted_attributes.push_back(std::move(styleable_attr));
278 }
279
280 // Sort the attributes by ID.
281 std::sort(sorted_attributes.begin(), sorted_attributes.end());
282
283 // Build the JavaDoc comment for the Styleable array. This has references to child attributes
284 // and what possible values can be used for them.
285 const size_t attr_count = sorted_attributes.size();
286 if (out_class_def != nullptr && attr_count > 0) {
287 std::stringstream styleable_comment;
288 if (!styleable.GetComment().empty()) {
289 styleable_comment << styleable.GetComment() << "\n";
290 } else {
291 // Apply a default intro comment if the styleable has no comments of its own.
292 styleable_comment << "Attributes that can be used with a " << array_field_name << ".\n";
293 }
294
295 styleable_comment << "<p>Includes the following attributes:</p>\n"
296 "<table>\n"
297 "<colgroup align=\"left\" />\n"
298 "<colgroup align=\"left\" />\n"
299 "<tr><th>Attribute</th><th>Description</th></tr>\n";
300
301 // Removed and hidden attributes are public but hidden from the documentation, so don't emit
302 // them as part of the class documentation.
303 std::vector<StyleableAttr> documentation_attrs = sorted_attributes;
304 auto documentation_remove_iter = std::remove_if(documentation_attrs.begin(),
305 documentation_attrs.end(),
306 [&](StyleableAttr entry) -> bool {
307 if (SkipSymbol(entry.symbol)) {
308 return true;
309 }
310 const StringPiece attr_comment_line = entry.symbol.value().attribute->GetComment();
311 return attr_comment_line.contains("@removed") || attr_comment_line.contains("@hide");
312 });
313 documentation_attrs.erase(documentation_remove_iter, documentation_attrs.end());
314
315 // Build the table of attributes with their links and names.
316 for (const StyleableAttr& entry : documentation_attrs) {
317 const ResourceName& attr_name = entry.attr_ref->name.value();
318 styleable_comment << "<tr><td><code>{@link #" << entry.field_name << " "
319 << (!attr_name.package.empty() ? attr_name.package
320 : package_name_to_generate)
321 << ":" << attr_name.entry << "}</code></td>";
322
323 // Only use the comment up until the first '.'. This is to stay compatible with
324 // the way old AAPT did it (presumably to keep it short and to avoid including
325 // annotations like @hide which would affect this Styleable).
326 StringPiece attr_comment_line = entry.symbol.value().attribute->GetComment();
327 styleable_comment << "<td>" << AnnotationProcessor::ExtractFirstSentence(attr_comment_line)
328 << "</td></tr>\n";
329 }
330 styleable_comment << "</table>\n";
331
332 // Generate the @see lines for each attribute.
333 for (const StyleableAttr& entry : documentation_attrs) {
334 styleable_comment << "@see #" << entry.field_name << "\n";
335 }
336
337 array_def->GetCommentBuilder()->AppendComment(styleable_comment.str());
338 }
339
340 if (r_txt_printer != nullptr) {
341 r_txt_printer->Print("int[] styleable ").Print(array_field_name).Print(" {");
342 }
343
344 // Add the ResourceIds to the array member.
345 for (size_t i = 0; i < attr_count; i++) {
346 const ResourceId id = sorted_attributes[i].attr_ref->id.value_or_default(ResourceId(0));
347 array_def->AddElement(id);
348
349 if (r_txt_printer != nullptr) {
350 if (i != 0) {
351 r_txt_printer->Print(",");
352 }
353 r_txt_printer->Print(" ").Print(id.to_string());
354 }
355 }
356
357 if (r_txt_printer != nullptr) {
358 r_txt_printer->Println(" }");
359 }
360
361 // Add the Styleable array to the Styleable class.
362 if (out_class_def != nullptr) {
363 out_class_def->AddMember(std::move(array_def));
364 }
365
366 // Now we emit the indices into the array.
367 for (size_t i = 0; i < attr_count; i++) {
368 const StyleableAttr& styleable_attr = sorted_attributes[i];
369 if (SkipSymbol(styleable_attr.symbol)) {
370 continue;
371 }
372
373 if (out_class_def != nullptr) {
374 StringPiece comment = styleable_attr.attr_ref->GetComment();
375 if (styleable_attr.symbol.value().attribute && comment.empty()) {
376 comment = styleable_attr.symbol.value().attribute->GetComment();
377 }
378
379 if (comment.contains("@removed")) {
380 // Removed attributes are public but hidden from the documentation, so
381 // don't emit them as part of the class documentation.
382 continue;
383 }
384
385 const ResourceName& attr_name = styleable_attr.attr_ref->name.value();
386
387 StringPiece package_name = attr_name.package;
388 if (package_name.empty()) {
389 package_name = package_name_to_generate;
390 }
391
392 std::unique_ptr<IntMember> index_member =
393 util::make_unique<IntMember>(sorted_attributes[i].field_name, static_cast<uint32_t>(i));
394
395 AnnotationProcessor* attr_processor = index_member->GetCommentBuilder();
396
397 if (!comment.empty()) {
398 attr_processor->AppendComment("<p>\n@attr description");
399 attr_processor->AppendComment(comment);
400 } else {
401 std::stringstream default_comment;
402 default_comment << "<p>This symbol is the offset where the "
403 << "{@link " << package_name << ".R.attr#"
404 << TransformToFieldName(attr_name.entry) << "}\n"
405 << "attribute's value can be found in the "
406 << "{@link #" << array_field_name << "} array.";
407 attr_processor->AppendComment(default_comment.str());
408 }
409
410 attr_processor->AppendNewLine();
411 AddAttributeFormatDoc(attr_processor, styleable_attr.symbol.value().attribute.get());
412 attr_processor->AppendNewLine();
413 attr_processor->AppendComment(
414 StringPrintf("@attr name %s:%s", package_name.data(), attr_name.entry.data()));
415
416 out_class_def->AddMember(std::move(index_member));
417 }
418
419 if (r_txt_printer != nullptr) {
420 r_txt_printer->Println(
421 StringPrintf("int styleable %s %zd", sorted_attributes[i].field_name.c_str(), i));
422 }
423 }
424
425 // If there is a rewrite method to generate, add the statements that rewrite package IDs
426 // for this styleable.
427 if (out_rewrite_method != nullptr) {
428 out_rewrite_method->AppendStatement(
429 StringPrintf("for (int i = 0; i < styleable.%s.length; i++) {", array_field_name.data()));
430 out_rewrite_method->AppendStatement(
431 StringPrintf(" if ((styleable.%s[i] & 0xff000000) == 0) {", array_field_name.data()));
432 out_rewrite_method->AppendStatement(
433 StringPrintf(" styleable.%s[i] = (styleable.%s[i] & 0x00ffffff) | packageIdBits;",
434 array_field_name.data(), array_field_name.data()));
435 out_rewrite_method->AppendStatement(" }");
436 out_rewrite_method->AppendStatement("}");
437 }
438 }
439
ProcessResource(const ResourceNameRef & name,const ResourceId & id,const ResourceEntry & entry,ClassDefinition * out_class_def,MethodDefinition * out_rewrite_method,text::Printer * r_txt_printer)440 void JavaClassGenerator::ProcessResource(const ResourceNameRef& name, const ResourceId& id,
441 const ResourceEntry& entry, ClassDefinition* out_class_def,
442 MethodDefinition* out_rewrite_method,
443 text::Printer* r_txt_printer) {
444 ResourceId real_id = id;
445 if (context_->GetMinSdkVersion() < SDK_O && name.type == ResourceType::kId &&
446 id.package_id() > kAppPackageId) {
447 // Workaround for feature splits using package IDs > 0x7F.
448 // See b/37498913.
449 real_id = ResourceId(kAppPackageId, id.package_id(), id.entry_id());
450 }
451
452 const std::string field_name = TransformToFieldName(name.entry);
453 if (out_class_def != nullptr) {
454 std::unique_ptr<ResourceMember> resource_member =
455 util::make_unique<ResourceMember>(field_name, real_id);
456
457 // Build the comments and annotations for this entry.
458 AnnotationProcessor* processor = resource_member->GetCommentBuilder();
459
460 // Add the comments from any <public> tags.
461 if (entry.visibility.level != Visibility::Level::kUndefined) {
462 processor->AppendComment(entry.visibility.comment);
463 }
464
465 // Add the comments from all configurations of this entry.
466 for (const auto& config_value : entry.values) {
467 processor->AppendComment(config_value->value->GetComment());
468 }
469
470 // If this is an Attribute, append the format Javadoc.
471 if (!entry.values.empty()) {
472 if (Attribute* attr = ValueCast<Attribute>(entry.values.front()->value.get())) {
473 // We list out the available values for the given attribute.
474 AddAttributeFormatDoc(processor, attr);
475 }
476 }
477
478 out_class_def->AddMember(std::move(resource_member));
479 }
480
481 if (r_txt_printer != nullptr) {
482 r_txt_printer->Print("int ")
483 .Print(to_string(name.type))
484 .Print(" ")
485 .Print(field_name)
486 .Print(" ")
487 .Println(real_id.to_string());
488 }
489
490 if (out_rewrite_method != nullptr) {
491 const StringPiece& type_str = to_string(name.type);
492 out_rewrite_method->AppendStatement(
493 StringPrintf("%s.%s = (%s.%s & 0x00ffffff) | packageIdBits;", type_str.data(),
494 field_name.data(), type_str.data(), field_name.data()));
495 }
496 }
497
UnmangleResource(const StringPiece & package_name,const StringPiece & package_name_to_generate,const ResourceEntry & entry)498 Maybe<std::string> JavaClassGenerator::UnmangleResource(const StringPiece& package_name,
499 const StringPiece& package_name_to_generate,
500 const ResourceEntry& entry) {
501 if (SkipSymbol(entry.visibility.level)) {
502 return {};
503 }
504
505 std::string unmangled_package;
506 std::string unmangled_name = entry.name;
507 if (NameMangler::Unmangle(&unmangled_name, &unmangled_package)) {
508 // The entry name was mangled, and we successfully unmangled it.
509 // Check that we want to emit this symbol.
510 if (package_name_to_generate != unmangled_package) {
511 // Skip the entry if it doesn't belong to the package we're writing.
512 return {};
513 }
514 } else if (package_name_to_generate != package_name) {
515 // We are processing a mangled package name,
516 // but this is a non-mangled resource.
517 return {};
518 }
519 return {std::move(unmangled_name)};
520 }
521
ProcessType(const StringPiece & package_name_to_generate,const ResourceTablePackage & package,const ResourceTableType & type,ClassDefinition * out_type_class_def,MethodDefinition * out_rewrite_method_def,Printer * r_txt_printer)522 bool JavaClassGenerator::ProcessType(const StringPiece& package_name_to_generate,
523 const ResourceTablePackage& package,
524 const ResourceTableType& type,
525 ClassDefinition* out_type_class_def,
526 MethodDefinition* out_rewrite_method_def,
527 Printer* r_txt_printer) {
528 for (const auto& entry : type.entries) {
529 const Maybe<std::string> unmangled_name =
530 UnmangleResource(package.name, package_name_to_generate, *entry);
531 if (!unmangled_name) {
532 continue;
533 }
534
535 // Create an ID if there is one (static libraries don't need one).
536 ResourceId id;
537 if (package.id && type.id && entry->id) {
538 id = ResourceId(package.id.value(), type.id.value(), entry->id.value());
539 }
540
541 // We need to make sure we hide the fact that we are generating kAttrPrivate attributes.
542 const ResourceNameRef resource_name(
543 package_name_to_generate,
544 type.type == ResourceType::kAttrPrivate ? ResourceType::kAttr : type.type,
545 unmangled_name.value());
546
547 // Check to see if the unmangled name is a valid Java name (not a keyword).
548 if (!IsValidSymbol(unmangled_name.value())) {
549 std::stringstream err;
550 err << "invalid symbol name '" << resource_name << "'";
551 error_ = err.str();
552 return false;
553 }
554
555 if (resource_name.type == ResourceType::kStyleable) {
556 CHECK(!entry->values.empty());
557
558 const Styleable* styleable =
559 static_cast<const Styleable*>(entry->values.front()->value.get());
560
561 ProcessStyleable(resource_name, id, *styleable, package_name_to_generate, out_type_class_def,
562 out_rewrite_method_def, r_txt_printer);
563 } else {
564 ProcessResource(resource_name, id, *entry, out_type_class_def, out_rewrite_method_def,
565 r_txt_printer);
566 }
567 }
568 return true;
569 }
570
Generate(const StringPiece & package_name_to_generate,OutputStream * out,OutputStream * out_r_txt)571 bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate, OutputStream* out,
572 OutputStream* out_r_txt) {
573 return Generate(package_name_to_generate, package_name_to_generate, out, out_r_txt);
574 }
575
AppendJavaDocAnnotations(const std::vector<std::string> & annotations,AnnotationProcessor * processor)576 static void AppendJavaDocAnnotations(const std::vector<std::string>& annotations,
577 AnnotationProcessor* processor) {
578 for (const std::string& annotation : annotations) {
579 std::string proper_annotation = "@";
580 proper_annotation += annotation;
581 processor->AppendComment(proper_annotation);
582 }
583 }
584
Generate(const StringPiece & package_name_to_generate,const StringPiece & out_package_name,OutputStream * out,OutputStream * out_r_txt)585 bool JavaClassGenerator::Generate(const StringPiece& package_name_to_generate,
586 const StringPiece& out_package_name, OutputStream* out,
587 OutputStream* out_r_txt) {
588 ClassDefinition r_class("R", ClassQualifier::kNone, true);
589 std::unique_ptr<MethodDefinition> rewrite_method;
590
591 std::unique_ptr<Printer> r_txt_printer;
592 if (out_r_txt != nullptr) {
593 r_txt_printer = util::make_unique<Printer>(out_r_txt);
594 }
595 // Generate an onResourcesLoaded() callback if requested.
596 if (out != nullptr && options_.rewrite_callback_options) {
597 rewrite_method =
598 util::make_unique<MethodDefinition>("public static void onResourcesLoaded(int p)");
599 for (const std::string& package_to_callback :
600 options_.rewrite_callback_options.value().packages_to_callback) {
601 rewrite_method->AppendStatement(
602 StringPrintf("%s.R.onResourcesLoaded(p);", package_to_callback.data()));
603 }
604 rewrite_method->AppendStatement("final int packageIdBits = p << 24;");
605 }
606
607 for (const auto& package : table_->packages) {
608 for (const auto& type : package->types) {
609 if (type->type == ResourceType::kAttrPrivate) {
610 // We generate these as part of the kAttr type, so skip them here.
611 continue;
612 }
613
614 // Stay consistent with AAPT and generate an empty type class if the R class is public.
615 const bool force_creation_if_empty =
616 (options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic);
617
618 std::unique_ptr<ClassDefinition> class_def;
619 if (out != nullptr) {
620 class_def = util::make_unique<ClassDefinition>(
621 to_string(type->type), ClassQualifier::kStatic, force_creation_if_empty);
622 }
623
624 if (!ProcessType(package_name_to_generate, *package, *type, class_def.get(),
625 rewrite_method.get(), r_txt_printer.get())) {
626 return false;
627 }
628
629 if (type->type == ResourceType::kAttr) {
630 // Also include private attributes in this same class.
631 const ResourceTableType* priv_type = package->FindType(ResourceType::kAttrPrivate);
632 if (priv_type) {
633 if (!ProcessType(package_name_to_generate, *package, *priv_type, class_def.get(),
634 rewrite_method.get(), r_txt_printer.get())) {
635 return false;
636 }
637 }
638 }
639
640 if (out != nullptr && type->type == ResourceType::kStyleable &&
641 options_.types == JavaClassGeneratorOptions::SymbolTypes::kPublic) {
642 // When generating a public R class, we don't want Styleable to be part
643 // of the API. It is only emitted for documentation purposes.
644 class_def->GetCommentBuilder()->AppendComment("@doconly");
645 }
646
647 if (out != nullptr) {
648 AppendJavaDocAnnotations(options_.javadoc_annotations, class_def->GetCommentBuilder());
649 r_class.AddMember(std::move(class_def));
650 }
651 }
652 }
653
654 if (rewrite_method != nullptr) {
655 r_class.AddMember(std::move(rewrite_method));
656 }
657
658 if (out != nullptr) {
659 AppendJavaDocAnnotations(options_.javadoc_annotations, r_class.GetCommentBuilder());
660 ClassDefinition::WriteJavaFile(&r_class, out_package_name, options_.use_final, out);
661 }
662 return true;
663 }
664
665 } // namespace aapt
666