[canvaskit] Refactor HtmlImageCodec to generalize to different renderers (flutter/engine#52905)

Refactor `HtmlImageCodec` to decouple it from the html renderer so other
renderers can create a `ui.Image` via `Image.decode()`.

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide] and the [C++,
Objective-C, Java style guides].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I added new tests to check the change I am making or feature I am
adding, or the PR is [test-exempt]. See [testing the engine] for
instructions on writing and running engine tests.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I signed the [CLA].
- [x] All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel
on [Discord].

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/wiki/Tree-hygiene#overview
[Tree Hygiene]: https://github.com/flutter/flutter/wiki/Tree-hygiene
[test-exempt]:
https://github.com/flutter/flutter/wiki/Tree-hygiene#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo
[C++, Objective-C, Java style guides]:
https://github.com/flutter/engine/blob/main/CONTRIBUTING.md#style
[testing the engine]:
https://github.com/flutter/flutter/wiki/Testing-the-engine
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[breaking change policy]:
https://github.com/flutter/flutter/wiki/Tree-hygiene#handling-breaking-changes
[Discord]: https://github.com/flutter/flutter/wiki/Chat
This commit is contained in:
Harry Terkelsen
2024-05-20 16:59:06 -07:00
committed by GitHub
parent dd229beeff
commit a554688620
14 changed files with 636 additions and 578 deletions

View File

@@ -43279,6 +43279,7 @@ ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/clip.dart + ../../../flu
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/color_filter.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/debug_canvas_reuse_overlay.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/dom_canvas.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/image.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/image_filter.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/offset.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/opacity.dart + ../../../flutter/LICENSE
@@ -43311,7 +43312,7 @@ ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/vertex_shaders.d
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/surface.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/surface_stats.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/transform.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html_image_codec.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html_image_element_codec.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/image_decoder.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/initialization.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/js_interop/js_app.dart + ../../../flutter/LICENSE
@@ -43328,7 +43329,6 @@ ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/navigation/history.dart + ../
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/noto_font.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/noto_font_encoding.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/onscreen_logging.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/picture.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/platform_dispatcher.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/platform_dispatcher/app_lifecycle_state.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/platform_dispatcher/view_focus_binding.dart + ../../../flutter/LICENSE
@@ -46156,6 +46156,7 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/clip.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/color_filter.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/debug_canvas_reuse_overlay.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/dom_canvas.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/image.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/image_filter.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/offset.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/opacity.dart
@@ -46188,7 +46189,7 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/vertex_shaders.dar
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/surface.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/surface_stats.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/transform.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html_image_codec.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html_image_element_codec.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/image_decoder.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/initialization.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/js_interop/js_app.dart
@@ -46205,7 +46206,6 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/navigation/history.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/noto_font.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/noto_font_encoding.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/onscreen_logging.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/picture.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/platform_dispatcher.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/platform_dispatcher/app_lifecycle_state.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/platform_dispatcher/view_focus_binding.dart

View File

@@ -73,6 +73,7 @@ export 'engine/html/clip.dart';
export 'engine/html/color_filter.dart';
export 'engine/html/debug_canvas_reuse_overlay.dart';
export 'engine/html/dom_canvas.dart';
export 'engine/html/image.dart';
export 'engine/html/image_filter.dart';
export 'engine/html/offset.dart';
export 'engine/html/opacity.dart';
@@ -105,7 +106,7 @@ export 'engine/html/shaders/vertex_shaders.dart';
export 'engine/html/surface.dart';
export 'engine/html/surface_stats.dart';
export 'engine/html/transform.dart';
export 'engine/html_image_codec.dart';
export 'engine/html_image_element_codec.dart';
export 'engine/image_decoder.dart';
export 'engine/initialization.dart';
export 'engine/js_interop/js_app.dart';
@@ -122,7 +123,6 @@ export 'engine/navigation/history.dart';
export 'engine/noto_font.dart';
export 'engine/noto_font_encoding.dart';
export 'engine/onscreen_logging.dart';
export 'engine/picture.dart';
export 'engine/platform_dispatcher.dart';
export 'engine/platform_dispatcher/app_lifecycle_state.dart';
export 'engine/platform_dispatcher/view_focus_binding.dart';

View File

