AssetManager2.h revision 7ad1110ecd6a840fcd2895c62668828a1ca029c6
1/* 2 * Copyright (C) 2016 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 ANDROIDFW_ASSETMANAGER2_H_ 18#define ANDROIDFW_ASSETMANAGER2_H_ 19 20#include "android-base/macros.h" 21 22#include <limits> 23#include <unordered_map> 24 25#include "androidfw/ApkAssets.h" 26#include "androidfw/Asset.h" 27#include "androidfw/AssetManager.h" 28#include "androidfw/ResourceTypes.h" 29#include "androidfw/Util.h" 30 31namespace android { 32 33class Theme; 34 35using ApkAssetsCookie = int32_t; 36 37enum : ApkAssetsCookie { 38 kInvalidCookie = -1, 39}; 40 41// Holds a bag that has been merged with its parent, if one exists. 42struct ResolvedBag { 43 // A single key-value entry in a bag. 44 struct Entry { 45 // The key, as described in ResTable_map::name. 46 uint32_t key; 47 48 Res_value value; 49 50 // Which ApkAssets this entry came from. 51 ApkAssetsCookie cookie; 52 53 ResStringPool* key_pool; 54 ResStringPool* type_pool; 55 }; 56 57 // Denotes the configuration axis that this bag varies with. 58 // If a configuration changes with respect to one of these axis, 59 // the bag should be reloaded. 60 uint32_t type_spec_flags; 61 62 // The number of entries in this bag. Access them by indexing into `entries`. 63 uint32_t entry_count; 64 65 // The array of entries for this bag. An empty array is a neat trick to force alignment 66 // of the Entry structs that follow this structure and avoids a bunch of casts. 67 Entry entries[0]; 68}; 69 70// AssetManager2 is the main entry point for accessing assets and resources. 71// AssetManager2 provides caching of resources retrieved via the underlying 72// ApkAssets. 73class AssetManager2 : public ::AAssetManager { 74 public: 75 struct ResourceName { 76 const char* package = nullptr; 77 size_t package_len = 0u; 78 79 const char* type = nullptr; 80 const char16_t* type16 = nullptr; 81 size_t type_len = 0u; 82 83 const char* entry = nullptr; 84 const char16_t* entry16 = nullptr; 85 size_t entry_len = 0u; 86 }; 87 88 AssetManager2(); 89 90 // Sets/resets the underlying ApkAssets for this AssetManager. The ApkAssets 91 // are not owned by the AssetManager, and must have a longer lifetime. 92 // 93 // Only pass invalidate_caches=false when it is known that the structure 94 // change in ApkAssets is due to a safe addition of resources with completely 95 // new resource IDs. 96 bool SetApkAssets(const std::vector<const ApkAssets*>& apk_assets, bool invalidate_caches = true); 97 98 const std::vector<const ApkAssets*> GetApkAssets() const; 99 100 // Returns the string pool for the given asset cookie. 101 // Use the string pool returned here with a valid Res_value object of 102 // type Res_value::TYPE_STRING. 103 const ResStringPool* GetStringPoolForCookie(ApkAssetsCookie cookie) const; 104 105 // Sets/resets the configuration for this AssetManager. This will cause all 106 // caches that are related to the configuration change to be invalidated. 107 void SetConfiguration(const ResTable_config& configuration); 108 109 const ResTable_config& GetConfiguration() const; 110 111 // Searches the set of APKs loaded by this AssetManager and opens the first one found located 112 // in the assets/ directory. 113 // `mode` controls how the file is opened. 114 // 115 // NOTE: The loaded APKs are searched in reverse order. 116 std::unique_ptr<Asset> Open(const std::string& filename, Asset::AccessMode mode); 117 118 // Opens a file within the assets/ directory of the APK specified by `cookie`. 119 // `mode` controls how the file is opened. 120 std::unique_ptr<Asset> Open(const std::string& filename, ApkAssetsCookie cookie, 121 Asset::AccessMode mode); 122 123 // Searches the set of APKs loaded by this AssetManager and opens the first one found. 124 // `mode` controls how the file is opened. 125 // `out_cookie` is populated with the cookie of the APK this file was found in. 126 // 127 // NOTE: The loaded APKs are searched in reverse order. 128 std::unique_ptr<Asset> OpenNonAsset(const std::string& filename, Asset::AccessMode mode, 129 ApkAssetsCookie* out_cookie = nullptr); 130 131 // Opens a file in the APK specified by `cookie`. `mode` controls how the file is opened. 132 // This is typically used to open a specific AndroidManifest.xml, or a binary XML file 133 // referenced by a resource lookup with GetResource(). 134 std::unique_ptr<Asset> OpenNonAsset(const std::string& filename, ApkAssetsCookie cookie, 135 Asset::AccessMode mode); 136 137 // Populates the `out_name` parameter with resource name information. 138 // Utf8 strings are preferred, and only if they are unavailable are 139 // the Utf16 variants populated. 140 // Returns false if the resource was not found or the name was missing/corrupt. 141 bool GetResourceName(uint32_t resid, ResourceName* out_name); 142 143 // Populates `out_flags` with the bitmask of configuration axis that this resource varies with. 144 // See ResTable_config for the list of configuration axis. 145 // Returns false if the resource was not found. 146 bool GetResourceFlags(uint32_t resid, uint32_t* out_flags); 147 148 // Retrieves the best matching resource with ID `resid`. The resource value is filled into 149 // `out_value` and the configuration for the selected value is populated in `out_selected_config`. 150 // `out_flags` holds the same flags as retrieved with GetResourceFlags(). 151 // If `density_override` is non-zero, the configuration to match against is overridden with that 152 // density. 153 // 154 // Returns a valid cookie if the resource was found. If the resource was not found, or if the 155 // resource was a map/bag type, then kInvalidCookie is returned. If `may_be_bag` is false, 156 // this function logs if the resource was a map/bag type before returning kInvalidCookie. 157 ApkAssetsCookie GetResource(uint32_t resid, bool may_be_bag, uint16_t density_override, 158 Res_value* out_value, ResTable_config* out_selected_config, 159 uint32_t* out_flags); 160 161 // Retrieves the best matching bag/map resource with ID `resid`. 162 // This method will resolve all parent references for this bag and merge keys with the child. 163 // To iterate over the keys, use the following idiom: 164 // 165 // const AssetManager2::ResolvedBag* bag = asset_manager->GetBag(id); 166 // if (bag != nullptr) { 167 // for (auto iter = begin(bag); iter != end(bag); ++iter) { 168 // ... 169 // } 170 // } 171 const ResolvedBag* GetBag(uint32_t resid); 172 173 // Creates a new Theme from this AssetManager. 174 std::unique_ptr<Theme> NewTheme(); 175 176 private: 177 DISALLOW_COPY_AND_ASSIGN(AssetManager2); 178 179 // Finds the best entry for `resid` amongst all the ApkAssets. The entry can be a simple 180 // Res_value, or a complex map/bag type. 181 // 182 // `density_override` overrides the density of the current configuration when doing a search. 183 // 184 // When `stop_at_first_match` is true, the first match found is selected and the search 185 // terminates. This is useful for methods that just look up the name of a resource and don't 186 // care about the value. In this case, the value of `out_flags` is incomplete and should not 187 // be used. 188 // 189 // `out_flags` stores the resulting bitmask of configuration axis with which the resource 190 // value varies. 191 ApkAssetsCookie FindEntry(uint32_t resid, uint16_t density_override, bool stop_at_first_match, 192 LoadedArsc::Entry* out_entry, ResTable_config* out_selected_config, 193 uint32_t* out_flags); 194 195 // Purge all resources that are cached and vary by the configuration axis denoted by the 196 // bitmask `diff`. 197 void InvalidateCaches(uint32_t diff); 198 199 // The ordered list of ApkAssets to search. These are not owned by the AssetManager, and must 200 // have a longer lifetime. 201 std::vector<const ApkAssets*> apk_assets_; 202 203 // The current configuration set for this AssetManager. When this changes, cached resources 204 // may need to be purged. 205 ResTable_config configuration_; 206 207 // Cached set of bags. These are cached because they can inherit keys from parent bags, 208 // which involves some calculation. 209 std::unordered_map<uint32_t, util::unique_cptr<ResolvedBag>> cached_bags_; 210}; 211 212class Theme { 213 friend class AssetManager2; 214 215 public: 216 // Applies the style identified by `resid` to this theme. This can be called 217 // multiple times with different styles. By default, any theme attributes that 218 // are already defined before this call are not overridden. If `force` is set 219 // to true, this behavior is changed and all theme attributes from the style at 220 // `resid` are applied. 221 // Returns false if the style failed to apply. 222 bool ApplyStyle(uint32_t resid, bool force = false); 223 224 // Sets this Theme to be a copy of `o` if `o` has the same AssetManager as this Theme. 225 // Returns false if the AssetManagers of the Themes were not compatible. 226 bool SetTo(const Theme& o); 227 228 void Clear(); 229 230 inline const AssetManager2* GetAssetManager() const { return asset_manager_; } 231 232 // Returns a bit mask of configuration changes that will impact this 233 // theme (and thus require completely reloading it). 234 inline uint32_t GetChangingConfigurations() const { return type_spec_flags_; } 235 236 // Retrieve a value in the theme. If the theme defines this value, 237 // returns an asset cookie indicating which ApkAssets it came from 238 // and populates `out_value` with the value. If `out_flags` is non-null, 239 // populates it with a bitmask of the configuration axis the resource 240 // varies with. 241 // 242 // If the attribute is not found, returns kInvalidCookie. 243 // 244 // NOTE: This function does not do reference traversal. If you want 245 // to follow references to other resources to get the "real" value to 246 // use, you need to call ResolveReference() after this function. 247 ApkAssetsCookie GetAttribute(uint32_t resid, Res_value* out_value, 248 uint32_t* out_flags = nullptr) const; 249 250 // This is like AssetManager2::ResolveReference(), but also takes 251 // care of resolving attribute references to the theme. 252 ApkAssetsCookie ResolveAttributeReference(Res_value* in_out_value, ApkAssetsCookie src_cookie, 253 uint32_t* out_last_ref = nullptr, 254 uint32_t* in_out_type_spec_flags = nullptr, 255 ResTable_config* out_selected_config = nullptr) const; 256 257 private: 258 DISALLOW_COPY_AND_ASSIGN(Theme); 259 260 // Called by AssetManager2. 261 explicit inline Theme(AssetManager2* asset_manager) : asset_manager_(asset_manager) {} 262 263 struct Entry { 264 ApkAssetsCookie cookie; 265 uint32_t type_spec_flags; 266 Res_value value; 267 }; 268 269 struct Type { 270 // Use uint32_t for fewer cycles when loading from memory. 271 uint32_t entry_count; 272 uint32_t entry_capacity; 273 Entry entries[0]; 274 }; 275 276 static constexpr const size_t kPackageCount = std::numeric_limits<uint8_t>::max() + 1; 277 static constexpr const size_t kTypeCount = std::numeric_limits<uint8_t>::max() + 1; 278 279 struct Package { 280 // Each element of Type will be a dynamically sized object 281 // allocated to have the entries stored contiguously with the Type. 282 util::unique_cptr<Type> types[kTypeCount]; 283 }; 284 285 AssetManager2* asset_manager_; 286 uint32_t type_spec_flags_ = 0u; 287 std::unique_ptr<Package> packages_[kPackageCount]; 288}; 289 290inline const ResolvedBag::Entry* begin(const ResolvedBag* bag) { return bag->entries; } 291 292inline const ResolvedBag::Entry* end(const ResolvedBag* bag) { 293 return bag->entries + bag->entry_count; 294} 295 296} // namespace android 297 298#endif /* ANDROIDFW_ASSETMANAGER2_H_ */ 299