-
Notifications
You must be signed in to change notification settings - Fork 30.2k
Expand file tree
/
Copy pathasset_bundle.dart
More file actions
418 lines (386 loc) · 16.3 KB
/
asset_bundle.dart
File metadata and controls
418 lines (386 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'package:flutter/material.dart';
library;
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'binding.dart';
export 'dart:typed_data' show ByteData;
export 'dart:ui' show ImmutableBuffer;
/// A collection of resources used by the application.
///
/// Asset bundles contain resources, such as images and strings, that can be
/// used by an application. Access to these resources is asynchronous so that
/// they can be transparently loaded over a network (e.g., from a
/// [NetworkAssetBundle]) or from the local file system without blocking the
/// application's user interface.
///
/// Applications have a [rootBundle], which contains the resources that were
/// packaged with the application when it was built. To add resources to the
/// [rootBundle] for your application, add them to the `assets` subsection of
/// the `flutter` section of your application's `pubspec.yaml` manifest.
///
/// For example:
///
/// ```yaml
/// name: my_awesome_application
/// flutter:
/// assets:
/// - images/hamilton.jpeg
/// - images/lafayette.jpeg
/// ```
///
/// Rather than accessing the [rootBundle] global static directly, consider
/// obtaining the [AssetBundle] for the current [BuildContext] using
/// [DefaultAssetBundle.of]. This layer of indirection lets ancestor widgets
/// substitute a different [AssetBundle] (e.g., for testing or localization) at
/// runtime rather than directly replying upon the [rootBundle] created at build
/// time. For convenience, the [WidgetsApp] or [MaterialApp] widget at the top
/// of the widget hierarchy configures the [DefaultAssetBundle] to be the
/// [rootBundle].
///
/// See also:
///
/// * [DefaultAssetBundle]
/// * [NetworkAssetBundle]
/// * [rootBundle]
abstract class AssetBundle {
/// Retrieve a binary resource from the asset bundle as a data stream.
///
/// Throws an exception if the asset is not found.
///
/// The returned [ByteData] can be converted to a [Uint8List] (a list of bytes)
/// using [Uint8List.sublistView]. Lists of bytes can be used with APIs that
/// accept [Uint8List] objects, such as [decodeImageFromList], as well as any
/// API that accepts a [List<int>], such as [File.writeAsBytes] or
/// [Utf8Codec.decode] (accessible via [utf8]).
Future<ByteData> load(String key);
/// Retrieve a binary resource from the asset bundle as an immutable
/// buffer.
///
/// Throws an exception if the asset is not found.
Future<ui.ImmutableBuffer> loadBuffer(String key) async {
final ByteData data = await load(key);
return ui.ImmutableBuffer.fromUint8List(Uint8List.sublistView(data));
}
/// Retrieve a string from the asset bundle.
///
/// Throws an exception if the asset is not found.
///
/// If the `cache` argument is set to false, then the data will not be
/// cached, and reading the data may bypass the cache. This is useful if the
/// caller is going to be doing its own caching. (It might not be cached if
/// it's set to true either, depending on the asset bundle implementation.)
///
/// The function expects the stored string to be UTF-8-encoded as
/// [Utf8Codec] will be used for decoding the string. If the string is
/// larger than 50 KB, the decoding process is delegated to an
/// isolate to avoid jank on the main thread.
Future<String> loadString(String key, {bool cache = true}) async {
final ByteData data = await load(key);
// 50 KB of data should take 2-3 ms to parse on a Moto G4, and about 400 μs
// on a Pixel 4. On the web we can't bail to isolates, though...
if (data.lengthInBytes < 50 * 1024 || kIsWeb) {
return utf8.decode(Uint8List.sublistView(data));
}
// For strings larger than 50 KB, run the computation in an isolate to
// avoid causing main thread jank.
return compute(_utf8decode, data, debugLabel: 'UTF8 decode for "$key"');
}
static String _utf8decode(ByteData data) {
return utf8.decode(Uint8List.sublistView(data));
}
/// Retrieve a string from the asset bundle, parse it with the given function,
/// and return that function's result.
///
/// The result is not cached by the default implementation; the parser is run
/// each time the resource is fetched. However, some subclasses may implement
/// caching (notably, subclasses of [CachingAssetBundle]).
Future<T> loadStructuredData<T>(String key, Future<T> Function(String value) parser) async {
return parser(await loadString(key));
}
/// Retrieve [ByteData] from the asset bundle, parse it with the given function,
/// and return that function's result.
///
/// The result is not cached by the default implementation; the parser is run
/// each time the resource is fetched. However, some subclasses may implement
/// caching (notably, subclasses of [CachingAssetBundle]).
Future<T> loadStructuredBinaryData<T>(
String key,
FutureOr<T> Function(ByteData data) parser,
) async {
return parser(await load(key));
}
/// If this is a caching asset bundle, and the given key describes a cached
/// asset, then evict the asset from the cache so that the next time it is
/// loaded, the cache will be reread from the asset bundle.
void evict(String key) {}
/// If this is a caching asset bundle, clear all cached data.
void clear() {}
@override
String toString() => '${describeIdentity(this)}()';
}
/// An [AssetBundle] that loads resources over the network.
///
/// This asset bundle does not cache any resources, though the underlying
/// network stack may implement some level of caching itself.
class NetworkAssetBundle extends AssetBundle {
/// Creates a network asset bundle that resolves asset keys as URLs relative
/// to the given base URL.
NetworkAssetBundle(Uri baseUrl) : _baseUrl = baseUrl, _httpClient = HttpClient();
final Uri _baseUrl;
final HttpClient _httpClient;
Uri _urlFromKey(String key) => _baseUrl.resolve(key);
@override
Future<ByteData> load(String key) async {
final HttpClientRequest request = await _httpClient.getUrl(_urlFromKey(key));
final HttpClientResponse response = await request.close();
if (response.statusCode != HttpStatus.ok) {
throw FlutterError.fromParts(<DiagnosticsNode>[
_errorSummaryWithKey(key),
IntProperty('HTTP status code', response.statusCode),
]);
}
final Uint8List bytes = await consolidateHttpClientResponseBytes(response);
return ByteData.sublistView(bytes);
}
// TODO(ianh): Once the underlying network logic learns about caching, we
// should implement evict().
@override
String toString() => '${describeIdentity(this)}($_baseUrl)';
}
/// An [AssetBundle] that permanently caches string and structured resources
/// that have been fetched.
///
/// Strings (for [loadString] and [loadStructuredData]) are decoded as UTF-8.
/// Data that is cached is cached for the lifetime of the asset bundle
/// (typically the lifetime of the application).
///
/// Binary resources (from [load]) are not cached.
abstract class CachingAssetBundle extends AssetBundle {
final Map<String, Future<String>> _stringCache = <String, Future<String>>{};
final Map<String, Future<dynamic>> _structuredDataCache = <String, Future<dynamic>>{};
final Map<String, Future<dynamic>> _structuredBinaryDataCache = <String, Future<dynamic>>{};
@override
Future<String> loadString(String key, {bool cache = true}) {
if (cache) {
return _stringCache.putIfAbsent(key, () => super.loadString(key));
}
return super.loadString(key);
}
/// Retrieve a string from the asset bundle, parse it with the given function,
/// and return the function's result.
///
/// The result of parsing the string is cached (the string itself is not,
/// unless you also fetch it with [loadString]). For any given `key`, the
/// `parser` is only run the first time.
///
/// Once the value has been successfully parsed, the future returned by this
/// function for subsequent calls will be a [SynchronousFuture], which
/// resolves its callback synchronously.
///
/// Failures are not cached, and are returned as [Future]s with errors.
@override
Future<T> loadStructuredData<T>(String key, Future<T> Function(String value) parser) {
if (_structuredDataCache.containsKey(key)) {
return _structuredDataCache[key]! as Future<T>;
}
// loadString can return a SynchronousFuture in certain cases, like in the
// flutter_test framework. So, we need to support both async and sync flows.
Completer<T>? completer; // For async flow.
Future<T>? synchronousResult; // For sync flow.
loadString(key, cache: false)
.then<T>(parser)
.then<void>(
(T value) {
synchronousResult = SynchronousFuture<T>(value);
_structuredDataCache[key] = synchronousResult!;
// We already returned from the loadStructuredData function, which means
// we are in the asynchronous mode. Pass the value to the completer. The
// completer's future is what we returned.
completer?.complete(value);
},
onError: (Object error, StackTrace stack) {
assert(completer != null, 'unexpected synchronous failure');
// Either loading or parsing failed. We must report the error back to the
// caller and anyone waiting on this call. We clear the cache for this
// key, however, because we want future attempts to try again.
_structuredDataCache.remove(key);
completer!.completeError(error, stack);
},
);
if (synchronousResult != null) {
// The above code ran synchronously. We can synchronously return the result.
return synchronousResult!;
}
// The code above hasn't yet run its "then" handler yet. Let's prepare a
// completer for it to use when it does run.
completer = Completer<T>();
_structuredDataCache[key] = completer.future;
return completer.future;
}
/// Retrieve bytedata from the asset bundle, parse it with the given function,
/// and return the function's result.
///
/// The result of parsing the bytedata is cached (the bytedata itself is not).
/// For any given `key`, the `parser` is only run the first time.
///
/// Once the value has been successfully parsed, the future returned by this
/// function for subsequent calls will be a [SynchronousFuture], which
/// resolves its callback synchronously.
///
/// Failures are not cached, and are returned as [Future]s with errors.
@override
Future<T> loadStructuredBinaryData<T>(String key, FutureOr<T> Function(ByteData data) parser) {
if (_structuredBinaryDataCache.containsKey(key)) {
return _structuredBinaryDataCache[key]! as Future<T>;
}
// load can return a SynchronousFuture in certain cases, like in the
// flutter_test framework. So, we need to support both async and sync flows.
Completer<T>? completer; // For async flow.
Future<T>? synchronousResult; // For sync flow.
load(key)
.then<T>(parser)
.then<void>(
(T value) {
synchronousResult = SynchronousFuture<T>(value);
_structuredBinaryDataCache[key] = synchronousResult!;
// The load and parse operation ran asynchronously. We already returned
// from the loadStructuredBinaryData function and therefore the caller
// was given the future of the completer.
completer?.complete(value);
},
onError: (Object error, StackTrace stack) {
assert(completer != null, 'unexpected synchronous failure');
// Either loading or parsing failed. We must report the error back to the
// caller and anyone waiting on this call. We clear the cache for this
// key, however, because we want future attempts to try again.
_structuredBinaryDataCache.remove(key);
completer!.completeError(error, stack);
},
);
if (synchronousResult != null) {
// The above code ran synchronously. We can synchronously return the result.
return synchronousResult!;
}
// Since the above code is being run asynchronously and thus hasn't run its
// `then` handler yet, we'll return a completer that will be completed
// when the handler does run.
completer = Completer<T>();
_structuredBinaryDataCache[key] = completer.future;
return completer.future;
}
@override
void evict(String key) {
_stringCache.remove(key);
_structuredDataCache.remove(key);
_structuredBinaryDataCache.remove(key);
}
@override
void clear() {
_stringCache.clear();
_structuredDataCache.clear();
_structuredBinaryDataCache.clear();
}
@override
Future<ui.ImmutableBuffer> loadBuffer(String key) async {
final ByteData data = await load(key);
return ui.ImmutableBuffer.fromUint8List(Uint8List.sublistView(data));
}
}
/// An [AssetBundle] that loads resources using platform messages.
class PlatformAssetBundle extends CachingAssetBundle {
@override
Future<ByteData> load(String key) {
final Uint8List encoded = utf8.encode(Uri(path: Uri.encodeFull(key)).path);
final Future<ByteData>? future = ServicesBinding.instance.defaultBinaryMessenger
.send('flutter/assets', ByteData.sublistView(encoded))
?.then((ByteData? asset) {
if (asset == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
_errorSummaryWithKey(key),
ErrorDescription('The asset does not exist or has empty data.'),
]);
}
return asset;
});
if (future == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
_errorSummaryWithKey(key),
ErrorDescription('The asset does not exist or has empty data.'),
]);
}
return future;
}
@override
Future<ui.ImmutableBuffer> loadBuffer(String key) async {
if (kIsWeb) {
final ByteData bytes = await load(key);
return ui.ImmutableBuffer.fromUint8List(Uint8List.sublistView(bytes));
}
var debugUsePlatformChannel = false;
assert(() {
// dart:io is safe to use here since we early return for web
// above. If that code is changed, this needs to be guarded on
// web presence. Override how assets are loaded in tests so that
// the old loader behavior that allows tests to load assets from
// the current package using the package prefix.
if (Platform.environment.containsKey('UNIT_TEST_ASSETS')) {
debugUsePlatformChannel = true;
}
return true;
}());
if (debugUsePlatformChannel) {
final ByteData bytes = await load(key);
return ui.ImmutableBuffer.fromUint8List(Uint8List.sublistView(bytes));
}
try {
return await ui.ImmutableBuffer.fromAsset(key);
} on Exception catch (e) {
throw FlutterError.fromParts(<DiagnosticsNode>[
_errorSummaryWithKey(key),
ErrorDescription(e.toString()),
]);
}
}
}
AssetBundle _initRootBundle() {
return PlatformAssetBundle();
}
ErrorSummary _errorSummaryWithKey(String key) {
return ErrorSummary('Unable to load asset: "$key".');
}
/// The [AssetBundle] from which this application was loaded.
///
/// The [rootBundle] contains the resources that were packaged with the
/// application when it was built. To add resources to the [rootBundle] for your
/// application, add them to the `assets` subsection of the `flutter` section of
/// your application's `pubspec.yaml` manifest.
///
/// For example:
///
/// ```yaml
/// name: my_awesome_application
/// flutter:
/// assets:
/// - images/hamilton.jpeg
/// - images/lafayette.jpeg
/// ```
///
/// Rather than using [rootBundle] directly, consider obtaining the
/// [AssetBundle] for the current [BuildContext] using [DefaultAssetBundle.of].
/// This layer of indirection lets ancestor widgets substitute a different
/// [AssetBundle] at runtime (e.g., for testing or localization) rather than
/// directly replying upon the [rootBundle] created at build time. For
/// convenience, the [WidgetsApp] or [MaterialApp] widget at the top of the
/// widget hierarchy configures the [DefaultAssetBundle] to be the [rootBundle].
///
/// See also:
///
/// * [DefaultAssetBundle]
/// * [NetworkAssetBundle]
final AssetBundle rootBundle = _initRootBundle();