@@ -13,13 +13,13 @@ import '../display.dart';
import '../dom.dart';
import '../engine_canvas.dart';
import '../frame_reference.dart';
import '../html_image_codec.dart';
import '../text/canvas_paragraph.dart';
import '../util.dart';
import '../vector_math.dart';
import 'clip.dart';
import 'color_filter.dart';
import 'dom_canvas.dart';
import 'image.dart';
import 'painting.dart';
import 'path/path.dart';
import 'recording_canvas.dart';
@@ -207,7 +207,8 @@ class BitmapCanvas extends EngineCanvas {
static int heightToPhysical(double height) {
final double boundsHeight = height + 1;
return (boundsHeight * EngineFlutterDisplay.instance.browserDevicePixelRatio)
return (boundsHeight *
EngineFlutterDisplay.instance.browserDevicePixelRatio)
.ceil() +
2 * kPaddingPixels;
}
@@ -252,7 +253,8 @@ class BitmapCanvas extends EngineCanvas {
/// * [PersistedPicture._recycleCanvas] which also uses this method
/// for the same reason.
bool isReusable() {
return _devicePixelRatio == EngineFlutterDisplay.instance.browserDevicePixelRatio;
return _devicePixelRatio ==
EngineFlutterDisplay.instance.browserDevicePixelRatio;
}
/// Returns a "data://" URI containing a representation of the image in this
@@ -365,12 +367,12 @@ class BitmapCanvas extends EngineCanvas {
return false;
}
return _renderStrategy.isInsideSvgFilterTree ||
_contains3dTransform ||
(_childOverdraw &&
!_canvasPool.hasCanvas &&
paint.maskFilter == null &&
paint.shader == null &&
paint.style != ui.PaintingStyle.stroke);
_contains3dTransform ||
(_childOverdraw &&
!_canvasPool.hasCanvas &&
paint.maskFilter == null &&
paint.shader == null &&
paint.style != ui.PaintingStyle.stroke);
}
/// Same as [_useDomForRenderingFill] but allows stroke as well.
@@ -381,13 +383,13 @@ class BitmapCanvas extends EngineCanvas {
return false;
}
return _renderStrategy.isInsideSvgFilterTree ||
_contains3dTransform ||
((_childOverdraw ||
_renderStrategy.hasImageElements ||
_renderStrategy.hasParagraphs) &&
!_canvasPool.hasCanvas &&
paint.maskFilter == null &&
paint.shader == null);
_contains3dTransform ||
((_childOverdraw ||
_renderStrategy.hasImageElements ||
_renderStrategy.hasParagraphs) &&
!_canvasPool.hasCanvas &&
paint.maskFilter == null &&
paint.shader == null);
}
@override
@@ -512,7 +514,8 @@ class BitmapCanvas extends EngineCanvas {
@override
void drawCircle(ui.Offset c, double radius, SurfacePaintData paint) {
if (_useDomForRenderingFillAndStroke(paint)) {
final ui.Rect rect = adjustRectForDom(ui.Rect.fromCircle(center: c, radius: radius), paint);
final ui.Rect rect = adjustRectForDom(
ui.Rect.fromCircle(center: c, radius: radius), paint);
final DomHTMLElement element = buildDrawRectElement(
rect, paint, 'draw-circle', _canvasPool.currentTransform);
_drawElement(element, rect.topLeft, paint);
@@ -572,7 +575,8 @@ class BitmapCanvas extends EngineCanvas {
final bool isStroke = paint.style == ui.PaintingStyle.stroke;
final String cssColor = colorValueToCssString(paint.color);
final double sigma = paint.maskFilter!.webOnlySigma;
if (ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit && !isStroke) {
if (ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit &&
!isStroke) {
// A bug in webkit leaves artifacts when this element is animated
// with filter: blur, we use boxShadow instead.
element.style.boxShadow = '0px 0px ${sigma * 2.0}px $cssColor';
@@ -625,7 +629,8 @@ class BitmapCanvas extends EngineCanvas {
ui.Image image, ui.Offset p, SurfacePaintData paint) {
final HtmlImage htmlImage = image as HtmlImage;
final ui.BlendMode? blendMode = paint.blendMode;
final EngineHtmlColorFilter? colorFilter = createHtmlColorFilter(paint.colorFilter);
final EngineHtmlColorFilter? colorFilter =
createHtmlColorFilter(paint.colorFilter);
DomHTMLElement imgElement;
if (colorFilter is ModeHtmlColorFilter) {
imgElement = _createImageElementWithBlend(
@@ -748,8 +753,7 @@ class BitmapCanvas extends EngineCanvas {
targetWidth *= image.width / src.width;
targetHeight *= image.height / src.height;
}
_applyTargetSize(
imgElement as DomHTMLElement, targetWidth, targetHeight);
_applyTargetSize(imgElement as DomHTMLElement, targetWidth, targetHeight);
if (requiresClipping) {
restore();
}
@@ -831,7 +835,8 @@ class BitmapCanvas extends EngineCanvas {
ui.BlendMode colorFilterBlendMode,
SurfacePaintData paint) {
// For srcIn blendMode, we use an svg filter to apply to image element.
final SvgFilter svgFilter = svgFilterFromBlendMode(filterColor, colorFilterBlendMode);
final SvgFilter svgFilter =
svgFilterFromBlendMode(filterColor, colorFilterBlendMode);
rootElement.append(svgFilter.element);
_children.add(svgFilter.element);
final DomHTMLElement imgElement = _reuseOrCreateImage(image);
@@ -893,7 +898,8 @@ class BitmapCanvas extends EngineCanvas {
///
/// The text is drawn starting at coordinates ([x], [y]). It uses the current
/// font set by the most recent call to [setCssFont].
void drawText(String text, double x, double y, {ui.PaintingStyle? style, List<ui.Shadow>? shadows}) {
void drawText(String text, double x, double y,
{ui.PaintingStyle? style, List<ui.Shadow>? shadows}) {
final DomCanvasRenderingContext2D ctx = _canvasPool.context;
if (shadows != null) {
ctx.save();
@@ -932,27 +938,23 @@ class BitmapCanvas extends EngineCanvas {
// Cannot composite if the paragraph cannot be drawn into bitmap canvas
// in the first place.
paragraph.canDrawOnCanvas &&
// Cannot composite if there's no bitmap canvas to composite into.
// Creating a new bitmap canvas just to draw text doesn't make sense.
_canvasPool.hasCanvas &&
!_childOverdraw &&
// Bitmap canvas introduces correctness issues in the presence of SVG
// filters, so prefer plain HTML in this case.
!_renderStrategy.isInsideSvgFilterTree;
// Cannot composite if there's no bitmap canvas to composite into.
// Creating a new bitmap canvas just to draw text doesn't make sense.
_canvasPool.hasCanvas &&
!_childOverdraw &&
// Bitmap canvas introduces correctness issues in the presence of SVG
// filters, so prefer plain HTML in this case.
!_renderStrategy.isInsideSvgFilterTree;
if (canCompositeIntoBitmapCanvas) {
paragraph.paint(this, offset);
return;
}
final DomElement paragraphElement =
drawParagraphElement(paragraph, offset);
final DomElement paragraphElement = drawParagraphElement(paragraph, offset);
if (_canvasPool.isClipped) {
final List<DomElement> clipElements = _clipContent(
_canvasPool.clipStack!,
paragraphElement,
offset,
_canvasPool.currentTransform);
final List<DomElement> clipElements = _clipContent(_canvasPool.clipStack!,
paragraphElement, offset, _canvasPool.currentTransform);
for (final DomElement clipElement in clipElements) {
rootElement.append(clipElement);
_children.add(clipElement);
@@ -1050,7 +1052,8 @@ class BitmapCanvas extends EngineCanvas {
void endOfPaint() {
_canvasPool.endOfPaint();
_elementCache?.commitFrame();
if (_contains3dTransform && ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit) {
if (_contains3dTransform &&
ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit) {
// Copy the children list to avoid concurrent modification.
final List<DomElement> children = rootElement.children.toList();
for (final DomElement element in children) {
@@ -1080,10 +1083,12 @@ class BitmapCanvas extends EngineCanvas {
final double width = ui.window.physicalSize.width * dpr;
final double height = ui.window.physicalSize.height * dpr;
final Vector3 topLeft = inverted.perspectiveTransform(x: 0, y: 0, z: 0);
final Vector3 topRight = inverted.perspectiveTransform(x: width, y: 0, z: 0);
final Vector3 topRight =
inverted.perspectiveTransform(x: width, y: 0, z: 0);
final Vector3 bottomRight =
inverted.perspectiveTransform(x: width, y: height, z: 0);
final Vector3 bottomLeft = inverted.perspectiveTransform(x: 0, y: height, z: 0);
final Vector3 bottomLeft =
inverted.perspectiveTransform(x: 0, y: height, z: 0);
return ui.Rect.fromLTRB(
math.min(topLeft.x,
math.min(topRight.x, math.min(bottomRight.x, bottomLeft.x))),
@@ -1254,13 +1259,17 @@ SvgBlendMode? blendModeToSvgEnum(ui.BlendMode? blendMode) {
case ui.BlendMode.srcATop:
return const SvgBlendMode(kCompositeSourceAtop, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.dstOver:
return const SvgBlendMode(kCompositeDestinationOver, SVG_FEBLEND_MODE_UNKNOWN);
return const SvgBlendMode(
kCompositeDestinationOver, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.dstIn:
return const SvgBlendMode(kCompositeDestinationIn, SVG_FEBLEND_MODE_UNKNOWN);
return const SvgBlendMode(
kCompositeDestinationIn, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.dstOut:
return const SvgBlendMode(kCompositeDestinationOut, SVG_FEBLEND_MODE_UNKNOWN);
return const SvgBlendMode(
kCompositeDestinationOut, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.dstATop:
return const SvgBlendMode(kCompositeDestinationAtop, SVG_FEBLEND_MODE_UNKNOWN);
return const SvgBlendMode(
kCompositeDestinationAtop, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.plus:
return const SvgBlendMode(kCompositeLighter, SVG_FEBLEND_MODE_UNKNOWN);
case ui.BlendMode.src:
@@ -1271,7 +1280,8 @@ SvgBlendMode? blendModeToSvgEnum(ui.BlendMode? blendMode) {
// Falling back to multiply, ignoring alpha channel.
// TODO(ferhat): only used for debug, find better fallback for web.
case ui.BlendMode.modulate:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_MULTIPLY);
return const SvgBlendMode(
kCompositeSourceOver, SVG_FEBLEND_MODE_MULTIPLY);
case ui.BlendMode.screen:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_SCREEN);
case ui.BlendMode.overlay:
@@ -1281,32 +1291,40 @@ SvgBlendMode? blendModeToSvgEnum(ui.BlendMode? blendMode) {
case ui.BlendMode.lighten:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_LIGHTEN);
case ui.BlendMode.colorDodge:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_COLOR_DODGE);
return const SvgBlendMode(
kCompositeSourceOver, SVG_FEBLEND_MODE_COLOR_DODGE);
case ui.BlendMode.colorBurn:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_COLOR_BURN);
return const SvgBlendMode(
kCompositeSourceOver, SVG_FEBLEND_MODE_COLOR_BURN);
case ui.BlendMode.hardLight:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_HARD_LIGHT);
return const SvgBlendMode(
kCompositeSourceOver, SVG_FEBLEND_MODE_HARD_LIGHT);
case ui.BlendMode.softLight:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_SOFT_LIGHT);
return const SvgBlendMode(
kCompositeSourceOver, SVG_FEBLEND_MODE_SOFT_LIGHT);
case ui.BlendMode.difference:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_DIFFERENCE);
return const SvgBlendMode(
kCompositeSourceOver, SVG_FEBLEND_MODE_DIFFERENCE);
case ui.BlendMode.exclusion:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_EXCLUSION);
return const SvgBlendMode(
kCompositeSourceOver, SVG_FEBLEND_MODE_EXCLUSION);
case ui.BlendMode.hue:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_HUE);
case ui.BlendMode.saturation:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_SATURATION);
return const SvgBlendMode(
kCompositeSourceOver, SVG_FEBLEND_MODE_SATURATION);
case ui.BlendMode.color:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_COLOR);
case ui.BlendMode.luminosity:
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_LUMINOSITY);
return const SvgBlendMode(
kCompositeSourceOver, SVG_FEBLEND_MODE_LUMINOSITY);
default:
assert(
false,
'Flutter Web does not support the blend mode: $blendMode',
);
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_NORMAL);
return const SvgBlendMode(kCompositeSourceOver, SVG_FEBLEND_MODE_NORMAL);
}
}
@@ -1344,8 +1362,8 @@ String stringForStrokeJoin(ui.StrokeJoin strokeJoin) {
/// overflow:hidden with bounds to clip child or sets a clip-path to clip
/// it's contents. The clipping rectangles are nested and returned together
/// with a list of svg elements that provide clip-paths.
List<DomElement> _clipContent(List<SaveClipEntry> clipStack,
DomElement content, ui.Offset offset, Matrix4 currentTransform) {
List<DomElement> _clipContent(List<SaveClipEntry> clipStack, DomElement content,
ui.Offset offset, Matrix4 currentTransform) {
DomElement? root, curElement;
final List<DomElement> clipDefs = <DomElement>[];
final int len = clipStack.length;

View File

@@ -7,11 +7,11 @@ import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../picture.dart';
import '../util.dart';
import '../validators.dart';
import '../vector_math.dart';
import 'painting.dart';
import 'picture.dart';
import 'recording_canvas.dart';
import 'render_vertices.dart';

View File

@@ -0,0 +1,126 @@
// 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.
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
class HtmlRendererImageCodec extends HtmlImageElementCodec {
HtmlRendererImageCodec(super.src, {super.chunkCallback});
@override
ui.Image createImageFromHTMLImageElement(
DomHTMLImageElement image,
int naturalWidth,
int naturalHeight,
) {
return HtmlImage(image, naturalWidth, naturalHeight);
}
}
class HtmlRendererBlobCodec extends HtmlBlobCodec {
HtmlRendererBlobCodec(super.blob);
@override
ui.Image createImageFromHTMLImageElement(
DomHTMLImageElement image,
int naturalWidth,
int naturalHeight,
) {
return HtmlImage(image, naturalWidth, naturalHeight);
}
}
class HtmlImage implements ui.Image {
HtmlImage(this.imgElement, this.width, this.height) {
ui.Image.onCreate?.call(this);
}
final DomHTMLImageElement imgElement;
bool _didClone = false;
bool _disposed = false;
@override
void dispose() {
ui.Image.onDispose?.call(this);
// Do nothing. The codec that owns this image should take care of
// releasing the object url.
assert(() {
_disposed = true;
return true;
}());
}
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _disposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError(
'Image.debugDisposed is only available when asserts are enabled.');
}
@override
ui.Image clone() => this;
@override
bool isCloneOf(ui.Image other) => other == this;
@override
List<StackTrace>? debugGetOpenHandleStackTraces() => null;
@override
final int width;
@override
final int height;
@override
Future<ByteData?> toByteData(
{ui.ImageByteFormat format = ui.ImageByteFormat.rawRgba}) {
switch (format) {
// TODO(ColdPaleLight): https://github.com/flutter/flutter/issues/89128
// The format rawRgba always returns straight rather than premul currently.
case ui.ImageByteFormat.rawRgba:
case ui.ImageByteFormat.rawStraightRgba:
final DomCanvasElement canvas = createDomCanvasElement()
..width = width.toDouble()
..height = height.toDouble();
final DomCanvasRenderingContext2D ctx = canvas.context2D;
ctx.drawImage(imgElement, 0, 0);
final DomImageData imageData = ctx.getImageData(0, 0, width, height);
return Future<ByteData?>.value(imageData.data.buffer.asByteData());
default:
if (imgElement.src?.startsWith('data:') ?? false) {
final UriData data = UriData.fromUri(Uri.parse(imgElement.src!));
return Future<ByteData?>.value(
data.contentAsBytes().buffer.asByteData());
} else {
return Future<ByteData?>.value();
}
}
}
@override
ui.ColorSpace get colorSpace => ui.ColorSpace.sRGB;
DomHTMLImageElement cloneImageElement() {
if (!_didClone) {
_didClone = true;
imgElement.style.position = 'absolute';
}
return imgElement.cloneNode(true) as DomHTMLImageElement;
}
@override
String toString() => '[$width\u00D7$height]';
}

View File

@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math' as math;
import 'dart:typed_data';
@@ -10,16 +11,133 @@ import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../engine_canvas.dart';
import '../frame_reference.dart';
import '../picture.dart';
import '../util.dart';
import '../vector_math.dart';
import 'bitmap_canvas.dart';
import 'debug_canvas_reuse_overlay.dart';
import 'dom_canvas.dart';
import 'image.dart';
import 'path/path_metrics.dart';
import 'recording_canvas.dart';
import 'surface.dart';
import 'surface_stats.dart';
class EnginePictureRecorder implements ui.PictureRecorder {
EnginePictureRecorder();
RecordingCanvas? _canvas;
late ui.Rect cullRect;
bool _isRecording = false;
RecordingCanvas beginRecording(ui.Rect bounds) {
assert(!_isRecording);
cullRect = bounds;
_isRecording = true;
return _canvas = RecordingCanvas(cullRect);
}
@override
bool get isRecording => _isRecording;
@override
EnginePicture endRecording() {
if (!_isRecording) {
// The mobile version returns an empty picture in this case. To match the
// behavior we produce a blank picture too.
beginRecording(ui.Rect.largest);
}
_isRecording = false;
_canvas!.endRecording();
final EnginePicture result = EnginePicture(_canvas, cullRect);
// We invoke the handler here, not in the Picture constructor, because we want
// [result.approximateBytesUsed] to be available for the handler.
ui.Picture.onCreate?.call(result);
return result;
}
}
/// An implementation of [ui.Picture] which is backed by a [RecordingCanvas].
class EnginePicture implements ui.Picture {
/// This class is created by the engine, and should not be instantiated
/// or extended directly.
///
/// To create a [Picture], use a [PictureRecorder].
EnginePicture(this.recordingCanvas, this.cullRect);
@override
Future<ui.Image> toImage(int width, int height) async {
final ui.Rect imageRect =
ui.Rect.fromLTRB(0, 0, width.toDouble(), height.toDouble());
final BitmapCanvas canvas = BitmapCanvas.imageData(imageRect);
recordingCanvas!.apply(canvas, imageRect);
final String imageDataUrl = canvas.toDataUrl();
final DomHTMLImageElement imageElement = createDomHTMLImageElement()
..src = imageDataUrl
..width = width.toDouble()
..height = height.toDouble();
// The image loads asynchronously. We need to wait before returning,
// otherwise the returned HtmlImage will be temporarily unusable.
final Completer<ui.Image> onImageLoaded = Completer<ui.Image>.sync();
// Ignoring the returned futures from onError and onLoad because we're
// communicating through the `onImageLoaded` completer.
late final DomEventListener errorListener;
errorListener = createDomEventListener((DomEvent event) {
onImageLoaded.completeError(event);
imageElement.removeEventListener('error', errorListener);
});
imageElement.addEventListener('error', errorListener);
late final DomEventListener loadListener;
loadListener = createDomEventListener((DomEvent event) {
onImageLoaded.complete(HtmlImage(
imageElement,
width,
height,
));
imageElement.removeEventListener('load', loadListener);
});
imageElement.addEventListener('load', loadListener);
return onImageLoaded.future;
}
@override
ui.Image toImageSync(int width, int height) {
throw UnsupportedError(
'toImageSync is not supported on the HTML backend. Use drawPicture instead, or toImage.');
}
bool _disposed = false;
@override
void dispose() {
ui.Picture.onDispose?.call(this);
_disposed = true;
}
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _disposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError(
'Picture.debugDisposed is only available when asserts are enabled.');
}
@override
int get approximateBytesUsed => 0;
final RecordingCanvas? recordingCanvas;
final ui.Rect? cullRect;
}
// TODO(yjbanov): this is currently very naive. We probably want to cache
// fewer large canvases than small canvases. We could also
// improve cache hit count if we did not require exact canvas
@@ -228,8 +346,7 @@ class PersistedPicture extends PersistedLeafSurface {
if (parent!.projectedClip == null) {
_exactLocalCullRect = localPaintBounds;
} else {
_exactLocalCullRect =
localPaintBounds!.intersect(parent!.projectedClip!);
_exactLocalCullRect = localPaintBounds!.intersect(parent!.projectedClip!);
}
if (_exactLocalCullRect!.width <= 0 || _exactLocalCullRect!.height <= 0) {
_exactLocalCullRect = ui.Rect.zero;

View File

@@ -8,7 +8,6 @@ import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../engine_canvas.dart';
import '../picture.dart';
import '../rrect_renderer.dart';
import '../shadow.dart';
import '../text/canvas_paragraph.dart';
@@ -17,6 +16,7 @@ import '../vector_math.dart';
import 'painting.dart';
import 'path/path.dart';
import 'path/path_utils.dart';
import 'picture.dart';
import 'render_vertices.dart';
import 'shaders/image_shader.dart';
@@ -24,7 +24,7 @@ import 'shaders/image_shader.dart';
const bool _debugDumpPaintCommands = false;
// Returns the squared length of the x, y (of a border radius).
double _measureBorderRadius(double x, double y) => x*x + y*y;
double _measureBorderRadius(double x, double y) => x * x + y * y;
/// Records canvas commands to be applied to a [EngineCanvas].
///
@@ -314,7 +314,8 @@ class RecordingCanvas {
_commands.add(command);
}
ui.Rect? getDestinationClipBounds() => _paintBounds.getDestinationClipBounds();
ui.Rect? getDestinationClipBounds() =>
_paintBounds.getDestinationClipBounds();
void drawColor(ui.Color color, ui.BlendMode blendMode) {
assert(!_recordingEnded);
@@ -539,7 +540,8 @@ class RecordingCanvas {
_didDraw = true;
final double left = offset.dx;
final double top = offset.dy;
final PaintDrawImage command = PaintDrawImage(image, offset, paint.paintData);
final PaintDrawImage command =
PaintDrawImage(image, offset, paint.paintData);
_paintBounds.growLTRB(
left, top, left + image.width, top + image.height, command);
_commands.add(command);
@@ -845,7 +847,8 @@ class PaintTransform extends PaintCommand {
String toString() {
String result = super.toString();
assert(() {
result = 'transform(Matrix4.fromFloat32List(Float32List.fromList(<double>[${matrix4.join(', ')}])))';
result =
'transform(Matrix4.fromFloat32List(Float32List.fromList(<double>[${matrix4.join(', ')}])))';
return true;
}());
return result;
@@ -1421,7 +1424,8 @@ class Ellipse extends PathCommand {
anticlockwise ? startAngle - endAngle : endAngle - startAngle,
matrix4,
bezierPath);
targetPath.addPathWithMode(bezierPath, 0, 0, matrix4, SPathAddPathMode.kAppend);
targetPath.addPathWithMode(
bezierPath, 0, 0, matrix4, SPathAddPathMode.kAppend);
}
void _drawArcWithBezier(
@@ -1680,7 +1684,8 @@ class RRectCommand extends PathCommand {
void transform(Float32List matrix4, SurfacePath targetPath) {
final ui.Path roundRectPath = ui.Path();
RRectToPathRenderer(roundRectPath).render(rrect);
targetPath.addPathWithMode(roundRectPath, 0, 0, matrix4, SPathAddPathMode.kAppend);
targetPath.addPathWithMode(
roundRectPath, 0, 0, matrix4, SPathAddPathMode.kAppend);
}
@override

View File

@@ -45,11 +45,8 @@ class HtmlRenderer implements Renderer {
List<ui.Offset>? textureCoordinates,
List<ui.Color>? colors,
List<int>? indices,
}) => SurfaceVertices(
mode,
positions,
colors: colors,
indices: indices);
}) =>
SurfaceVertices(mode, positions, colors: colors, indices: indices);
@override
ui.Vertices createVerticesRaw(
@@ -58,25 +55,20 @@ class HtmlRenderer implements Renderer {
Float32List? textureCoordinates,
Int32List? colors,
Uint16List? indices,
}) => SurfaceVertices.raw(
mode,
positions,
colors: colors,
indices: indices);
}) =>
SurfaceVertices.raw(mode, positions, colors: colors, indices: indices);
@override
ui.Canvas createCanvas(ui.PictureRecorder recorder, [ui.Rect? cullRect]) =>
SurfaceCanvas(recorder as EnginePictureRecorder, cullRect);
SurfaceCanvas(recorder as EnginePictureRecorder, cullRect);
@override
ui.Gradient createLinearGradient(
ui.Offset from,
ui.Offset to,
List<ui.Color> colors, [
List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
Float32List? matrix4
]) => GradientLinear(from, to, colors, colorStops, tileMode, matrix4);
ui.Offset from, ui.Offset to, List<ui.Color> colors,
[List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
Float32List? matrix4]) =>
GradientLinear(from, to, colors, colorStops, tileMode, matrix4);
@override
ui.Gradient createRadialGradient(
@@ -86,38 +78,27 @@ class HtmlRenderer implements Renderer {
List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
Float32List? matrix4,
]) => GradientRadial(center, radius, colors, colorStops, tileMode, matrix4);
]) =>
GradientRadial(center, radius, colors, colorStops, tileMode, matrix4);
@override
ui.Gradient createConicalGradient(
ui.Offset focal,
double focalRadius,
ui.Offset center,
double radius,
List<ui.Color> colors,
[List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
Float32List? matrix
]) => GradientConical(
focal,
focalRadius,
center,
radius,
colors,
colorStops,
tileMode,
matrix);
ui.Gradient createConicalGradient(ui.Offset focal, double focalRadius,
ui.Offset center, double radius, List<ui.Color> colors,
[List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
Float32List? matrix]) =>
GradientConical(focal, focalRadius, center, radius, colors, colorStops,
tileMode, matrix);
@override
ui.Gradient createSweepGradient(
ui.Offset center,
List<ui.Color> colors, [
List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
double startAngle = 0.0,
double endAngle = math.pi * 2,
Float32List? matrix4
]) => GradientSweep(center, colors, colorStops, tileMode, startAngle, endAngle, matrix4);
ui.Gradient createSweepGradient(ui.Offset center, List<ui.Color> colors,
[List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
double startAngle = 0.0,
double endAngle = math.pi * 2,
Float32List? matrix4]) =>
GradientSweep(
center, colors, colorStops, tileMode, startAngle, endAngle, matrix4);
@override
ui.PictureRecorder createPictureRecorder() => EnginePictureRecorder();
@@ -127,45 +108,48 @@ class HtmlRenderer implements Renderer {
// TODO(ferhat): implement TileMode.
@override
ui.ImageFilter createBlurImageFilter({
double sigmaX = 0.0,
double sigmaY = 0.0,
ui.TileMode tileMode = ui.TileMode.clamp
}) => EngineImageFilter.blur(sigmaX: sigmaX, sigmaY: sigmaY, tileMode: tileMode);
ui.ImageFilter createBlurImageFilter(
{double sigmaX = 0.0,
double sigmaY = 0.0,
ui.TileMode tileMode = ui.TileMode.clamp}) =>
EngineImageFilter.blur(
sigmaX: sigmaX, sigmaY: sigmaY, tileMode: tileMode);
@override
ui.ImageFilter createDilateImageFilter({double radiusX = 0.0, double radiusY = 0.0}) {
ui.ImageFilter createDilateImageFilter(
{double radiusX = 0.0, double radiusY = 0.0}) {
// TODO(fzyzcjy): implement dilate. https://github.com/flutter/flutter/issues/101085
throw UnimplementedError('ImageFilter.dilate not implemented for HTML renderer.');
throw UnimplementedError(
'ImageFilter.dilate not implemented for HTML renderer.');
}
@override
ui.ImageFilter createErodeImageFilter({double radiusX = 0.0, double radiusY = 0.0}) {
ui.ImageFilter createErodeImageFilter(
{double radiusX = 0.0, double radiusY = 0.0}) {
// TODO(fzyzcjy): implement erode. https://github.com/flutter/flutter/issues/101085
throw UnimplementedError('ImageFilter.erode not implemented for HTML renderer.');
throw UnimplementedError(
'ImageFilter.erode not implemented for HTML renderer.');
}
@override
ui.ImageFilter createMatrixImageFilter(
Float64List matrix4, {
ui.FilterQuality filterQuality = ui.FilterQuality.low
}) => EngineImageFilter.matrix(matrix: matrix4, filterQuality: filterQuality);
ui.ImageFilter createMatrixImageFilter(Float64List matrix4,
{ui.FilterQuality filterQuality = ui.FilterQuality.low}) =>
EngineImageFilter.matrix(matrix: matrix4, filterQuality: filterQuality);
@override
ui.ImageFilter composeImageFilters({required ui.ImageFilter outer, required ui.ImageFilter inner}) {
ui.ImageFilter composeImageFilters(
{required ui.ImageFilter outer, required ui.ImageFilter inner}) {
// TODO(ferhat): add implementation and remove the "ignore".
// ignore: avoid_unused_constructor_parameters
throw UnimplementedError('ImageFilter.erode not implemented for HTML renderer.');
throw UnimplementedError(
'ImageFilter.erode not implemented for HTML renderer.');
}
@override
Future<ui.Codec> instantiateImageCodec(
Uint8List list, {
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true}) async {
Future<ui.Codec> instantiateImageCodec(Uint8List list,
{int? targetWidth, int? targetHeight, bool allowUpscaling = true}) async {
final DomBlob blob = createDomBlob(<dynamic>[list.buffer]);
return HtmlBlobCodec(blob);
return HtmlRendererBlobCodec(blob);
}
@override
@@ -173,38 +157,35 @@ class HtmlRenderer implements Renderer {
Uri uri, {
ui_web.ImageCodecChunkCallback? chunkCallback,
}) async {
return HtmlCodec(uri.toString(), chunkCallback: chunkCallback);
return HtmlRendererImageCodec(uri.toString(), chunkCallback: chunkCallback);
}
@override
void decodeImageFromPixels(
Uint8List pixels,
int width,
int height,
ui.PixelFormat format,
ui.ImageDecoderCallback callback, {
int? rowBytes,
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true
}) {
void decodeImageFromPixels(Uint8List pixels, int width, int height,
ui.PixelFormat format, ui.ImageDecoderCallback callback,
{int? rowBytes,
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true}) {
void executeCallback(ui.Codec codec) {
codec.getNextFrame().then((ui.FrameInfo frameInfo) {
callback(frameInfo.image);
});
}
ui.createBmp(pixels, width, height, rowBytes ?? width, format).then(
executeCallback);
ui
.createBmp(pixels, width, height, rowBytes ?? width, format)
.then(executeCallback);
}
@override
ui.ImageShader createImageShader(
ui.Image image,
ui.TileMode tmx,
ui.TileMode tmy,
Float64List matrix4,
ui.FilterQuality? filterQuality
) => EngineImageShader(image, tmx, tmy, matrix4, filterQuality);
ui.Image image,
ui.TileMode tmx,
ui.TileMode tmy,
Float64List matrix4,
ui.FilterQuality? filterQuality) =>
EngineImageShader(image, tmx, tmy, matrix4, filterQuality);
@override
ui.Path createPath() => SurfacePath();
@@ -218,111 +199,112 @@ class HtmlRenderer implements Renderer {
}
@override
ui.TextStyle createTextStyle({
ui.Color? color,
ui.TextDecoration? decoration,
ui.Color? decorationColor,
ui.TextDecorationStyle? decorationStyle,
double? decorationThickness,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
ui.TextBaseline? textBaseline,
String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
double? letterSpacing,
double? wordSpacing,
double? height,
ui.TextLeadingDistribution? leadingDistribution,
ui.Locale? locale,
ui.Paint? background,
ui.Paint? foreground,
List<ui.Shadow>? shadows,
List<ui.FontFeature>? fontFeatures,
List<ui.FontVariation>? fontVariations
}) => EngineTextStyle(
color: color,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
decorationThickness: decorationThickness,
fontWeight: fontWeight,
fontStyle: fontStyle,
textBaseline: textBaseline,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSize: fontSize,
letterSpacing: letterSpacing,
wordSpacing: wordSpacing,
height: height,
leadingDistribution: leadingDistribution,
locale: locale,
background: background,
foreground: foreground,
shadows: shadows,
fontFeatures: fontFeatures,
fontVariations: fontVariations,
);
ui.TextStyle createTextStyle(
{ui.Color? color,
ui.TextDecoration? decoration,
ui.Color? decorationColor,
ui.TextDecorationStyle? decorationStyle,
double? decorationThickness,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
ui.TextBaseline? textBaseline,
String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
double? letterSpacing,
double? wordSpacing,
double? height,
ui.TextLeadingDistribution? leadingDistribution,
ui.Locale? locale,
ui.Paint? background,
ui.Paint? foreground,
List<ui.Shadow>? shadows,
List<ui.FontFeature>? fontFeatures,
List<ui.FontVariation>? fontVariations}) =>
EngineTextStyle(
color: color,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
decorationThickness: decorationThickness,
fontWeight: fontWeight,
fontStyle: fontStyle,
textBaseline: textBaseline,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSize: fontSize,
letterSpacing: letterSpacing,
wordSpacing: wordSpacing,
height: height,
leadingDistribution: leadingDistribution,
locale: locale,
background: background,
foreground: foreground,
shadows: shadows,
fontFeatures: fontFeatures,
fontVariations: fontVariations,
);
@override
ui.ParagraphStyle createParagraphStyle({
ui.TextAlign? textAlign,
ui.TextDirection? textDirection,
int? maxLines,
String? fontFamily,
double? fontSize,
double? height,
ui.TextHeightBehavior? textHeightBehavior,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
ui.StrutStyle? strutStyle,
String? ellipsis,
ui.Locale? locale
}) => EngineParagraphStyle(
textAlign: textAlign,
textDirection: textDirection,
maxLines: maxLines,
fontFamily: fontFamily,
fontSize: fontSize,
height: height,
textHeightBehavior: textHeightBehavior,
fontWeight: fontWeight,
fontStyle: fontStyle,
strutStyle: strutStyle,
ellipsis: ellipsis,
locale: locale,
);
ui.ParagraphStyle createParagraphStyle(
{ui.TextAlign? textAlign,
ui.TextDirection? textDirection,
int? maxLines,
String? fontFamily,
double? fontSize,
double? height,
ui.TextHeightBehavior? textHeightBehavior,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
ui.StrutStyle? strutStyle,
String? ellipsis,
ui.Locale? locale}) =>
EngineParagraphStyle(
textAlign: textAlign,
textDirection: textDirection,
maxLines: maxLines,
fontFamily: fontFamily,
fontSize: fontSize,
height: height,
textHeightBehavior: textHeightBehavior,
fontWeight: fontWeight,
fontStyle: fontStyle,
strutStyle: strutStyle,
ellipsis: ellipsis,
locale: locale,
);
@override
ui.StrutStyle createStrutStyle({
String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
double? height,
ui.TextLeadingDistribution? leadingDistribution,
double? leading,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
bool? forceStrutHeight
}) => EngineStrutStyle(
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSize: fontSize,
height: height,
leadingDistribution: leadingDistribution,
leading: leading,
fontWeight: fontWeight,
fontStyle: fontStyle,
forceStrutHeight: forceStrutHeight,
);
ui.StrutStyle createStrutStyle(
{String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
double? height,
ui.TextLeadingDistribution? leadingDistribution,
double? leading,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
bool? forceStrutHeight}) =>
EngineStrutStyle(
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSize: fontSize,
height: height,
leadingDistribution: leadingDistribution,
leading: leading,
fontWeight: fontWeight,
fontStyle: fontStyle,
forceStrutHeight: forceStrutHeight,
);
@override
ui.ParagraphBuilder createParagraphBuilder(ui.ParagraphStyle style) =>
CanvasParagraphBuilder(style as EngineParagraphStyle);
CanvasParagraphBuilder(style as EngineParagraphStyle);
@override
Future<void> renderScene(ui.Scene scene, ui.FlutterView view) async {
final EngineFlutterView implicitView = EnginePlatformDispatcher.instance.implicitView!;
final EngineFlutterView implicitView =
EnginePlatformDispatcher.instance.implicitView!;
scene as SurfaceScene;
implicitView.dom.setScene(scene.webOnlyRootElement!);
final FrameTimingRecorder? recorder = scene.timingRecorder;
@@ -331,7 +313,7 @@ class HtmlRenderer implements Renderer {
}
@override
void clearFragmentProgramCache() { }
void clearFragmentProgramCache() {}
@override
Future<ui.FragmentProgram> createFragmentProgram(String assetKey) {
@@ -339,34 +321,35 @@ class HtmlRenderer implements Renderer {
}
@override
ui.LineMetrics createLineMetrics({
required bool hardBreak,
required double ascent,
required double descent,
required double unscaledAscent,
required double height,
required double width,
required double left,
required double baseline,
required int lineNumber
}) => EngineLineMetrics(
hardBreak: hardBreak,
ascent: ascent,
descent: descent,
unscaledAscent: unscaledAscent,
height: height,
width: width,
left: left,
baseline: baseline,
lineNumber: lineNumber
);
ui.LineMetrics createLineMetrics(
{required bool hardBreak,
required double ascent,
required double descent,
required double unscaledAscent,
required double height,
required double width,
required double left,
required double baseline,
required int lineNumber}) =>
EngineLineMetrics(
hardBreak: hardBreak,
ascent: ascent,
descent: descent,
unscaledAscent: unscaledAscent,
height: height,
width: width,
left: left,
baseline: baseline,
lineNumber: lineNumber);
@override
Future<ui.Image> createImageFromImageBitmap(DomImageBitmap imageSource) async {
Future<ui.Image> createImageFromImageBitmap(
DomImageBitmap imageSource) async {
final int width = imageSource.width.toDartInt;
final int height = imageSource.height.toDartInt;
final OffScreenCanvas canvas = OffScreenCanvas(width, height);
final DomCanvasRenderingContextBitmapRenderer context = canvas.getBitmapRendererContext()!;
final DomCanvasRenderingContextBitmapRenderer context =
canvas.getBitmapRendererContext()!;
context.transferFromImageBitmap(imageSource);
final DomHTMLImageElement imageElement = createDomHTMLImageElement();
late final DomEventListener loadListener;
@@ -378,7 +361,8 @@ class HtmlRenderer implements Renderer {
imageElement.removeEventListener('error', errorListener);
});
errorListener = createDomEventListener((DomEvent event) {
completer.completeError(Exception('Failed to create image from image bitmap.'));
completer.completeError(
Exception('Failed to create image from image bitmap.'));
imageElement.removeEventListener('load', loadListener);
imageElement.removeEventListener('error', errorListener);
});

View File

@@ -10,7 +10,6 @@ import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../../engine.dart' show FrameTimingRecorder, kProfileApplyFrame, kProfilePrerollFrame;
import '../display.dart';
import '../dom.dart';
import '../picture.dart';
import '../profiler.dart';
import '../util.dart';
import '../vector_math.dart';

View File

@@ -8,9 +8,9 @@ import 'package:ui/ui.dart' as ui;
import '../../browser_detection.dart';
import '../../dom.dart';
import '../../html_image_codec.dart';
import '../../safe_browser_api.dart';
import '../../vector_math.dart';
import '../image.dart';
import '../render_vertices.dart';
import 'vertex_shaders.dart';
@@ -83,7 +83,8 @@ class EngineImageShader implements ui.ImageShader {
final int imageHeight = image.height;
final int newWidth = imageWidth * mirrorX;
final int newHeight = imageHeight * mirrorY;
final OffScreenCanvas offscreenCanvas = OffScreenCanvas(newWidth, newHeight);
final OffScreenCanvas offscreenCanvas =
OffScreenCanvas(newWidth, newHeight);
final Object renderContext = offscreenCanvas.getContext2d()!;
for (int y = 0; y < mirrorY; y++) {
for (int x = 0; x < mirrorX; x++) {
@@ -151,7 +152,8 @@ class EngineImageShader implements ui.ImageShader {
const int vertexCount = 6;
final Float32List vertices = Float32List(vertexCount * 2);
final ui.Rect vRect = shaderBounds.translate(-shaderBounds.left, -shaderBounds.top);
final ui.Rect vRect =
shaderBounds.translate(-shaderBounds.left, -shaderBounds.top);
vertices[0] = vRect.left;
vertices[1] = vRect.top;
vertices[2] = vRect.right;
@@ -168,20 +170,15 @@ class EngineImageShader implements ui.ImageShader {
final Object positionAttributeLocation =
gl.getAttributeLocation(glProgram.program, 'position');
setupVertexTransforms(gl, glProgram, 0, 0,
widthInPixels.toDouble(), heightInPixels.toDouble(), transform);
setupVertexTransforms(gl, glProgram, 0, 0, widthInPixels.toDouble(),
heightInPixels.toDouble(), transform);
requiresTileOffset = shaderBounds.left !=0 || shaderBounds.top != 0;
requiresTileOffset = shaderBounds.left != 0 || shaderBounds.top != 0;
/// To map from vertex position to texture coordinate in 0..1 range,
/// we setup scalar to be used in vertex shader.
setupTextureTransform(
gl,
glProgram,
shaderBounds.left,
shaderBounds.top,
1.0 / image.width.toDouble(),
1.0 / image.height.toDouble());
setupTextureTransform(gl, glProgram, shaderBounds.left, shaderBounds.top,
1.0 / image.width.toDouble(), 1.0 / image.height.toDouble());
/// Setup geometry.
///
@@ -192,12 +189,14 @@ class EngineImageShader implements ui.ImageShader {
if (isWebGl2) {
/// Create a vertex array object.
vao = gl.createVertexArray();
/// Set vertex array object as active one.
gl.bindVertexArray(vao!);
}
/// Turn on position attribute.
gl.enableVertexAttribArray(positionAttributeLocation);
/// Bind buffer as position buffer and transfer data.
gl.bindArrayBuffer(positionsBuffer);
bufferVertexData(gl, vertices, ui.window.devicePixelRatio);
@@ -215,6 +214,7 @@ class EngineImageShader implements ui.ImageShader {
/// Copy image to the texture.
final Object? texture = gl.createTexture();
/// Texture units are a global array of references to the textures.
/// By setting activeTexture, we associate the bound texture to a unit.
/// Every time we call a texture function such as texImage2D with a target
@@ -230,11 +230,11 @@ class EngineImageShader implements ui.ImageShader {
if (isWebGl2) {
/// Texture REPEAT and MIRROR is only supported in WebGL 2, for
/// WebGL 1.0 we let shader compute correct uv coordinates.
gl.texParameteri(gl.kTexture2D, gl.kTextureWrapS,
tileModeToGlWrapping(gl, tileModeX));
gl.texParameteri(
gl.kTexture2D, gl.kTextureWrapS, tileModeToGlWrapping(gl, tileModeX));
gl.texParameteri(gl.kTexture2D, gl.kTextureWrapT,
tileModeToGlWrapping(gl, tileModeY));
gl.texParameteri(
gl.kTexture2D, gl.kTextureWrapT, tileModeToGlWrapping(gl, tileModeY));
/// Mipmapping saves your texture in different resolutions
/// so the graphics card can choose which resolution is optimal

View File

@@ -3,7 +3,6 @@
// found in the LICENSE file.
import 'dart:async';
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
@@ -12,20 +11,20 @@ import 'dom.dart';
import 'safe_browser_api.dart';
Object? get _jsImageDecodeFunction => getJsProperty<Object?>(
getJsProperty<Object>(
getJsProperty<Object>(domWindow, 'Image'),
'prototype',
),
'decode',
);
getJsProperty<Object>(
getJsProperty<Object>(domWindow, 'Image'),
'prototype',
),
'decode',
);
final bool _supportsDecode = _jsImageDecodeFunction != null;
// TODO(mdebbar): Deprecate this and remove it.
// https://github.com/flutter/flutter/issues/127395
typedef WebOnlyImageCodecChunkCallback = ui_web.ImageCodecChunkCallback;
class HtmlCodec implements ui.Codec {
HtmlCodec(this.src, {this.chunkCallback});
abstract class HtmlImageElementCodec implements ui.Codec {
HtmlImageElementCodec(this.src, {this.chunkCallback});
final String src;
final ui_web.ImageCodecChunkCallback? chunkCallback;
@@ -42,7 +41,7 @@ class HtmlCodec implements ui.Codec {
// Currently there is no way to watch decode progress, so
// we add 0/100 , 100/100 progress callbacks to enable loading progress
// builders to create UI.
chunkCallback?.call(0, 100);
chunkCallback?.call(0, 100);
if (_supportsDecode) {
final DomHTMLImageElement imgElement = createDomHTMLImageElement();
imgElement.src = src;
@@ -56,12 +55,14 @@ class HtmlCodec implements ui.Codec {
int naturalWidth = imgElement.naturalWidth.toInt();
int naturalHeight = imgElement.naturalHeight.toInt();
// Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=700533.
if (naturalWidth == 0 && naturalHeight == 0 && ui_web.browser.browserEngine == ui_web.BrowserEngine.firefox) {
if (naturalWidth == 0 &&
naturalHeight == 0 &&
ui_web.browser.browserEngine == ui_web.BrowserEngine.firefox) {
const int kDefaultImageSizeFallback = 300;
naturalWidth = kDefaultImageSizeFallback;
naturalHeight = kDefaultImageSizeFallback;
}
final HtmlImage image = HtmlImage(
final ui.Image image = createImageFromHTMLImageElement(
imgElement,
naturalWidth,
naturalHeight,
@@ -101,7 +102,7 @@ class HtmlCodec implements ui.Codec {
}
imgElement.removeEventListener('load', loadListener);
imgElement.removeEventListener('error', errorListener);
final HtmlImage image = HtmlImage(
final ui.Image image = createImageFromHTMLImageElement(
imgElement,
imgElement.naturalWidth.toInt(),
imgElement.naturalHeight.toInt(),
@@ -112,11 +113,18 @@ class HtmlCodec implements ui.Codec {
imgElement.src = src;
}
/// Creates a [ui.Image] from an [HTMLImageElement] that has been loaded.
ui.Image createImageFromHTMLImageElement(
DomHTMLImageElement image,
int naturalWidth,
int naturalHeight,
);
@override
void dispose() {}
}
class HtmlBlobCodec extends HtmlCodec {
abstract class HtmlBlobCodec extends HtmlImageElementCodec {
HtmlBlobCodec(this.blob) : super(domWindow.URL.createObjectURL(blob));
final DomBlob blob;
@@ -136,93 +144,3 @@ class SingleFrameInfo implements ui.FrameInfo {
@override
final ui.Image image;
}
class HtmlImage implements ui.Image {
HtmlImage(this.imgElement, this.width, this.height) {
ui.Image.onCreate?.call(this);
}
final DomHTMLImageElement imgElement;
bool _didClone = false;
bool _disposed = false;
@override
void dispose() {
ui.Image.onDispose?.call(this);
// Do nothing. The codec that owns this image should take care of
// releasing the object url.
assert(() {
_disposed = true;
return true;
}());
}
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _disposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError('Image.debugDisposed is only available when asserts are enabled.');
}
@override
ui.Image clone() => this;
@override
bool isCloneOf(ui.Image other) => other == this;
@override
List<StackTrace>? debugGetOpenHandleStackTraces() => null;
@override
final int width;
@override
final int height;
@override
Future<ByteData?> toByteData({ui.ImageByteFormat format = ui.ImageByteFormat.rawRgba}) {
switch (format) {
// TODO(ColdPaleLight): https://github.com/flutter/flutter/issues/89128
// The format rawRgba always returns straight rather than premul currently.
case ui.ImageByteFormat.rawRgba:
case ui.ImageByteFormat.rawStraightRgba:
final DomCanvasElement canvas = createDomCanvasElement()
..width = width.toDouble()
..height = height.toDouble();
final DomCanvasRenderingContext2D ctx = canvas.context2D;
ctx.drawImage(imgElement, 0, 0);
final DomImageData imageData = ctx.getImageData(0, 0, width, height);
return Future<ByteData?>.value(imageData.data.buffer.asByteData());
default:
if (imgElement.src?.startsWith('data:') ?? false) {
final UriData data = UriData.fromUri(Uri.parse(imgElement.src!));
return Future<ByteData?>.value(data.contentAsBytes().buffer.asByteData());
} else {
return Future<ByteData?>.value();
}
}
}
@override
ui.ColorSpace get colorSpace => ui.ColorSpace.sRGB;
DomHTMLImageElement cloneImageElement() {
if (!_didClone) {
_didClone = true;
imgElement.style.position = 'absolute';
}
return imgElement.cloneNode(true) as DomHTMLImageElement;
}
@override
String toString() => '[$width\u00D7$height]';
}

View File

@@ -60,10 +60,8 @@ abstract class BrowserImageDecoder implements ui.Codec {
}
void _debugCheckNotDisposed() {
assert(
!_isDisposed,
'Cannot use this image decoder. It has been disposed of.'
);
assert(!_isDisposed,
'Cannot use this image decoder. It has been disposed of.');
}
/// The index of the frame that will be decoded on the next call of [getNextFrame];
@@ -95,7 +93,8 @@ abstract class BrowserImageDecoder implements ui.Codec {
if (_cachedWebDecoder != null) {
// Give the cached value some time for reuse, e.g. if the image is
// currently animating.
_cacheExpirationClock.datetime = DateTime.now().add(_kWebDecoderExpireDuration);
_cacheExpirationClock.datetime =
DateTime.now().add(_kWebDecoderExpireDuration);
return _cachedWebDecoder!;
}
@@ -131,9 +130,11 @@ abstract class BrowserImageDecoder implements ui.Codec {
// We coerce the DOM's `repetitionCount` into an int by explicitly
// handling `infinity`. Note: This will still throw if the DOM returns a
// `NaN`.
final double rawRepetitionCount = webDecoder.tracks.selectedTrack!.repetitionCount;
repetitionCount = rawRepetitionCount == double.infinity ? -1 :
rawRepetitionCount.toInt();
final double rawRepetitionCount =
webDecoder.tracks.selectedTrack!.repetitionCount;
repetitionCount = rawRepetitionCount == double.infinity
? -1
: rawRepetitionCount.toInt();
_cachedWebDecoder = webDecoder;
// Expire the decoder if it's not used for several seconds. If the image is
@@ -150,7 +151,8 @@ abstract class BrowserImageDecoder implements ui.Codec {
_cachedWebDecoder = null;
_cacheExpirationClock.callback = null;
};
_cacheExpirationClock.datetime = DateTime.now().add(_kWebDecoderExpireDuration);
_cacheExpirationClock.datetime =
DateTime.now().add(_kWebDecoderExpireDuration);
return webDecoder;
} catch (error) {
@@ -163,10 +165,9 @@ abstract class BrowserImageDecoder implements ui.Codec {
}
}
throw ImageCodecException(
"Failed to decode image using the browser's ImageDecoder API.\n"
'Image source: $debugSource\n'
'Original browser error: $error'
);
"Failed to decode image using the browser's ImageDecoder API.\n"
'Image source: $debugSource\n'
'Original browser error: $error');
}
}
@@ -183,11 +184,15 @@ abstract class BrowserImageDecoder implements ui.Codec {
// 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?.toInt() ?? 0);
final Duration duration =
Duration(microseconds: frame.duration?.toInt() ?? 0);
final ui.Image image = generateImageFromVideoFrame(frame);
return AnimatedImageFrameInfo(duration, image);
}
/// Creates a [ui.Image] from a [VideoFrame]. Implementers of this class
/// should override this method to create a [ui.Image] that is appropriate
/// for their associated renderer.
ui.Image generateImageFromVideoFrame(VideoFrame frame);
}
@@ -213,7 +218,8 @@ String? detectContentType(Uint8List data) {
return debugContentTypeDetector!.call(data);
}
formatLoop: for (final ImageFileFormat format in ImageFileFormat.values) {
formatLoop:
for (final ImageFileFormat format in ImageFileFormat.values) {
if (data.length < format.header.length) {
continue;
}
@@ -274,7 +280,8 @@ class ImageFileFormat {
// 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'),
ImageFileFormat(
<int?>[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A], 'image/png'),
// GIF87a
ImageFileFormat(<int?>[0x47, 0x49, 0x46, 0x38, 0x37, 0x61], 'image/gif'),
@@ -286,7 +293,20 @@ class ImageFileFormat {
ImageFileFormat(<int?>[0xFF, 0xD8, 0xFF], 'image/jpeg'),
// WebP
ImageFileFormat(<int?>[0x52, 0x49, 0x46, 0x46, null, null, null, null, 0x57, 0x45, 0x42, 0x50], 'image/webp'),
ImageFileFormat(<int?>[
0x52,
0x49,
0x46,
0x46,
null,
null,
null,
null,
0x57,
0x45,
0x42,
0x50
], 'image/webp'),
// BMP
ImageFileFormat(<int?>[0x42, 0x4D], 'image/bmp'),
@@ -302,7 +322,7 @@ typedef DebugContentTypeDetector = String? Function(Uint8List);
/// This is useful in tests, for example, to test unsupported content types.
DebugContentTypeDetector? debugContentTypeDetector;
/// A string of bytes that every AVIF image contains somehwere in its first 16
/// A string of bytes that every AVIF image contains somewhere in its first 16
/// bytes.
///
/// This signature is necessary but not sufficient, which may lead to false
@@ -320,7 +340,8 @@ 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) {
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.
@@ -360,12 +381,10 @@ class ResizingCodec implements ui.Codec {
final ui.FrameInfo frameInfo = await delegate.getNextFrame();
return AnimatedImageFrameInfo(
frameInfo.duration,
scaleImageIfNeeded(
frameInfo.image,
targetWidth: targetWidth,
targetHeight: targetHeight,
allowUpscaling: allowUpscaling
),
scaleImageIfNeeded(frameInfo.image,
targetWidth: targetWidth,
targetHeight: targetHeight,
allowUpscaling: allowUpscaling),
);
}
@@ -407,21 +426,18 @@ ui.Image scaleImageIfNeeded(
}) {
final int width = image.width;
final int height = image.height;
final ui.Size? scaledSize = _scaledSize(
width,
height,
targetWidth,
targetHeight
);
final ui.Size? scaledSize =
_scaledSize(width, height, targetWidth, targetHeight);
if (scaledSize == null) {
return image;
}
if (!allowUpscaling &&
(scaledSize.width > width || scaledSize.height > height)) {
return image;
(scaledSize.width > width || scaledSize.height > height)) {
return image;
}
final ui.Rect outputRect = ui.Rect.fromLTWH(0, 0, scaledSize.width, scaledSize.height);
final ui.Rect outputRect =
ui.Rect.fromLTWH(0, 0, scaledSize.width, scaledSize.height);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder, outputRect);
@@ -432,10 +448,8 @@ ui.Image scaleImageIfNeeded(
ui.Paint(),
);
final ui.Picture picture = recorder.endRecording();
final ui.Image finalImage = picture.toImageSync(
scaledSize.width.round(),
scaledSize.height.round()
);
final ui.Image finalImage =
picture.toImageSync(scaledSize.width.round(), scaledSize.height.round());
picture.dispose();
image.dispose();
return finalImage;

View File

@@ -1,127 +0,0 @@
// 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.
import 'dart:async';
import 'package:ui/ui.dart' as ui;
import 'dom.dart';
import 'html/bitmap_canvas.dart';
import 'html/recording_canvas.dart';
import 'html_image_codec.dart';
/// An implementation of [ui.PictureRecorder] backed by a [RecordingCanvas].
class EnginePictureRecorder implements ui.PictureRecorder {
EnginePictureRecorder();
RecordingCanvas? _canvas;
late ui.Rect cullRect;
bool _isRecording = false;
RecordingCanvas beginRecording(ui.Rect bounds) {
assert(!_isRecording);
cullRect = bounds;
_isRecording = true;
return _canvas = RecordingCanvas(cullRect);
}
@override
bool get isRecording => _isRecording;
@override
EnginePicture endRecording() {
if (!_isRecording) {
// The mobile version returns an empty picture in this case. To match the
// behavior we produce a blank picture too.
beginRecording(ui.Rect.largest);
}
_isRecording = false;
_canvas!.endRecording();
final EnginePicture result = EnginePicture(_canvas, cullRect);
// We invoke the handler here, not in the Picture constructor, because we want
// [result.approximateBytesUsed] to be available for the handler.
ui.Picture.onCreate?.call(result);
return result;
}
}
/// An implementation of [ui.Picture] which is backed by a [RecordingCanvas].
class EnginePicture implements ui.Picture {
/// This class is created by the engine, and should not be instantiated
/// or extended directly.
///
/// To create a [Picture], use a [PictureRecorder].
EnginePicture(this.recordingCanvas, this.cullRect);
@override
Future<ui.Image> toImage(int width, int height) async {
final ui.Rect imageRect = ui.Rect.fromLTRB(0, 0, width.toDouble(), height.toDouble());
final BitmapCanvas canvas = BitmapCanvas.imageData(imageRect);
recordingCanvas!.apply(canvas, imageRect);
final String imageDataUrl = canvas.toDataUrl();
final DomHTMLImageElement imageElement = createDomHTMLImageElement()
..src = imageDataUrl
..width = width.toDouble()
..height = height.toDouble();
// The image loads asynchronously. We need to wait before returning,
// otherwise the returned HtmlImage will be temporarily unusable.
final Completer<ui.Image> onImageLoaded = Completer<ui.Image>.sync();
// Ignoring the returned futures from onError and onLoad because we're
// communicating through the `onImageLoaded` completer.
late final DomEventListener errorListener;
errorListener = createDomEventListener((DomEvent event) {
onImageLoaded.completeError(event);
imageElement.removeEventListener('error', errorListener);
});
imageElement.addEventListener('error', errorListener);
late final DomEventListener loadListener;
loadListener = createDomEventListener((DomEvent event) {
onImageLoaded.complete(HtmlImage(
imageElement,
width,
height,
));
imageElement.removeEventListener('load', loadListener);
});
imageElement.addEventListener('load', loadListener);
return onImageLoaded.future;
}
@override
ui.Image toImageSync(int width, int height) {
throw UnsupportedError('toImageSync is not supported on the HTML backend. Use drawPicture instead, or toImage.');
}
bool _disposed = false;
@override
void dispose() {
ui.Picture.onDispose?.call(this);
_disposed = true;
}
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _disposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError('Picture.debugDisposed is only available when asserts are enabled.');
}
@override
int get approximateBytesUsed => 0;
final RecordingCanvas? recordingCanvas;
final ui.Rect? cullRect;
}

View File

@@ -7,7 +7,8 @@ import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine/html_image_codec.dart';
import 'package:ui/src/engine/html/image.dart';
import 'package:ui/src/engine/html_image_element_codec.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
@@ -19,7 +20,7 @@ void main() {
Future<void> testMain() async {
setUpUnitTests();
group('HtmCodec', () {
group('$HtmlImageElementCodec', () {
test('supports raw images - RGBA8888', () async {
final Completer<ui.Image> completer = Completer<ui.Image>();
const int width = 200;
@@ -59,14 +60,16 @@ Future<void> testMain() async {
expect(image.height, height);
});
test('loads sample image', () async {
final HtmlCodec codec = HtmlCodec('sample_image1.png');
final HtmlImageElementCodec codec =
HtmlRendererImageCodec('sample_image1.png');
final ui.FrameInfo frameInfo = await codec.getNextFrame();
expect(frameInfo.image, isNotNull);
expect(frameInfo.image.width, 100);
expect(frameInfo.image.toString(), '[100×100]');
});
test('dispose image image', () async {
final HtmlCodec codec = HtmlCodec('sample_image1.png');
final HtmlImageElementCodec codec =
HtmlRendererImageCodec('sample_image1.png');
final ui.FrameInfo frameInfo = await codec.getNextFrame();
expect(frameInfo.image, isNotNull);
expect(frameInfo.image.debugDisposed, isFalse);
@@ -75,8 +78,8 @@ Future<void> testMain() async {
});
test('provides image loading progress', () async {
final StringBuffer buffer = StringBuffer();
final HtmlCodec codec = HtmlCodec('sample_image1.png',
chunkCallback: (int loaded, int total) {
final HtmlImageElementCodec codec = HtmlRendererImageCodec(
'sample_image1.png', chunkCallback: (int loaded, int total) {
buffer.write('$loaded/$total,');
});
await codec.getNextFrame();
@@ -86,7 +89,7 @@ Future<void> testMain() async {
/// Regression test for Firefox
/// https://github.com/flutter/flutter/issues/66412
test('Returns nonzero natural width/height', () async {
final HtmlCodec codec = HtmlCodec(
final HtmlImageElementCodec codec = HtmlRendererImageCodec(
'data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHZpZXdCb3g9I'
'jAgMCAyNCAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dG'
'l0bGU+QWJzdHJhY3QgaWNvbjwvdGl0bGU+PHBhdGggZD0iTTEyIDBjOS42MDEgMCAx'
@@ -105,7 +108,8 @@ Future<void> testMain() async {
group('ImageCodecUrl', () {
test('loads sample image from web', () async {
final Uri uri = Uri.base.resolve('sample_image1.png');
final HtmlCodec codec = await ui_web.createImageCodecFromUrl(uri) as HtmlCodec;
final HtmlImageElementCodec codec =
await ui_web.createImageCodecFromUrl(uri) as HtmlImageElementCodec;
final ui.FrameInfo frameInfo = await codec.getNextFrame();
expect(frameInfo.image, isNotNull);
expect(frameInfo.image.width, 100);
@@ -113,10 +117,10 @@ Future<void> testMain() async {
test('provides image loading progress from web', () async {
final Uri uri = Uri.base.resolve('sample_image1.png');
final StringBuffer buffer = StringBuffer();
final HtmlCodec codec = await ui_web.createImageCodecFromUrl(uri,
chunkCallback: (int loaded, int total) {
final HtmlImageElementCodec codec = await ui_web
.createImageCodecFromUrl(uri, chunkCallback: (int loaded, int total) {
buffer.write('$loaded/$total,');
}) as HtmlCodec;
}) as HtmlImageElementCodec;
await codec.getNextFrame();
expect(buffer.toString(), '0/100,100/100,');
});