From 7f4a254e762806844259a340930b62f106c386f0 Mon Sep 17 00:00:00 2001 From: Mouad Debbar Date: Fri, 9 Jul 2021 12:26:01 -0700 Subject: [PATCH] [web] Librarify html renderer files (flutter/engine#27232) --- .../flutter/lib/web_ui/lib/src/engine.dart | 100 ++++++++------- .../web_ui/lib/src/engine/canvas_pool.dart | 90 ++++++++----- .../web_ui/lib/src/engine/engine_canvas.dart | 49 +++++--- .../lib/src/engine/frame_reference.dart | 4 +- .../lib/src/engine/html/backdrop_filter.dart | 28 +++-- .../lib/src/engine/html/bitmap_canvas.dart | 119 +++++++++++------- .../web_ui/lib/src/engine/html/canvas.dart | 13 +- .../lib/web_ui/lib/src/engine/html/clip.dart | 63 ++++++---- .../lib/src/engine/html/color_filter.dart | 51 ++++---- .../html/debug_canvas_reuse_overlay.dart | 4 +- .../lib/src/engine/html/dom_canvas.dart | 32 +++-- .../lib/src/engine/html/image_filter.dart | 7 +- .../web_ui/lib/src/engine/html/offset.dart | 21 +++- .../web_ui/lib/src/engine/html/opacity.dart | 21 +++- .../web_ui/lib/src/engine/html/path/path.dart | 32 ++++- .../web_ui/lib/src/engine/html/picture.dart | 96 ++++++++------ .../lib/src/engine/html/platform_view.dart | 9 +- .../lib/src/engine/html/recording_canvas.dart | 27 +++- .../lib/web_ui/lib/src/engine/html/scene.dart | 21 +++- .../lib/src/engine/html/scene_builder.dart | 27 +++- .../lib/src/engine/html/shader_mask.dart | 13 +- .../web_ui/lib/src/engine/html/surface.dart | 90 +++++++------ .../lib/src/engine/html/surface_stats.dart | 58 +++++---- .../web_ui/lib/src/engine/html/transform.dart | 48 +++++-- .../lib/src/engine/onscreen_logging.dart | 2 +- .../lib/web_ui/lib/src/engine/picture.dart | 9 +- .../web_ui/lib/src/engine/rrect_renderer.dart | 18 +-- .../web_ui/lib/src/engine/text/paragraph.dart | 4 +- .../engine/surface/scene_builder_test.dart | 14 +-- 29 files changed, 679 insertions(+), 391 deletions(-) diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine.dart b/engine/src/flutter/lib/web_ui/lib/src/engine.dart index e09ec78b8e..ed824416a8 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine.dart @@ -24,6 +24,7 @@ import 'dart:developer' as developer; import 'dart:html' as html; import 'dart:js' as js; import 'dart:js_util' as js_util; +// ignore: unused_import import 'dart:math' as math; import 'dart:typed_data'; @@ -39,56 +40,82 @@ export 'engine/assets.dart'; import 'engine/browser_detection.dart'; export 'engine/browser_detection.dart'; +export 'engine/canvas_pool.dart'; + +export 'engine/engine_canvas.dart'; + +export 'engine/frame_reference.dart'; + import 'engine/host_node.dart'; export 'engine/host_node.dart'; -import 'engine/html_image_codec.dart'; export 'engine/html_image_codec.dart'; +export 'engine/html/backdrop_filter.dart'; + +export 'engine/html/bitmap_canvas.dart'; + +export 'engine/html/canvas.dart'; + +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_filter.dart'; + export 'engine/html/offscreen_canvas.dart'; -import 'engine/html/painting.dart'; +export 'engine/html/offset.dart'; + +export 'engine/html/opacity.dart'; + export 'engine/html/painting.dart'; -import 'engine/html/path_to_svg_clip.dart'; +export 'engine/html/path/path.dart'; + export 'engine/html/path_to_svg_clip.dart'; -import 'engine/html/path/conic.dart'; export 'engine/html/path/conic.dart'; -import 'engine/html/path/cubic.dart'; export 'engine/html/path/cubic.dart'; -import 'engine/html/path/path_iterator.dart'; export 'engine/html/path/path_iterator.dart'; -import 'engine/html/path/path_metrics.dart'; export 'engine/html/path/path_metrics.dart'; -import 'engine/html/path/path_ref.dart'; export 'engine/html/path/path_ref.dart'; -import 'engine/html/path/path_to_svg.dart'; export 'engine/html/path/path_to_svg.dart'; -import 'engine/html/path/path_utils.dart'; export 'engine/html/path/path_utils.dart'; -import 'engine/html/path/path_windings.dart'; export 'engine/html/path/path_windings.dart'; -import 'engine/html/path/tangent.dart'; export 'engine/html/path/tangent.dart'; -import 'engine/html/render_vertices.dart'; +export 'engine/html/picture.dart'; + +export 'engine/html/platform_view.dart'; + +export 'engine/html/recording_canvas.dart'; + export 'engine/html/render_vertices.dart'; -import 'engine/html/shaders/image_shader.dart'; +import 'engine/html/scene.dart'; +export 'engine/html/scene.dart'; + +export 'engine/html/scene_builder.dart'; + +export 'engine/html/shader_mask.dart'; + export 'engine/html/shaders/image_shader.dart'; export 'engine/html/shaders/normalized_gradient.dart'; -import 'engine/html/shaders/shader.dart'; export 'engine/html/shaders/shader.dart'; export 'engine/html/shaders/shader_builder.dart'; @@ -97,6 +124,12 @@ export 'engine/html/shaders/vertex_shaders.dart'; export 'engine/html/shaders/webgl_context.dart'; +export 'engine/html/surface.dart'; + +export 'engine/html/surface_stats.dart'; + +export 'engine/html/transform.dart'; + import 'engine/keyboard_binding.dart'; export 'engine/keyboard_binding.dart'; @@ -117,6 +150,10 @@ export 'engine/navigation/js_url_strategy.dart'; import 'engine/navigation/url_strategy.dart'; export 'engine/navigation/url_strategy.dart'; +export 'engine/onscreen_logging.dart'; + +export 'engine/picture.dart'; + import 'engine/plugins.dart'; export 'engine/plugins.dart'; @@ -130,6 +167,8 @@ export 'engine/pointer_converter.dart'; import 'engine/profiler.dart'; export 'engine/profiler.dart'; +export 'engine/rrect_renderer.dart'; + import 'engine/semantics/accessibility.dart'; export 'engine/semantics/accessibility.dart'; @@ -166,7 +205,6 @@ export 'engine/services/message_codecs.dart'; // import 'engine/services/serialization.dart'; export 'engine/services/serialization.dart'; -import 'engine/shadow.dart'; export 'engine/shadow.dart'; import 'engine/test_embedding.dart'; @@ -185,7 +223,6 @@ export 'engine/text/measurement.dart'; export 'engine/text/paint_service.dart'; -import 'engine/text/paragraph.dart'; export 'engine/text/paragraph.dart'; export 'engine/text/canvas_paragraph.dart'; @@ -212,10 +249,8 @@ export 'engine/text_editing/text_editing.dart'; import 'engine/util.dart'; export 'engine/util.dart'; -import 'engine/validators.dart'; export 'engine/validators.dart'; -import 'engine/vector_math.dart'; export 'engine/vector_math.dart'; import 'engine/web_experiments.dart'; @@ -247,7 +282,6 @@ export 'engine/canvaskit/initialization.dart'; export 'engine/canvaskit/interval_tree.dart'; -import 'engine/canvaskit/layer.dart'; export 'engine/canvaskit/layer.dart'; import 'engine/canvaskit/layer_scene_builder.dart'; @@ -288,41 +322,15 @@ export 'engine/canvaskit/util.dart'; export 'engine/canvaskit/vertices.dart'; -part 'engine/html/bitmap_canvas.dart'; -part 'engine/canvas_pool.dart'; part 'engine/clipboard.dart'; part 'engine/color_filter.dart'; -part 'engine/html/dom_canvas.dart'; part 'engine/dom_renderer.dart'; -part 'engine/engine_canvas.dart'; part 'engine/font_change_util.dart'; -part 'engine/frame_reference.dart'; -part 'engine/html/backdrop_filter.dart'; -part 'engine/html/canvas.dart'; -part 'engine/html/clip.dart'; -part 'engine/html/color_filter.dart'; -part 'engine/html/debug_canvas_reuse_overlay.dart'; -part 'engine/html/image_filter.dart'; -part 'engine/html/offset.dart'; -part 'engine/html/opacity.dart'; -part 'engine/html/path/path.dart'; -part 'engine/html/picture.dart'; -part 'engine/html/platform_view.dart'; -part 'engine/html/recording_canvas.dart'; -part 'engine/html/scene.dart'; -part 'engine/html/scene_builder.dart'; -part 'engine/html/shader_mask.dart'; -part 'engine/html/surface.dart'; -part 'engine/html/surface_stats.dart'; -part 'engine/html/transform.dart'; -part 'engine/onscreen_logging.dart'; -part 'engine/picture.dart'; part 'engine/platform_dispatcher.dart'; part 'engine/platform_views.dart'; part 'engine/platform_views/content_manager.dart'; part 'engine/platform_views/message_handler.dart'; part 'engine/platform_views/slots.dart'; -part 'engine/rrect_renderer.dart'; part 'engine/window.dart'; // The mode the app is running in. diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/canvas_pool.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/canvas_pool.dart index e017e8fddf..384ed3f7e8 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/canvas_pool.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/canvas_pool.dart @@ -2,7 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; +import 'dart:js_util' as js_util; +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:meta/meta.dart'; +import 'package:ui/src/engine.dart' show DomRenderer, EnginePlatformDispatcher, window; +import 'package:ui/ui.dart' as ui; + +import 'browser_detection.dart'; +import 'engine_canvas.dart'; +import 'html/bitmap_canvas.dart'; +import 'html/painting.dart'; +import 'html/picture.dart'; +import 'html/path/conic.dart'; +import 'html/path/path.dart'; +import 'html/path/path_ref.dart'; +import 'html/path/path_utils.dart'; +import 'html/shaders/image_shader.dart'; +import 'html/shaders/shader.dart'; +import 'rrect_renderer.dart'; +import 'shadow.dart'; +import 'util.dart'; +import 'vector_math.dart'; /// Renders picture to a CanvasElement by allocating and caching 0 or more /// canvas(s) for [BitmapCanvas]. @@ -13,14 +36,14 @@ part of engine; /// and adds the canvas(s) to [_activeCanvasList]. /// /// To make sure transformations and clips are preserved correctly when a new -/// canvas is allocated, [_CanvasPool] replays the current stack on the newly +/// canvas is allocated, [CanvasPool] replays the current stack on the newly /// allocated canvas. It also maintains a [_saveContextCount] so that /// the context stack can be reinitialized to default when reused in the future. /// /// On a subsequent repaint, when a Picture determines that a [BitmapCanvas] -/// can be reused, [_CanvasPool] will move canvas(s) from pool to reusablePool +/// can be reused, [CanvasPool] will move canvas(s) from pool to reusablePool /// to prevent reallocation. -class _CanvasPool extends _SaveStackTracking { +class CanvasPool extends _SaveStackTracking { html.CanvasRenderingContext2D? _context; ContextStateHandle? _contextHandle; final int _widthInBitmapPixels, _heightInBitmapPixels; @@ -29,13 +52,14 @@ class _CanvasPool extends _SaveStackTracking { // List of canvases available to reuse from prior paint cycle. List? _reusablePool; // Current canvas element or null if marked for lazy allocation. + html.CanvasElement? get canvas => _canvas; html.CanvasElement? _canvas; html.HtmlElement? _rootElement; int _saveContextCount = 0; final double _density; - _CanvasPool(this._widthInBitmapPixels, this._heightInBitmapPixels, + CanvasPool(this._widthInBitmapPixels, this._heightInBitmapPixels, this._density); html.CanvasRenderingContext2D get context { @@ -116,7 +140,7 @@ class _CanvasPool extends _SaveStackTracking { // browser more memory to allocate a new canvas. if (_canvas == null) { // Evict BitmapCanvas(s) and retry. - _reduceCanvasMemoryUsage(); + reduceCanvasMemoryUsage(); canvas = _allocCanvas(_widthInBitmapPixels, _heightInBitmapPixels); } canvas!.style @@ -144,7 +168,7 @@ class _CanvasPool extends _SaveStackTracking { // Handle OOM. } if (_context == null) { - _reduceCanvasMemoryUsage(); + reduceCanvasMemoryUsage(); _context = canvas.context2D; } if (_context == null) { @@ -209,13 +233,13 @@ class _CanvasPool extends _SaveStackTracking { } int _replaySingleSaveEntry(int clipDepth, Matrix4 prevTransform, - Matrix4 transform, List<_SaveClipEntry>? clipStack) { + Matrix4 transform, List? clipStack) { final html.CanvasRenderingContext2D ctx = context; if (clipStack != null) { for (int clipCount = clipStack.length; clipDepth < clipCount; clipDepth++) { - _SaveClipEntry clipEntry = clipStack[clipDepth]; + SaveClipEntry clipEntry = clipStack[clipDepth]; Matrix4 clipTimeTransform = clipEntry.currentTransform; // If transform for entry recording change since last element, update. // Comparing only matrix3 elements since Canvas API restricted. @@ -275,7 +299,7 @@ class _CanvasPool extends _SaveStackTracking { for (int saveStackIndex = 0, len = _saveStack.length; saveStackIndex < len; saveStackIndex++) { - _SaveStackEntry saveEntry = _saveStack[saveStackIndex]; + SaveStackEntry saveEntry = _saveStack[saveStackIndex]; clipDepth = _replaySingleSaveEntry( clipDepth, prevTransform, saveEntry.transform, saveEntry.clipStack); prevTransform = saveEntry.transform; @@ -283,7 +307,7 @@ class _CanvasPool extends _SaveStackTracking { ++_saveContextCount; } _replaySingleSaveEntry( - clipDepth, prevTransform, _currentTransform, _clipStack); + clipDepth, prevTransform, _currentTransform, clipStack); } // Marks this pool for reuse. @@ -668,14 +692,14 @@ class _CanvasPool extends _SaveStackTracking { void drawRRect(ui.RRect roundRect, ui.PaintingStyle? style) { final ui.Rect? shaderBounds = contextHandle._shaderBounds; - _RRectToCanvasRenderer(context).render( + RRectToCanvasRenderer(context).render( shaderBounds == null ? roundRect : roundRect.shift(ui.Offset(-shaderBounds.left, -shaderBounds.top))); contextHandle.paint(style); } void drawDRRect(ui.RRect outer, ui.RRect inner, ui.PaintingStyle? style) { - _RRectRenderer renderer = _RRectToCanvasRenderer(context); + RRectRenderer renderer = RRectToCanvasRenderer(context); final ui.Rect? shaderBounds = contextHandle._shaderBounds; if (shaderBounds == null) { renderer.render(outer); @@ -748,7 +772,7 @@ class _CanvasPool extends _SaveStackTracking { // alpha for the paint the path is painted in addition to the shadow, // which is undesirable. context.translate(shadow.offset.dx, shadow.offset.dy); - context.filter = _maskFilterToCanvasFilter( + context.filter = maskFilterToCanvasFilter( ui.MaskFilter.blur(ui.BlurStyle.normal, shadow.blurWidth)); context.strokeStyle = ''; context.fillStyle = solidColor; @@ -815,7 +839,7 @@ class _CanvasPool extends _SaveStackTracking { // class ContextStateHandle { final html.CanvasRenderingContext2D context; - final _CanvasPool _canvasPool; + final CanvasPool _canvasPool; final double density; ContextStateHandle(this._canvasPool, this.context, this.density); @@ -832,7 +856,7 @@ class ContextStateHandle { if (blendMode != _currentBlendMode) { _currentBlendMode = blendMode; context.globalCompositeOperation = - _stringForBlendMode(blendMode) ?? 'source-over'; + stringForBlendMode(blendMode) ?? 'source-over'; } } @@ -840,7 +864,7 @@ class ContextStateHandle { strokeCap ??= ui.StrokeCap.butt; if (strokeCap != _currentStrokeCap) { _currentStrokeCap = strokeCap; - context.lineCap = _stringForStrokeCap(strokeCap)!; + context.lineCap = stringForStrokeCap(strokeCap)!; } } @@ -855,7 +879,7 @@ class ContextStateHandle { strokeJoin ??= ui.StrokeJoin.miter; if (strokeJoin != _currentStrokeJoin) { _currentStrokeJoin = strokeJoin; - context.lineJoin = _stringForStrokeJoin(strokeJoin); + context.lineJoin = stringForStrokeJoin(strokeJoin); } } @@ -949,7 +973,7 @@ class ContextStateHandle { if (!_renderMaskFilterForWebkit) { if (_currentFilter != maskFilter) { _currentFilter = maskFilter; - context.filter = _maskFilterToCanvasFilter(maskFilter); + context.filter = maskFilterToCanvasFilter(maskFilter); } } else { // WebKit does not support the `filter` property. Instead we apply a @@ -1074,21 +1098,21 @@ class _SaveStackTracking { // !Warning: this vector should not be mutated. static final Vector3 _unitZ = Vector3(0.0, 0.0, 1.0); - final List<_SaveStackEntry> _saveStack = <_SaveStackEntry>[]; + final List _saveStack = []; /// The stack that maintains clipping operations used when text is painted /// onto bitmap canvas but is composited as separate element. - List<_SaveClipEntry>? _clipStack; + List? clipStack; /// Returns whether there are active clipping regions on the canvas. - bool get isClipped => _clipStack != null; + bool get isClipped => clipStack != null; /// Empties the save stack and the element stack, and resets the transform /// and clip parameters. @mustCallSuper void clear() { _saveStack.clear(); - _clipStack = null; + clipStack = null; _currentTransform = Matrix4.identity(); } @@ -1099,10 +1123,10 @@ class _SaveStackTracking { /// Saves current clip and transform on the save stack. @mustCallSuper void save() { - _saveStack.add(_SaveStackEntry( + _saveStack.add(SaveStackEntry( transform: _currentTransform.clone(), clipStack: - _clipStack == null ? null : List<_SaveClipEntry>.from(_clipStack!), + clipStack == null ? null : List.from(clipStack!), )); } @@ -1112,9 +1136,9 @@ class _SaveStackTracking { if (_saveStack.isEmpty) { return; } - final _SaveStackEntry entry = _saveStack.removeLast(); + final SaveStackEntry entry = _saveStack.removeLast(); _currentTransform = entry.transform; - _clipStack = entry.clipStack; + clipStack = entry.clipStack; } /// Multiplies the [currentTransform] matrix by a translation. @@ -1154,21 +1178,21 @@ class _SaveStackTracking { /// Adds a rectangle to clipping stack. @mustCallSuper void clipRect(ui.Rect rect) { - _clipStack ??= <_SaveClipEntry>[]; - _clipStack!.add(_SaveClipEntry.rect(rect, _currentTransform.clone())); + clipStack ??= []; + clipStack!.add(SaveClipEntry.rect(rect, _currentTransform.clone())); } /// Adds a round rectangle to clipping stack. @mustCallSuper void clipRRect(ui.RRect rrect) { - _clipStack ??= <_SaveClipEntry>[]; - _clipStack!.add(_SaveClipEntry.rrect(rrect, _currentTransform.clone())); + clipStack ??= []; + clipStack!.add(SaveClipEntry.rrect(rrect, _currentTransform.clone())); } /// Adds a path to clipping stack. @mustCallSuper void clipPath(ui.Path path) { - _clipStack ??= <_SaveClipEntry>[]; - _clipStack!.add(_SaveClipEntry.path(path, _currentTransform.clone())); + clipStack ??= []; + clipStack!.add(SaveClipEntry.path(path, _currentTransform.clone())); } } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/engine_canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/engine_canvas.dart index 23c2263fcc..0ec547048e 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/engine_canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/engine_canvas.dart @@ -2,7 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:typed_data'; +import 'dart:html' as html; + +import 'package:ui/ui.dart' as ui; + +import 'html/painting.dart'; +import 'html/render_vertices.dart'; +import 'text/paragraph.dart'; +import 'util.dart'; +import 'vector_math.dart'; /// Defines canvas interface common across canvases that the [SceneBuilder] /// renders to. @@ -92,29 +101,29 @@ Matrix4 transformWithOffset(Matrix4 transform, ui.Offset offset) { return effectiveTransform; } -class _SaveStackEntry { - _SaveStackEntry({ +class SaveStackEntry { + SaveStackEntry({ required this.transform, required this.clipStack, }); final Matrix4 transform; - final List<_SaveClipEntry>? clipStack; + final List? clipStack; } /// Tagged union of clipping parameters used for canvas. -class _SaveClipEntry { +class SaveClipEntry { final ui.Rect? rect; final ui.RRect? rrect; final ui.Path? path; final Matrix4 currentTransform; - _SaveClipEntry.rect(this.rect, this.currentTransform) + SaveClipEntry.rect(this.rect, this.currentTransform) : rrect = null, path = null; - _SaveClipEntry.rrect(this.rrect, this.currentTransform) + SaveClipEntry.rrect(this.rrect, this.currentTransform) : rect = null, path = null; - _SaveClipEntry.path(this.path, this.currentTransform) + SaveClipEntry.path(this.path, this.currentTransform) : rect = null, rrect = null; } @@ -124,11 +133,11 @@ class _SaveClipEntry { mixin SaveStackTracking on EngineCanvas { static final Vector3 _unitZ = Vector3(0.0, 0.0, 1.0); - final List<_SaveStackEntry> _saveStack = <_SaveStackEntry>[]; + final List _saveStack = []; /// The stack that maintains clipping operations used when text is painted /// onto bitmap canvas but is composited as separate element. - List<_SaveClipEntry>? _clipStack; + List? _clipStack; /// Returns whether there are active clipping regions on the canvas. bool get isClipped => _clipStack != null; @@ -153,10 +162,10 @@ mixin SaveStackTracking on EngineCanvas { /// Classes that override this method must call `super.save()`. @override void save() { - _saveStack.add(_SaveStackEntry( + _saveStack.add(SaveStackEntry( transform: _currentTransform.clone(), clipStack: - _clipStack == null ? null : List<_SaveClipEntry>.from(_clipStack!), + _clipStack == null ? null : List.from(_clipStack!), )); } @@ -168,7 +177,7 @@ mixin SaveStackTracking on EngineCanvas { if (_saveStack.isEmpty) { return; } - final _SaveStackEntry entry = _saveStack.removeLast(); + final SaveStackEntry entry = _saveStack.removeLast(); _currentTransform = entry.transform; _clipStack = entry.clipStack; } @@ -222,8 +231,8 @@ mixin SaveStackTracking on EngineCanvas { /// Classes that override this method must call `super.clipRect()`. @override void clipRect(ui.Rect rect, ui.ClipOp op) { - _clipStack ??= <_SaveClipEntry>[]; - _clipStack!.add(_SaveClipEntry.rect(rect, _currentTransform.clone())); + _clipStack ??= []; + _clipStack!.add(SaveClipEntry.rect(rect, _currentTransform.clone())); } /// Adds a round rectangle to clipping stack. @@ -231,8 +240,8 @@ mixin SaveStackTracking on EngineCanvas { /// Classes that override this method must call `super.clipRRect()`. @override void clipRRect(ui.RRect rrect) { - _clipStack ??= <_SaveClipEntry>[]; - _clipStack!.add(_SaveClipEntry.rrect(rrect, _currentTransform.clone())); + _clipStack ??= []; + _clipStack!.add(SaveClipEntry.rrect(rrect, _currentTransform.clone())); } /// Adds a path to clipping stack. @@ -240,12 +249,12 @@ mixin SaveStackTracking on EngineCanvas { /// Classes that override this method must call `super.clipPath()`. @override void clipPath(ui.Path path) { - _clipStack ??= <_SaveClipEntry>[]; - _clipStack!.add(_SaveClipEntry.path(path, _currentTransform.clone())); + _clipStack ??= []; + _clipStack!.add(SaveClipEntry.path(path, _currentTransform.clone())); } } -html.Element _drawParagraphElement( +html.Element drawParagraphElement( EngineParagraph paragraph, ui.Offset offset, { Matrix4? transform, diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/frame_reference.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/frame_reference.dart index 07bc7487ba..1a4f8735de 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/frame_reference.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/frame_reference.dart @@ -2,12 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; - /// A monotonically increasing frame number being rendered. /// /// Used for debugging only. -int _debugFrameNumber = 1; +int debugFrameNumber = 1; List> frameReferences = >[]; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/backdrop_filter.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/backdrop_filter.dart index 64adaa3319..0ebbe2aaf3 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/backdrop_filter.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/backdrop_filter.dart @@ -2,7 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; + +import 'package:ui/src/engine.dart' show DomRenderer; +import 'package:ui/ui.dart' as ui; + +import '../browser_detection.dart'; +import '../util.dart'; +import '../vector_math.dart'; +import 'shaders/shader.dart'; +import 'surface.dart'; +import 'surface_stats.dart'; /// A surface that applies an image filter to background. class PersistedBackdropFilter extends PersistedContainerSurface @@ -20,7 +30,7 @@ class PersistedBackdropFilter extends PersistedContainerSurface html.Element? _childContainer; html.Element? _filterElement; ui.Rect? _activeClipBounds; - // Cached inverted transform for _transform. + // Cached inverted transform for [transform]. late Matrix4 _invertedTransform; // Reference to transform last used to cache [_invertedTransform]. Matrix4? _previousTransform; @@ -39,9 +49,9 @@ class PersistedBackdropFilter extends PersistedContainerSurface ..style.transformOrigin = '0 0 0'; _childContainer = html.Element.tag('flt-backdrop-interior'); _childContainer!.style.position = 'absolute'; - if (_debugExplainSurfaceStats) { + if (debugExplainSurfaceStats) { // This creates an additional interior element. Count it too. - _surfaceStatsFor(this).allocatedDomNodeCount++; + surfaceStatsFor(this).allocatedDomNodeCount++; } _filterElement = defaultCreateElement('flt-backdrop-filter'); _filterElement!.style.transformOrigin = '0 0 0'; @@ -61,9 +71,9 @@ class PersistedBackdropFilter extends PersistedContainerSurface @override void apply() { - if (_previousTransform != _transform) { - _invertedTransform = Matrix4.inverted(_transform!); - _previousTransform = _transform; + if (_previousTransform != transform) { + _invertedTransform = Matrix4.inverted(transform!); + _previousTransform = transform; } // https://api.flutter.dev/flutter/widgets/BackdropFilter-class.html // Defines the effective area as the parent/ancestor clip or if not @@ -84,7 +94,7 @@ class PersistedBackdropFilter extends PersistedContainerSurface PersistedContainerSurface? parentSurface = parent; while (parentSurface != null) { if (parentSurface.isClipping) { - final ui.Rect activeClipBounds = (_activeClipBounds = parentSurface._localClipBounds)!; + final ui.Rect activeClipBounds = (_activeClipBounds = parentSurface.localClipBounds)!; left = activeClipBounds.left; top = activeClipBounds.top; width = activeClipBounds.width; @@ -134,7 +144,7 @@ class PersistedBackdropFilter extends PersistedContainerSurface PersistedContainerSurface? parentSurface = parent; while (parentSurface != null) { if (parentSurface.isClipping) { - if (parentSurface._localClipBounds != _activeClipBounds) { + if (parentSurface.localClipBounds != _activeClipBounds) { apply(); } break; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/bitmap_canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/bitmap_canvas.dart index d62f067db4..6c9065ed1b 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/bitmap_canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/bitmap_canvas.dart @@ -2,7 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:ui/src/engine.dart' show domRenderer, EngineColorFilter, EnginePlatformDispatcher, NullTreeSanitizer, window; +import 'package:ui/ui.dart' as ui; + +import '../browser_detection.dart'; +import '../canvas_pool.dart'; +import '../canvaskit/color_filter.dart'; +import '../engine_canvas.dart'; +import '../frame_reference.dart'; +import '../html_image_codec.dart'; +import '../text/paragraph.dart'; +import '../util.dart'; +import '../vector_math.dart'; +import 'clip.dart'; +import 'color_filter.dart'; +import 'dom_canvas.dart'; +import 'recording_canvas.dart'; +import 'render_vertices.dart'; +import 'painting.dart'; +import 'path/path.dart'; +import 'shaders/image_shader.dart'; /// A raw HTML canvas that is directly written to. class BitmapCanvas extends EngineCanvas { @@ -34,7 +57,7 @@ class BitmapCanvas extends EngineCanvas { @override final html.Element rootElement = html.Element.tag('flt-canvas'); - final _CanvasPool _canvasPool; + final CanvasPool _canvasPool; /// The size of the paint [bounds]. ui.Size get size => _bounds.size; @@ -51,20 +74,20 @@ class BitmapCanvas extends EngineCanvas { /// /// These pixels are different from the logical CSS pixels. Here a pixel /// literally means 1 point with a RGBA color. - final int _widthInBitmapPixels; + final int widthInBitmapPixels; /// The number of pixels along the width of the bitmap that the canvas element /// renders into. /// /// These pixels are different from the logical CSS pixels. Here a pixel /// literally means 1 point with a RGBA color. - final int _heightInBitmapPixels; + final int heightInBitmapPixels; /// The number of pixels in the bitmap that the canvas element renders into. /// /// These pixels are different from the logical CSS pixels. Here a pixel /// literally means 1 point with a RGBA color. - int get bitmapPixelCount => _widthInBitmapPixels * _heightInBitmapPixels; + int get bitmapPixelCount => widthInBitmapPixels * heightInBitmapPixels; int _saveCount = 0; @@ -106,6 +129,7 @@ class BitmapCanvas extends EngineCanvas { /// Canvas pixel to screen pixel ratio. Similar to dpi but /// uses global transform of canvas to compute ratio. + double get density => _density; final double _density; final RenderStrategy _renderStrategy; @@ -121,10 +145,10 @@ class BitmapCanvas extends EngineCanvas { : assert(_bounds != null), // ignore: unnecessary_null_comparison _density = density, _renderStrategy = renderStrategy, - _widthInBitmapPixels = _widthToPhysical(_bounds.width), - _heightInBitmapPixels = _heightToPhysical(_bounds.height), - _canvasPool = _CanvasPool(_widthToPhysical(_bounds.width), - _heightToPhysical(_bounds.height), density) { + widthInBitmapPixels = widthToPhysical(_bounds.width), + heightInBitmapPixels = heightToPhysical(_bounds.height), + _canvasPool = CanvasPool(widthToPhysical(_bounds.width), + heightToPhysical(_bounds.height), density) { rootElement.style.position = 'absolute'; // Adds one extra pixel to the requested size. This is to compensate for // _initializeViewport() snapping canvas position to 1 pixel, causing @@ -175,14 +199,14 @@ class BitmapCanvas extends EngineCanvas { ); } - static int _widthToPhysical(double width) { + static int widthToPhysical(double width) { final double boundsWidth = width + 1; return (boundsWidth * EnginePlatformDispatcher.browserDevicePixelRatio) .ceil() + 2 * kPaddingPixels; } - static int _heightToPhysical(double height) { + static int heightToPhysical(double height) { final double boundsHeight = height + 1; return (boundsHeight * EnginePlatformDispatcher.browserDevicePixelRatio) .ceil() + @@ -192,8 +216,8 @@ class BitmapCanvas extends EngineCanvas { // Used by picture to assess if canvas is large enough to reuse as is. bool doesFitBounds(ui.Rect newBounds, double newDensity) { assert(newBounds != null); // ignore: unnecessary_null_comparison - return _widthInBitmapPixels >= _widthToPhysical(newBounds.width) && - _heightInBitmapPixels >= _heightToPhysical(newBounds.height) && + return widthInBitmapPixels >= widthToPhysical(newBounds.width) && + heightInBitmapPixels >= heightToPhysical(newBounds.height) && _density == newDensity; } @@ -343,7 +367,7 @@ class BitmapCanvas extends EngineCanvas { _renderStrategy.isInsideShaderMask || (_preserveImageData == false && _contains3dTransform) || (_childOverdraw && - _canvasPool._canvas == null && + _canvasPool.canvas == null && paint.maskFilter == null && paint.shader == null && paint.style != ui.PaintingStyle.stroke); @@ -357,7 +381,7 @@ class BitmapCanvas extends EngineCanvas { ((_childOverdraw || _renderStrategy.hasImageElements || _renderStrategy.hasParagraphs) && - _canvasPool._canvas == null && + _canvasPool.canvas == null && paint.maskFilter == null && paint.shader == null); @@ -367,7 +391,7 @@ class BitmapCanvas extends EngineCanvas { ..color = color ..blendMode = blendMode; if (_useDomForRenderingFill(paintData)) { - drawRect(_computeScreenBounds(_canvasPool._currentTransform), paintData); + drawRect(_computeScreenBounds(_canvasPool.currentTransform), paintData); } else { _canvasPool.drawColor(color, blendMode); } @@ -392,7 +416,7 @@ class BitmapCanvas extends EngineCanvas { @override void drawPaint(SurfacePaintData paint) { if (_useDomForRenderingFill(paint)) { - drawRect(_computeScreenBounds(_canvasPool._currentTransform), paint); + drawRect(_computeScreenBounds(_canvasPool.currentTransform), paint); } else { ui.Rect? shaderBounds = (paint.shader != null) ? _computePictureBounds() : null; @@ -405,8 +429,8 @@ class BitmapCanvas extends EngineCanvas { @override void drawRect(ui.Rect rect, SurfacePaintData paint) { if (_useDomForRenderingFillAndStroke(paint)) { - html.HtmlElement element = _buildDrawRectElement( - rect, paint, 'draw-rect', _canvasPool._currentTransform); + html.HtmlElement element = buildDrawRectElement( + rect, paint, 'draw-rect', _canvasPool.currentTransform); _drawElement( element, ui.Offset( @@ -425,10 +449,10 @@ class BitmapCanvas extends EngineCanvas { html.Element element, ui.Offset offset, SurfacePaintData paint) { if (_canvasPool.isClipped) { final List clipElements = _clipContent( - _canvasPool._clipStack!, + _canvasPool.clipStack!, element, ui.Offset.zero, - transformWithOffset(_canvasPool._currentTransform, offset)); + transformWithOffset(_canvasPool.currentTransform, offset)); for (html.Element clipElement in clipElements) { rootElement.append(clipElement); _children.add(clipElement); @@ -439,7 +463,7 @@ class BitmapCanvas extends EngineCanvas { } ui.BlendMode? blendMode = paint.blendMode; if (blendMode != null) { - element.style.mixBlendMode = _stringForBlendMode(blendMode) ?? ''; + element.style.mixBlendMode = stringForBlendMode(blendMode) ?? ''; } // Switch to preferring DOM from now on, and close the current canvas. _closeCurrentCanvas(); @@ -449,9 +473,9 @@ class BitmapCanvas extends EngineCanvas { void drawRRect(ui.RRect rrect, SurfacePaintData paint) { final ui.Rect rect = rrect.outerRect; if (_useDomForRenderingFillAndStroke(paint)) { - html.HtmlElement element = _buildDrawRectElement( - rect, paint, 'draw-rrect', _canvasPool._currentTransform); - _applyRRectBorderRadius(element.style, rrect); + html.HtmlElement element = buildDrawRectElement( + rect, paint, 'draw-rrect', _canvasPool.currentTransform); + applyRRectBorderRadius(element.style, rrect); _drawElement( element, ui.Offset( @@ -474,8 +498,8 @@ class BitmapCanvas extends EngineCanvas { @override void drawOval(ui.Rect rect, SurfacePaintData paint) { if (_useDomForRenderingFill(paint)) { - html.HtmlElement element = _buildDrawRectElement( - rect, paint, 'draw-oval', _canvasPool._currentTransform); + html.HtmlElement element = buildDrawRectElement( + rect, paint, 'draw-oval', _canvasPool.currentTransform); _drawElement( element, ui.Offset( @@ -494,8 +518,8 @@ class BitmapCanvas extends EngineCanvas { void drawCircle(ui.Offset c, double radius, SurfacePaintData paint) { ui.Rect rect = ui.Rect.fromCircle(center: c, radius: radius); if (_useDomForRenderingFillAndStroke(paint)) { - html.HtmlElement element = _buildDrawRectElement( - rect, paint, 'draw-circle', _canvasPool._currentTransform); + html.HtmlElement element = buildDrawRectElement( + rect, paint, 'draw-circle', _canvasPool.currentTransform); _drawElement( element, ui.Offset( @@ -516,7 +540,7 @@ class BitmapCanvas extends EngineCanvas { @override void drawPath(ui.Path path, SurfacePaintData paint) { if (_useDomForRenderingFill(paint)) { - final Matrix4 transform = _canvasPool._currentTransform; + final Matrix4 transform = _canvasPool.currentTransform; final SurfacePath surfacePath = path as SurfacePath; final ui.Rect? pathAsLine = surfacePath.toStraightLine(); if (pathAsLine != null) { @@ -526,8 +550,8 @@ class BitmapCanvas extends EngineCanvas { : ui.Rect.fromLTWH( pathAsLine.left, pathAsLine.top, 1, pathAsLine.height); - html.HtmlElement element = _buildDrawRectElement( - rect, paint, 'draw-rect', _canvasPool._currentTransform); + html.HtmlElement element = buildDrawRectElement( + rect, paint, 'draw-rect', _canvasPool.currentTransform); _drawElement( element, ui.Offset(math.min(rect.left, rect.right), @@ -546,7 +570,7 @@ class BitmapCanvas extends EngineCanvas { return; } final ui.Rect pathBounds = surfacePath.getBounds(); - html.Element svgElm = _pathToSvgElement( + html.Element svgElm = pathToSvgElement( surfacePath, paint, '${pathBounds.right}', '${pathBounds.bottom}'); if (!_canvasPool.isClipped) { html.CssStyleDeclaration style = svgElm.style; @@ -640,12 +664,12 @@ class BitmapCanvas extends EngineCanvas { // No Blending, create an image by cloning original loaded image. imgElement = _reuseOrCreateImage(htmlImage); } - imgElement.style.mixBlendMode = _stringForBlendMode(blendMode) ?? ''; + imgElement.style.mixBlendMode = stringForBlendMode(blendMode) ?? ''; if (_canvasPool.isClipped) { // Reset width/height since they may have been previously set. imgElement.style..removeProperty('width')..removeProperty('height'); final List clipElements = _clipContent( - _canvasPool._clipStack!, imgElement, p, _canvasPool.currentTransform); + _canvasPool.clipStack!, imgElement, p, _canvasPool.currentTransform); for (html.Element clipElement in clipElements) { rootElement.append(clipElement); _children.add(clipElement); @@ -808,8 +832,7 @@ class BitmapCanvas extends EngineCanvas { style ..position = 'absolute' ..backgroundImage = "url('${image.imgElement.src}')" - ..backgroundBlendMode = - _stringForBlendMode(colorFilterBlendMode) ?? '' + ..backgroundBlendMode = stringForBlendMode(colorFilterBlendMode) ?? '' ..backgroundColor = colorToCssString(filterColor); break; } @@ -830,7 +853,7 @@ class BitmapCanvas extends EngineCanvas { rootElement.append(filterElement); _children.add(filterElement); final html.HtmlElement imgElement = _reuseOrCreateImage(image); - imgElement.style.filter = 'url(#_fcf${_filterIdCounter})'; + imgElement.style.filter = 'url(#_fcf${filterIdCounter})'; if (colorFilterBlendMode == ui.BlendMode.saturation) { imgElement.style.backgroundColor = colorToCssString(filterColor); } @@ -847,7 +870,7 @@ class BitmapCanvas extends EngineCanvas { rootElement.append(filterElement); _children.add(filterElement); final html.HtmlElement imgElement = _reuseOrCreateImage(image); - imgElement.style.filter = 'url(#_fcf${_filterIdCounter})'; + imgElement.style.filter = 'url(#_fcf${filterIdCounter})'; return imgElement; } @@ -915,10 +938,10 @@ class BitmapCanvas extends EngineCanvas { } final html.Element paragraphElement = - _drawParagraphElement(paragraph, offset); + drawParagraphElement(paragraph, offset); if (_canvasPool.isClipped) { final List clipElements = _clipContent( - _canvasPool._clipStack!, + _canvasPool.clipStack!, paragraphElement as html.HtmlElement, offset, _canvasPool.currentTransform); @@ -981,7 +1004,7 @@ class BitmapCanvas extends EngineCanvas { restore(); return; } - glRenderer!.drawVertices(ctx, _widthInBitmapPixels, _heightInBitmapPixels, + glRenderer!.drawVertices(ctx, widthInBitmapPixels, heightInBitmapPixels, _canvasPool.currentTransform, vertices, blendMode, paint); } @@ -1066,7 +1089,7 @@ class BitmapCanvas extends EngineCanvas { } } -String? _stringForBlendMode(ui.BlendMode? blendMode) { +String? stringForBlendMode(ui.BlendMode? blendMode) { if (blendMode == null) { return null; } @@ -1132,7 +1155,7 @@ String? _stringForBlendMode(ui.BlendMode? blendMode) { } } -String? _stringForStrokeCap(ui.StrokeCap? strokeCap) { +String? stringForStrokeCap(ui.StrokeCap? strokeCap) { if (strokeCap == null) { return null; } @@ -1147,7 +1170,7 @@ String? _stringForStrokeCap(ui.StrokeCap? strokeCap) { } } -String _stringForStrokeJoin(ui.StrokeJoin strokeJoin) { +String stringForStrokeJoin(ui.StrokeJoin strokeJoin) { assert(strokeJoin != null); // ignore: unnecessary_null_comparison switch (strokeJoin) { case ui.StrokeJoin.round: @@ -1167,13 +1190,13 @@ 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 _clipContent(List<_SaveClipEntry> clipStack, +List _clipContent(List clipStack, html.Element content, ui.Offset offset, Matrix4 currentTransform) { html.Element? root, curElement; final List clipDefs = []; final int len = clipStack.length; for (int clipIndex = 0; clipIndex < len; clipIndex++) { - final _SaveClipEntry entry = clipStack[clipIndex]; + final SaveClipEntry entry = clipStack[clipIndex]; final html.HtmlElement newElement = html.DivElement(); newElement.style.position = 'absolute'; applyWebkitClipFix(newElement); @@ -1273,7 +1296,7 @@ List _clipContent(List<_SaveClipEntry> clipStack, /// Converts a [maskFilter] to the value to be used on a ``. /// /// Only supported in non-WebKit browsers. -String _maskFilterToCanvasFilter(ui.MaskFilter? maskFilter) { +String maskFilterToCanvasFilter(ui.MaskFilter? maskFilter) { assert( browserEngine != BrowserEngine.webkit, 'WebKit (Safari) does not support `filter` canvas property.', diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/canvas.dart index 675e730c62..556583756e 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/canvas.dart @@ -2,7 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:ui/src/engine.dart' show toMatrix32; +import 'package:ui/ui.dart' as ui; + +import '../picture.dart'; +import '../util.dart'; +import '../validators.dart'; +import 'recording_canvas.dart'; +import 'render_vertices.dart'; +import 'painting.dart'; class SurfaceCanvas implements ui.Canvas { RecordingCanvas _canvas; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/clip.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/clip.dart index 94ba014948..4113894c7e 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/clip.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/clip.dart @@ -2,7 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; + +import 'package:ui/src/engine.dart' show domRenderer, DomRenderer, NullTreeSanitizer; +import 'package:ui/ui.dart' as ui; + +import '../shadow.dart'; +import '../util.dart'; +import 'dom_canvas.dart'; +import 'painting.dart'; +import 'path_to_svg_clip.dart'; +import 'path/path.dart'; +import 'surface.dart'; +import 'surface_stats.dart'; /// Mixin used by surfaces that clip their contents using an overflowing DOM /// element. @@ -25,9 +37,9 @@ mixin _DomClip on PersistedContainerSurface { html.Element createElement() { final html.Element element = defaultCreateElement('flt-clip'); _childContainer = html.Element.tag('flt-clip-interior'); - if (_debugExplainSurfaceStats) { + if (debugExplainSurfaceStats) { // This creates an additional interior element. Count it too. - _surfaceStatsFor(this).allocatedDomNodeCount++; + surfaceStatsFor(this).allocatedDomNodeCount++; } _childContainer!.style.position = 'absolute'; @@ -74,14 +86,13 @@ class PersistedClipRect extends PersistedContainerSurface @override void recomputeTransformAndClip() { - _transform = parent!._transform; + transform = parent!.transform; if (clipBehavior != ui.Clip.none) { - _localClipBounds = rect; + localClipBounds = rect; } else { - _localClipBounds = null; + localClipBounds = null; } - _localTransformInverse = null; - _projectedClip = null; + projectedClip = null; } @override @@ -110,7 +121,7 @@ class PersistedClipRect extends PersistedContainerSurface void update(PersistedClipRect oldSurface) { super.update(oldSurface); if (rect != oldSurface.rect || clipBehavior != oldSurface.clipBehavior) { - _localClipBounds = null; + localClipBounds = null; apply(); } } @@ -132,14 +143,13 @@ class PersistedClipRRect extends PersistedContainerSurface @override void recomputeTransformAndClip() { - _transform = parent!._transform; + transform = parent!.transform; if (clipBehavior != ui.Clip.none) { - _localClipBounds = rrect.outerRect; + localClipBounds = rrect.outerRect; } else { - _localClipBounds = null; + localClipBounds = null; } - _localTransformInverse = null; - _projectedClip = null; + projectedClip = null; } @override @@ -173,7 +183,7 @@ class PersistedClipRRect extends PersistedContainerSurface void update(PersistedClipRRect oldSurface) { super.update(oldSurface); if (rrect != oldSurface.rrect || clipBehavior != oldSurface.clipBehavior) { - _localClipBounds = null; + localClipBounds = null; apply(); } } @@ -203,25 +213,24 @@ class PersistedPhysicalShape extends PersistedContainerSurface @override void recomputeTransformAndClip() { - _transform = parent!._transform; + transform = parent!.transform; if (clipBehavior != ui.Clip.none) { final ui.RRect? roundRect = path.toRoundedRect(); if (roundRect != null) { - _localClipBounds = roundRect.outerRect; + localClipBounds = roundRect.outerRect; } else { final ui.Rect? rect = path.toRect(); if (rect != null) { - _localClipBounds = rect; + localClipBounds = rect; } else { - _localClipBounds = null; + localClipBounds = null; } } } else { - _localClipBounds = null; + localClipBounds = null; } - _localTransformInverse = null; - _projectedClip = null; + projectedClip = null; } void _applyColor() { @@ -376,7 +385,7 @@ class PersistedPhysicalShape extends PersistedContainerSurface ..height = '${pathBounds.bottom}px'; final ui.Rect pathBounds2 = path.getBounds(); - _svgElement = _pathToSvgElement( + _svgElement = pathToSvgElement( path, SurfacePaintData() ..style = ui.PaintingStyle.fill @@ -404,7 +413,7 @@ class PersistedPhysicalShape extends PersistedContainerSurface super.update(oldSurface); bool pathChanged = oldSurface.path != path; if (pathChanged) { - _localClipBounds = null; + localClipBounds = null; } if (pathChanged || oldSurface.elevation != elevation || @@ -457,9 +466,9 @@ class PersistedClipPath extends PersistedContainerSurface void recomputeTransformAndClip() { super.recomputeTransformAndClip(); if (clipBehavior != ui.Clip.none) { - _localClipBounds ??= clipPath.getBounds(); + localClipBounds ??= clipPath.getBounds(); } else { - _localClipBounds = null; + localClipBounds = null; } } @@ -477,7 +486,7 @@ class PersistedClipPath extends PersistedContainerSurface void update(PersistedClipPath oldSurface) { super.update(oldSurface); if (oldSurface.clipPath != clipPath) { - _localClipBounds = null; + localClipBounds = null; oldSurface._clipElement?.remove(); apply(); } else { diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/color_filter.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/color_filter.dart index 32bc43c5b1..58b094ede1 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/color_filter.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/color_filter.dart @@ -2,7 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; + +import 'package:ui/src/engine.dart' show EngineColorFilter, NullTreeSanitizer; +import 'package:ui/ui.dart' as ui; + +import '../canvaskit/color_filter.dart'; +import '../util.dart'; +import 'bitmap_canvas.dart'; +import 'path_to_svg_clip.dart'; +import 'surface.dart'; /// A surface that applies an [ColorFilter] to its children. class PersistedColorFilter extends PersistedContainerSurface @@ -121,7 +130,7 @@ class PersistedColorFilter extends PersistedContainerSurface _filterElement = html.Element.html(svgFilter, treeSanitizer: NullTreeSanitizer()); rootElement!.append(_filterElement!); - rootElement!.style.filter = 'url(#_fcf${_filterIdCounter})'; + rootElement!.style.filter = 'url(#_fcf${filterIdCounter})'; if (colorFilterBlendMode == ui.BlendMode.saturation || colorFilterBlendMode == ui.BlendMode.multiply || colorFilterBlendMode == ui.BlendMode.modulate) { @@ -136,7 +145,7 @@ class PersistedColorFilter extends PersistedContainerSurface _filterElement = html.Element.html(svgFilter, treeSanitizer: NullTreeSanitizer()); rootElement!.append(_filterElement!); - rootElement!.style.filter = 'url(#_fcf${_filterIdCounter})'; + rootElement!.style.filter = 'url(#_fcf${filterIdCounter})'; } } @@ -210,7 +219,7 @@ String? svgFilterFromBlendMode( case ui.BlendMode.difference: case ui.BlendMode.exclusion: svgFilter = _blendColorFilterToSvg( - filterColor, _stringForBlendMode(colorFilterBlendMode)); + filterColor, stringForBlendMode(colorFilterBlendMode)); break; case ui.BlendMode.src: case ui.BlendMode.dst: @@ -229,7 +238,7 @@ String? svgFilterFromBlendMode( } String? svgFilterFromColorMatrix(List matrix) { - _filterIdCounter += 1; + filterIdCounter += 1; final StringBuffer sbMatrix = StringBuffer(); assert(matrix.length == 20); for (int i = 0; i < 20; i++) { @@ -239,13 +248,13 @@ String? svgFilterFromColorMatrix(List matrix) { sbMatrix.write(matrix[i]); } return '$kSvgResourceHeader' - '' '' ''; } -int _filterIdCounter = 0; +int filterIdCounter = 0; // The color matrix for feColorMatrix element changes colors based on // the following: @@ -261,9 +270,9 @@ int _filterIdCounter = 0; // B' = b1*R + b2*G + b3*B + b4*A + b5 // A' = a1*R + a2*G + a3*B + a4*A + a5 String _srcInColorFilterToSvg(ui.Color? color) { - _filterIdCounter += 1; + filterIdCounter += 1; return '$kSvgResourceHeader' - '' '' '' '' @@ -292,9 +301,9 @@ String _dstATopColorFilterToSvg(ui.Color? color) { } String _srcOutColorFilterToSvg(ui.Color? color) { - _filterIdCounter += 1; + filterIdCounter += 1; return '$kSvgResourceHeader' - '' '' '' @@ -304,9 +313,9 @@ String _srcOutColorFilterToSvg(ui.Color? color) { } String _xorColorFilterToSvg(ui.Color? color) { - _filterIdCounter += 1; + filterIdCounter += 1; return '$kSvgResourceHeader' - '' '' '' @@ -319,9 +328,9 @@ String _xorColorFilterToSvg(ui.Color? color) { // result = k1 *in*in2 + k2*in + k3*in2 + k4. String _compositeColorFilterToSvg( ui.Color? color, double k1, double k2, double k3, double k4) { - _filterIdCounter += 1; + filterIdCounter += 1; return '$kSvgResourceHeader' - '' '' '' @@ -335,12 +344,12 @@ String _compositeColorFilterToSvg( // First apply color filter to source to change it to [color], then // composite using multiplication. String _modulateColorFilterToSvg(ui.Color color) { - _filterIdCounter += 1; + filterIdCounter += 1; final double r = color.red / 255.0; final double b = color.blue / 255.0; final double g = color.green / 255.0; return '$kSvgResourceHeader' - '' '' '' '' + diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/debug_canvas_reuse_overlay.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/debug_canvas_reuse_overlay.dart index 2e9d78c75e..79a2fd99c3 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/debug_canvas_reuse_overlay.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/debug_canvas_reuse_overlay.dart @@ -2,7 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; + +import '../util.dart'; html.HtmlElement _createContainer() { final html.HtmlElement container = html.DivElement(); diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/dom_canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/dom_canvas.dart index 5cc9ace4ac..99b5dcec70 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/dom_canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/dom_canvas.dart @@ -2,7 +2,23 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:ui/src/engine.dart' show domRenderer, NullTreeSanitizer; +import 'package:ui/ui.dart' as ui; + +import '../browser_detection.dart'; +import '../engine_canvas.dart'; +import '../html_image_codec.dart'; +import '../text/paragraph.dart'; +import '../util.dart'; +import '../vector_math.dart'; +import 'painting.dart'; +import 'path/path.dart'; +import 'path/path_to_svg.dart'; +import 'shaders/image_shader.dart'; /// A canvas that renders to DOM elements and CSS properties. class DomCanvas extends EngineCanvas with SaveElementStackTracking { @@ -61,14 +77,14 @@ class DomCanvas extends EngineCanvas with SaveElementStackTracking { @override void drawRect(ui.Rect rect, SurfacePaintData paint) { currentElement.append( - _buildDrawRectElement(rect, paint, 'draw-rect', currentTransform)); + buildDrawRectElement(rect, paint, 'draw-rect', currentTransform)); } @override void drawRRect(ui.RRect rrect, SurfacePaintData paint) { - html.Element element = _buildDrawRectElement( + html.Element element = buildDrawRectElement( rrect.outerRect, paint, 'draw-rrect', currentTransform); - _applyRRectBorderRadius(element.style, rrect); + applyRRectBorderRadius(element.style, rrect); currentElement.append(element); } @@ -111,7 +127,7 @@ class DomCanvas extends EngineCanvas with SaveElementStackTracking { @override void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) { - final html.Element paragraphElement = _drawParagraphElement( + final html.Element paragraphElement = drawParagraphElement( paragraph as EngineParagraph, offset, transform: currentTransform); currentElement.append(paragraphElement); @@ -145,7 +161,7 @@ ui.Color blurColor(ui.Color color, double sigma) { return ui.Color((reducedAlpha & 0xff) << 24 | (color.value & 0x00ffffff)); } -html.HtmlElement _buildDrawRectElement( +html.HtmlElement buildDrawRectElement( ui.Rect rect, SurfacePaintData paint, String tagName, Matrix4 transform) { assert(paint.shader == null); final html.HtmlElement rectangle = @@ -226,7 +242,7 @@ void _applyImageShaderToElement(html.HtmlElement targetElement, targetElement.style.backgroundImage = image.imgElement.src; } -void _applyRRectBorderRadius(html.CssStyleDeclaration style, ui.RRect rrect) { +void applyRRectBorderRadius(html.CssStyleDeclaration style, ui.RRect rrect) { if (rrect.tlRadiusX == rrect.trRadiusX && rrect.tlRadiusX == rrect.blRadiusX && rrect.tlRadiusX == rrect.brRadiusX && @@ -256,7 +272,7 @@ String _borderStrokeToCssUnit(double value) { return '${value.toStringAsFixed(3)}px'; } -html.Element _pathToSvgElement( +html.Element pathToSvgElement( SurfacePath path, SurfacePaintData paint, String width, String height) { final StringBuffer sb = StringBuffer(); sb.write( diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/image_filter.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/image_filter.dart index 7c7df2a43d..e2a37e78ec 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/image_filter.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/image_filter.dart @@ -2,7 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; + +import 'package:ui/ui.dart' as ui; + +import 'surface.dart'; +import 'shaders/shader.dart'; /// A surface that applies an [imageFilter] to its children. class PersistedImageFilter extends PersistedContainerSurface diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/offset.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/offset.dart index 62058c6805..79025e1b82 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/offset.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/offset.dart @@ -2,7 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; + +import 'package:ui/src/engine.dart' show DomRenderer; +import 'package:ui/ui.dart' as ui; + +import '../vector_math.dart'; +import 'surface.dart'; /// A surface that translates its children using CSS transform and translate. class PersistedOffset extends PersistedContainerSurface @@ -17,15 +23,18 @@ class PersistedOffset extends PersistedContainerSurface @override void recomputeTransformAndClip() { - _transform = parent!._transform; + transform = parent!.transform; if (dx != 0.0 || dy != 0.0) { - _transform = _transform!.clone(); - _transform!.translate(dx, dy); + transform = transform!.clone(); + transform!.translate(dx, dy); } - _projectedClip = null; - _localTransformInverse = null; + projectedClip = null; } + /// Cached inverse of transform on this node. Unlike transform, this + /// Matrix only contains local transform (not chain multiplied since root). + Matrix4? _localTransformInverse; + @override Matrix4 get localTransformInverse => _localTransformInverse ??= Matrix4.translationValues(-dx, -dy, 0); diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/opacity.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/opacity.dart index 37988abdd7..8fffe5175f 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/opacity.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/opacity.dart @@ -2,7 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; + +import 'package:ui/src/engine.dart' show domRenderer, DomRenderer; +import 'package:ui/ui.dart' as ui; + +import '../vector_math.dart'; +import 'surface.dart'; /// A surface that makes its children transparent. class PersistedOpacity extends PersistedContainerSurface @@ -15,19 +21,22 @@ class PersistedOpacity extends PersistedContainerSurface @override void recomputeTransformAndClip() { - _transform = parent!._transform; + transform = parent!.transform; final double dx = offset.dx; final double dy = offset.dy; if (dx != 0.0 || dy != 0.0) { - _transform = _transform!.clone(); - _transform!.translate(dx, dy); + transform = transform!.clone(); + transform!.translate(dx, dy); } - _localTransformInverse = null; - _projectedClip = null; + projectedClip = null; } + /// Cached inverse of transform on this node. Unlike transform, this + /// Matrix only contains local transform (not chain multiplied since root). + Matrix4? _localTransformInverse; + @override Matrix4 get localTransformInverse => _localTransformInverse ??= Matrix4.translationValues(-offset.dx, -offset.dy, 0); diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/path/path.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/path/path.dart index 1384a58bf7..8865f99fa3 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/path/path.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/path/path.dart @@ -2,7 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:ui/src/engine.dart' show toMatrix32; +import 'package:ui/ui.dart' as ui; + +import '../../util.dart'; +import '../../validators.dart'; +import 'conic.dart'; +import 'cubic.dart'; +import 'path_iterator.dart'; +import 'path_metrics.dart'; +import 'path_ref.dart'; +import 'path_utils.dart'; +import 'path_windings.dart'; +import 'tangent.dart'; /// A complex, one-dimensional subset of a plane. /// @@ -63,7 +78,7 @@ class SurfacePath implements ui.Path { _copyFields(source); } - SurfacePath._shallowCopy(SurfacePath source) + SurfacePath.shallowCopy(SurfacePath source) : pathRef = PathRef.shallowCopy(source.pathRef) { _copyFields(source); } @@ -101,7 +116,7 @@ class SurfacePath implements ui.Path { return true; } out.reset(); - out._addPath(this, 0, 0, null, SPathAddPathMode.kAppend); + out.addPathWithMode(this, 0, 0, null, SPathAddPathMode.kAppend); PathRef.interpolate(ending.pathRef, weight, out.pathRef); return true; } @@ -1056,11 +1071,16 @@ class SurfacePath implements ui.Path { /// matrix stored in column major order. @override void addPath(ui.Path path, ui.Offset offset, {Float64List? matrix4}) { - _addPath(path, offset.dx, offset.dy, + addPathWithMode(path, offset.dx, offset.dy, matrix4 == null ? null : toMatrix32(matrix4), SPathAddPathMode.kAppend); } - void _addPath(ui.Path path, double offsetX, double offsetY, + /// Adds a new subpath that consists of the given `path` offset by the given + /// `offset`, and using the given [mode]. + /// + /// If `matrix4` is not null, the path will be transformed by this matrix + /// after the matrix is translated by the given offset. + void addPathWithMode(ui.Path path, double offsetX, double offsetY, Float32List? matrix4, int mode) { SurfacePath source = path as SurfacePath; if (source.pathRef.isEmpty) { @@ -1173,7 +1193,7 @@ class SurfacePath implements ui.Path { @override void extendWithPath(ui.Path path, ui.Offset offset, {Float64List? matrix4}) { assert(offsetIsValid(offset)); - _addPath(path, offset.dx, offset.dy, + addPathWithMode(path, offset.dx, offset.dy, matrix4 == null ? null : toMatrix32(matrix4), SPathAddPathMode.kExtend); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/picture.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/picture.dart index 6562dfa5c9..66e1f41632 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/picture.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/picture.dart @@ -2,7 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:ui/src/engine.dart' show domRenderer; +import 'package:ui/ui.dart' as ui; + +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 'path/path_metrics.dart'; +import 'shader_mask.dart'; +import 'surface.dart'; +import 'surface_stats.dart'; // TODO(yjbanov): this is currently very naive. We probably want to cache // fewer large canvases than small canvases. We could also @@ -16,10 +34,11 @@ part of engine; const int _kCanvasCacheSize = 30; /// Canvases available for reuse, capped at [_kCanvasCacheSize]. +List get recycledCanvases => _recycledCanvases; final List _recycledCanvases = []; /// Reduces recycled canvas list by 50% to reduce bitmap canvas memory use. -void _reduceCanvasMemoryUsage() { +void reduceCanvasMemoryUsage() { final int canvasCount = _recycledCanvases.length; for (int i = 0; i < canvasCount; i++) { _recycledCanvases[i].dispose(); @@ -33,8 +52,8 @@ void _reduceCanvasMemoryUsage() { /// makes canvas allocation more efficient by letting large pictures claim /// larger recycled canvases. Otherwise, small pictures would claim the large /// canvases forcing us to allocate new large canvases. -class _PaintRequest { - _PaintRequest({ +class PaintRequest { + PaintRequest({ required this.canvasSize, required this.paintCallback, }) : assert(canvasSize != null), // ignore: unnecessary_null_comparison @@ -47,7 +66,7 @@ class _PaintRequest { /// Repaint requests produced by [PersistedPicture]s that actually paint on the /// canvas. Painting is delayed until the layer tree is updated to maximize /// the number of reusable canvases. -List<_PaintRequest> _paintQueue = <_PaintRequest>[]; +List paintQueue = []; void _recycleCanvas(EngineCanvas? canvas) { // If a canvas is in the paint queue it maybe be recycled. To @@ -62,11 +81,11 @@ void _recycleCanvas(EngineCanvas? canvas) { if (_recycledCanvases.length > _kCanvasCacheSize) { final BitmapCanvas removedCanvas = _recycledCanvases.removeAt(0); removedCanvas.dispose(); - if (_debugShowCanvasReuseStats) { + if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.disposedCount++; } } - if (_debugShowCanvasReuseStats) { + if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.inRecycleCount = _recycledCanvases.length; } @@ -85,9 +104,7 @@ class PersistedPicture extends PersistedLeafSurface { EngineCanvas? _canvas; /// Returns the canvas used by this picture layer. - /// - /// Useful for tests. - EngineCanvas? get debugCanvas => _canvas; + EngineCanvas? get canvas => _canvas; final double dx; final double dy; @@ -120,17 +137,17 @@ class PersistedPicture extends PersistedLeafSurface { @override void recomputeTransformAndClip() { - _transform = parent!._transform; + transform = parent!.transform; if (dx != 0.0 || dy != 0.0) { - _transform = _transform!.clone(); - _transform!.translate(dx, dy); + transform = transform!.clone(); + transform!.translate(dx, dy); } final double paintWidth = localPaintBounds!.width; final double paintHeight = localPaintBounds!.height; final double newDensity = localPaintBounds == null || paintWidth == 0 || paintHeight == 0 ? 1.0 - : _computePixelDensity(_transform, paintWidth, paintHeight); + : _computePixelDensity(transform, paintWidth, paintHeight); if (newDensity != _density) { _density = newDensity; _requiresRepaint = true; @@ -166,7 +183,7 @@ class PersistedPicture extends PersistedLeafSurface { assert(transform != null); assert(localPaintBounds != null); - if (parent!._projectedClip == null) { + if (parent!.projectedClip == null) { // Compute and cache chain of clipping bounds on parent of picture since // parent may include multiple pictures so it can be reused by all // child pictures. @@ -174,7 +191,7 @@ class PersistedPicture extends PersistedLeafSurface { PersistedSurface? parentSurface = parent; final Matrix4 clipTransform = Matrix4.identity(); while (parentSurface != null) { - final ui.Rect? localClipBounds = parentSurface._localClipBounds; + final ui.Rect? localClipBounds = parentSurface.localClipBounds; if (localClipBounds != null) { if (bounds == null) { bounds = transformRect(clipTransform, localClipBounds); @@ -193,15 +210,15 @@ class PersistedPicture extends PersistedLeafSurface { bounds = ui.Rect.zero; } // Cache projected clip on parent. - parent!._projectedClip = bounds; + parent!.projectedClip = bounds; } // Intersect localPaintBounds with parent projected clip to calculate // and cache [_exactLocalCullRect]. - if (parent!._projectedClip == null) { + if (parent!.projectedClip == null) { _exactLocalCullRect = localPaintBounds; } else { _exactLocalCullRect = - localPaintBounds!.intersect(parent!._projectedClip!); + localPaintBounds!.intersect(parent!.projectedClip!); } if (_exactLocalCullRect!.width <= 0 || _exactLocalCullRect!.height <= 0) { _exactLocalCullRect = ui.Rect.zero; @@ -342,8 +359,8 @@ class PersistedPicture extends PersistedLeafSurface { return; } - if (_debugExplainSurfaceStats) { - _surfaceStatsFor(this).paintCount++; + if (debugExplainSurfaceStats) { + surfaceStatsFor(this).paintCount++; } assert(_optimalLocalCullRect != null); @@ -386,10 +403,10 @@ class PersistedPicture extends PersistedLeafSurface { return 1.0; } else { final int newPixelCount = - BitmapCanvas._widthToPhysical(_exactLocalCullRect!.width) * - BitmapCanvas._heightToPhysical(_exactLocalCullRect!.height); + BitmapCanvas.widthToPhysical(_exactLocalCullRect!.width) * + BitmapCanvas.heightToPhysical(_exactLocalCullRect!.height); final int oldPixelCount = - oldCanvas._widthInBitmapPixels * oldCanvas._heightInBitmapPixels; + oldCanvas.widthInBitmapPixels * oldCanvas.heightInBitmapPixels; if (oldPixelCount == 0) { return 1.0; @@ -403,9 +420,6 @@ class PersistedPicture extends PersistedLeafSurface { } } - @override - Matrix4? get localTransformInverse => null; - void applyPaint(EngineCanvas? oldCanvas) { if (picture.recordingCanvas!.renderStrategy.hasArbitraryPaint) { _applyBitmapPaint(oldCanvas); @@ -427,7 +441,7 @@ class PersistedPicture extends PersistedLeafSurface { oldCanvas.doesFitBounds(_optimalLocalCullRect!, _density) && oldCanvas.isReusable()) { final BitmapCanvas reusedCanvas = oldCanvas; - if (_debugShowCanvasReuseStats) { + if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.keptCount++; } // Re-use old bitmap canvas. @@ -448,15 +462,15 @@ class PersistedPicture extends PersistedLeafSurface { // able to reuse have been released yet. So instead we enqueue this // picture to be painted after the update cycle is done syncing the layer // tree then reuse canvases that were freed up. - _paintQueue.add(_PaintRequest( + paintQueue.add(PaintRequest( canvasSize: _optimalLocalCullRect!.size, paintCallback: () { final BitmapCanvas bitmapCanvas = _findOrCreateCanvas(_optimalLocalCullRect!); _canvas = bitmapCanvas; bitmapCanvas.setElementCache(_elementCache); - if (_debugExplainSurfaceStats) { - _surfaceStatsFor(this).paintPixelCount += + if (debugExplainSurfaceStats) { + surfaceStatsFor(this).paintPixelCount += bitmapCanvas.bitmapPixelCount; } domRenderer.clearDom(rootElement!); @@ -516,15 +530,15 @@ class PersistedPicture extends PersistedLeafSurface { } if (bestRecycledCanvas != null) { - if (_debugExplainSurfaceStats) { - _surfaceStatsFor(this).reuseCanvasCount++; + if (debugExplainSurfaceStats) { + surfaceStatsFor(this).reuseCanvasCount++; } _recycledCanvases.remove(bestRecycledCanvas); - if (_debugShowCanvasReuseStats) { + if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.inRecycleCount = _recycledCanvases.length; } - if (_debugShowCanvasReuseStats) { + if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.reusedCount++; } bestRecycledCanvas.bounds = bounds; @@ -532,18 +546,18 @@ class PersistedPicture extends PersistedLeafSurface { return bestRecycledCanvas; } - if (_debugShowCanvasReuseStats) { + if (debugShowCanvasReuseStats) { DebugCanvasReuseOverlay.instance.createdCount++; } final BitmapCanvas canvas = BitmapCanvas( bounds, picture.recordingCanvas!.renderStrategy, density: _density); canvas.setElementCache(_elementCache); - if (_debugExplainSurfaceStats) { - _surfaceStatsFor(this) + if (debugExplainSurfaceStats) { + surfaceStatsFor(this) ..allocateBitmapCanvasCount += 1 ..allocatedBitmapSizeInPixels = - canvas._widthInBitmapPixels * canvas._heightInBitmapPixels; + canvas.widthInBitmapPixels * canvas.heightInBitmapPixels; } return canvas; } @@ -581,7 +595,7 @@ class PersistedPicture extends PersistedLeafSurface { _computeOptimalCullRect(oldSurface); if (identical(picture, oldSurface.picture)) { bool densityChanged = (_canvas is BitmapCanvas && - _density != (_canvas as BitmapCanvas)._density); + _density != (_canvas as BitmapCanvas).density); // The picture is the same. Attempt to avoid repaint. if (_requiresRepaint || densityChanged) { @@ -635,7 +649,7 @@ class PersistedPicture extends PersistedLeafSurface { super.debugValidate(validationErrors); if (picture.recordingCanvas!.didDraw) { - if (!_optimalLocalCullRect!.isEmpty && debugCanvas == null) { + if (!_optimalLocalCullRect!.isEmpty && canvas == null) { validationErrors .add('$runtimeType has non-trivial picture but it has null canvas'); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/platform_view.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/platform_view.dart index ad1e1da413..4494534110 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/platform_view.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/platform_view.dart @@ -2,7 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; + +import 'package:ui/src/engine.dart' show createPlatformViewSlot; + +import 'surface.dart'; /// A surface containing a platform view, which is an HTML element. class PersistedPlatformView extends PersistedLeafSurface { @@ -19,9 +23,6 @@ class PersistedPlatformView extends PersistedLeafSurface { return createPlatformViewSlot(viewId); } - @override - Matrix4? get localTransformInverse => null; - @override void apply() { // See `_compositeWithParams` in the HtmlViewEmbedder for the canvaskit equivalent. diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/recording_canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/recording_canvas.dart index 660a395245..910cd72828 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/recording_canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/recording_canvas.dart @@ -2,7 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:math' as math; +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/paragraph.dart'; +import '../util.dart'; +import '../vector_math.dart'; +import 'bitmap_canvas.dart'; +import 'painting.dart'; +import 'path/path.dart'; +import 'path/path_utils.dart'; +import 'render_vertices.dart'; +import 'shaders/image_shader.dart'; /// Enable this to print every command applied by a canvas. const bool _debugDumpPaintCommands = false; @@ -503,7 +520,7 @@ class RecordingCanvas { pathBounds = pathBounds.inflate(paintSpread); } // Clone path so it can be reused for subsequent draw calls. - final ui.Path clone = SurfacePath._shallowCopy(path); + final ui.Path clone = SurfacePath.shallowCopy(path); final PaintDrawPath command = PaintDrawPath(clone as SurfacePath, paint.paintData); _paintBounds.grow(pathBounds, command); @@ -1373,7 +1390,7 @@ class Ellipse extends PathCommand { anticlockwise ? startAngle - endAngle : endAngle - startAngle, matrix4, bezierPath); - targetPath._addPath(bezierPath, 0, 0, matrix4, SPathAddPathMode.kAppend); + targetPath.addPathWithMode(bezierPath, 0, 0, matrix4, SPathAddPathMode.kAppend); } void _drawArcWithBezier( @@ -1627,8 +1644,8 @@ class RRectCommand extends PathCommand { @override void transform(Float32List matrix4, SurfacePath targetPath) { final ui.Path roundRectPath = ui.Path(); - _RRectToPathRenderer(roundRectPath).render(rrect); - targetPath._addPath(roundRectPath, 0, 0, matrix4, SPathAddPathMode.kAppend); + RRectToPathRenderer(roundRectPath).render(rrect); + targetPath.addPathWithMode(roundRectPath, 0, 0, matrix4, SPathAddPathMode.kAppend); } @override diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene.dart index 9f2e3f33b2..8198af52eb 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene.dart @@ -2,7 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; + +import 'package:ui/ui.dart' as ui; + +import '../vector_math.dart'; +import 'surface.dart'; class SurfaceScene implements ui.Scene { /// This class is created by the engine, and should not be instantiated @@ -28,7 +33,7 @@ class SurfaceScene implements ui.Scene { /// A surface that creates a DOM element for whole app. class PersistedScene extends PersistedContainerSurface { PersistedScene(PersistedScene? oldLayer) : super(oldLayer) { - _transform = Matrix4.identity(); + transform = Matrix4.identity(); } @override @@ -39,13 +44,17 @@ class PersistedScene extends PersistedContainerSurface { // update this code when we add add2app support. final double screenWidth = html.window.innerWidth!.toDouble(); final double screenHeight = html.window.innerHeight!.toDouble(); - _localClipBounds = ui.Rect.fromLTRB(0, 0, screenWidth, screenHeight); - _localTransformInverse = Matrix4.identity(); - _projectedClip = null; + localClipBounds = ui.Rect.fromLTRB(0, 0, screenWidth, screenHeight); + projectedClip = null; } + /// Cached inverse of transform on this node. Unlike transform, this + /// Matrix only contains local transform (not chain multiplied since root). + Matrix4? _localTransformInverse; + @override - Matrix4? get localTransformInverse => _localTransformInverse; + Matrix4? get localTransformInverse => + _localTransformInverse ??= Matrix4.identity(); @override html.Element createElement() { diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene_builder.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene_builder.dart index 533eab4cc8..a2fd3a78e3 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene_builder.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/scene_builder.dart @@ -2,7 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:typed_data'; + +import 'package:ui/src/engine.dart' show kProfileApplyFrame, kProfilePrerollFrame, toMatrix32, window; +import 'package:ui/ui.dart' as ui; + +import '../picture.dart'; +import '../profiler.dart'; +import '../util.dart'; +import '../vector_math.dart'; +import 'backdrop_filter.dart'; +import 'clip.dart'; +import 'color_filter.dart'; +import 'image_filter.dart'; +import 'offset.dart'; +import 'opacity.dart'; +import 'path/path.dart'; +import 'path_to_svg_clip.dart'; +import 'picture.dart'; +import 'platform_view.dart'; +import 'scene.dart'; +import 'shader_mask.dart'; +import 'shaders/shader.dart'; +import 'surface.dart'; +import 'transform.dart'; class SurfaceSceneBuilder implements ui.SceneBuilder { SurfaceSceneBuilder() { @@ -502,7 +525,7 @@ class SurfaceSceneBuilder implements ui.SceneBuilder { _lastFrameScene?.rootElement?.remove(); _lastFrameScene = null; resetSvgClipIds(); - _recycledCanvases.clear(); + recycledCanvases.clear(); } /// Finishes building the scene. diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/shader_mask.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/shader_mask.dart index 12faa93586..fc5e4cab77 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/shader_mask.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/shader_mask.dart @@ -2,7 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; + +import 'package:ui/src/engine.dart' show NullTreeSanitizer; +import 'package:ui/ui.dart' as ui; + +import '../browser_detection.dart'; +import 'bitmap_canvas.dart'; +import 'path_to_svg_clip.dart'; +import 'shaders/shader.dart'; +import 'surface.dart'; /// A surface that applies a shader to its children. /// @@ -230,7 +239,7 @@ String? svgMaskFilterFromImageAndBlendMode( case ui.BlendMode.difference: case ui.BlendMode.exclusion: svgFilter = _blendImageToSvg( - imageUrl, _stringForBlendMode(blendMode), width, height); + imageUrl, stringForBlendMode(blendMode), width, height); break; case ui.BlendMode.src: case ui.BlendMode.dst: diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/surface.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/surface.dart index 9642834764..86510c9c6d 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/surface.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/surface.dart @@ -2,19 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:html' as html; + +import 'package:meta/meta.dart'; +import 'package:ui/ui.dart' as ui; + +import '../frame_reference.dart'; +import '../onscreen_logging.dart'; +import '../semantics.dart'; +import '../util.dart'; +import '../vector_math.dart'; +import 'picture.dart'; +import 'scene.dart'; +import 'surface_stats.dart'; + /// When `true` prints statistics about what happened to the surface tree when - -part of engine; - /// it was composited. /// /// Also paints an on-screen overlay with the numbers visualized as a timeline. -const bool _debugExplainSurfaceStats = false; +const bool debugExplainSurfaceStats = false; /// When `true` shows an overlay that contains stats about canvas reuse. /// /// The overlay also includes a button to reset the stats. -const bool _debugShowCanvasReuseStats = false; +const bool debugShowCanvasReuseStats = false; /// When `true` renders the outlines of clip layers on the screen instead of /// clipping the contents. @@ -28,44 +39,44 @@ bool debugShowClipLayers = false; /// As we improve canvas utilization we should decrease this number. It is /// unlikely that we will hit 1.0, but something around 3.0 should be /// reasonable. -const double _kScreenPixelRatioWarningThreshold = 6.0; +const double kScreenPixelRatioWarningThreshold = 6.0; /// Performs any outstanding painting work enqueued by [PersistedPicture]s. void commitScene(PersistedScene scene) { - if (_paintQueue.isNotEmpty) { + if (paintQueue.isNotEmpty) { try { - if (_paintQueue.length > 1) { + if (paintQueue.length > 1) { // Sort paint requests in decreasing canvas size order. Paint requests // attempt to reuse canvases. For efficiency we want the biggest pictures // to find canvases before the smaller ones claim them. - _paintQueue.sort((_PaintRequest a, _PaintRequest b) { + paintQueue.sort((PaintRequest a, PaintRequest b) { final double aSize = a.canvasSize.height * a.canvasSize.width; final double bSize = b.canvasSize.height * b.canvasSize.width; return bSize.compareTo(aSize); }); } - for (_PaintRequest request in _paintQueue) { + for (PaintRequest request in paintQueue) { request.paintCallback(); } } finally { - _paintQueue = <_PaintRequest>[]; + paintQueue = []; } } // After the update the retained surfaces are back to active. - if (_retainedSurfaces.isNotEmpty) { - for (int i = 0; i < _retainedSurfaces.length; i++) { - final PersistedSurface retainedSurface = _retainedSurfaces[i]; + if (retainedSurfaces.isNotEmpty) { + for (int i = 0; i < retainedSurfaces.length; i++) { + final PersistedSurface retainedSurface = retainedSurfaces[i]; assert(debugAssertSurfaceState( retainedSurface, PersistedSurfaceState.pendingRetention)); retainedSurface.state = PersistedSurfaceState.active; } - _retainedSurfaces = []; + retainedSurfaces = []; } - if (_debugExplainSurfaceStats) { - _debugPrintSurfaceStats(scene, _debugFrameNumber); - _debugRepaintSurfaceStatsOverlay(scene); + if (debugExplainSurfaceStats) { + debugPrintSurfaceStats(scene, debugFrameNumber); + debugRepaintSurfaceStatsOverlay(scene); } assert(() { @@ -83,11 +94,11 @@ void commitScene(PersistedScene scene) { } frameReferences = >[]; - if (_debugExplainSurfaceStats) { - _surfaceStats = {}; + if (debugExplainSurfaceStats) { + surfaceStats = {}; } assert(() { - _debugFrameNumber++; + debugFrameNumber++; return true; }()); } @@ -361,8 +372,8 @@ abstract class PersistedSurface implements ui.EngineLayer { rootElement = createElement(); assert(rootElement != null); applyWebkitClipFix(rootElement); - if (_debugExplainSurfaceStats) { - _surfaceStatsFor(this).allocatedDomNodeCount++; + if (debugExplainSurfaceStats) { + surfaceStatsFor(this).allocatedDomNodeCount++; } apply(); state = PersistedSurfaceState.active; @@ -388,8 +399,8 @@ abstract class PersistedSurface implements ui.EngineLayer { return true; }()); rootElement = oldSurface.rootElement; - if (_debugExplainSurfaceStats) { - _surfaceStatsFor(this).reuseElementCount++; + if (debugExplainSurfaceStats) { + surfaceStatsFor(this).reuseElementCount++; } // We took ownership of the old element. @@ -434,13 +445,13 @@ abstract class PersistedSurface implements ui.EngineLayer { // it is set to active state. We do not set the state to active // immediately. Otherwise, another surface could match on it and steal // this surface's DOM elements. - _retainedSurfaces.add(this); + retainedSurfaces.add(this); } if (assertionsEnabled) { rootElement!.setAttribute('flt-layer-state', 'retained'); } - if (_debugExplainSurfaceStats) { - _surfaceStatsFor(this).retainSurfaceCount++; + if (debugExplainSurfaceStats) { + surfaceStatsFor(this).retainSurfaceCount++; } } @@ -514,6 +525,9 @@ abstract class PersistedSurface implements ui.EngineLayer { /// /// The value is update by [recomputeTransformAndClip]. Matrix4? get transform => _transform; + set transform(Matrix4? value) { + _transform = value; + } Matrix4? _transform; /// The intersection at this surface level. @@ -522,20 +536,16 @@ abstract class PersistedSurface implements ui.EngineLayer { /// the clip added by this layer (if any). /// /// The value is update by [recomputeTransformAndClip]. - ui.Rect? _projectedClip; + ui.Rect? projectedClip; /// Bounds of clipping performed by this layer. - ui.Rect? _localClipBounds; - // Cached inverse of transform on this node. Unlike transform, this - // Matrix only contains local transform (not chain multiplied since root). - Matrix4? _localTransformInverse; + ui.Rect? localClipBounds; /// The inverse of the local transform that this surface applies to its children. /// /// The default implementation is identity transform. Concrete /// implementations may override this getter to supply a different transform. - Matrix4? get localTransformInverse => - _localTransformInverse ??= Matrix4.identity(); + Matrix4? get localTransformInverse => null; /// Recomputes [transform] and [globalClip] fields. /// @@ -546,9 +556,8 @@ abstract class PersistedSurface implements ui.EngineLayer { /// This method is called by the [preroll] method. void recomputeTransformAndClip() { _transform = parent!._transform; - _localClipBounds = null; - _localTransformInverse = null; - _projectedClip = null; + localClipBounds = null; + projectedClip = null; } /// Performs computations before [build], [update], or [retain] are called. @@ -653,9 +662,8 @@ abstract class PersistedContainerSurface extends PersistedSurface { @override void recomputeTransformAndClip() { _transform = parent!._transform; - _localClipBounds = null; - _localTransformInverse = null; - _projectedClip = null; + localClipBounds = null; + projectedClip = null; } @override diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/surface_stats.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/surface_stats.dart index 056dfa71b7..e0360f4162 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/surface_stats.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/surface_stats.dart @@ -2,29 +2,37 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:async'; +import 'dart:html' as html; + +import 'package:ui/src/engine.dart' show EnginePlatformDispatcher; + +import 'bitmap_canvas.dart'; +import 'dom_canvas.dart'; +import 'picture.dart'; +import 'scene.dart'; +import 'surface.dart'; /// Surfaces that were retained this frame. /// /// Surfaces should be added to this list directly. Instead, if a surface needs /// to be retained call [_retainSurface]. -List get debugRetainedSurfaces => _retainedSurfaces; -List _retainedSurfaces = []; +List retainedSurfaces = []; /// Maps every surface currently active on the screen to debug statistics. -Map _surfaceStats = - {}; +Map surfaceStats = + {}; -List> _surfaceStatsTimeline = - >[]; +List> _surfaceStatsTimeline = + >[]; /// Returns debug statistics for the given [surface]. -_DebugSurfaceStats _surfaceStatsFor(PersistedSurface surface) { - if (!_debugExplainSurfaceStats) { +DebugSurfaceStats surfaceStatsFor(PersistedSurface surface) { + if (!debugExplainSurfaceStats) { throw Exception( - '_surfaceStatsFor is only available when _debugExplainSurfaceStats is set to true.'); + 'surfaceStatsFor is only available when debugExplainSurfaceStats is set to true.'); } - return _surfaceStats.putIfAbsent(surface, () => _DebugSurfaceStats(surface)); + return surfaceStats.putIfAbsent(surface, () => DebugSurfaceStats(surface)); } /// Compositor information collected for one frame useful for assessing the @@ -34,8 +42,8 @@ _DebugSurfaceStats _surfaceStatsFor(PersistedSurface surface) { /// /// For stats pertaining to a single surface the numeric counter fields are /// typically either 0 or 1. For aggregated stats, the numbers can be >1. -class _DebugSurfaceStats { - _DebugSurfaceStats(this.surface); +class DebugSurfaceStats { + DebugSurfaceStats(this.surface); /// The surface these stats are for, or `null` if these are aggregated stats. final PersistedSurface? surface; @@ -75,7 +83,7 @@ class _DebugSurfaceStats { int allocatedDomNodeCount = 0; /// Adds all counters of [oneSurfaceStats] into this object. - void aggregate(_DebugSurfaceStats oneSurfaceStats) { + void aggregate(DebugSurfaceStats oneSurfaceStats) { retainSurfaceCount += oneSurfaceStats.retainSurfaceCount; reuseElementCount += oneSurfaceStats.reuseElementCount; paintCount += oneSurfaceStats.paintCount; @@ -89,14 +97,14 @@ class _DebugSurfaceStats { html.CanvasRenderingContext2D? _debugSurfaceStatsOverlayCtx; -void _debugRepaintSurfaceStatsOverlay(PersistedScene scene) { +void debugRepaintSurfaceStatsOverlay(PersistedScene scene) { final int overlayWidth = html.window.innerWidth!; const int rowHeight = 30; const int rowCount = 4; const int overlayHeight = rowHeight * rowCount; const int strokeWidth = 2; - _surfaceStatsTimeline.add(_surfaceStats); + _surfaceStatsTimeline.add(surfaceStats); while (_surfaceStatsTimeline.length > (overlayWidth / strokeWidth)) { _surfaceStatsTimeline.removeAt(0); @@ -133,11 +141,11 @@ void _debugRepaintSurfaceStatsOverlay(PersistedScene scene) { final int totalDomNodeCount = scene.rootElement!.querySelectorAll('*').length; for (int i = 0; i < _surfaceStatsTimeline.length; i++) { - final Map statsMap = + final Map statsMap = _surfaceStatsTimeline[i]; - final _DebugSurfaceStats totals = _DebugSurfaceStats(null); + final DebugSurfaceStats totals = DebugSurfaceStats(null); int pixelCount = 0; - for (_DebugSurfaceStats oneSurfaceStats in statsMap.values) { + for (DebugSurfaceStats oneSurfaceStats in statsMap.values) { totals.aggregate(oneSurfaceStats); if (oneSurfaceStats.surface is PersistedPicture) { final PersistedPicture picture = oneSurfaceStats.surface as PersistedPicture; @@ -210,7 +218,7 @@ void _debugRepaintSurfaceStatsOverlay(PersistedScene scene) { } /// Prints debug statistics for the current frame to the console. -void _debugPrintSurfaceStats(PersistedScene scene, int frameNumber) { +void debugPrintSurfaceStats(PersistedScene scene, int frameNumber) { int pictureCount = 0; int paintCount = 0; @@ -229,7 +237,7 @@ void _debugPrintSurfaceStats(PersistedScene scene, int frameNumber) { int totalAllocatedDomNodeCount = 0; void countReusesRecursively(PersistedSurface surface) { - final _DebugSurfaceStats stats = _surfaceStatsFor(surface); + final DebugSurfaceStats stats = surfaceStatsFor(surface); assert(stats != null); // ignore: unnecessary_null_comparison surfaceRetainCount += stats.retainSurfaceCount; @@ -240,12 +248,12 @@ void _debugPrintSurfaceStats(PersistedScene scene, int frameNumber) { pictureCount += 1; paintCount += stats.paintCount; - if (surface._canvas is DomCanvas) { + if (surface.canvas is DomCanvas) { domCanvasCount++; domPaintCount += stats.paintCount; } - if (surface._canvas is BitmapCanvas) { + if (surface.canvas is BitmapCanvas) { bitmapCanvasCount++; bitmapPaintCount += stats.paintCount; } @@ -279,7 +287,7 @@ void _debugPrintSurfaceStats(PersistedScene scene, int frameNumber) { ..writeln(' Reused: $bitmapReuseCount') ..writeln(' Allocated: $bitmapAllocationCount') ..writeln(' Allocated pixels: $bitmapPixelsAllocated') - ..writeln(' Available for reuse: ${_recycledCanvases.length}'); + ..writeln(' Available for reuse: ${recycledCanvases.length}'); // A microtask will fire after the DOM is flushed, letting us probe into // actual tags. @@ -311,7 +319,7 @@ void _debugPrintSurfaceStats(PersistedScene scene, int frameNumber) { ..writeln(' Pixels: $canvasPixelDescription; $screenDescription)') ..writeln('-----------------------------------------------------------'); final bool screenPixelRatioTooHigh = - screenPixelRatio > _kScreenPixelRatioWarningThreshold; + screenPixelRatio > kScreenPixelRatioWarningThreshold; if (screenPixelRatioTooHigh) { print( 'WARNING: pixel/screen ratio too high (${screenPixelRatio.toStringAsFixed(2)}x)'); diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html/transform.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html/transform.dart index 25e96a41a6..255ba62d2b 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html/transform.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html/transform.dart @@ -2,27 +2,42 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; +import 'dart:typed_data'; + +import 'package:ui/src/engine.dart' show domRenderer, DomRenderer; +import 'package:ui/ui.dart' as ui; + +import '../util.dart'; +import '../vector_math.dart'; +import 'surface.dart'; /// A surface that transforms its children using CSS transform. class PersistedTransform extends PersistedContainerSurface implements ui.TransformEngineLayer { - PersistedTransform(PersistedTransform? oldLayer, this.matrix4) + PersistedTransform(PersistedTransform? oldLayer, this._matrixStorage) : super(oldLayer); - final Float32List matrix4; + /// The storage representing the transform of this surface. + final Float32List _matrixStorage; + + /// The matrix representing the transform of this surface. + Matrix4 get matrix4 => _matrix4 ??= Matrix4.fromFloat32List(_matrixStorage); + Matrix4? _matrix4; @override void recomputeTransformAndClip() { - _transform = parent!._transform!.multiplied(Matrix4.fromFloat32List(matrix4)); - _localTransformInverse = null; - _projectedClip = null; + transform = parent!.transform!.multiplied(matrix4); + projectedClip = null; } + /// Cached inverse of transform on this node. Unlike [transform], this + /// Matrix only contains local transform (not chain multiplied since root). + Matrix4? _localTransformInverse; + @override Matrix4? get localTransformInverse { - _localTransformInverse ??= - Matrix4.tryInvert(Matrix4.fromFloat32List(matrix4)); + _localTransformInverse ??= Matrix4.tryInvert(matrix4); return _localTransformInverse; } @@ -36,20 +51,24 @@ class PersistedTransform extends PersistedContainerSurface @override void apply() { - rootElement!.style.transform = float64ListToCssTransform(matrix4); + rootElement!.style.transform = float64ListToCssTransform(_matrixStorage); } @override void update(PersistedTransform oldSurface) { super.update(oldSurface); - if (identical(oldSurface.matrix4, matrix4)) { + if (identical(oldSurface._matrixStorage, _matrixStorage)) { + // The matrix storage is identical, so we can copy the matrices from the + // old surface to avoid recomputing them. + _matrix4 = oldSurface._matrix4; + _localTransformInverse = oldSurface._localTransformInverse; return; } bool matrixChanged = false; - for (int i = 0; i < matrix4.length; i++) { - if (matrix4[i] != oldSurface.matrix4[i]) { + for (int i = 0; i < _matrixStorage.length; i++) { + if (_matrixStorage[i] != oldSurface._matrixStorage[i]) { matrixChanged = true; break; } @@ -57,6 +76,11 @@ class PersistedTransform extends PersistedContainerSurface if (matrixChanged) { apply(); + } else { + // The matrix storage hasn't changed, so we can copy the matrices from the + // old surface to avoid recomputing them. + _matrix4 = oldSurface._matrix4; + _localTransformInverse = oldSurface._localTransformInverse; } } } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/onscreen_logging.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/onscreen_logging.dart index e0a7058345..0087080c69 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/onscreen_logging.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/onscreen_logging.dart @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; html.Element? _logElement; late html.Element _logContainer; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/picture.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/picture.dart index d7d52b1947..889862b402 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/picture.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/picture.dart @@ -2,7 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:async'; +import 'dart:html' as html; + +import 'package:ui/ui.dart' as ui; + +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 { diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/rrect_renderer.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/rrect_renderer.dart index e8c2543795..386753e509 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/rrect_renderer.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/rrect_renderer.dart @@ -2,10 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of engine; +import 'dart:html' as html; +import 'dart:math' as math; + +import 'package:ui/src/engine.dart' show DomRenderer; +import 'package:ui/ui.dart' as ui; /// Renders an RRect using path primitives. -abstract class _RRectRenderer { +abstract class RRectRenderer { // To draw the rounded rectangle, perform the following steps: // 0. Ensure border radius don't overlap // 1. Flip left,right top,bottom since web doesn't support flipped @@ -177,9 +181,9 @@ abstract class _RRectRenderer { } /// Renders RRect to a 2d canvas. -class _RRectToCanvasRenderer extends _RRectRenderer { +class RRectToCanvasRenderer extends RRectRenderer { final html.CanvasRenderingContext2D context; - _RRectToCanvasRenderer(this.context); + RRectToCanvasRenderer(this.context); void beginPath() { context.beginPath(); } @@ -200,9 +204,9 @@ class _RRectToCanvasRenderer extends _RRectRenderer { } /// Renders RRect to a path. -class _RRectToPathRenderer extends _RRectRenderer { +class RRectToPathRenderer extends RRectRenderer { final ui.Path path; - _RRectToPathRenderer(this.path); + RRectToPathRenderer(this.path); void beginPath() {} void moveTo(double x, double y) { path.moveTo(x, y); @@ -226,7 +230,7 @@ typedef RRectRendererEllipseCallback = void Function(double centerX, double cent typedef RRectRendererCallback = void Function(double x, double y); /// Converts RRect to path primitives with callbacks. -class RRectMetricsRenderer extends _RRectRenderer { +class RRectMetricsRenderer extends RRectRenderer { RRectMetricsRenderer({this.moveToCallback, this.lineToCallback, this.ellipseCallback}); final RRectRendererEllipseCallback? ellipseCallback; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/text/paragraph.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/text/paragraph.dart index 70be159e07..6479ee80be 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/text/paragraph.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/paragraph.dart @@ -7,9 +7,11 @@ import 'dart:js_util' as js_util; import 'dart:math' as math; import 'package:ui/ui.dart' as ui; -import 'package:ui/src/engine.dart' show assertionsEnabled, BitmapCanvas, colorToCssString, canonicalizeFontFamily, domRenderer, DomRenderer, SurfacePaint; +import 'package:ui/src/engine.dart' show domRenderer, DomRenderer; import '../browser_detection.dart'; +import '../html/bitmap_canvas.dart'; +import '../html/painting.dart'; import '../profiler.dart'; import '../util.dart'; import 'canvas_paragraph.dart'; diff --git a/engine/src/flutter/lib/web_ui/test/engine/surface/scene_builder_test.dart b/engine/src/flutter/lib/web_ui/test/engine/surface/scene_builder_test.dart index 01c55cf863..da97b161a7 100644 --- a/engine/src/flutter/lib/web_ui/test/engine/surface/scene_builder_test.dart +++ b/engine/src/flutter/lib/web_ui/test/engine/surface/scene_builder_test.dart @@ -321,7 +321,7 @@ void testMain() { builder.pop(); html.Element content = builder.build().webOnlyRootElement!; expect(content.querySelectorAll('flt-picture').single.children, isEmpty); - expect(findPictureSurfaceChild(clip)!.debugCanvas, isNull); + expect(findPictureSurfaceChild(clip)!.canvas, isNull); } }); @@ -394,7 +394,7 @@ void testMain() { builder1.pop(); html.Element content1 = builder1.build().webOnlyRootElement!; expect(content1.querySelectorAll('flt-picture').single.children, isNotEmpty); - expect(findPictureSurfaceChild(offset1)!.debugCanvas, isNotNull); + expect(findPictureSurfaceChild(offset1)!.canvas, isNotNull); // Frame 2: picture is clipped out after an update final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder(); @@ -403,7 +403,7 @@ void testMain() { builder2.pop(); html.Element content = builder2.build().webOnlyRootElement!; expect(content.querySelectorAll('flt-picture').single.children, isEmpty); - expect(findPictureSurfaceChild(offset2)!.debugCanvas, isNull); + expect(findPictureSurfaceChild(offset2)!.canvas, isNull); }); test('releases old canvas when picture is fully clipped out after addRetained', () async { @@ -418,7 +418,7 @@ void testMain() { builder1.pop(); html.Element content1 = builder1.build().webOnlyRootElement!; expect(content1.querySelectorAll('flt-picture').single.children, isNotEmpty); - expect(findPictureSurfaceChild(subOffset1)!.debugCanvas, isNotNull); + expect(findPictureSurfaceChild(subOffset1)!.canvas, isNotNull); // Frame 2: picture is clipped out after addRetained final SurfaceSceneBuilder builder2 = SurfaceSceneBuilder(); @@ -431,7 +431,7 @@ void testMain() { builder2.pop(); html.Element content = builder2.build().webOnlyRootElement!; expect(content.querySelectorAll('flt-picture').single.children, isEmpty); - expect(findPictureSurfaceChild(subOffset1)!.debugCanvas, isNull); + expect(findPictureSurfaceChild(subOffset1)!.canvas, isNull); }); test('auto-pops pushed layers', () async { @@ -752,7 +752,7 @@ void testLayerLifeCycle( expect(surface3.rootElement, isNotNull); // offset3 should be rehydrated. // Make sure we clear retained surface list. - expect(debugRetainedSurfaces, isEmpty); + expect(retainedSurfaces, isEmpty); } class MockPersistedPicture extends PersistedPicture { @@ -774,7 +774,7 @@ class MockPersistedPicture extends PersistedPicture { final BitmapCanvas _fakeCanvas = BitmapCanvas(const ui.Rect.fromLTRB(0, 0, 10, 10), RenderStrategy()); @override - EngineCanvas get debugCanvas { + EngineCanvas get canvas { return _fakeCanvas; }