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 #ifndef AAPT_RESOURCEUTILS_H 18 #define AAPT_RESOURCEUTILS_H 19 20 #include <functional> 21 #include <memory> 22 23 #include "androidfw/AssetManager2.h" 24 #include "androidfw/ConfigDescription.h" 25 #include "androidfw/ResourceTypes.h" 26 #include "androidfw/StringPiece.h" 27 28 #include "NameMangler.h" 29 #include "Resource.h" 30 #include "ResourceValues.h" 31 #include "StringPool.h" 32 33 namespace aapt { 34 namespace ResourceUtils { 35 36 /** 37 * Returns true if the string was parsed as a resource name 38 * ([*][package:]type/name), with 39 * `out_resource` set to the parsed resource name and `out_private` set to true 40 * if a '*' prefix was present. 41 */ 42 bool ParseResourceName(const android::StringPiece& str, ResourceNameRef* out_resource, 43 bool* out_private = nullptr); 44 45 /* 46 * Returns true if the string was parsed as a reference 47 * (@[+][package:]type/name), with 48 * `out_reference` set to the parsed reference. 49 * 50 * If '+' was present in the reference, `out_create` is set to true. 51 * If '*' was present in the reference, `out_private` is set to true. 52 */ 53 bool ParseReference(const android::StringPiece& str, ResourceNameRef* out_reference, 54 bool* out_create = nullptr, bool* out_private = nullptr); 55 56 /* 57 * Returns true if the string is in the form of a resource reference 58 * (@[+][package:]type/name). 59 */ 60 bool IsReference(const android::StringPiece& str); 61 62 /* 63 * Returns true if the string was parsed as an attribute reference 64 * (?[package:][type/]name), 65 * with `out_reference` set to the parsed reference. 66 */ 67 bool ParseAttributeReference(const android::StringPiece& str, ResourceNameRef* out_reference); 68 69 /** 70 * Returns true if the string is in the form of an attribute 71 * reference(?[package:][type/]name). 72 */ 73 bool IsAttributeReference(const android::StringPiece& str); 74 75 /** 76 * Convert an android::ResTable::resource_name to an aapt::ResourceName struct. 77 */ 78 std::optional<ResourceName> ToResourceName(const android::ResTable::resource_name& name); 79 80 /** 81 * Convert an android::AssetManager2::ResourceName to an aapt::ResourceName struct. 82 */ 83 std::optional<ResourceName> ToResourceName(const android::AssetManager2::ResourceName& name_in); 84 85 /** 86 * Returns a boolean value if the string is equal to TRUE, true, True, FALSE, 87 * false, or False. 88 */ 89 std::optional<bool> ParseBool(const android::StringPiece& str); 90 91 /** 92 * Returns a uint32_t if the string is an integer. 93 */ 94 std::optional<uint32_t> ParseInt(const android::StringPiece& str); 95 96 /** 97 * Returns an ID if it the string represented a valid ID. 98 */ 99 std::optional<ResourceId> ParseResourceId(const android::StringPiece& str); 100 101 /** 102 * Parses an SDK version, which can be an integer, or a letter from A-Z. 103 */ 104 std::optional<int> ParseSdkVersion(const android::StringPiece& str); 105 106 /* 107 * Returns a Reference, or None Maybe instance if the string `str` was parsed as 108 * a 109 * valid reference to a style. 110 * The format for a style parent is slightly more flexible than a normal 111 * reference: 112 * 113 * @[package:]style/<entry> or 114 * ?[package:]style/<entry> or 115 * <package>:[style/]<entry> 116 */ 117 std::optional<Reference> ParseStyleParentReference(const android::StringPiece& str, 118 std::string* out_error); 119 120 /* 121 * Returns a Reference if the string `str` was parsed as a valid XML attribute 122 * name. 123 * The valid format for an XML attribute name is: 124 * 125 * package:entry 126 */ 127 std::optional<Reference> ParseXmlAttributeName(const android::StringPiece& str); 128 129 /* 130 * Returns a Reference object if the string was parsed as a resource or 131 * attribute reference, 132 * ( @[+][package:]type/name | ?[package:]type/name ) setting outCreate to true 133 * if 134 * the '+' was present in the string. 135 */ 136 std::unique_ptr<Reference> TryParseReference(const android::StringPiece& str, 137 bool* out_create = nullptr); 138 139 /* 140 * Returns a BinaryPrimitve object representing @null or @empty if the string 141 * was parsed as one. 142 */ 143 std::unique_ptr<Item> TryParseNullOrEmpty(const android::StringPiece& str); 144 145 // Returns a Reference representing @null. 146 // Due to runtime compatibility issues, this is encoded as a reference with ID 0. 147 // The runtime will convert this to TYPE_NULL. 148 std::unique_ptr<Reference> MakeNull(); 149 150 // Returns a BinaryPrimitive representing @empty. This is encoded as a Res_value with 151 // type Res_value::TYPE_NULL and data Res_value::DATA_NULL_EMPTY. 152 std::unique_ptr<BinaryPrimitive> MakeEmpty(); 153 154 /* 155 * Returns a BinaryPrimitve object representing a color if the string was parsed 156 * as one. 157 */ 158 std::unique_ptr<BinaryPrimitive> TryParseColor(const android::StringPiece& str); 159 160 /* 161 * Returns a BinaryPrimitve object representing a boolean if the string was 162 * parsed as one. 163 */ 164 std::unique_ptr<BinaryPrimitive> TryParseBool(const android::StringPiece& str); 165 166 // Returns a boolean BinaryPrimitive. 167 std::unique_ptr<BinaryPrimitive> MakeBool(bool val); 168 169 /* 170 * Returns a BinaryPrimitve object representing an integer if the string was 171 * parsed as one. 172 */ 173 std::unique_ptr<BinaryPrimitive> TryParseInt(const android::StringPiece& str); 174 175 // Returns an integer BinaryPrimitive. 176 std::unique_ptr<BinaryPrimitive> MakeInt(uint32_t value); 177 178 /* 179 * Returns a BinaryPrimitve object representing a floating point number 180 * (float, dimension, etc) if the string was parsed as one. 181 */ 182 std::unique_ptr<BinaryPrimitive> TryParseFloat(const android::StringPiece& str); 183 184 /* 185 * Returns a BinaryPrimitve object representing an enum symbol if the string was 186 * parsed as one. 187 */ 188 std::unique_ptr<BinaryPrimitive> TryParseEnumSymbol(const Attribute* enum_attr, 189 const android::StringPiece& str); 190 191 /* 192 * Returns a BinaryPrimitve object representing a flag symbol if the string was 193 * parsed as one. 194 */ 195 std::unique_ptr<BinaryPrimitive> TryParseFlagSymbol(const Attribute* enum_attr, 196 const android::StringPiece& str); 197 /* 198 * Try to convert a string to an Item for the given attribute. The attribute 199 * will 200 * restrict what values the string can be converted to. 201 * The callback function on_create_reference is called when the parsed item is a 202 * reference to an ID that must be created (@+id/foo). 203 */ 204 std::unique_ptr<Item> TryParseItemForAttribute( 205 const android::StringPiece& value, const Attribute* attr, 206 const std::function<bool(const ResourceName&)>& on_create_reference = {}); 207 208 std::unique_ptr<Item> TryParseItemForAttribute( 209 const android::StringPiece& value, uint32_t type_mask, 210 const std::function<bool(const ResourceName&)>& on_create_reference = {}); 211 212 uint32_t AndroidTypeToAttributeTypeMask(uint16_t type); 213 214 /** 215 * Returns a string path suitable for use within an APK. The path will look 216 * like: 217 * 218 * res/type[-config]/<name>.<ext> 219 * 220 * Then name may be mangled if a NameMangler is supplied (can be nullptr) and 221 * the package 222 * requires mangling. 223 */ 224 std::string BuildResourceFileName(const ResourceFile& res_file, 225 const NameMangler* mangler = nullptr); 226 227 // Parses the binary form of a resource value. `type` is used as a hint to know when a value is 228 // an ID versus a False boolean value, etc. `config` is for sorting strings in the string pool. 229 std::unique_ptr<Item> ParseBinaryResValue(const ResourceType& type, 230 const android::ConfigDescription& config, 231 const android::ResStringPool& src_pool, 232 const android::Res_value& res_value, 233 StringPool* dst_pool); 234 235 // A string flattened from an XML hierarchy, which maintains tags and untranslatable sections 236 // in parallel data structures. 237 struct FlattenedXmlString { 238 std::string text; 239 std::vector<UntranslatableSection> untranslatable_sections; 240 std::vector<Span> spans; 241 }; 242 243 // Flattens an XML hierarchy into a FlattenedXmlString, formatting the text, escaping characters, 244 // and removing whitespace, all while keeping the untranslatable sections and spans in sync with the 245 // transformations. 246 // 247 // Specifically, the StringBuilder will handle escaped characters like \t, \n, \\, \', etc. 248 // Single quotes *must* be escaped, unless within a pair of double-quotes. 249 // Pairs of double-quotes disable whitespace stripping of the enclosed text. 250 // Unicode escape codes (\u0049) are interpreted and the represented Unicode character is inserted. 251 // 252 // A NOTE ON WHITESPACE: 253 // 254 // When preserve_spaces is false, and when text is not enclosed within double-quotes, 255 // StringBuilder replaces a series of whitespace with a single space character. This happens at the 256 // start and end of the string as well, so leading and trailing whitespace is possible. 257 // 258 // When a Span is started or stopped, the whitespace counter is reset, meaning if whitespace 259 // is encountered directly after the span, it will be emitted. This leads to situations like the 260 // following: "This <b> is </b> spaced" -> "This is spaced". Without spans, this would be properly 261 // compressed: "This is spaced" -> "This is spaced". 262 // 263 // Untranslatable sections do not have the same problem: 264 // "This <xliff:g> is </xliff:g> not spaced" -> "This is not spaced". 265 // 266 // NOTE: This is all the way it is because AAPT1 did it this way. Maintaining backwards 267 // compatibility is important. 268 // 269 class StringBuilder { 270 public: 271 using SpanHandle = size_t; 272 using UntranslatableHandle = size_t; 273 274 // Creates a StringBuilder. If preserve_spaces is true, whitespace removal is not performed, and 275 // single quotations can be used without escaping them. 276 explicit StringBuilder(bool preserve_spaces = false); 277 278 // Appends a chunk of text. 279 StringBuilder& AppendText(const std::string& text); 280 281 // Starts a Span (tag) with the given name. The name is expected to be of the form: 282 // "tag_name;attr1=value;attr2=value;" 283 // Which is how Spans are encoded in the ResStringPool. 284 // To end the span, pass back the SpanHandle received from this method to the EndSpan() method. 285 SpanHandle StartSpan(const std::string& name); 286 287 // Ends a Span (tag). Pass in the matching SpanHandle previously obtained from StartSpan(). 288 void EndSpan(SpanHandle handle); 289 290 // Starts an Untranslatable section. 291 // To end the section, pass back the UntranslatableHandle received from this method to 292 // the EndUntranslatable() method. 293 UntranslatableHandle StartUntranslatable(); 294 295 // Ends an Untranslatable section. Pass in the matching UntranslatableHandle previously obtained 296 // from StartUntranslatable(). 297 void EndUntranslatable(UntranslatableHandle handle); 298 299 // Returns the flattened XML string, with all spans and untranslatable sections encoded as 300 // parallel data structures. 301 FlattenedXmlString GetFlattenedString() const; 302 303 // Returns just the flattened XML text, with no spans or untranslatable sections. 304 std::string to_string() const; 305 306 // Returns true if there was no error. 307 explicit operator bool() const; 308 309 std::string GetError() const; 310 311 private: 312 DISALLOW_COPY_AND_ASSIGN(StringBuilder); 313 314 void ResetTextState(); 315 316 std::string error_; 317 FlattenedXmlString xml_string_; 318 uint32_t utf16_len_ = 0u; 319 bool preserve_spaces_; 320 bool quote_; 321 bool last_codepoint_was_space_ = false; 322 }; 323 324 } // namespace ResourceUtils 325 } // namespace aapt 326 327 #endif /* AAPT_RESOURCEUTILS_H */ 328