[web] feature-detect and use ImageDecoder for all image decoding (flutter/engine#29419)

This commit is contained in:
Yegor
2021-11-18 10:01:02 -08:00
committed by GitHub
parent 3d60f36a21
commit 9a75a379aa
22 changed files with 1154 additions and 250 deletions

View File

@@ -487,6 +487,8 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/font_fallbacks.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/fonts.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/image.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/image_filter.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/image_wasm_codecs.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/image_web_codecs.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/initialization.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/interval_tree.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/layer.dart

View File

@@ -93,7 +93,14 @@ class Chrome extends Browser {
'--headless',
if (isChromeNoSandbox)
'--no-sandbox',
'--window-size=$kMaxScreenshotWidth,$kMaxScreenshotHeight', // When headless, this is the actual size of the viewport
// When headless, this is the actual size of the viewport.
if (!debug)
'--window-size=$kMaxScreenshotWidth,$kMaxScreenshotHeight',
// When debugging, run in maximized mode so there's enough room for DevTools.
if (debug)
'--start-maximized',
if (debug)
'--auto-open-devtools-for-tabs',
'--disable-extensions',
'--disable-popup-blocking',
// Indicates that the browser is in "browse without sign-in" (Guest session) mode.

View File

@@ -1,2 +1,2 @@
repository: https://github.com/flutter/goldens.git
revision: 8e169f3ca5cf4af283a2ff4cfd98a564fb173adf
revision: 0dd2e82050422c05e9daf652fa4267fb7c01f260

View File

@@ -52,6 +52,7 @@ class RunCommand extends Command<bool> with ArgUtils<bool> {
browserName: browserName,
isDebug: false,
doUpdateScreenshotGoldens: false,
overridePathToCanvasKit: null,
),
};

View File

@@ -39,12 +39,14 @@ class RunTestsStep implements PipelineStep {
required this.isDebug,
required this.doUpdateScreenshotGoldens,
this.testFiles,
required this.overridePathToCanvasKit,
}) : _browserEnvironment = getBrowserEnvironment(browserName);
final String browserName;
final List<FilePath>? testFiles;
final bool isDebug;
final bool doUpdateScreenshotGoldens;
final String? overridePathToCanvasKit;
final BrowserEnvironment _browserEnvironment;
@@ -120,6 +122,7 @@ class RunTestsStep implements PipelineStep {
isDebug: isDebug,
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
skiaClient: skiaClient,
overridePathToCanvasKit: overridePathToCanvasKit,
);
}
@@ -133,6 +136,7 @@ class RunTestsStep implements PipelineStep {
isDebug: isDebug,
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
skiaClient: skiaClient,
overridePathToCanvasKit: overridePathToCanvasKit,
);
_checkExitCode('Unit tests');
}
@@ -148,6 +152,7 @@ class RunTestsStep implements PipelineStep {
isDebug: isDebug,
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
skiaClient: skiaClient,
overridePathToCanvasKit: overridePathToCanvasKit,
);
_checkExitCode('Golden tests');
}
@@ -234,6 +239,7 @@ Future<void> _runTestBatch({
required int concurrency,
required bool expectFailure,
required SkiaGoldClient? skiaClient,
required String? overridePathToCanvasKit,
}) async {
final String configurationFilePath = pathlib.join(
environment.webUiRootDir.path,
@@ -271,6 +277,7 @@ Future<void> _runTestBatch({
// expected to fail.
doUpdateScreenshotGoldens: !expectFailure && doUpdateScreenshotGoldens,
skiaClient: skiaClient,
overridePathToCanvasKit: overridePathToCanvasKit,
);
});

View File

@@ -53,6 +53,7 @@ class BrowserPlatform extends PlatformPlugin {
required BrowserEnvironment browserEnvironment,
required bool doUpdateScreenshotGoldens,
required SkiaGoldClient? skiaClient,
required String? overridePathToCanvasKit,
}) async {
final shelf_io.IOServer server = shelf_io.IOServer(await HttpMultiServer.loopback(0));
return BrowserPlatform._(
@@ -62,6 +63,7 @@ class BrowserPlatform extends PlatformPlugin {
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
packageConfig: await loadPackageConfigUri((await Isolate.packageConfig)!),
skiaClient: skiaClient,
overridePathToCanvasKit: overridePathToCanvasKit,
);
}
@@ -105,6 +107,8 @@ class BrowserPlatform extends PlatformPlugin {
/// and update images.
final SkiaGoldClient? skiaClient;
final String? overridePathToCanvasKit;
BrowserPlatform._({
required this.browserEnvironment,
required this.server,
@@ -112,6 +116,7 @@ class BrowserPlatform extends PlatformPlugin {
required this.doUpdateScreenshotGoldens,
required this.packageConfig,
required this.skiaClient,
required this.overridePathToCanvasKit,
}) : _screenshotManager = browserEnvironment.getScreenshotManager() {
// The cascade of request handlers.
final shelf.Cascade cascade = shelf.Cascade()
@@ -128,9 +133,13 @@ class BrowserPlatform extends PlatformPlugin {
// * Assets that are part of the engine sources, such as Ahem.ttf
.add(_packageUrlHandler)
.add(_canvasKitOverrideHandler)
// Serves files from the web_ui/build/ directory at the root (/) URL path.
.add(buildDirectoryHandler)
.add(_testImageListingHandler)
// Serves the initial HTML for the test.
.add(_testBootstrapHandler)
@@ -153,6 +162,76 @@ class BrowserPlatform extends PlatformPlugin {
server.mount(cascade.handler);
}
/// If a path to a custom local build of CanvasKit was specified, serve from
/// there instead of serving the default CanvasKit in the build/ directory.
Future<shelf.Response> _canvasKitOverrideHandler(shelf.Request request) async {
final String? pathOverride = overridePathToCanvasKit;
if (pathOverride == null || !request.url.path.startsWith('canvaskit/')) {
return shelf.Response.notFound('Not a request for CanvasKit.');
}
final File file = File(p.joinAll(<String>[
pathOverride,
...p.split(request.url.path).skip(1),
]));
if (!file.existsSync()) {
return shelf.Response.notFound('File not found: ${request.url.path}');
}
final String extension = p.extension(file.path);
final String? contentType = contentTypes[extension];
if (contentType == null) {
final String error = 'Failed to determine Content-Type for "${request.url.path}".';
stderr.writeln(error);
return shelf.Response.internalServerError(body: error);
}
return shelf.Response.ok(
file.readAsBytesSync(),
headers: <String, Object>{
HttpHeaders.contentTypeHeader: contentType,
},
);
}
/// Lists available test images under `web_ui/build/test_images`.
Future<shelf.Response> _testImageListingHandler(shelf.Request request) async {
const Map<String, String> supportedImageTypes = <String, String>{
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
};
if (request.url.path != 'test_images/') {
return shelf.Response.notFound('Not found.');
}
final Directory testImageDirectory = Directory(p.join(
env.environment.webUiBuildDir.path,
'test_images',
));
final List<String> testImageFiles = testImageDirectory
.listSync(recursive: true)
.whereType<File>()
.map<String>((File file) => p.relative(file.path, from: testImageDirectory.path))
.where((String path) => supportedImageTypes.containsKey(p.extension(path)))
.toList();
return shelf.Response.ok(
json.encode(testImageFiles),
headers: <String, Object>{
HttpHeaders.contentTypeHeader: 'application/json',
},
);
}
Future<shelf.Response> _fileNotFoundCatcher(shelf.Request request) async {
print('HTTP 404: ${request.url}');
return shelf.Response.notFound('File not found');

View File

@@ -69,8 +69,8 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
..addOption(
'browser',
defaultsTo: 'chrome',
help: 'An option to choose a browser to run the tests. Tests only work '
' on Chrome for now.',
help: 'An option to choose a browser to run the tests. By default '
'tests run in Chrome.',
)
..addFlag(
'fail-early',
@@ -80,6 +80,12 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
'failure. If not set, the test runner will continue running '
'test despite failures and will report them after all tests '
'finish.',
)
..addOption(
'canvaskit-path',
help: 'Optional. The path to a local build of CanvasKit to use in '
'tests. If omitted, the test runner uses the default CanvasKit '
'build.',
);
}
@@ -118,6 +124,9 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
/// Whether to fetch the goldens repo prior to running tests.
bool get skipGoldensRepoFetch => boolArg('skip-goldens-repo-fetch');
/// Path to a CanvasKit build. Overrides the default CanvasKit.
String? get overridePathToCanvasKit => argResults!['canvaskit-path'] as String?;
@override
Future<bool> run() async {
final List<FilePath> testFiles = runAllTests
@@ -135,6 +144,7 @@ class TestCommand extends Command<bool> with ArgUtils<bool> {
testFiles: testFiles,
isDebug: isDebug,
doUpdateScreenshotGoldens: doUpdateScreenshotGoldens,
overridePathToCanvasKit: overridePathToCanvasKit,
),
]);
await testPipeline.run();

View File

@@ -76,6 +76,10 @@ export 'engine/canvaskit/image.dart';
export 'engine/canvaskit/image_filter.dart';
export 'engine/canvaskit/image_wasm_codecs.dart';
export 'engine/canvaskit/image_web_codecs.dart';
export 'engine/canvaskit/initialization.dart';
export 'engine/canvaskit/interval_tree.dart';

View File

@@ -123,11 +123,15 @@ class CanvasKit {
/// Typically pixel data is obtained using [SkImage.readPixels]. The
/// parameters specified in [SkImageInfo] passed [SkImage.readPixels] must
/// match [info].
external SkImage MakeImage(
external SkImage? MakeImage(
SkImageInfo info,
Uint8List pixels,
int bytesPerRow,
);
external SkImage? MakeLazyImageFromTextureSource(
Object src,
SkPartialImageInfo info,
);
}
@JS('window.CanvasKitInit')
@@ -2141,3 +2145,20 @@ class SkImageInfo {
external SkImageInfo makeColorType(SkColorType colorType);
external SkImageInfo makeWH(int width, int height);
}
@JS()
@anonymous
class SkPartialImageInfo {
external factory SkPartialImageInfo({
required int width,
required int height,
required SkColorType colorType,
required SkAlphaType alphaType,
required ColorSpace colorSpace,
});
external SkAlphaType get alphaType;
external ColorSpace get colorSpace;
external SkColorType get colorType;
external int get height;
external int get width;
}

View File

@@ -697,7 +697,7 @@ class HtmlViewEmbedder {
// Try reusing a cached overlay created for another platform view.
final Surface overlay = SurfaceFactory.instance.getOverlay()!;
overlay.createOrUpdateSurfaces(_frameSize);
overlay.createOrUpdateSurface(_frameSize);
_overlays[viewId] = overlay;
}

View File

@@ -11,12 +11,25 @@ import 'package:ui/ui.dart' as ui;
import '../html_image_codec.dart';
import '../util.dart';
import 'canvaskit_api.dart';
import 'image_wasm_codecs.dart';
import 'image_web_codecs.dart';
import 'skia_object_cache.dart';
/// Instantiates a [ui.Codec] backed by an `SkAnimatedImage` from Skia.
ui.Codec skiaInstantiateImageCodec(Uint8List list,
[int? width, int? height, int? format, int? rowBytes]) {
return CkAnimatedImage.decodeFromBytes(list, 'encoded image bytes');
// TODO(yjbanov): Implement targetWidth and targetHeight support.
// https://github.com/flutter/flutter/issues/34075
FutureOr<ui.Codec> skiaInstantiateImageCodec(Uint8List list,
[int? targetWidth, int? targetHeight]) {
if (browserSupportsImageDecoder) {
return CkBrowserImageDecoder.create(
data: list,
debugSource: 'encoded image bytes',
targetWidth: targetWidth,
targetHeight: targetHeight,
);
} else {
return CkAnimatedImage.decodeFromBytes(list, 'encoded image bytes');
}
}
// TODO(yjbanov): add support for targetWidth/targetHeight (https://github.com/flutter/flutter/issues/34075)
@@ -34,7 +47,7 @@ void skiaDecodeImageFromPixels(
// Run in a timer to avoid janking the current frame by moving the decoding
// work outside the frame event.
Timer.run(() {
final SkImage skImage = canvasKit.MakeImage(
final SkImage? skImage = canvasKit.MakeImage(
SkImageInfo(
width: width,
height: height,
@@ -45,6 +58,12 @@ void skiaDecodeImageFromPixels(
pixels,
rowBytes ?? 4 * width,
);
if (skImage == null) {
html.window.console.warn('Failed to create image from pixels.');
return;
}
return callback(CkImage(skImage));
});
}
@@ -72,8 +91,19 @@ void debugRestoreHttpRequestFactory() {
/// Instantiates a [ui.Codec] backed by an `SkAnimatedImage` from Skia after
/// requesting from URI.
Future<ui.Codec> skiaInstantiateWebImageCodec(
String url, WebOnlyImageCodecChunkCallback? chunkCallback) async {
final Uint8List list = await fetchImage(url, chunkCallback);
if (browserSupportsImageDecoder) {
return CkBrowserImageDecoder.create(data: list, debugSource: url.toString());
} else {
return CkAnimatedImage.decodeFromBytes(list, url);
}
}
/// Sends a request to fetch image data.
Future<Uint8List> fetchImage(
String url, WebOnlyImageCodecChunkCallback? chunkCallback) {
final Completer<ui.Codec> completer = Completer<ui.Codec>();
final Completer<Uint8List> completer = Completer<Uint8List>();
final html.HttpRequest request = httpRequestFactory();
request.open('GET', url, async: true);
@@ -108,110 +138,13 @@ Future<ui.Codec> skiaInstantiateWebImageCodec(
return;
}
try {
final Uint8List list =
Uint8List.view(request.response as ByteBuffer);
final CkAnimatedImage codec = CkAnimatedImage.decodeFromBytes(list, url);
completer.complete(codec);
} catch (error, stackTrace) {
completer.completeError(error, stackTrace);
}
completer.complete(Uint8List.view(request.response as ByteBuffer));
});
request.send();
return completer.future;
}
/// The CanvasKit implementation of [ui.Codec].
///
/// Wraps `SkAnimatedImage`.
class CkAnimatedImage extends ManagedSkiaObject<SkAnimatedImage>
implements ui.Codec {
/// Decodes an image from a list of encoded bytes.
CkAnimatedImage.decodeFromBytes(this._bytes, this.src);
final String src;
final Uint8List _bytes;
int _frameCount = 0;
int _repetitionCount = -1;
/// The index to the next frame to be decoded.
int _nextFrameIndex = 0;
@override
SkAnimatedImage createDefault() {
final SkAnimatedImage? animatedImage =
canvasKit.MakeAnimatedImageFromEncoded(_bytes);
if (animatedImage == null) {
throw ImageCodecException(
'Failed to decode image data.\n'
'Image source: $src',
);
}
_frameCount = animatedImage.getFrameCount();
_repetitionCount = animatedImage.getRepetitionCount();
// If the object has been deleted then resurrected, it may already have
// iterated over some frames. We need to skip over them.
for (int i = 0; i < _nextFrameIndex; i++) {
animatedImage.decodeNextFrame();
}
return animatedImage;
}
@override
SkAnimatedImage resurrect() => createDefault();
@override
bool get isResurrectionExpensive => true;
@override
void delete() {
rawSkiaObject?.delete();
}
bool _disposed = false;
bool get debugDisposed => _disposed;
bool _debugCheckIsNotDisposed() {
assert(!_disposed, 'This image has been disposed.');
return true;
}
@override
void dispose() {
assert(
!_disposed,
'Cannot dispose a codec that has already been disposed.',
);
_disposed = true;
delete();
}
@override
int get frameCount {
assert(_debugCheckIsNotDisposed());
return _frameCount;
}
@override
int get repetitionCount {
assert(_debugCheckIsNotDisposed());
return _repetitionCount;
}
@override
Future<ui.FrameInfo> getNextFrame() {
assert(_debugCheckIsNotDisposed());
final int durationMillis = skiaObject.decodeNextFrame();
final Duration duration = Duration(milliseconds: durationMillis);
final CkImage image = CkImage(skiaObject.makeImageAtCurrentFrame());
_nextFrameIndex = (_nextFrameIndex + 1) % _frameCount;
return Future<ui.FrameInfo>.value(AnimatedImageFrameInfo(duration, image));
}
}
/// A [ui.Image] backed by an `SkImage` from Skia.
class CkImage implements ui.Image, StackTraceDebugger {
CkImage(SkImage skImage) {
@@ -244,16 +177,23 @@ class CkImage implements ui.Image, StackTraceDebugger {
final int originalWidth = skImage.width();
final int originalHeight = skImage.height();
box = SkiaObjectBox<CkImage, SkImage>.resurrectable(this, skImage, () {
return canvasKit.MakeImage(
SkImageInfo(
alphaType: canvasKit.AlphaType.Premul,
colorType: canvasKit.ColorType.RGBA_8888,
colorSpace: SkColorSpaceSRGB,
width: originalWidth,
height: originalHeight,
),
originalBytes.buffer.asUint8List(),
4 * originalWidth);
final SkImage? skImage = canvasKit.MakeImage(
SkImageInfo(
alphaType: canvasKit.AlphaType.Premul,
colorType: canvasKit.ColorType.RGBA_8888,
colorSpace: SkColorSpaceSRGB,
width: originalWidth,
height: originalHeight,
),
originalBytes.buffer.asUint8List(),
4 * originalWidth,
);
if (skImage == null) {
throw ImageCodecException(
'Failed to resurrect image from pixels.'
);
}
return skImage;
});
}
}

View File

@@ -0,0 +1,109 @@
// Copyright 2013 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.
/// Uses image codecs supplied by the CanvasKit WASM bundle.
///
/// See also:
///
/// * `image_web_codecs.dart`, which uses the `ImageDecoder` supplied by the browser.
library image_wasm_codecs;
import 'dart:async';
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'canvaskit_api.dart';
import 'image.dart';
import 'skia_object_cache.dart';
/// The CanvasKit implementation of [ui.Codec].
///
/// Wraps `SkAnimatedImage`.
class CkAnimatedImage extends ManagedSkiaObject<SkAnimatedImage>
implements ui.Codec {
/// Decodes an image from a list of encoded bytes.
CkAnimatedImage.decodeFromBytes(this._bytes, this.src);
final String src;
final Uint8List _bytes;
int _frameCount = 0;
int _repetitionCount = -1;
/// The index to the next frame to be decoded.
int _nextFrameIndex = 0;
@override
SkAnimatedImage createDefault() {
final SkAnimatedImage? animatedImage =
canvasKit.MakeAnimatedImageFromEncoded(_bytes);
if (animatedImage == null) {
throw ImageCodecException(
'Failed to decode image data.\n'
'Image source: $src',
);
}
_frameCount = animatedImage.getFrameCount();
_repetitionCount = animatedImage.getRepetitionCount();
// If the object has been deleted then resurrected, it may already have
// iterated over some frames. We need to skip over them.
for (int i = 0; i < _nextFrameIndex; i++) {
animatedImage.decodeNextFrame();
}
return animatedImage;
}
@override
SkAnimatedImage resurrect() => createDefault();
@override
bool get isResurrectionExpensive => true;
@override
void delete() {
rawSkiaObject?.delete();
}
bool _disposed = false;
bool get debugDisposed => _disposed;
bool _debugCheckIsNotDisposed() {
assert(!_disposed, 'This image has been disposed.');
return true;
}
@override
void dispose() {
assert(
!_disposed,
'Cannot dispose a codec that has already been disposed.',
);
_disposed = true;
delete();
}
@override
int get frameCount {
assert(_debugCheckIsNotDisposed());
return _frameCount;
}
@override
int get repetitionCount {
assert(_debugCheckIsNotDisposed());
return _repetitionCount;
}
@override
Future<ui.FrameInfo> getNextFrame() {
assert(_debugCheckIsNotDisposed());
final int durationMillis = skiaObject.decodeNextFrame();
final Duration duration = Duration(milliseconds: durationMillis);
final CkImage image = CkImage(skiaObject.makeImageAtCurrentFrame());
_nextFrameIndex = (_nextFrameIndex + 1) % _frameCount;
return Future<ui.FrameInfo>.value(AnimatedImageFrameInfo(duration, image));
}
}

View File

@@ -0,0 +1,433 @@
// Copyright 2013 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.
/// Uses the `ImageDecoder` class supplied by the browser.
///
/// See also:
///
/// * `image_wasm_codecs.dart`, which uses codecs supplied by the CanvasKit WASM bundle.
@JS()
library image_web_codecs;
import 'dart:async';
import 'dart:html' as html;
import 'dart:js_util' as js_util;
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:js/js.dart';
import 'package:ui/ui.dart' as ui;
import '../browser_detection.dart';
import '../util.dart';
import 'canvaskit_api.dart';
import 'image.dart';
@JS('window.ImageDecoder')
external Object? get _imageDecoderConstructor;
/// Whether the current browser supports `ImageDecoder`.
bool browserSupportsImageDecoder =
_imageDecoderConstructor != null && browserEngine == BrowserEngine.blink;
/// Sets the value of [browserSupportsImageDecoder] to its default value.
void debugResetBrowserSupportsImageDecoder() {
browserSupportsImageDecoder =
_imageDecoderConstructor != null;
}
/// Image decoder backed by the browser's `ImageDecoder`.
class CkBrowserImageDecoder implements ui.Codec {
static Future<CkBrowserImageDecoder> create({
required Uint8List data,
required String debugSource,
int? targetWidth,
int? targetHeight,
}) async {
// ImageDecoder does not detect image type automatically. It requires us to
// tell it what the image type is.
final String? contentType = detectContentType(data);
if (contentType == null) {
final String fileHeader;
if (data.isNotEmpty) {
fileHeader = '[' + bytesToHexString(data.sublist(0, math.min(10, data.length))) + ']';
} else {
fileHeader = 'empty';
}
throw ImageCodecException(
'Failed to detect image file format using the file header.\n'
'File header was $fileHeader.\n'
'Image source: $debugSource'
);
}
try {
final _ImageDecoder webDecoder = _ImageDecoder(_ImageDecoderOptions(
type: contentType,
data: data,
// Flutter always uses premultiplied alpha.
premultiplyAlpha: 'premultiply',
desiredWidth: targetWidth,
desiredHeight: targetHeight,
// "default" gives the browser the liberty to convert to display-appropriate
// color space, typically SRGB, which is what we want.
colorSpaceConversion: 'default',
// Flutter doesn't give the developer a way to customize this, so if this
// is an animated image we should prefer the animated track.
preferAnimation: true,
));
await js_util.promiseToFuture<void>(webDecoder.tracks.ready);
// Flutter doesn't have an API for progressive loading of images, so we
// wait until the image is fully decoded.
// package:js bindings don't work with getters that return a Promise, which
// is why js_util is used instead.
await js_util.promiseToFuture<void>(js_util.getProperty(webDecoder, 'completed'));
return CkBrowserImageDecoder._(webDecoder, debugSource);
} catch (error) {
if (error is html.DomException) {
if (error.name == html.DomException.NOT_SUPPORTED) {
throw ImageCodecException(
'Image file format ($contentType) is not supported by this browser\'s ImageDecoder API.\n'
'Image source: $debugSource',
);
}
}
throw ImageCodecException(
'Failed to decode image using the browser\'s ImageDecoder API.\n'
'Image source: $debugSource\n'
'Original browser error: $error'
);
}
}
CkBrowserImageDecoder._(this.webDecoder, this.debugSource);
final _ImageDecoder webDecoder;
final String debugSource;
/// Whether this decoded has been disposed of.
///
/// Once this turns true it stays true forever, and this decoder becomes
/// unusable.
bool _isDisposed = false;
@override
void dispose() {
_isDisposed = true;
// This releases all resources, including any currently running decoding work.
webDecoder.close();
}
void _debugCheckNotDisposed() {
assert(
!_isDisposed,
'Cannot use this image decoder. It has been disposed of.'
);
}
@override
int get frameCount {
_debugCheckNotDisposed();
return webDecoder.tracks.selectedTrack!.frameCount;
}
/// The index of the frame that will be decoded on the next call of [getNextFrame];
int _nextFrameIndex = 0;
@override
Future<ui.FrameInfo> getNextFrame() async {
_debugCheckNotDisposed();
final _DecodeResult result = await js_util.promiseToFuture<_DecodeResult>(
webDecoder.decode(_DecodeOptions(frameIndex: _nextFrameIndex)),
);
final _VideoFrame frame = result.image;
_nextFrameIndex = (_nextFrameIndex + 1) % frameCount;
final SkImage? skImage = canvasKit.MakeLazyImageFromTextureSource(
frame,
SkPartialImageInfo(
alphaType: canvasKit.AlphaType.Premul,
colorType: canvasKit.ColorType.RGBA_8888,
colorSpace: SkColorSpaceSRGB,
width: frame.displayWidth,
height: frame.displayHeight,
),
);
// Duration can be null if the image is not animated. However, Flutter
// requires a non-null value. 0 indicates that the frame is meant to be
// displayed indefinitely, which is fine for a static image.
final Duration duration = Duration(microseconds: frame.duration ?? 0);
if (skImage == null) {
throw ImageCodecException(
'Failed to create image from pixel data decoded using the browser\'s ImageDecoder.',
);
}
final CkImage image = CkImage(skImage);
return Future<ui.FrameInfo>.value(AnimatedImageFrameInfo(duration, image));
}
@override
int get repetitionCount {
_debugCheckNotDisposed();
return webDecoder.tracks.selectedTrack!.repetitionCount;
}
}
/// Corresponds to JavaScript's `Promise`.
///
/// This type doesn't need any members. Instead, it should be first converted
/// to Dart's [Future] using [promiseToFuture] then interacted with through the
/// [Future] API.
@JS()
@anonymous
class JsPromise {}
/// Corresponds to the browser's `ImageDecoder` type.
///
/// See also:
///
/// * https://www.w3.org/TR/webcodecs/#imagedecoder-interface
@JS('window.ImageDecoder')
class _ImageDecoder {
external _ImageDecoder(_ImageDecoderOptions options);
external _ImageTrackList get tracks;
external bool get complete;
external JsPromise decode(_DecodeOptions options);
external void close();
}
/// The result of [_ImageDecoder.decode].
///
/// See also:
///
/// * https://www.w3.org/TR/webcodecs/#imagedecoderesult-interface
@JS()
@anonymous
class _DecodeResult {
external _VideoFrame get image;
external bool get complete;
}
/// Options passed to [_ImageDecoder.decode].
///
/// See also:
///
/// * https://www.w3.org/TR/webcodecs/#dictdef-imagedecodeoptions
@JS()
@anonymous
class _DecodeOptions {
external factory _DecodeOptions({
required int frameIndex,
});
}
/// The only frame in a static image, or one of the frames in an animated one.
///
/// This class maps to the `VideoFrame` type provided by the browser.
///
/// See also:
///
/// * https://www.w3.org/TR/webcodecs/#videoframe-interface
@JS()
@anonymous
class _VideoFrame {
external int allocationSize();
external JsPromise copyTo(Uint8List destination);
external String? get format;
external int get codedWidth;
external int get codedHeight;
external int get displayWidth;
external int get displayHeight;
external int? get duration;
external void close();
}
/// Corresponds to the browser's `ImageTrackList` type.
///
/// See also:
///
/// * https://www.w3.org/TR/webcodecs/#imagetracklist-interface
@JS()
@anonymous
class _ImageTrackList {
external JsPromise get ready;
external _ImageTrack? get selectedTrack;
}
/// Corresponds to the browser's `ImageTrack` type.
///
/// See also:
///
/// * https://www.w3.org/TR/webcodecs/#imagetrack
@JS()
@anonymous
class _ImageTrack {
external int get repetitionCount;
external int get frameCount;
}
/// Represents an image file format, such as PNG or JPEG.
class ImageFileFormat {
const ImageFileFormat(this.header, this.contentType);
/// First few bytes in the file that uniquely identify the image file format.
///
/// Null elements are treated as wildcard values and are not checked. This is
/// used to detect formats whose header is split up into multiple disjoint
/// parts, such that the first part is not unique enough to identify the
/// format. For example, without this, WebP may be confused with .ani
/// (animated cursor), .cda, and other formats that start with "RIFF".
final List<int?> header;
/// The value that's passed as [_ImageDecoderOptions.type].
///
/// The server typically also uses this value as the "Content-Type" header,
/// but servers are not required to correctly detect the type. This value
/// is also known as MIME type.
final String contentType;
/// All image file formats known to the Flutter Web engine.
///
/// This list may need to be changed as browsers adopt new formats, and drop
/// support for obsolete ones.
///
/// This list is checked linearly from top to bottom when detecting an image
/// type. It should therefore contain the most popular file formats at the
/// top, and less popular towards the bottom.
static const List<ImageFileFormat> values = <ImageFileFormat>[
// ICO is not supported in Chrome. It is deemed too simple and too specific. See also:
// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/modules/webcodecs/image_decoder_external.cc;l=38;drc=fd8802b593110ea18a97ef044f8a40dd24a622ec
// PNG
ImageFileFormat(<int?>[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A], 'image/png'),
// GIF87a
ImageFileFormat(<int?>[0x47, 0x49, 0x46, 0x38, 0x37, 0x61], 'image/gif'),
// GIF89a
ImageFileFormat(<int?>[0x47, 0x49, 0x46, 0x38, 0x39, 0x61], 'image/gif'),
// JPEG
ImageFileFormat(<int?>[0xFF, 0xD8, 0xFF, 0xDB], 'image/jpeg'),
ImageFileFormat(<int?>[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01], 'image/jpeg'),
ImageFileFormat(<int?>[0xFF, 0xD8, 0xFF, 0xEE], 'image/jpeg'),
ImageFileFormat(<int?>[0xFF, 0xD8, 0xFF, 0xE1], 'image/jpeg'),
// WebP
ImageFileFormat(<int?>[0x52, 0x49, 0x46, 0x46, null, null, null, null, 0x57, 0x45, 0x42, 0x50], 'image/webp'),
// BMP
ImageFileFormat(<int?>[0x42, 0x4D], 'image/bmp'),
];
}
/// Function signature of [debugContentTypeDetector], which is the same as the
/// signature of [detectContentType].
typedef DebugContentTypeDetector = String? Function(Uint8List);
/// If not null, replaced the functionality of [detectContentType] with its own.
///
/// This is useful in tests, for example, to test unsupported content types.
DebugContentTypeDetector? debugContentTypeDetector;
/// Detects the image file format and returns the corresponding "Content-Type"
/// value (a.k.a. MIME type).
///
/// The returned value can be passed to `ImageDecoder` when decoding an image.
///
/// Returns null if [data] cannot be mapped to a known content type.
String? detectContentType(Uint8List data) {
if (debugContentTypeDetector != null) {
return debugContentTypeDetector!.call(data);
}
formatLoop: for (final ImageFileFormat format in ImageFileFormat.values) {
if (data.length < format.header.length) {
continue;
}
for (int i = 0; i < format.header.length; i++) {
final int? magicByte = format.header[i];
if (magicByte == null) {
// Wildcard, accepts everything.
continue;
}
final int headerByte = data[i];
if (headerByte != magicByte) {
continue formatLoop;
}
}
return format.contentType;
}
if (isAvif(data)) {
return 'image/avif';
}
return null;
}
/// A string of bytes that every AVIF image contains somehwere in its first 16
/// bytes.
///
/// This signature is necessary but not sufficient, which may lead to false
/// positives. For example, the file may be HEIC or a video. This is OK,
/// because in the worst case, the image decoder fails to decode the file.
/// This is something we must anticipate regardless of this detection logic.
/// The codec must already protect itself from downloaded files lying about
/// their contents.
///
/// The alternative would be to implement a more precise detection, which would
/// add complexity and code size. This is how Chromium does it:
///
/// https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/image-decoders/avif/avif_image_decoder.cc;l=504;drc=fd8802b593110ea18a97ef044f8a40dd24a622ec
final List<int> _avifSignature = 'ftyp'.codeUnits;
/// Optimistically detects whether [data] is an AVIF image file.
bool isAvif(Uint8List data) {
firstByteLoop: for (int i = 0; i < 16; i += 1) {
for (int j = 0; j < _avifSignature.length; j += 1) {
if (i + j >= data.length) {
// Reached EOF without finding the signature.
return false;
}
if (data[i + j] != _avifSignature[j]) {
continue firstByteLoop;
}
}
return true;
}
return false;
}
/// Options passed to the `ImageDecoder` constructor.
///
/// See also:
///
/// * https://www.w3.org/TR/webcodecs/#imagedecoderinit-interface
@JS()
@anonymous
class _ImageDecoderOptions {
external factory _ImageDecoderOptions({
required String type,
required Uint8List data,
required String premultiplyAlpha,
required int? desiredWidth,
required int? desiredHeight,
required String colorSpaceConversion,
required bool preferAnimation,
});
}

View File

@@ -113,7 +113,7 @@ class Surface {
///
/// The given [size] is in physical pixels.
SurfaceFrame acquireFrame(ui.Size size) {
final CkSurface surface = createOrUpdateSurfaces(size);
final CkSurface surface = createOrUpdateSurface(size);
// ignore: prefer_function_declarations_over_variables
final SubmitCallback submitCallback =
@@ -136,7 +136,7 @@ class Surface {
double _currentDevicePixelRatio = -1;
/// Creates a <canvas> and SkSurface for the given [size].
CkSurface createOrUpdateSurfaces(ui.Size size) {
CkSurface createOrUpdateSurface(ui.Size size) {
if (size.isEmpty) {
throw CanvasKitError('Cannot create surfaces of empty size.');
}
@@ -385,31 +385,36 @@ class Surface {
/// A Dart wrapper around Skia's CkSurface.
class CkSurface {
final SkSurface _surface;
final int? _glContext;
CkSurface(this._surface, this._glContext);
CkSurface(this.surface, this._glContext);
CkCanvas getCanvas() {
assert(!_isDisposed, 'Attempting to use the canvas of a disposed surface');
return CkCanvas(_surface.getCanvas());
return CkCanvas(surface.getCanvas());
}
/// The underlying CanvasKit surface object.
///
/// Only borrow this value temporarily. Do not store it as it may be deleted
/// at any moment. Storing it may lead to dangling pointer bugs.
final SkSurface surface;
final int? _glContext;
/// Flushes the graphics to be rendered on screen.
void flush() {
_surface.flush();
surface.flush();
}
int? get context => _glContext;
int width() => _surface.width();
int height() => _surface.height();
int width() => surface.width();
int height() => surface.height();
void dispose() {
if (_isDisposed) {
return;
}
_surface.dispose();
surface.dispose();
_isDisposed = true;
}

View File

@@ -669,3 +669,16 @@ num? parseFloat(String source) {
}
return result;
}
/// Prints a list of bytes in hex format.
///
/// Bytes are separated by one space and are padded on the left to always show
/// two digits.
///
/// Example:
///
/// Input: [0, 1, 2, 3]
/// Output: 0x00 0x01 0x02 0x03
String bytesToHexString(List<int> data) {
return data.map((int byte) => '0x' + byte.toRadixString(16).padLeft(2, '0')).join(' ');
}

View File

@@ -463,8 +463,7 @@ Future<Codec> instantiateImageCodec(
bool allowUpscaling = true,
}) async {
if (engine.useCanvasKit) {
// TODO(hterkelsen): Implement targetWidth and targetHeight support.
return engine.skiaInstantiateImageCodec(list);
return engine.skiaInstantiateImageCodec(list, targetWidth, targetHeight);
} else {
final html.Blob blob = html.Blob(<dynamic>[list.buffer]);
return engine.HtmlBlobCodec(blob);

View File

@@ -27,18 +27,6 @@ void main() {
const ui.Rect kDefaultRegion = ui.Rect.fromLTRB(0, 0, 500, 250);
Future<void> matchPictureGolden(String goldenFile, CkPicture picture,
{ui.Rect region = kDefaultRegion, bool write = false}) async {
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, picture);
dispatcher.rasterizer!.draw(sb.build().layerTree);
await matchGoldenFile(goldenFile,
region: region, maxDiffRatePercent: 0.0, write: write);
}
void testMain() {
group('CkCanvas', () {
setUpCanvasKitTest();
@@ -63,7 +51,10 @@ void testMain() {
expect(canvas.runtimeType, CkCanvas);
drawTestPicture(canvas);
await matchPictureGolden(
'canvaskit_picture.png', recorder.endRecording());
'canvaskit_picture.png',
recorder.endRecording(),
region: kDefaultRegion,
);
// Safari does not support weak refs (FinalizationRegistry).
// This test should be revisited when Safari ships weak refs.
// TODO(yjbanov): skip Firefox due to a crash: https://github.com/flutter/flutter/issues/86632
@@ -78,7 +69,7 @@ void testMain() {
drawTestPicture(canvas);
final CkPicture originalPicture = recorder.endRecording();
await matchPictureGolden('canvaskit_picture.png', originalPicture);
await matchPictureGolden('canvaskit_picture.png', originalPicture, region: kDefaultRegion);
final ByteData originalPixels =
(await (await originalPicture.toImage(50, 50)).toByteData())!;
@@ -93,7 +84,7 @@ void testMain() {
final ByteData restoredPixels =
(await (await restoredPicture.toImage(50, 50)).toByteData())!;
await matchPictureGolden('canvaskit_picture.png', restoredPicture);
await matchPictureGolden('canvaskit_picture.png', restoredPicture, region: kDefaultRegion);
expect(restoredPixels.buffer.asUint8List(),
originalPixels.buffer.asUint8List());
});
@@ -140,11 +131,7 @@ void testMain() {
);
canvas.drawRect(psl.paintBounds, shadowBoundsPaint);
final CkParagraphBuilder pb = CkParagraphBuilder(
CkParagraphStyle(),
);
pb.addText('$elevation');
final CkParagraph p = pb.build();
final CkParagraph p = makeSimpleText('$elevation');
p.layout(const ui.ParagraphConstraints(width: 1000));
canvas.drawParagraph(
p, ui.Offset(20 - p.maxIntrinsicWidth / 2, 20 - p.height / 2));
@@ -1137,19 +1124,7 @@ void drawTestPicture(CkCanvas canvas) {
canvas.restore();
canvas.translate(60, 0);
final CkParagraphBuilder pb = CkParagraphBuilder(CkParagraphStyle(
fontFamily: 'Roboto',
fontStyle: ui.FontStyle.normal,
fontWeight: ui.FontWeight.normal,
fontSize: 18,
));
pb.pushStyle(CkTextStyle(
color: const ui.Color(0xFF0000AA),
));
pb.addText('Hello');
pb.pop();
final CkParagraph p = pb.build();
p.layout(const ui.ParagraphConstraints(width: 1000));
final CkParagraph p = makeSimpleText('Hello', fontSize: 18, color: const ui.Color(0xFF0000AA));
canvas.drawParagraph(
p,
const ui.Offset(10, 20),
@@ -1192,7 +1167,7 @@ CkImage generateTestImage() {
colorSpace: SkColorSpaceSRGB,
),
imageData,
4 * 20);
4 * 20)!;
return CkImage(skImage);
}

View File

@@ -2,10 +2,13 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:web_engine_tester/golden_tester.dart';
export '../common.dart';
@@ -15,6 +18,8 @@ export '../common.dart';
/// See [TestCollector] for usage.
late TestCollector testCollector;
const MethodCodec codec = StandardMethodCodec();
/// Common test setup for all CanvasKit unit-tests.
void setUpCanvasKitTest() {
setUpAll(() async {
@@ -170,3 +175,73 @@ class TestCollector implements Collector {
_completedCollections.clear();
}
}
/// Checks that a [picture] matches the [goldenFile].
///
/// The picture is drawn onto the UI at [ui.Offset.zero] with no additional
/// layers.
Future<void> matchPictureGolden(String goldenFile, CkPicture picture,
{required ui.Rect region, bool write = false}) async {
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, picture);
dispatcher.rasterizer!.draw(sb.build().layerTree);
await matchGoldenFile(goldenFile,
region: region, maxDiffRatePercent: 0.0, write: write);
}
/// Sends a platform message to create a Platform View with the given id and viewType.
Future<void> createPlatformView(int id, String viewType) {
final Completer<void> completer = Completer<void>();
window.sendPlatformMessage(
'flutter/platform_views',
codec.encodeMethodCall(MethodCall(
'create',
<String, dynamic>{
'id': id,
'viewType': viewType,
},
)),
(dynamic _) => completer.complete(),
);
return completer.future;
}
/// Disposes of the platform view with the given [id].
Future<void> disposePlatformView(int id) {
final Completer<void> completer = Completer<void>();
window.sendPlatformMessage(
'flutter/platform_views',
codec.encodeMethodCall(MethodCall('dispose', id)),
(dynamic _) => completer.complete(),
);
return completer.future;
}
/// Creates a pre-laid out one-line paragraph of text.
///
/// Useful in tests that need a simple label to annotate goldens.
CkParagraph makeSimpleText(String text, {
String? fontFamily,
double? fontSize,
ui.FontStyle? fontStyle,
ui.FontWeight? fontWeight,
ui.Color? color,
}) {
final CkParagraphBuilder builder = CkParagraphBuilder(CkParagraphStyle(
fontFamily: fontFamily ?? 'Roboto',
fontSize: fontSize ?? 14,
fontStyle: fontStyle ?? ui.FontStyle.normal,
fontWeight: fontWeight ?? ui.FontWeight.normal,
));
builder.pushStyle(CkTextStyle(
color: color ?? const ui.Color(0xFF000000),
));
builder.addText(text);
builder.pop();
final CkParagraph paragraph = builder.build();
paragraph.layout(const ui.ParagraphConstraints(width: 10000));
return paragraph;
}

View File

@@ -12,8 +12,6 @@ import 'package:ui/ui.dart' as ui;
import 'common.dart';
const MethodCodec codec = StandardMethodCodec();
void main() {
internalBootstrapBrowserTest(() => testMain);
}
@@ -31,7 +29,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-0',
);
await _createPlatformView(0, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
@@ -67,7 +65,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-0',
);
await _createPlatformView(0, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
@@ -105,7 +103,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-0',
);
await _createPlatformView(0, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
@@ -150,7 +148,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-0',
);
await _createPlatformView(0, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
@@ -177,7 +175,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-0',
);
await _createPlatformView(0, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
@@ -218,7 +216,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-$i',
);
await _createPlatformView(i, 'test-platform-view');
await createPlatformView(i, 'test-platform-view');
platformViewIds.add(i);
}
@@ -303,7 +301,7 @@ void testMain() {
// Frame 7:
// Render: a platform view after error.
// Expect: success. Just checking the system is not left in a corrupted state.
await _createPlatformView(0, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
renderTestScene(viewCount: 0);
// TODO(yjbanov): skipped due to https://github.com/flutter/flutter/issues/73867
}, skip: isSafari);
@@ -321,7 +319,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-$i',
);
await _createPlatformView(i, 'test-platform-view');
await createPlatformView(i, 'test-platform-view');
platformViewIds.add(i);
}
@@ -370,7 +368,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-0',
);
await _createPlatformView(0, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
@@ -389,7 +387,7 @@ void testMain() {
isNotNull,
);
await _disposePlatformView(0);
await disposePlatformView(0);
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
@@ -410,7 +408,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-0',
);
await _createPlatformView(0, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
@@ -430,7 +428,7 @@ void testMain() {
);
// Render a frame with a different platform view.
await _createPlatformView(1, 'test-platform-view');
await createPlatformView(1, 'test-platform-view');
sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPlatformView(1, width: 10, height: 10);
@@ -468,7 +466,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'test-view',
);
await _createPlatformView(0, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
@@ -561,7 +559,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-0',
);
await _createPlatformView(0, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
@@ -585,7 +583,7 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-0',
);
await _createPlatformView(0, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
@@ -611,8 +609,8 @@ void testMain() {
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-0',
);
await _createPlatformView(0, 'test-platform-view');
await _createPlatformView(1, 'test-platform-view');
await createPlatformView(0, 'test-platform-view');
await createPlatformView(1, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
@@ -646,30 +644,3 @@ void testMain() {
// TODO(dit): https://github.com/flutter/flutter/issues/60040
}, skip: isIosSafari);
}
// Sends a platform message to create a Platform View with the given id and viewType.
Future<void> _createPlatformView(int id, String viewType) {
final Completer<void> completer = Completer<void>();
window.sendPlatformMessage(
'flutter/platform_views',
codec.encodeMethodCall(MethodCall(
'create',
<String, dynamic>{
'id': id,
'viewType': viewType,
},
)),
(dynamic _) => completer.complete(),
);
return completer.future;
}
Future<void> _disposePlatformView(int id) {
final Completer<void> completer = Completer<void>();
window.sendPlatformMessage(
'flutter/platform_views',
codec.encodeMethodCall(MethodCall('dispose', id)),
(dynamic _) => completer.complete(),
);
return completer.future;
}

View File

@@ -12,8 +12,6 @@ import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:web_engine_tester/golden_tester.dart';
import 'common.dart';
void main() {
@@ -22,18 +20,6 @@ void main() {
const ui.Rect kDefaultRegion = ui.Rect.fromLTRB(0, 0, 100, 50);
Future<void> matchPictureGolden(String goldenFile, CkPicture picture,
{ui.Rect region = kDefaultRegion, bool write = false}) async {
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(0, 0);
sb.addPicture(ui.Offset.zero, picture);
dispatcher.rasterizer!.draw(sb.build().layerTree);
await matchGoldenFile(goldenFile,
region: region, maxDiffRatePercent: 0.0, write: write);
}
void testMain() {
group('Font fallbacks', () {
setUpCanvasKitTest();
@@ -101,7 +87,10 @@ void testMain() {
canvas.drawParagraph(paragraph, const ui.Offset(0, 0));
await matchPictureGolden(
'canvaskit_font_fallback_arabic.png', recorder.endRecording());
'canvaskit_font_fallback_arabic.png',
recorder.endRecording(),
region: kDefaultRegion,
);
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
}, skip: isIosSafari || isFirefox);
@@ -208,7 +197,10 @@ void testMain() {
canvas.drawParagraph(paragraph, const ui.Offset(0, 0));
await matchPictureGolden(
'canvaskit_font_fallback_emoji.png', recorder.endRecording());
'canvaskit_font_fallback_emoji.png',
recorder.endRecording(),
region: kDefaultRegion,
);
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520
}, skip: isIosSafari || isFirefox);

View File

@@ -10,6 +10,7 @@ import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:web_engine_tester/golden_tester.dart';
import '../matchers.dart';
import 'common.dart';
@@ -20,13 +21,53 @@ void main() {
}
void testMain() {
group('CanvasKit image', () {
group('CanvasKit Images', () {
setUpCanvasKitTest();
tearDown(() {
debugRestoreHttpRequestFactory();
});
_testForImageCodecs(useBrowserImageDecoder: false);
if (browserSupportsImageDecoder) {
_testForImageCodecs(useBrowserImageDecoder: true);
}
test('isAvif', () {
expect(isAvif(Uint8List.fromList(<int>[])), isFalse);
expect(isAvif(Uint8List.fromList(<int>[1, 2, 3])), isFalse);
expect(
isAvif(Uint8List.fromList(<int>[
0x00, 0x00, 0x00, 0x1c, 0x66, 0x74, 0x79, 0x70,
0x61, 0x76, 0x69, 0x66, 0x00, 0x00, 0x00, 0x00,
])),
isTrue,
);
expect(
isAvif(Uint8List.fromList(<int>[
0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70,
0x61, 0x76, 0x69, 0x66, 0x00, 0x00, 0x00, 0x00,
])),
isTrue,
);
});
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
}, skip: isIosSafari);
}
void _testForImageCodecs({required bool useBrowserImageDecoder}) {
final String mode = useBrowserImageDecoder ? 'webcodecs' : 'wasm';
group('($mode})', () {
setUp(() {
browserSupportsImageDecoder = useBrowserImageDecoder;
});
tearDown(() {
debugResetBrowserSupportsImageDecoder();
});
test('CkAnimatedImage can be explicitly disposed of', () {
final CkAnimatedImage image = CkAnimatedImage.decodeFromBytes(kTransparentImage, 'test');
expect(image.debugDisposed, isFalse);
@@ -167,7 +208,7 @@ void testMain() {
return TestHttpRequest()
..status = 200
..onLoad = Stream<html.ProgressEvent>.fromIterable(<html.ProgressEvent>[
html.ProgressEvent('test error'),
html.ProgressEvent('test progress event'),
])
..response = kTransparentImage.buffer;
};
@@ -179,6 +220,38 @@ void testMain() {
testCollector.collectNow();
});
test('instantiateImageCodec respects target image size',
() async {
const List<List<int>> targetSizes = <List<int>>[
<int>[1, 1],
<int>[1, 2],
<int>[2, 3],
<int>[3, 4],
<int>[4, 4],
<int>[10, 20],
];
for (final List<int> targetSize in targetSizes) {
final int targetWidth = targetSize[0];
final int targetHeight = targetSize[1];
final ui.Codec codec = await ui.instantiateImageCodec(
k4x4PngImage,
targetWidth: targetWidth,
targetHeight: targetHeight,
);
final ui.Image image = (await codec.getNextFrame()).image;
// TODO(yjbanov): https://github.com/flutter/flutter/issues/34075
// expect(image.width, targetWidth);
// expect(image.height, targetHeight);
image.dispose();
codec.dispose();
}
testCollector.collectNow();
});
test('skiaInstantiateWebImageCodec throws exception on request error',
() async {
httpRequestFactory = () {
@@ -224,7 +297,7 @@ void testMain() {
return TestHttpRequest()
..status = 200
..onLoad = Stream<html.ProgressEvent>.fromIterable(<html.ProgressEvent>[
html.ProgressEvent('test error'),
html.ProgressEvent('test progress event'),
])
..response = Uint8List(0).buffer;
};
@@ -232,25 +305,124 @@ void testMain() {
await skiaInstantiateWebImageCodec('http://image-server.com/picture.jpg', null);
fail('Expected to throw');
} on ImageCodecException catch (exception) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: http://image-server.com/picture.jpg',
);
if (!browserSupportsImageDecoder) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: http://image-server.com/picture.jpg',
);
} else {
expect(
exception.toString(),
'ImageCodecException: Failed to detect image file format using the file header.\n'
'File header was empty.\n'
'Image source: http://image-server.com/picture.jpg',
);
}
}
testCollector.collectNow();
});
test('Reports error when failing to decode image data', () async {
test('Reports error when failing to decode empty image data', () async {
try {
await ui.instantiateImageCodec(Uint8List(0));
fail('Expected to throw');
} on ImageCodecException catch (exception) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: encoded image bytes'
);
if (!browserSupportsImageDecoder) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: encoded image bytes',
);
} else {
expect(
exception.toString(),
'ImageCodecException: Failed to detect image file format using the file header.\n'
'File header was empty.\n'
'Image source: encoded image bytes',
);
}
}
});
test('Reports error when failing to decode malformed image data', () async {
try {
await ui.instantiateImageCodec(Uint8List.fromList(<int>[
0xFF, 0xD8, 0xFF, 0xDB, 0x00, 0x00, 0x00,
]));
fail('Expected to throw');
} on ImageCodecException catch (exception) {
if (!browserSupportsImageDecoder) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: encoded image bytes'
);
} else {
expect(
exception.toString(),
// Browser error message is not checked as it can depend on the
// browser engine and version.
matches(RegExp(
r"ImageCodecException: Failed to decode image using the browser's ImageDecoder API.\n"
r'Image source: encoded image bytes\n'
r'Original browser error: .+'
))
);
}
}
});
test('Includes file header in the error message when fails to detect file type', () async {
try {
await ui.instantiateImageCodec(Uint8List.fromList(<int>[
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00,
]));
fail('Expected to throw');
} on ImageCodecException catch (exception) {
if (!browserSupportsImageDecoder) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: encoded image bytes'
);
} else {
expect(
exception.toString(),
'ImageCodecException: Failed to detect image file format using the file header.\n'
'File header was [0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x00].\n'
'Image source: encoded image bytes'
);
}
}
});
test('Provides readable error message when image type is unsupported', () async {
addTearDown(() {
debugContentTypeDetector = null;
});
debugContentTypeDetector = (_) {
return 'unsupported/image-type';
};
try {
await ui.instantiateImageCodec(Uint8List.fromList(<int>[
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00,
]));
fail('Expected to throw');
} on ImageCodecException catch (exception) {
if (!browserSupportsImageDecoder) {
expect(
exception.toString(),
'ImageCodecException: Failed to decode image data.\n'
'Image source: encoded image bytes'
);
} else {
expect(
exception.toString(),
'ImageCodecException: Image file format (unsupported/image-type) is not supported by this browser\'s ImageDecoder API.\n'
'Image source: encoded image bytes'
);
}
}
});
@@ -279,8 +451,88 @@ void testMain() {
expect(image2.width, 40);
expect(image2.height, 100);
});
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/60040
}, skip: isIosSafari);
test('Decode test images', () async {
final html.Body listingResponse = await httpFetch('/test_images/');
final List<String> testFiles = (await listingResponse.json() as List<dynamic>).cast<String>();
// Sanity-check the test file list. If suddenly test files are moved or
// deleted, and the test server returns an empty list, or is missing some
// important test files, we want to know.
expect(testFiles, isNotEmpty);
expect(testFiles, contains(matches(RegExp(r'.*\.jpg'))));
expect(testFiles, contains(matches(RegExp(r'.*\.png'))));
expect(testFiles, contains(matches(RegExp(r'.*\.gif'))));
expect(testFiles, contains(matches(RegExp(r'.*\.webp'))));
expect(testFiles, contains(matches(RegExp(r'.*\.bmp'))));
for (final String testFile in testFiles) {
final html.Body imageResponse = await httpFetch('/test_images/$testFile');
final Uint8List imageData = (await imageResponse.arrayBuffer() as ByteBuffer).asUint8List();
final ui.Codec codec = await skiaInstantiateImageCodec(imageData);
expect(codec.frameCount, greaterThan(0));
expect(codec.repetitionCount, isNotNull);
for (int i = 0; i < codec.frameCount; i++) {
final ui.FrameInfo frame = await codec.getNextFrame();
expect(frame.duration, isNotNull);
expect(frame.image, isNotNull);
}
codec.dispose();
}
});
// This is a regression test for the issues with transferring textures from
// one GL context to another, such as:
//
// * https://github.com/flutter/flutter/issues/86809
// * https://github.com/flutter/flutter/issues/91881
test('the same image can be rendered on difference surfaces', () async {
ui.platformViewRegistry.registerViewFactory(
'test-platform-view',
(int viewId) => html.DivElement()..id = 'view-0',
);
await createPlatformView(0, 'test-platform-view');
final EnginePlatformDispatcher dispatcher =
ui.window.platformDispatcher as EnginePlatformDispatcher;
final ui.Codec codec = await ui.instantiateImageCodec(k4x4PngImage);
final CkImage image = (await codec.getNextFrame()).image as CkImage;
final LayerSceneBuilder sb = LayerSceneBuilder();
sb.pushOffset(4, 4);
{
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.save();
canvas.scale(16, 16);
canvas.drawImage(image, ui.Offset.zero, CkPaint());
canvas.restore();
canvas.drawParagraph(makeSimpleText('1'), const ui.Offset(4, 4));
sb.addPicture(ui.Offset.zero, recorder.endRecording());
}
sb.addPlatformView(0, width: 100, height: 100);
sb.pushOffset(20, 20);
{
final CkPictureRecorder recorder = CkPictureRecorder();
final CkCanvas canvas = recorder.beginRecording(ui.Rect.largest);
canvas.save();
canvas.scale(16, 16);
canvas.drawImage(image, ui.Offset.zero, CkPaint());
canvas.restore();
canvas.drawParagraph(makeSimpleText('2'), const ui.Offset(2, 2));
sb.addPicture(ui.Offset.zero, recorder.endRecording());
}
dispatcher.rasterizer!.draw(sb.build().layerTree);
await matchGoldenFile(
'canvaskit_cross_gl_context_image_$mode.png',
region: const ui.Rect.fromLTRB(0, 0, 100, 100),
maxDiffRatePercent: 0,
);
await disposePlatformView(0);
});
});
}
class TestHttpRequest implements html.HttpRequest {

View File

@@ -2,15 +2,24 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
/// A 1x1 fully transparent PNG image.
final Uint8List kTransparentImage = Uint8List.fromList(<int>[
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49,
0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06,
0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44,
0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D,
0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE,
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x04, 0x00, 0x00, 0x00, 0xb5, 0x1c, 0x0c,
0x02, 0x00, 0x00, 0x00, 0x0b, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x63, 0x64, 0x60, 0x00, 0x00,
0x00, 0x06, 0x00, 0x02, 0x30, 0x81, 0xd0, 0x2f, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44,
0xae, 0x42, 0x60, 0x82,
]);
/// A 4x4 PNG image sample.
final Uint8List k4x4PngImage = Uint8List.fromList(<int>[
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x08, 0x06, 0x00, 0x00, 0x00, 0xa9, 0xf1, 0x9e,
0x7e, 0x00, 0x00, 0x00, 0x13, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x63, 0xfc, 0xcf, 0xc0, 0x50,
0xcf, 0x80, 0x04, 0x18, 0x49, 0x17, 0x00, 0x00, 0xf2, 0xae, 0x05, 0xfd, 0x52, 0x01, 0xc2, 0xde,
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
]);
/// An animated GIF image with 3 1x1 pixel frames (a red, green, and blue