[web] Actual removal of HTML code (#164003)

All usages of this code have been cleaned up. There's nothing using this
code at this point.

Closes https://github.com/flutter/flutter/issues/145954
This commit is contained in:
Mouad Debbar
2025-02-24 14:32:13 -05:00
committed by GitHub
parent a488d104f2
commit 6b5b468a60
89 changed files with 18 additions and 41492 deletions

View File

@@ -42587,7 +42587,6 @@ ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine.dart + ../../../flutter/LICEN
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/alarm_clock.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/app_bootstrap.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/browser_detection.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/canvas_pool.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/canvas.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/canvaskit_api.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/canvaskit_canvas.dart + ../../../flutter/LICENSE
@@ -42630,7 +42629,6 @@ ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/color_filter.dart + ../../../
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/configuration.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/display.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/dom.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/engine_canvas.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/font_change_util.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/font_fallback_data.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/font_fallbacks.dart + ../../../flutter/LICENSE
@@ -42638,47 +42636,6 @@ ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/fonts.dart + ../../../flutter
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/frame_service.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/frame_timing_recorder.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/high_contrast.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/backdrop_filter.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/bitmap_canvas.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/canvas.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/clip.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/color_filter.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/debug_canvas_reuse_overlay.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/dom_canvas.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/frame_reference.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/image.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/image_filter.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/offset.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/opacity.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/painting.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/path/conic.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/path/cubic.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_iterator.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_metrics.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_ref.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_to_svg.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_utils.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_windings.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/path/tangent.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/path_to_svg_clip.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/picture.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/platform_view.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/recording_canvas.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/render_vertices.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/renderer.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/resource_manager.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/scene.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/scene_builder.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/shader_mask.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/image_shader.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/normalized_gradient.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/shader.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/shader_builder.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/vertex_shaders.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/surface.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/surface_stats.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html/transform.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/html_image_element_codec.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/image_decoder.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/image_format_detector.dart + ../../../flutter/LICENSE
@@ -42785,21 +42742,8 @@ ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/skwasm/skwasm_stub.dart + ../
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/skwasm/skwasm_stub/renderer.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/svg.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/test_embedding.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/canvas_paragraph.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/font_collection.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/fragmenter.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/layout_fragmenter.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/layout_service.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/line_break_properties.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/line_breaker.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/measurement.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/paint_service.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/paragraph.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/ruler.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/text_direction.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/unicode_range.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/word_break_properties.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text/word_breaker.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text_editing/autofill_hint.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text_editing/composition_aware_mixin.dart + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/lib/web_ui/lib/src/engine/text_editing/input_action.dart + ../../../flutter/LICENSE
@@ -45559,7 +45503,6 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/alarm_clock.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/app_bootstrap.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/browser_detection.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvas_pool.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/canvas.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/canvaskit_api.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/canvaskit/canvaskit_canvas.dart
@@ -45602,7 +45545,6 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/color_filter.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/configuration.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/display.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/dom.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/engine_canvas.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/font_change_util.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/font_fallback_data.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/font_fallbacks.dart
@@ -45610,47 +45552,6 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/fonts.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/frame_service.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/frame_timing_recorder.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/high_contrast.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/backdrop_filter.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/bitmap_canvas.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/canvas.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/clip.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/color_filter.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/debug_canvas_reuse_overlay.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/dom_canvas.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/frame_reference.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/image.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/image_filter.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/offset.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/opacity.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/painting.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/path/conic.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/path/cubic.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_iterator.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_metrics.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_ref.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_to_svg.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_utils.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/path/path_windings.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/path/tangent.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/path_to_svg_clip.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/picture.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/platform_view.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/recording_canvas.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/render_vertices.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/renderer.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/resource_manager.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/scene.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/scene_builder.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/shader_mask.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/image_shader.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/normalized_gradient.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/shader.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/shader_builder.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/shaders/vertex_shaders.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/surface.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/surface_stats.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html/transform.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/html_image_element_codec.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/image_decoder.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/image_format_detector.dart
@@ -45757,21 +45658,8 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/skwasm/skwasm_stub.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/skwasm/skwasm_stub/renderer.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/svg.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/test_embedding.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/canvas_paragraph.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/font_collection.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/fragmenter.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/layout_fragmenter.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/layout_service.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/line_break_properties.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/line_breaker.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/measurement.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/paint_service.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/paragraph.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/ruler.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/text_direction.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/unicode_range.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/word_break_properties.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/word_breaker.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text_editing/autofill_hint.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text_editing/composition_aware_mixin.dart
FILE: ../../../flutter/lib/web_ui/lib/src/engine/text_editing/input_action.dart

View File

@@ -18,7 +18,6 @@ library engine;
export 'engine/alarm_clock.dart';
export 'engine/app_bootstrap.dart';
export 'engine/browser_detection.dart';
export 'engine/canvas_pool.dart';
export 'engine/canvaskit/canvas.dart';
export 'engine/canvaskit/canvaskit_api.dart';
export 'engine/canvaskit/canvaskit_canvas.dart';
@@ -60,7 +59,6 @@ export 'engine/color_filter.dart';
export 'engine/configuration.dart';
export 'engine/display.dart';
export 'engine/dom.dart';
export 'engine/engine_canvas.dart';
export 'engine/font_change_util.dart';
export 'engine/font_fallback_data.dart';
export 'engine/font_fallbacks.dart';
@@ -68,47 +66,6 @@ export 'engine/fonts.dart';
export 'engine/frame_service.dart';
export 'engine/frame_timing_recorder.dart';
export 'engine/high_contrast.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/frame_reference.dart';
export 'engine/html/image.dart';
export 'engine/html/image_filter.dart';
export 'engine/html/offset.dart';
export 'engine/html/opacity.dart';
export 'engine/html/painting.dart';
export 'engine/html/path/conic.dart';
export 'engine/html/path/cubic.dart';
export 'engine/html/path/path.dart';
export 'engine/html/path/path_iterator.dart';
export 'engine/html/path/path_metrics.dart';
export 'engine/html/path/path_ref.dart';
export 'engine/html/path/path_to_svg.dart';
export 'engine/html/path/path_utils.dart';
export 'engine/html/path/path_windings.dart';
export 'engine/html/path/tangent.dart';
export 'engine/html/path_to_svg_clip.dart';
export 'engine/html/picture.dart';
export 'engine/html/platform_view.dart';
export 'engine/html/recording_canvas.dart';
export 'engine/html/render_vertices.dart';
export 'engine/html/renderer.dart';
export 'engine/html/resource_manager.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';
export 'engine/html/shaders/shader.dart';
export 'engine/html/shaders/shader_builder.dart';
export 'engine/html/shaders/vertex_shaders.dart';
export 'engine/html/surface.dart';
export 'engine/html/surface_stats.dart';
export 'engine/html/transform.dart';
export 'engine/html_image_element_codec.dart';
export 'engine/image_decoder.dart';
export 'engine/image_format_detector.dart';
@@ -173,21 +130,8 @@ export 'engine/shader_data.dart';
export 'engine/shadow.dart';
export 'engine/svg.dart';
export 'engine/test_embedding.dart';
export 'engine/text/canvas_paragraph.dart';
export 'engine/text/font_collection.dart';
export 'engine/text/fragmenter.dart';
export 'engine/text/layout_fragmenter.dart';
export 'engine/text/layout_service.dart';
export 'engine/text/line_break_properties.dart';
export 'engine/text/line_breaker.dart';
export 'engine/text/measurement.dart';
export 'engine/text/paint_service.dart';
export 'engine/text/paragraph.dart';
export 'engine/text/ruler.dart';
export 'engine/text/text_direction.dart';
export 'engine/text/unicode_range.dart';
export 'engine/text/word_break_properties.dart';
export 'engine/text/word_breaker.dart';
export 'engine/text_editing/autofill_hint.dart';
export 'engine/text_editing/composition_aware_mixin.dart';
export 'engine/text_editing/input_action.dart';

File diff suppressed because it is too large Load Diff

View File

@@ -8,7 +8,6 @@ import 'package:ui/ui.dart' as ui;
import '../../engine.dart' show PlatformViewManager, configuration, longestIncreasingSubsequence;
import '../display.dart';
import '../dom.dart';
import '../html/path_to_svg_clip.dart';
import '../platform_views/slots.dart';
import '../svg.dart';
import '../util.dart';
@@ -22,6 +21,16 @@ import 'picture.dart';
import 'picture_recorder.dart';
import 'rasterizer.dart';
/// Used for clipping and filter svg resources.
///
/// Position needs to be absolute since these svgs are sandwiched between
/// canvas elements and can cause layout shifts otherwise.
final SVGSVGElement kSvgResourceHeader =
createSVGSVGElement()
..setAttribute('width', 0)
..setAttribute('height', 0)
..style.position = 'absolute';
/// This composites HTML views into the [ui.Scene].
class HtmlViewEmbedder {
HtmlViewEmbedder(this.sceneHost, this.rasterizer);

View File

@@ -1,386 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// For member documentation see https://api.flutter.dev/flutter/dart-ui/Canvas-class.html
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'dom.dart';
import 'html/painting.dart';
import 'html/render_vertices.dart';
import 'text/canvas_paragraph.dart';
import 'util.dart';
import 'vector_math.dart';
/// Defines canvas interface common across canvases that the [SceneBuilder]
/// renders to.
///
/// This can be used either as an interface or super-class.
abstract class EngineCanvas {
/// The element that is attached to the DOM.
DomElement get rootElement;
void dispose() {
clear();
}
void clear();
void save();
void restore();
void translate(double dx, double dy);
void scale(double sx, double sy);
void rotate(double radians);
void skew(double sx, double sy);
void transform(Float32List matrix4);
void clipRect(ui.Rect rect, ui.ClipOp clipOp);
void clipRRect(ui.RRect rrect);
void clipRSuperellipse(ui.RSuperellipse rse);
void clipPath(ui.Path path);
void drawColor(ui.Color color, ui.BlendMode blendMode);
void drawLine(ui.Offset p1, ui.Offset p2, SurfacePaintData paint);
void drawPaint(SurfacePaintData paint);
void drawRect(ui.Rect rect, SurfacePaintData paint);
void drawRRect(ui.RRect rrect, SurfacePaintData paint);
void drawDRRect(ui.RRect outer, ui.RRect inner, SurfacePaintData paint);
void drawOval(ui.Rect rect, SurfacePaintData paint);
void drawCircle(ui.Offset c, double radius, SurfacePaintData paint);
void drawPath(ui.Path path, SurfacePaintData paint);
void drawShadow(ui.Path path, ui.Color color, double elevation, bool transparentOccluder);
void drawImage(ui.Image image, ui.Offset p, SurfacePaintData paint);
void drawImageRect(ui.Image image, ui.Rect src, ui.Rect dst, SurfacePaintData paint);
void drawParagraph(CanvasParagraph paragraph, ui.Offset offset);
void drawVertices(SurfaceVertices vertices, ui.BlendMode blendMode, SurfacePaintData paint);
void drawPoints(ui.PointMode pointMode, Float32List points, SurfacePaintData paint);
/// Extension of Canvas API to mark the end of a stream of painting commands
/// to enable re-use/dispose optimizations.
void endOfPaint();
}
/// Adds an [offset] transformation to a [transform] matrix and returns the
/// combined result.
///
/// If the given offset is zero, returns [transform] matrix as is. Otherwise,
/// returns a new [Matrix4] object representing the combined transformation.
Matrix4 transformWithOffset(Matrix4 transform, ui.Offset offset) {
if (offset == ui.Offset.zero) {
return transform;
}
// Clone to avoid mutating transform.
final Matrix4 effectiveTransform = transform.clone();
effectiveTransform.translate(offset.dx, offset.dy);
return effectiveTransform;
}
class SaveStackEntry {
SaveStackEntry({required this.transform, required this.clipStack});
final Matrix4 transform;
final List<SaveClipEntry>? clipStack;
}
/// Tagged union of clipping parameters used for canvas.
class SaveClipEntry {
SaveClipEntry.rect(this.rect, this.currentTransform) : rrect = null, path = null;
SaveClipEntry.rrect(this.rrect, this.currentTransform) : rect = null, path = null;
SaveClipEntry.path(this.path, this.currentTransform) : rect = null, rrect = null;
final ui.Rect? rect;
final ui.RRect? rrect;
final ui.Path? path;
final Matrix4 currentTransform;
}
/// Provides save stack tracking functionality to implementations of
/// [EngineCanvas].
mixin SaveStackTracking on EngineCanvas {
final List<SaveStackEntry> _saveStack = <SaveStackEntry>[];
/// The stack that maintains clipping operations used when text is painted
/// onto bitmap canvas but is composited as separate element.
List<SaveClipEntry>? _clipStack;
/// Returns whether there are active clipping regions on the canvas.
bool get isClipped => _clipStack != null;
/// Empties the save stack and the element stack, and resets the transform
/// and clip parameters.
///
/// Classes that override this method must call `super.clear()`.
@override
void clear() {
_saveStack.clear();
_clipStack = null;
_currentTransform = Matrix4.identity();
}
/// The current transformation matrix.
Matrix4 get currentTransform => _currentTransform;
Matrix4 _currentTransform = Matrix4.identity();
/// Saves current clip and transform on the save stack.
///
/// Classes that override this method must call `super.save()`.
@override
void save() {
_saveStack.add(
SaveStackEntry(
transform: _currentTransform.clone(),
clipStack: _clipStack == null ? null : List<SaveClipEntry>.from(_clipStack!),
),
);
}
/// Restores current clip and transform from the save stack.
///
/// Classes that override this method must call `super.restore()`.
@override
void restore() {
if (_saveStack.isEmpty) {
return;
}
final SaveStackEntry entry = _saveStack.removeLast();
_currentTransform = entry.transform;
_clipStack = entry.clipStack;
}
/// Multiplies the [currentTransform] matrix by a translation.
///
/// Classes that override this method must call `super.translate()`.
@override
void translate(double dx, double dy) {
_currentTransform.translate(dx, dy);
}
/// Scales the [currentTransform] matrix.
///
/// Classes that override this method must call `super.scale()`.
@override
void scale(double sx, double sy) {
_currentTransform.scale(sx, sy);
}
/// Rotates the [currentTransform] matrix.
///
/// Classes that override this method must call `super.rotate()`.
@override
void rotate(double radians) {
_currentTransform.rotate(kUnitZ, radians);
}
/// Skews the [currentTransform] matrix.
///
/// Classes that override this method must call `super.skew()`.
@override
void skew(double sx, double sy) {
final Matrix4 skewMatrix = Matrix4.identity();
final Float32List storage = skewMatrix.storage;
storage[1] = sy;
storage[4] = sx;
_currentTransform.multiply(skewMatrix);
}
/// Multiplies the [currentTransform] matrix by another matrix.
///
/// Classes that override this method must call `super.transform()`.
@override
void transform(Float32List matrix4) {
_currentTransform.multiply(Matrix4.fromFloat32List(matrix4));
}
/// Adds a rectangle to clipping stack.
///
/// 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()));
}
/// Adds a round rectangle to clipping stack.
///
/// Classes that override this method must call `super.clipRRect()`.
@override
void clipRRect(ui.RRect rrect) {
_clipStack ??= <SaveClipEntry>[];
_clipStack!.add(SaveClipEntry.rrect(rrect, _currentTransform.clone()));
}
/// Adds a round superellipse to clipping stack.
///
/// Classes that override this method must call `super.clipRSuperellipse()`.
@override
void clipRSuperellipse(ui.RSuperellipse rse) {
_clipStack ??= <SaveClipEntry>[];
// TODO(dkwingsmt): Properly implement clipRSE on Web instead of falling
// back to RRect. https://github.com/flutter/flutter/issues/163718
_clipStack!.add(SaveClipEntry.rrect(rse.toApproximateRRect(), _currentTransform.clone()));
}
/// Adds a path to clipping stack.
///
/// Classes that override this method must call `super.clipPath()`.
@override
void clipPath(ui.Path path) {
_clipStack ??= <SaveClipEntry>[];
_clipStack!.add(SaveClipEntry.path(path, _currentTransform.clone()));
}
}
DomElement drawParagraphElement(CanvasParagraph paragraph, ui.Offset offset, {Matrix4? transform}) {
assert(paragraph.isLaidOut);
final DomElement paragraphElement = paragraph.toDomElement();
if (transform != null) {
setElementTransform(paragraphElement, transformWithOffset(transform, offset).storage);
}
return paragraphElement;
}
class _SaveElementStackEntry {
_SaveElementStackEntry({required this.savedElement, required this.transform});
final DomElement savedElement;
final Matrix4 transform;
}
/// Provides save stack tracking functionality to implementations of
/// [EngineCanvas].
mixin SaveElementStackTracking on EngineCanvas {
final List<_SaveElementStackEntry> _saveStack = <_SaveElementStackEntry>[];
/// The element at the top of the element stack, or [rootElement] if the stack
/// is empty.
DomElement get currentElement => _elementStack.isEmpty ? rootElement : _elementStack.last;
/// The stack that maintains the DOM elements used to express certain paint
/// operations, such as clips.
final List<DomElement> _elementStack = <DomElement>[];
/// Pushes the [element] onto the element stack for the purposes of applying
/// a paint effect using a DOM element, e.g. for clipping.
///
/// The [restore] method automatically pops the element off the stack.
void pushElement(DomElement element) {
_elementStack.add(element);
}
/// Empties the save stack and the element stack, and resets the transform
/// and clip parameters.
///
/// Classes that override this method must call `super.clear()`.
@override
void clear() {
_saveStack.clear();
_elementStack.clear();
_currentTransform = Matrix4.identity();
}
/// The current transformation matrix.
Matrix4 get currentTransform => _currentTransform;
Matrix4 _currentTransform = Matrix4.identity();
/// Saves current clip and transform on the save stack.
///
/// Classes that override this method must call `super.save()`.
@override
void save() {
_saveStack.add(
_SaveElementStackEntry(savedElement: currentElement, transform: _currentTransform.clone()),
);
}
/// Restores current clip and transform from the save stack.
///
/// Classes that override this method must call `super.restore()`.
@override
void restore() {
if (_saveStack.isEmpty) {
return;
}
final _SaveElementStackEntry entry = _saveStack.removeLast();
_currentTransform = entry.transform;
// Pop out of any clips.
while (currentElement != entry.savedElement) {
_elementStack.removeLast();
}
}
/// Multiplies the [currentTransform] matrix by a translation.
///
/// Classes that override this method must call `super.translate()`.
@override
void translate(double dx, double dy) {
_currentTransform.translate(dx, dy);
}
/// Scales the [currentTransform] matrix.
///
/// Classes that override this method must call `super.scale()`.
@override
void scale(double sx, double sy) {
_currentTransform.scale(sx, sy);
}
/// Rotates the [currentTransform] matrix.
///
/// Classes that override this method must call `super.rotate()`.
@override
void rotate(double radians) {
_currentTransform.rotate(kUnitZ, radians);
}
/// Skews the [currentTransform] matrix.
///
/// Classes that override this method must call `super.skew()`.
@override
void skew(double sx, double sy) {
// DO NOT USE Matrix4.skew(sx, sy)! It treats sx and sy values as radians,
// but in our case they are transform matrix values.
final Matrix4 skewMatrix = Matrix4.identity();
final Float32List storage = skewMatrix.storage;
storage[1] = sy;
storage[4] = sx;
_currentTransform.multiply(skewMatrix);
}
/// Multiplies the [currentTransform] matrix by another matrix.
///
/// Classes that override this method must call `super.transform()`.
@override
void transform(Float32List matrix4) {
_currentTransform.multiply(Matrix4.fromFloat32List(matrix4));
}
}

View File

@@ -1,189 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../color_filter.dart';
import '../dom.dart';
import '../util.dart';
import '../vector_math.dart';
import 'resource_manager.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
implements ui.BackdropFilterEngineLayer {
PersistedBackdropFilter(PersistedBackdropFilter? super.oldLayer, this.filter);
final ui.ImageFilter filter;
/// The dedicated child container element that's separate from the
/// [rootElement] is used to host child in front of [filterElement] that
/// is transformed to cover background.
@override
DomElement? get childContainer => _childContainer;
DomElement? _childContainer;
DomElement? _filterElement;
DomElement? _svgFilter;
ui.Rect? _activeClipBounds;
// Cached inverted transform for [transform].
late Matrix4 _invertedTransform;
// Reference to transform last used to cache [_invertedTransform].
Matrix4? _previousTransform;
@override
void adoptElements(PersistedBackdropFilter oldSurface) {
super.adoptElements(oldSurface);
_childContainer = oldSurface._childContainer;
_filterElement = oldSurface._filterElement;
_svgFilter = oldSurface._svgFilter;
oldSurface._childContainer = null;
}
@override
DomElement createElement() {
final DomElement element = defaultCreateElement('flt-backdrop');
element.style.transformOrigin = '0 0 0';
_childContainer = createDomElement('flt-backdrop-interior');
_childContainer!.style.position = 'absolute';
if (debugExplainSurfaceStats) {
// This creates an additional interior element. Count it too.
surfaceStatsFor(this).allocatedDomNodeCount++;
}
_filterElement = defaultCreateElement('flt-backdrop-filter');
_filterElement!.style.transformOrigin = '0 0 0';
element
..append(_filterElement!)
..append(_childContainer!);
return element;
}
@override
void discard() {
super.discard();
// Do not detach the child container from the root. It is permanently
// attached. The elements are reused together and are detached from the DOM
// together.
ResourceManager.instance.removeResource(_svgFilter);
_svgFilter = null;
_childContainer = null;
_filterElement = null;
}
@override
void apply() {
EngineImageFilter backendFilter;
if (filter is ui.ColorFilter) {
backendFilter = createHtmlColorFilter(filter as EngineColorFilter)!;
} else {
backendFilter = filter as EngineImageFilter;
}
ResourceManager.instance.removeResource(_svgFilter);
_svgFilter = null;
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
// available, the whole screen.
//
// The CSS backdrop-filter will use isolation boundary defined in
// https://drafts.fxtf.org/filter-effects-2/#BackdropFilterProperty
// Therefore we need to use parent clip element bounds for
// backdrop boundary.
final double dpr = ui.window.devicePixelRatio;
final ui.Rect rect = _invertedTransform.transformRect(
ui.Rect.fromLTRB(
0,
0,
ui.window.physicalSize.width * dpr,
ui.window.physicalSize.height * dpr,
),
);
double left = rect.left;
double top = rect.top;
double width = rect.width;
double height = rect.height;
PersistedContainerSurface? parentSurface = parent;
while (parentSurface != null) {
if (parentSurface.isClipping) {
final ui.Rect activeClipBounds = (_activeClipBounds = parentSurface.localClipBounds)!;
left = activeClipBounds.left;
top = activeClipBounds.top;
width = activeClipBounds.width;
height = activeClipBounds.height;
break;
}
parentSurface = parentSurface.parent;
}
final DomCSSStyleDeclaration filterElementStyle = _filterElement!.style;
filterElementStyle
..position = 'absolute'
..left = '${left}px'
..top = '${top}px'
..width = '${width}px'
..height = '${height}px';
if (ui_web.browser.browserEngine == ui_web.BrowserEngine.firefox) {
// For FireFox for now render transparent black background.
// TODO(ferhat): Switch code to use filter when
// See https://caniuse.com/#feat=css-backdrop-filter.
filterElementStyle
..backgroundColor = '#000'
..opacity = '0.2';
} else {
if (backendFilter is ModeHtmlColorFilter) {
_svgFilter = backendFilter.makeSvgFilter(_filterElement);
/// Some blendModes do not make an svgFilter. See [EngineHtmlColorFilter.makeSvgFilter()]
if (_svgFilter == null) {
return;
}
} else if (backendFilter is MatrixHtmlColorFilter) {
_svgFilter = backendFilter.makeSvgFilter(_filterElement);
}
// CSS uses pixel radius for blur. Flutter & SVG use sigma parameters. For
// Gaussian blur with standard deviation (normal distribution),
// the blur will fall within 2 * sigma pixels.
if (ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit) {
setElementStyle(_filterElement!, '-webkit-backdrop-filter', backendFilter.filterAttribute);
}
setElementStyle(_filterElement!, 'backdrop-filter', backendFilter.filterAttribute);
}
}
@override
void update(PersistedBackdropFilter oldSurface) {
super.update(oldSurface);
if (filter != oldSurface.filter) {
apply();
} else {
_checkForUpdatedAncestorClipElement();
}
}
void _checkForUpdatedAncestorClipElement() {
// If parent clip element has moved, adjust bounds.
PersistedContainerSurface? parentSurface = parent;
while (parentSurface != null) {
if (parentSurface.isClipping) {
if (parentSurface.localClipBounds != _activeClipBounds) {
apply();
}
break;
}
parentSurface = parentSurface.parent;
}
}
@override
void retain() {
super.retain();
_checkForUpdatedAncestorClipElement();
}
}

View File

@@ -1,503 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../util.dart';
import '../validators.dart';
import '../vector_math.dart';
import 'painting.dart';
import 'picture.dart';
import 'recording_canvas.dart';
import 'render_vertices.dart';
class SurfaceCanvas implements ui.Canvas {
factory SurfaceCanvas(EnginePictureRecorder recorder, [ui.Rect? cullRect]) {
if (recorder.isRecording) {
throw ArgumentError('"recorder" must not already be associated with another Canvas.');
}
cullRect ??= ui.Rect.largest;
return SurfaceCanvas._(recorder.beginRecording(cullRect));
}
SurfaceCanvas._(this._canvas);
RecordingCanvas _canvas;
@override
void save() {
_canvas.save();
}
@override
void saveLayer(ui.Rect? bounds, ui.Paint paint) {
if (bounds == null) {
_saveLayerWithoutBounds(paint);
} else {
assert(rectIsValid(bounds));
_saveLayer(bounds, paint);
}
}
void _saveLayerWithoutBounds(ui.Paint paint) {
_canvas.saveLayerWithoutBounds(paint as SurfacePaint);
}
void _saveLayer(ui.Rect bounds, ui.Paint paint) {
_canvas.saveLayer(bounds, paint as SurfacePaint);
}
@override
void restore() {
_canvas.restore();
}
@override
void restoreToCount(int count) {
_canvas.restoreToCount(count);
}
@override
int getSaveCount() => _canvas.saveCount;
@override
void translate(double dx, double dy) {
_canvas.translate(dx, dy);
}
@override
void scale(double sx, [double? sy]) => _scale(sx, sy ?? sx);
void _scale(double sx, double sy) {
_canvas.scale(sx, sy);
}
@override
void rotate(double radians) {
_canvas.rotate(radians);
}
@override
void skew(double sx, double sy) {
_canvas.skew(sx, sy);
}
@override
void transform(Float64List matrix4) {
if (matrix4.length != 16) {
throw ArgumentError('"matrix4" must have 16 entries.');
}
_transform(toMatrix32(matrix4));
}
void _transform(Float32List matrix4) {
_canvas.transform(matrix4);
}
@override
Float64List getTransform() {
return Float64List.fromList(_canvas.getCurrentMatrixUnsafe());
}
@override
void clipRect(ui.Rect rect, {ui.ClipOp clipOp = ui.ClipOp.intersect, bool doAntiAlias = true}) {
assert(rectIsValid(rect));
_clipRect(rect, clipOp, doAntiAlias);
}
void _clipRect(ui.Rect rect, ui.ClipOp clipOp, bool doAntiAlias) {
_canvas.clipRect(rect, clipOp);
}
@override
void clipRRect(ui.RRect rrect, {bool doAntiAlias = true}) {
assert(rrectIsValid(rrect));
_clipRRect(rrect, doAntiAlias);
}
void _clipRRect(ui.RRect rrect, bool doAntiAlias) {
_canvas.clipRRect(rrect);
}
@override
void clipRSuperellipse(ui.RSuperellipse rse, {bool doAntiAlias = true}) {
assert(rsuperellipseIsValid(rse));
// TODO(dkwingsmt): Properly implement clipRSE on Web instead of falling
// back to RRect. https://github.com/flutter/flutter/issues/163718
_clipRRect(rse.toApproximateRRect(), doAntiAlias);
}
@override
void clipPath(ui.Path path, {bool doAntiAlias = true}) {
_clipPath(path, doAntiAlias);
}
void _clipPath(ui.Path path, bool doAntiAlias) {
_canvas.clipPath(path, doAntiAlias: doAntiAlias);
}
@override
ui.Rect getDestinationClipBounds() {
return _canvas.getDestinationClipBounds() ?? ui.Rect.largest;
}
ui.Rect _roundOut(ui.Rect rect) {
return ui.Rect.fromLTRB(
rect.left.floorToDouble(),
rect.top.floorToDouble(),
rect.right.ceilToDouble(),
rect.bottom.ceilToDouble(),
);
}
@override
ui.Rect getLocalClipBounds() {
final ui.Rect? destBounds = _canvas.getDestinationClipBounds();
if (destBounds == null) {
return ui.Rect.largest;
}
final Matrix4 transform = Matrix4.fromFloat32List(_canvas.getCurrentMatrixUnsafe());
if (transform.invert() == 0) {
// non-invertible transforms collapse space to a line or point
return ui.Rect.zero;
}
return transform.transformRect(_roundOut(destBounds));
}
@override
void drawColor(ui.Color color, ui.BlendMode blendMode) {
_drawColor(color, blendMode);
}
void _drawColor(ui.Color color, ui.BlendMode blendMode) {
_canvas.drawColor(color, blendMode);
}
@override
void drawLine(ui.Offset p1, ui.Offset p2, ui.Paint paint) {
assert(offsetIsValid(p1));
assert(offsetIsValid(p2));
_drawLine(p1, p2, paint);
}
void _drawLine(ui.Offset p1, ui.Offset p2, ui.Paint paint) {
_canvas.drawLine(p1, p2, paint as SurfacePaint);
}
@override
void drawPaint(ui.Paint paint) {
_drawPaint(paint);
}
void _drawPaint(ui.Paint paint) {
_canvas.drawPaint(paint as SurfacePaint);
}
@override
void drawRect(ui.Rect rect, ui.Paint paint) {
assert(rectIsValid(rect));
_drawRect(rect, paint);
}
void _drawRect(ui.Rect rect, ui.Paint paint) {
_canvas.drawRect(rect, paint as SurfacePaint);
}
@override
void drawRRect(ui.RRect rrect, ui.Paint paint) {
assert(rrectIsValid(rrect));
_drawRRect(rrect, paint);
}
void _drawRRect(ui.RRect rrect, ui.Paint paint) {
_canvas.drawRRect(rrect, paint as SurfacePaint);
}
@override
void drawDRRect(ui.RRect outer, ui.RRect inner, ui.Paint paint) {
assert(rrectIsValid(outer));
assert(rrectIsValid(inner));
_drawDRRect(outer, inner, paint);
}
void _drawDRRect(ui.RRect outer, ui.RRect inner, ui.Paint paint) {
_canvas.drawDRRect(outer, inner, paint as SurfacePaint);
}
@override
void drawRSuperellipse(ui.RSuperellipse rse, ui.Paint paint) {
assert(rsuperellipseIsValid(rse));
// TODO(dkwingsmt): Properly implement clipRSE on Web instead of falling
// back to RRect. https://github.com/flutter/flutter/issues/163718
_drawRRect(rse.toApproximateRRect(), paint);
}
@override
void drawOval(ui.Rect rect, ui.Paint paint) {
assert(rectIsValid(rect));
_drawOval(rect, paint);
}
void _drawOval(ui.Rect rect, ui.Paint paint) {
_canvas.drawOval(rect, paint as SurfacePaint);
}
@override
void drawCircle(ui.Offset c, double radius, ui.Paint paint) {
assert(offsetIsValid(c));
_drawCircle(c, radius, paint);
}
void _drawCircle(ui.Offset c, double radius, ui.Paint paint) {
_canvas.drawCircle(c, radius, paint as SurfacePaint);
}
@override
void drawArc(ui.Rect rect, double startAngle, double sweepAngle, bool useCenter, ui.Paint paint) {
assert(rectIsValid(rect));
const double pi = math.pi;
const double pi2 = 2.0 * pi;
final ui.Path path = ui.Path();
if (useCenter) {
path.moveTo((rect.left + rect.right) / 2.0, (rect.top + rect.bottom) / 2.0);
}
bool forceMoveTo = !useCenter;
if (sweepAngle <= -pi2) {
path.arcTo(rect, startAngle, -pi, forceMoveTo);
startAngle -= pi;
path.arcTo(rect, startAngle, -pi, false);
startAngle -= pi;
forceMoveTo = false;
sweepAngle += pi2;
}
while (sweepAngle >= pi2) {
path.arcTo(rect, startAngle, pi, forceMoveTo);
startAngle += pi;
path.arcTo(rect, startAngle, pi, false);
startAngle += pi;
forceMoveTo = false;
sweepAngle -= pi2;
}
path.arcTo(rect, startAngle, sweepAngle, forceMoveTo);
if (useCenter) {
path.close();
}
_canvas.drawPath(path, paint as SurfacePaint);
}
@override
void drawPath(ui.Path path, ui.Paint paint) {
_drawPath(path, paint);
}
void _drawPath(ui.Path path, ui.Paint paint) {
_canvas.drawPath(path, paint as SurfacePaint);
}
@override
void drawImage(ui.Image image, ui.Offset offset, ui.Paint paint) {
assert(offsetIsValid(offset));
_drawImage(image, offset, paint);
}
void _drawImage(ui.Image image, ui.Offset p, ui.Paint paint) {
_canvas.drawImage(image, p, paint as SurfacePaint);
}
@override
void drawImageRect(ui.Image image, ui.Rect src, ui.Rect dst, ui.Paint paint) {
assert(rectIsValid(src));
assert(rectIsValid(dst));
_drawImageRect(image, src, dst, paint);
}
void _drawImageRect(ui.Image image, ui.Rect src, ui.Rect dst, ui.Paint paint) {
_canvas.drawImageRect(image, src, dst, paint as SurfacePaint);
}
// Return a list of slice coordinates based on the size of the nine-slice parameters in
// one dimension. Each set of slice coordinates contains a begin/end pair for each of the
// source (image) and dest (screen) in the order (src0, dst0, src1, dst1).
// The area from src0 => src1 of the image is painted on the screen from dst0 => dst1
// The slices for each dimension are generated independently.
List<double> _initSlices(
double img0,
double imgC0,
double imgC1,
double img1,
double dst0,
double dst1,
) {
final double imageDim = img1 - img0;
final double destDim = dst1 - dst0;
if (imageDim == destDim) {
// If the src and dest are the same size then we do not need scaling
// We return 4 values for a single slice
return <double>[img0, dst0, img1, dst1];
}
final double edge0Dim = imgC0 - img0;
final double edge1Dim = img1 - imgC1;
final double edgesDim = edge0Dim + edge1Dim;
if (edgesDim >= destDim) {
// the center portion has disappeared, leaving only the edges to scale to a common
// center position in the destination
// this produces only 2 slices which is 8 values
final double dstC = dst0 + destDim * edge0Dim / edgesDim;
return <double>[img0, dst0, imgC0, dstC, imgC1, dstC, img1, dst1];
}
// center portion is nonEmpty and only that part is scaled
// we need 3 slices which is 12 values
final double dstC0 = dst0 + edge0Dim;
final double dstC1 = dst1 - edge1Dim;
return <double>[img0, dst0, imgC0, dstC0, imgC0, dstC0, imgC1, dstC1, imgC1, dstC1, img1, dst1];
}
@override
void drawImageNine(ui.Image image, ui.Rect center, ui.Rect dst, ui.Paint paint) {
assert(rectIsValid(center));
assert(rectIsValid(dst));
if (dst.isEmpty) {
return;
}
final List<double> hSlices = _initSlices(
0,
center.left,
center.right,
image.width.toDouble(),
dst.left,
dst.right,
);
final List<double> vSlices = _initSlices(
0,
center.top,
center.bottom,
image.height.toDouble(),
dst.top,
dst.bottom,
);
for (int yi = 0; yi < vSlices.length; yi += 4) {
final double srcY0 = vSlices[yi];
final double dstY0 = vSlices[yi + 1];
final double srcY1 = vSlices[yi + 2];
final double dstY1 = vSlices[yi + 3];
for (int xi = 0; xi < hSlices.length; xi += 4) {
final double srcX0 = hSlices[xi];
final double dstX0 = hSlices[xi + 1];
final double srcX1 = hSlices[xi + 2];
final double dstX1 = hSlices[xi + 3];
drawImageRect(
image,
ui.Rect.fromLTRB(srcX0, srcY0, srcX1, srcY1),
ui.Rect.fromLTRB(dstX0, dstY0, dstX1, dstY1),
paint,
);
}
}
}
@override
void drawPicture(ui.Picture picture) {
_canvas.drawPicture(picture);
}
@override
void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) {
assert(offsetIsValid(offset));
_drawParagraph(paragraph, offset);
}
void _drawParagraph(ui.Paragraph paragraph, ui.Offset offset) {
_canvas.drawParagraph(paragraph, offset);
}
@override
void drawPoints(ui.PointMode pointMode, List<ui.Offset> points, ui.Paint paint) {
final Float32List pointList = offsetListToFloat32List(points);
drawRawPoints(pointMode, pointList, paint);
}
@override
void drawRawPoints(ui.PointMode pointMode, Float32List points, ui.Paint paint) {
if (points.length % 2 != 0) {
throw ArgumentError('"points" must have an even number of values.');
}
_canvas.drawRawPoints(pointMode, points, paint as SurfacePaint);
}
@override
void drawVertices(ui.Vertices vertices, ui.BlendMode blendMode, ui.Paint paint) {
_canvas.drawVertices(vertices as SurfaceVertices, blendMode, paint as SurfacePaint);
}
@override
void drawAtlas(
ui.Image atlas,
List<ui.RSTransform> transforms,
List<ui.Rect> rects,
List<ui.Color>? colors,
ui.BlendMode? blendMode,
ui.Rect? cullRect,
ui.Paint paint,
) {
assert(colors == null || colors.isEmpty || blendMode != null);
final int rectCount = rects.length;
if (transforms.length != rectCount) {
throw ArgumentError('"transforms" and "rects" lengths must match.');
}
if (colors != null && colors.isNotEmpty && colors.length != rectCount) {
throw ArgumentError(
'If non-null, "colors" length must match that of "transforms" and "rects".',
);
}
// TODO(het): Do we need to support this?
throw UnimplementedError();
}
@override
void drawRawAtlas(
ui.Image atlas,
Float32List rstTransforms,
Float32List rects,
Int32List? colors,
ui.BlendMode? blendMode,
ui.Rect? cullRect,
ui.Paint paint,
) {
assert(colors == null || blendMode != null);
final int rectCount = rects.length;
if (rstTransforms.length != rectCount) {
throw ArgumentError('"rstTransforms" and "rects" lengths must match.');
}
if (rectCount % 4 != 0) {
throw ArgumentError('"rstTransforms" and "rects" lengths must be a multiple of four.');
}
if (colors != null && colors.length * 4 != rectCount) {
throw ArgumentError(
'If non-null, "colors" length must be one fourth the length of "rstTransforms" and "rects".',
);
}
// TODO(het): Do we need to support this?
throw UnimplementedError();
}
@override
void drawShadow(ui.Path path, ui.Color color, double elevation, bool transparentOccluder) {
_canvas.drawShadow(path, color, elevation, transparentOccluder);
}
}

View File

@@ -1,326 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../svg.dart';
import '../util.dart';
import 'path_to_svg_clip.dart';
import 'surface.dart';
import 'surface_stats.dart';
/// Mixin used by surfaces that clip their contents using an overflowing DOM
/// element.
mixin _DomClip on PersistedContainerSurface {
/// The dedicated child container element that's separate from the
/// [rootElement] is used to compensate for the coordinate system shift
/// introduced by the [rootElement] translation.
@override
DomElement? get childContainer => _childContainer;
DomElement? _childContainer;
@override
void adoptElements(_DomClip oldSurface) {
super.adoptElements(oldSurface);
_childContainer = oldSurface._childContainer;
oldSurface._childContainer = null;
}
@override
DomElement createElement() {
final DomElement element = defaultCreateElement('flt-clip');
_childContainer = createDomElement('flt-clip-interior');
if (debugExplainSurfaceStats) {
// This creates an additional interior element. Count it too.
surfaceStatsFor(this).allocatedDomNodeCount++;
}
_childContainer!.style.position = 'absolute';
element.append(_childContainer!);
return element;
}
@override
void discard() {
super.discard();
// Do not detach the child container from the root. It is permanently
// attached. The elements are reused together and are detached from the DOM
// together.
_childContainer = null;
}
void applyOverflow(DomElement element, ui.Clip? clipBehaviour) {
if (!debugShowClipLayers) {
// Hide overflow in production mode. When debugging we want to see the
// clipped picture in full.
if (clipBehaviour != ui.Clip.none) {
element.style
..overflow = 'hidden'
..zIndex = '0';
}
} else {
// Display the outline of the clipping region. When debugShowClipLayers is
// `true` we don't hide clip overflow (see above). This outline helps
// visualizing clip areas.
element.style.boxShadow = 'inset 0 0 10px green';
}
}
}
/// A surface that creates a rectangular clip.
class PersistedClipRect extends PersistedContainerSurface
with _DomClip
implements ui.ClipRectEngineLayer {
PersistedClipRect(PersistedClipRect? super.oldLayer, this.rect, this.clipBehavior);
final ui.Clip? clipBehavior;
final ui.Rect rect;
@override
void recomputeTransformAndClip() {
transform = parent!.transform;
if (clipBehavior != ui.Clip.none) {
localClipBounds = rect;
} else {
localClipBounds = null;
}
projectedClip = null;
}
@override
DomElement createElement() {
return super.createElement()..setAttribute('clip-type', 'rect');
}
@override
void apply() {
rootElement!.style
..left = '${rect.left}px'
..top = '${rect.top}px'
..width = '${rect.right - rect.left}px'
..height = '${rect.bottom - rect.top}px';
applyOverflow(rootElement!, clipBehavior);
// Translate the child container in the opposite direction to compensate for
// the shift in the coordinate system introduced by the translation of the
// rootElement. Clipping in Flutter has no effect on the coordinate system.
childContainer!.style
..left = '${-rect.left}px'
..top = '${-rect.top}px';
}
@override
void update(PersistedClipRect oldSurface) {
super.update(oldSurface);
if (rect != oldSurface.rect || clipBehavior != oldSurface.clipBehavior) {
localClipBounds = null;
apply();
}
}
@override
bool get isClipping => true;
}
/// A surface that creates a rounded rectangular clip.
class PersistedClipRRect extends PersistedContainerSurface
with _DomClip
implements ui.ClipRRectEngineLayer {
PersistedClipRRect(ui.EngineLayer? oldLayer, this.rrect, this.clipBehavior)
: super(oldLayer as PersistedSurface?);
final ui.RRect rrect;
// TODO(yjbanov): can this be controlled in the browser?
final ui.Clip? clipBehavior;
@override
void recomputeTransformAndClip() {
transform = parent!.transform;
if (clipBehavior != ui.Clip.none) {
localClipBounds = rrect.outerRect;
} else {
localClipBounds = null;
}
projectedClip = null;
}
@override
DomElement createElement() {
return super.createElement()..setAttribute('clip-type', 'rrect');
}
@override
void apply() {
final DomCSSStyleDeclaration style = rootElement!.style;
style
..left = '${rrect.left}px'
..top = '${rrect.top}px'
..width = '${rrect.width}px'
..height = '${rrect.height}px'
..borderTopLeftRadius = '${rrect.tlRadiusX}px'
..borderTopRightRadius = '${rrect.trRadiusX}px'
..borderBottomRightRadius = '${rrect.brRadiusX}px'
..borderBottomLeftRadius = '${rrect.blRadiusX}px';
applyOverflow(rootElement!, clipBehavior);
// Translate the child container in the opposite direction to compensate for
// the shift in the coordinate system introduced by the translation of the
// rootElement. Clipping in Flutter has no effect on the coordinate system.
childContainer!.style
..left = '${-rrect.left}px'
..top = '${-rrect.top}px';
}
@override
void update(PersistedClipRRect oldSurface) {
super.update(oldSurface);
if (rrect != oldSurface.rrect || clipBehavior != oldSurface.clipBehavior) {
localClipBounds = null;
apply();
}
}
@override
bool get isClipping => true;
}
/// A surface that creates a rounded superellipse clip.
///
/// Implemented by falling back to RRect.
class PersistedClipRSuperellipse extends PersistedContainerSurface
with _DomClip
implements ui.ClipRSuperellipseEngineLayer {
PersistedClipRSuperellipse(ui.EngineLayer? oldLayer, this.rse, this.clipBehavior)
: super(oldLayer as PersistedSurface?);
final ui.RSuperellipse rse;
// TODO(yjbanov): can this be controlled in the browser?
final ui.Clip? clipBehavior;
@override
void recomputeTransformAndClip() {
transform = parent!.transform;
if (clipBehavior != ui.Clip.none) {
localClipBounds = rse.outerRect;
} else {
localClipBounds = null;
}
projectedClip = null;
}
@override
DomElement createElement() {
// Fall back to rrect.
return super.createElement()..setAttribute('clip-type', 'rrect');
}
@override
void apply() {
final DomCSSStyleDeclaration style = rootElement!.style;
style
..left = '${rse.left}px'
..top = '${rse.top}px'
..width = '${rse.width}px'
..height = '${rse.height}px'
..borderTopLeftRadius = '${rse.tlRadiusX}px'
..borderTopRightRadius = '${rse.trRadiusX}px'
..borderBottomRightRadius = '${rse.brRadiusX}px'
..borderBottomLeftRadius = '${rse.blRadiusX}px';
applyOverflow(rootElement!, clipBehavior);
// Translate the child container in the opposite direction to compensate for
// the shift in the coordinate system introduced by the translation of the
// rootElement. Clipping in Flutter has no effect on the coordinate system.
childContainer!.style
..left = '${-rse.left}px'
..top = '${-rse.top}px';
}
@override
void update(PersistedClipRSuperellipse oldSurface) {
super.update(oldSurface);
if (rse != oldSurface.rse || clipBehavior != oldSurface.clipBehavior) {
localClipBounds = null;
apply();
}
}
@override
bool get isClipping => true;
}
/// A surface that clips it's children.
class PersistedClipPath extends PersistedContainerSurface implements ui.ClipPathEngineLayer {
PersistedClipPath(PersistedClipPath? super.oldLayer, this.clipPath, this.clipBehavior);
final ui.Path clipPath;
final ui.Clip clipBehavior;
DomElement? _clipElement;
@override
DomElement createElement() {
return defaultCreateElement('flt-clippath');
}
@override
void recomputeTransformAndClip() {
super.recomputeTransformAndClip();
if (clipBehavior != ui.Clip.none) {
localClipBounds ??= clipPath.getBounds();
} else {
localClipBounds = null;
}
}
@override
void apply() {
_clipElement?.remove();
_clipElement = createSvgClipDef(childContainer!, clipPath);
childContainer!.append(_clipElement!);
}
@override
void update(PersistedClipPath oldSurface) {
super.update(oldSurface);
if (oldSurface.clipPath != clipPath) {
localClipBounds = null;
oldSurface._clipElement?.remove();
apply();
} else {
_clipElement = oldSurface._clipElement;
}
oldSurface._clipElement = null;
}
@override
void discard() {
_clipElement?.remove();
_clipElement = null;
super.discard();
}
@override
bool get isClipping => true;
}
/// Creates an svg clipPath and applies it to [element].
SVGSVGElement createSvgClipDef(DomElement element, ui.Path clipPath) {
final ui.Rect pathBounds = clipPath.getBounds();
final SVGSVGElement svgClipPath = pathToSvgClipPath(
clipPath,
scaleX: 1.0 / pathBounds.right,
scaleY: 1.0 / pathBounds.bottom,
);
setClipPath(element, createSvgClipUrl());
// We need to set width and height for the clipElement to cover the
// bounds of the path since browsers such as Safari and Edge
// seem to incorrectly intersect the element bounding rect with
// the clip path. Chrome and Firefox don't perform intersect instead they
// use the path itself as source of truth.
element.style
..width = '${pathBounds.right}px'
..height = '${pathBounds.bottom}px';
return svgClipPath;
}

View File

@@ -1,496 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../../engine/color_filter.dart';
import '../dom.dart';
import '../svg.dart';
import '../util.dart';
import 'bitmap_canvas.dart';
import 'path_to_svg_clip.dart';
import 'resource_manager.dart';
import 'shaders/shader.dart';
import 'surface.dart';
/// A surface that applies an [ColorFilter] to its children.
class PersistedColorFilter extends PersistedContainerSurface implements ui.ColorFilterEngineLayer {
PersistedColorFilter(PersistedColorFilter? super.oldLayer, this.filter);
@override
DomElement? get childContainer => _childContainer;
/// The dedicated child container element that's separate from the
/// [rootElement] is used to compensate for the coordinate system shift
/// introduced by the [rootElement] translation.
DomElement? _childContainer;
/// Color filter to apply to this surface.
final ui.ColorFilter filter;
DomElement? _filterElement;
bool containerVisible = true;
@override
void adoptElements(PersistedColorFilter oldSurface) {
super.adoptElements(oldSurface);
_childContainer = oldSurface._childContainer;
_filterElement = oldSurface._filterElement;
oldSurface._childContainer = null;
}
@override
void preroll(PrerollSurfaceContext prerollContext) {
++prerollContext.activeColorFilterCount;
super.preroll(prerollContext);
--prerollContext.activeColorFilterCount;
}
@override
void discard() {
super.discard();
ResourceManager.instance.removeResource(_filterElement);
_filterElement = null;
// Do not detach the child container from the root. It is permanently
// attached. The elements are reused together and are detached from the DOM
// together.
_childContainer = null;
}
@override
DomElement createElement() {
final DomElement element = defaultCreateElement('flt-color-filter');
final DomElement container = createDomElement('flt-filter-interior');
container.style.position = 'absolute';
_childContainer = container;
element.append(_childContainer!);
return element;
}
@override
void apply() {
ResourceManager.instance.removeResource(_filterElement);
_filterElement = null;
final EngineHtmlColorFilter? engineValue = createHtmlColorFilter(filter as EngineColorFilter);
if (engineValue == null) {
rootElement!.style.backgroundColor = '';
childContainer?.style.visibility = 'visible';
return;
}
if (engineValue is ModeHtmlColorFilter) {
_applyBlendModeFilter(engineValue);
} else if (engineValue is MatrixHtmlColorFilter) {
_applyMatrixColorFilter(engineValue);
} else {
childContainer?.style.visibility = 'visible';
}
}
void _applyBlendModeFilter(ModeHtmlColorFilter colorFilter) {
_filterElement = colorFilter.makeSvgFilter(childContainer);
/// Some blendModes do not make an svgFilter. See [EngineHtmlColorFilter.makeSvgFilter()]
if (_filterElement == null) {
return;
}
childContainer!.style.filter = colorFilter.filterAttribute;
}
void _applyMatrixColorFilter(MatrixHtmlColorFilter colorFilter) {
_filterElement = colorFilter.makeSvgFilter(childContainer);
childContainer!.style.filter = colorFilter.filterAttribute;
}
@override
void update(PersistedColorFilter oldSurface) {
super.update(oldSurface);
if (oldSurface.filter != filter) {
apply();
}
}
}
SvgFilter svgFilterFromBlendMode(ui.Color? filterColor, ui.BlendMode colorFilterBlendMode) {
final SvgFilter svgFilter;
switch (colorFilterBlendMode) {
case ui.BlendMode.srcIn:
case ui.BlendMode.srcATop:
svgFilter = _srcInColorFilterToSvg(filterColor);
case ui.BlendMode.srcOut:
svgFilter = _srcOutColorFilterToSvg(filterColor);
case ui.BlendMode.dstATop:
svgFilter = _dstATopColorFilterToSvg(filterColor);
case ui.BlendMode.xor:
svgFilter = _xorColorFilterToSvg(filterColor);
case ui.BlendMode.plus:
// Porter duff source + destination.
svgFilter = _compositeColorFilterToSvg(filterColor, 0, 1, 1, 0);
case ui.BlendMode.modulate:
// Porter duff source * destination but preserves alpha.
svgFilter = _modulateColorFilterToSvg(filterColor!);
case ui.BlendMode.overlay:
// Since overlay is the same as hard-light by swapping layers,
// pass hard-light blend function.
svgFilter = _blendColorFilterToSvg(
filterColor,
blendModeToSvgEnum(ui.BlendMode.hardLight)!,
swapLayers: true,
);
// Several of the filters below (although supported) do not render the
// same (close but not exact) as native flutter when used as blend mode
// for a background-image with a background color. They only look
// identical when feBlend is used within an svg filter definition.
//
// Saturation filter uses destination when source is transparent.
// cMax = math.max(r, math.max(b, g));
// cMin = math.min(r, math.min(b, g));
// delta = cMax - cMin;
// lightness = (cMax + cMin) / 2.0;
// saturation = delta / (1.0 - (2 * lightness - 1.0).abs());
case ui.BlendMode.saturation:
case ui.BlendMode.colorDodge:
case ui.BlendMode.colorBurn:
case ui.BlendMode.hue:
case ui.BlendMode.color:
case ui.BlendMode.luminosity:
case ui.BlendMode.multiply:
case ui.BlendMode.screen:
case ui.BlendMode.darken:
case ui.BlendMode.lighten:
case ui.BlendMode.hardLight:
case ui.BlendMode.softLight:
case ui.BlendMode.difference:
case ui.BlendMode.exclusion:
svgFilter = _blendColorFilterToSvg(filterColor, blendModeToSvgEnum(colorFilterBlendMode)!);
case ui.BlendMode.src:
case ui.BlendMode.dst:
case ui.BlendMode.dstIn:
case ui.BlendMode.dstOut:
case ui.BlendMode.dstOver:
case ui.BlendMode.clear:
case ui.BlendMode.srcOver:
throw UnimplementedError('Blend mode not supported in HTML renderer: $colorFilterBlendMode');
}
return svgFilter;
}
// See: https://www.w3.org/TR/SVG11/types.html#InterfaceSVGUnitTypes
const int kObjectBoundingBox = 2;
// See: https://www.w3.org/TR/SVG11/filters.html#InterfaceSVGFEColorMatrixElement
const int kMatrixType = 1;
// See: https://www.w3.org/TR/SVG11/filters.html#InterfaceSVGFECompositeElement
const int kOperatorOut = 3;
const int kOperatorAtop = 4;
const int kOperatorXor = 5;
const int kOperatorArithmetic = 6;
/// Builds an [SvgFilter].
class SvgFilterBuilder {
SvgFilterBuilder() : id = '_fcf${++_filterIdCounter}' {
filter.id = id;
// SVG filters that contain `<feImage>` will fail on several browsers
// (e.g. Firefox) if bounds are not specified.
filter.filterUnits!.baseVal = kObjectBoundingBox;
// On Firefox percentage width/height 100% works however fails in Chrome 88.
filter.x!.baseVal!.valueAsString = '0%';
filter.y!.baseVal!.valueAsString = '0%';
filter.width!.baseVal!.valueAsString = '100%';
filter.height!.baseVal!.valueAsString = '100%';
}
static int _filterIdCounter = 0;
final String id;
final SVGSVGElement root = kSvgResourceHeader.cloneNode(false) as SVGSVGElement;
final SVGFilterElement filter = createSVGFilterElement();
set colorInterpolationFilters(String filters) {
filter.setAttribute('color-interpolation-filters', filters);
}
void setFeColorMatrix(List<double> matrix, {required String result}) {
final SVGFEColorMatrixElement element = createSVGFEColorMatrixElement();
element.type!.baseVal = kMatrixType;
element.result!.baseVal = result;
final SVGNumberList value = element.values!.baseVal!;
for (int i = 0; i < matrix.length; i++) {
value.appendItem(root.createSVGNumber()..value = matrix[i]);
}
filter.append(element);
}
void setFeFlood({
required String floodColor,
required String floodOpacity,
required String result,
}) {
final SVGFEFloodElement element = createSVGFEFloodElement();
element.setAttribute('flood-color', floodColor);
element.setAttribute('flood-opacity', floodOpacity);
element.result!.baseVal = result;
filter.append(element);
}
void setFeBlend({required String in1, required String in2, required int mode}) {
final SVGFEBlendElement element = createSVGFEBlendElement();
element.in1!.baseVal = in1;
element.in2!.baseVal = in2;
element.mode!.baseVal = mode;
filter.append(element);
}
void setFeComposite({
required String in1,
required String in2,
required int operator,
num? k1,
num? k2,
num? k3,
num? k4,
required String result,
}) {
final SVGFECompositeElement element = createSVGFECompositeElement();
element.in1!.baseVal = in1;
element.in2!.baseVal = in2;
element.operator!.baseVal = operator;
if (k1 != null) {
element.k1!.baseVal = k1;
}
if (k2 != null) {
element.k2!.baseVal = k2;
}
if (k3 != null) {
element.k3!.baseVal = k3;
}
if (k4 != null) {
element.k4!.baseVal = k4;
}
element.result!.baseVal = result;
filter.append(element);
}
void setFeImage({
required String href,
required String result,
required double width,
required double height,
}) {
final SVGFEImageElement element = createSVGFEImageElement();
element.href!.baseVal = href;
element.result!.baseVal = result;
// WebKit will not render if x/y/width/height is specified. So we return
// explicit size here unless running on WebKit.
if (ui_web.browser.browserEngine != ui_web.BrowserEngine.webkit) {
element.x!.baseVal!.newValueSpecifiedUnits(svgLengthTypeNumber, 0);
element.y!.baseVal!.newValueSpecifiedUnits(svgLengthTypeNumber, 0);
element.width!.baseVal!.newValueSpecifiedUnits(svgLengthTypeNumber, width);
element.height!.baseVal!.newValueSpecifiedUnits(svgLengthTypeNumber, height);
}
filter.append(element);
}
SvgFilter build() {
root.append(filter);
return SvgFilter._(id, root);
}
}
class SvgFilter {
SvgFilter._(this.id, this.element);
final String id;
final SVGSVGElement element;
}
SvgFilter svgFilterFromColorMatrix(List<double> matrix) {
final SvgFilterBuilder builder = SvgFilterBuilder();
/// Flutter documentation says the translation column of the color matrix
/// is specified in unnormalized 0..255 space. `feColorMatrix` expects the
/// translation values to be normalized to 0..1 space.
///
/// See [https://api.flutter.dev/flutter/dart-ui/ColorFilter/ColorFilter.matrix.html]
final normalizedMatrix = List<double>.generate(
matrix.length,
(int i) => (i % 5 == 4) ? matrix[i] / 255.0 : matrix[i],
growable: false,
);
builder.setFeColorMatrix(normalizedMatrix, result: 'comp');
return builder.build();
}
// The color matrix for feColorMatrix element changes colors based on
// the following:
//
// | R' | | r1 r2 r3 r4 r5 | | R |
// | G' | | g1 g2 g3 g4 g5 | | G |
// | B' | = | b1 b2 b3 b4 b5 | * | B |
// | A' | | a1 a2 a3 a4 a5 | | A |
// | 1 | | 0 0 0 0 1 | | 1 |
//
// R' = r1*R + r2*G + r3*B + r4*A + r5
// G' = g1*R + g2*G + g3*B + g4*A + g5
// B' = b1*R + b2*G + b3*B + b4*A + b5
// A' = a1*R + a2*G + a3*B + a4*A + a5
SvgFilter _srcInColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.colorInterpolationFilters = 'sRGB';
builder.setFeColorMatrix(const <double>[
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
1,
0,
], result: 'destalpha');
builder.setFeFlood(floodColor: color?.toCssString() ?? '', floodOpacity: '1', result: 'flood');
builder.setFeComposite(
in1: 'flood',
in2: 'destalpha',
operator: kOperatorArithmetic,
k1: 1,
k2: 0,
k3: 0,
k4: 0,
result: 'comp',
);
return builder.build();
}
/// The destination that overlaps the source is composited with the source and
/// replaces the destination. dst-atop CR = CB*αB*αA+CA*αA*(1-αB) αR=αA
SvgFilter _dstATopColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(floodColor: color?.toCssString() ?? '', floodOpacity: '1', result: 'flood');
builder.setFeComposite(
in1: 'SourceGraphic',
in2: 'flood',
operator: kOperatorAtop,
result: 'comp',
);
return builder.build();
}
SvgFilter _srcOutColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(floodColor: color?.toCssString() ?? '', floodOpacity: '1', result: 'flood');
builder.setFeComposite(
in1: 'flood',
in2: 'SourceGraphic',
operator: kOperatorOut,
result: 'comp',
);
return builder.build();
}
SvgFilter _xorColorFilterToSvg(ui.Color? color) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(floodColor: color?.toCssString() ?? '', floodOpacity: '1', result: 'flood');
builder.setFeComposite(
in1: 'flood',
in2: 'SourceGraphic',
operator: kOperatorXor,
result: 'comp',
);
return builder.build();
}
// The source image and color are composited using :
// result = k1 *in*in2 + k2*in + k3*in2 + k4.
SvgFilter _compositeColorFilterToSvg(ui.Color? color, double k1, double k2, double k3, double k4) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(floodColor: color?.toCssString() ?? '', floodOpacity: '1', result: 'flood');
builder.setFeComposite(
in1: 'flood',
in2: 'SourceGraphic',
operator: kOperatorArithmetic,
k1: k1,
k2: k2,
k3: k3,
k4: k4,
result: 'comp',
);
return builder.build();
}
// Porter duff source * destination , keep source alpha.
// First apply color filter to source to change it to [color], then
// composite using multiplication.
SvgFilter _modulateColorFilterToSvg(ui.Color color) {
final double r = color.red / 255.0;
final double b = color.blue / 255.0;
final double g = color.green / 255.0;
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeColorMatrix(<double>[
0,
0,
0,
0,
r,
0,
0,
0,
0,
g,
0,
0,
0,
0,
b,
0,
0,
0,
1,
0,
], result: 'recolor');
builder.setFeComposite(
in1: 'recolor',
in2: 'SourceGraphic',
operator: kOperatorArithmetic,
k1: 1,
k2: 0,
k3: 0,
k4: 0,
result: 'comp',
);
return builder.build();
}
// Uses feBlend element to blend source image with a color.
SvgFilter _blendColorFilterToSvg(
ui.Color? color,
SvgBlendMode svgBlendMode, {
bool swapLayers = false,
}) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeFlood(floodColor: color?.toCssString() ?? '', floodOpacity: '1', result: 'flood');
if (swapLayers) {
builder.setFeBlend(in1: 'SourceGraphic', in2: 'flood', mode: svgBlendMode.blendMode);
} else {
builder.setFeBlend(in1: 'flood', in2: 'SourceGraphic', mode: svgBlendMode.blendMode);
}
return builder.build();
}

View File

@@ -1,138 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../dom.dart';
DomHTMLElement _createContainer() {
final DomHTMLElement container = createDomHTMLDivElement();
container.style
..position = 'fixed'
..top = '0'
..right = '0'
..padding = '6px'
..color = '#fff'
..backgroundColor = '#000'
..opacity = '0.8';
return container;
}
/// An overlay in the top right corner of the page that shows statistics
/// regarding canvas reuse.
///
/// This should only be used for development purposes and never included in
/// release builds.
class DebugCanvasReuseOverlay {
DebugCanvasReuseOverlay._() {
final DomHTMLElement container = _createContainer();
final DomHTMLElement title = createDomHTMLDivElement();
title.style
..fontWeight = 'bold'
..textDecoration = 'underline';
title.text = 'Canvas Reuse';
domDocument.body!.append(
container
..append(title)
..append(
createDomHTMLDivElement()
..appendText('Created: ')
..append(_created),
)
..append(
createDomHTMLDivElement()
..appendText('Kept: ')
..append(_kept),
)
..append(
createDomHTMLDivElement()
..appendText('Reused: ')
..append(_reused),
)
..append(
createDomHTMLDivElement()
..appendText('Disposed: ')
..append(_disposed),
)
..append(
createDomHTMLDivElement()
..appendText('In Recycle List: ')
..append(_inRecycle),
)
..append(
createDomHTMLDivElement()..append(
createDomHTMLButtonElement()
..text = 'Reset'
..addEventListener('click', createDomEventListener((_) => _reset())),
),
),
);
}
static DebugCanvasReuseOverlay? _instance;
static DebugCanvasReuseOverlay get instance {
if (_instance == null) {
// Only call the constructor when assertions are enabled to guard against
// mistakingly including this class in a release build.
assert(() {
_instance = DebugCanvasReuseOverlay._();
return true;
}());
}
return _instance!;
}
final DomText _created = createDomText('0');
final DomText _kept = createDomText('0');
final DomText _reused = createDomText('0');
final DomText _disposed = createDomText('0');
final DomText _inRecycle = createDomText('0');
int _createdCount = 0;
int get createdCount => _createdCount;
set createdCount(int createdCount) {
_createdCount = createdCount;
_update();
}
int _keptCount = 0;
int get keptCount => _keptCount;
set keptCount(int keptCount) {
_keptCount = keptCount;
_update();
}
int _reusedCount = 0;
int get reusedCount => _reusedCount;
set reusedCount(int reusedCount) {
_reusedCount = reusedCount;
_update();
}
int _disposedCount = 0;
int get disposedCount => _disposedCount;
set disposedCount(int disposedCount) {
_disposedCount = disposedCount;
_update();
}
int _inRecycleCount = 0;
int get inRecycleCount => _inRecycleCount;
set inRecycleCount(int inRecycleCount) {
_inRecycleCount = inRecycleCount;
_update();
}
void _update() {
_created.text = '$_createdCount';
_kept.text = '$_keptCount';
_reused.text = '$_reusedCount';
_disposed.text = '$_disposedCount';
_inRecycle.text = '$_inRecycleCount';
}
void _reset() {
_createdCount = _keptCount = _reusedCount = _disposedCount = _inRecycleCount = 0;
_update();
}
}

View File

@@ -1,370 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../dom.dart';
import '../engine_canvas.dart';
import '../svg.dart';
import '../text/canvas_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';
import 'shaders/shader.dart';
/// A canvas that renders to DOM elements and CSS properties.
class DomCanvas extends EngineCanvas with SaveElementStackTracking {
DomCanvas(this.rootElement);
@override
final DomElement rootElement;
/// Prepare to reuse this canvas by clearing it's current contents.
@override
void clear() {
super.clear();
removeAllChildren(rootElement);
}
@override
void clipRect(ui.Rect rect, ui.ClipOp clipOp) {
throw UnimplementedError();
}
@override
void clipRRect(ui.RRect rrect) {
throw UnimplementedError();
}
@override
void clipRSuperellipse(ui.RSuperellipse rse, {bool doAntiAlias = true}) {
throw UnimplementedError();
}
@override
void clipPath(ui.Path path) {
throw UnimplementedError();
}
@override
void drawColor(ui.Color color, ui.BlendMode blendMode) {
// TODO(yjbanov): implement blendMode
final DomElement box = createDomElement('draw-color');
box.style
..position = 'absolute'
..top = '0'
..right = '0'
..bottom = '0'
..left = '0'
..backgroundColor = color.toCssString();
currentElement.append(box);
}
@override
void drawLine(ui.Offset p1, ui.Offset p2, SurfacePaintData paint) {
throw UnimplementedError();
}
@override
void drawPaint(SurfacePaintData paint) {
throw UnimplementedError();
}
@override
void drawRect(ui.Rect rect, SurfacePaintData paint) {
rect = adjustRectForDom(rect, paint);
currentElement.append(buildDrawRectElement(rect, paint, 'draw-rect', currentTransform));
}
@override
void drawRRect(ui.RRect rrect, SurfacePaintData paint) {
final ui.Rect outerRect = adjustRectForDom(rrect.outerRect, paint);
final DomElement element = buildDrawRectElement(
outerRect,
paint,
'draw-rrect',
currentTransform,
);
applyRRectBorderRadius(element.style, rrect);
currentElement.append(element);
}
@override
void drawDRRect(ui.RRect outer, ui.RRect inner, SurfacePaintData paint) {
throw UnimplementedError();
}
@override
void drawOval(ui.Rect rect, SurfacePaintData paint) {
throw UnimplementedError();
}
@override
void drawCircle(ui.Offset c, double radius, SurfacePaintData paint) {
throw UnimplementedError();
}
@override
void drawPath(ui.Path path, SurfacePaintData paint) {
throw UnimplementedError();
}
@override
void drawShadow(ui.Path path, ui.Color color, double elevation, bool transparentOccluder) {
throw UnimplementedError();
}
@override
void drawImage(ui.Image image, ui.Offset p, SurfacePaintData paint) {
throw UnimplementedError();
}
@override
void drawImageRect(ui.Image image, ui.Rect src, ui.Rect dst, SurfacePaintData paint) {
throw UnimplementedError();
}
@override
void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) {
final DomElement paragraphElement = drawParagraphElement(
paragraph as CanvasParagraph,
offset,
transform: currentTransform,
);
currentElement.append(paragraphElement);
}
@override
void drawVertices(ui.Vertices vertices, ui.BlendMode blendMode, SurfacePaintData paint) {
throw UnimplementedError();
}
@override
void drawPoints(ui.PointMode pointMode, Float32List points, SurfacePaintData paint) {
throw UnimplementedError();
}
@override
void endOfPaint() {
// No reuse of elements yet to handle here. Noop.
}
}
/// Converts a shadow color specified by the framework to the color that should
/// actually be applied when rendering the element.
///
/// Returns a color for box-shadow based on blur filter at sigma.
ui.Color blurColor(ui.Color color, double sigma) {
final double strength = math.min(math.sqrt(sigma) / (math.pi * 2.0), 1.0);
final int reducedAlpha = ((1.0 - strength) * color.alpha).round();
return ui.Color((reducedAlpha & 0xff) << 24 | (color.value & 0x00ffffff));
}
/// When drawing a shape (rect, rrect, circle, etc) in DOM/CSS, the [rect] given
/// by Flutter needs to be adjusted to what DOM/CSS expect.
///
/// This method takes Flutter's [rect] and produces a new rect that can be used
/// to generate the correct CSS properties to match Flutter's expectations.
///
///
/// Here's what Flutter's given [rect] and [paint.strokeWidth] represent:
///
/// top-left ↓
/// ┌──↓──────────────────────┐
/// →→→→x x │←←
/// │ ┌───────────────┐ │ |
/// │ │ │ │ |
/// │ │ │ │ | height
/// │ │ │ │ |
/// │ └───────────────┘ │ |
/// │ x x │←←
/// └─────────────────────────┘
/// stroke-width ↑----↑ ↑
/// ↑-------------------↑ width
///
///
///
/// In the DOM/CSS, here's how the coordinates should look like:
///
/// top-left ↓
/// →→x─────────────────────────┐
/// │ │
/// │ x───────────────x │←←
/// │ │ │ │ |
/// │ │ │ │ | height
/// │ │ │ │ |
/// │ x───────────────x │←←
/// │ │
/// └─────────────────────────┘
/// border-width ↑----↑ ↑
/// ↑---------------↑ width
///
/// As shown in the drawing above, the width/height don't start at the top-left
/// coordinates. Instead, they start from the inner top-left (inside the border).
ui.Rect adjustRectForDom(ui.Rect rect, SurfacePaintData paint) {
double left = math.min(rect.left, rect.right);
double top = math.min(rect.top, rect.bottom);
double width = rect.width.abs();
double height = rect.height.abs();
final bool isStroke = paint.style == ui.PaintingStyle.stroke;
final double strokeWidth = paint.strokeWidth ?? 0.0;
if (isStroke && strokeWidth > 0.0) {
left -= strokeWidth / 2.0;
top -= strokeWidth / 2.0;
// width and height shouldn't go below zero.
width = math.max(0, width - strokeWidth);
height = math.max(0, height - strokeWidth);
}
if (left != rect.left || top != rect.top || width != rect.width || height != rect.height) {
return ui.Rect.fromLTWH(left, top, width, height);
}
return rect;
}
DomHTMLElement buildDrawRectElement(
ui.Rect rect,
SurfacePaintData paint,
String tagName,
Matrix4 transform,
) {
assert(rect.left <= rect.right);
assert(rect.top <= rect.bottom);
final DomHTMLElement rectangle = domDocument.createElement(tagName) as DomHTMLElement;
assert(() {
rectangle.setAttribute('flt-rect', '$rect');
rectangle.setAttribute('flt-paint', '$paint');
return true;
}());
String effectiveTransform;
final bool isStroke = paint.style == ui.PaintingStyle.stroke;
final double strokeWidth = paint.strokeWidth ?? 0.0;
if (transform.isIdentity()) {
effectiveTransform = 'translate(${rect.left}px, ${rect.top}px)';
} else {
// Clone to avoid mutating `transform`.
final Matrix4 translated = transform.clone()..translate(rect.left, rect.top);
effectiveTransform = matrix4ToCssTransform(translated);
}
final DomCSSStyleDeclaration style = rectangle.style;
style
..position = 'absolute'
..transformOrigin = '0 0 0'
..transform = effectiveTransform;
String cssColor = colorValueToCssString(paint.color);
if (paint.maskFilter != null) {
final double sigma = paint.maskFilter!.webOnlySigma;
if (ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit && !isStroke) {
// A bug in webkit leaves artifacts when this element is animated
// with filter: blur, we use boxShadow instead.
style.boxShadow = '0px 0px ${sigma * 2.0}px $cssColor';
cssColor = blurColor(ui.Color(paint.color), sigma).toCssString();
} else {
style.filter = 'blur(${sigma}px)';
}
}
style
..width = '${rect.width}px'
..height = '${rect.height}px';
if (isStroke) {
style.border = '${_borderStrokeToCssUnit(strokeWidth)} solid $cssColor';
} else {
style
..backgroundColor = cssColor
..backgroundImage = _getBackgroundImageCssValue(paint.shader, rect);
}
return rectangle;
}
String _getBackgroundImageCssValue(ui.Shader? shader, ui.Rect bounds) {
final String url = _getBackgroundImageUrl(shader, bounds);
return (url != '') ? "url('$url'" : '';
}
String _getBackgroundImageUrl(ui.Shader? shader, ui.Rect bounds) {
if (shader != null) {
if (shader is EngineImageShader) {
return shader.image.imgElement.src ?? '';
}
if (shader is EngineGradient) {
return shader.createImageBitmap(bounds, 1, true) as String;
}
}
return '';
}
void applyRRectBorderRadius(DomCSSStyleDeclaration style, ui.RRect rrect) {
if (rrect.tlRadiusX == rrect.trRadiusX &&
rrect.tlRadiusX == rrect.blRadiusX &&
rrect.tlRadiusX == rrect.brRadiusX &&
rrect.tlRadiusX == rrect.tlRadiusY &&
rrect.trRadiusX == rrect.trRadiusY &&
rrect.blRadiusX == rrect.blRadiusY &&
rrect.brRadiusX == rrect.brRadiusY) {
style.borderRadius = _borderStrokeToCssUnit(rrect.blRadiusX);
return;
}
// Non-uniform. Apply each corner radius.
style.borderTopLeftRadius =
'${_borderStrokeToCssUnit(rrect.tlRadiusX)} '
'${_borderStrokeToCssUnit(rrect.tlRadiusY)}';
style.borderTopRightRadius =
'${_borderStrokeToCssUnit(rrect.trRadiusX)} '
'${_borderStrokeToCssUnit(rrect.trRadiusY)}';
style.borderBottomLeftRadius =
'${_borderStrokeToCssUnit(rrect.blRadiusX)} '
'${_borderStrokeToCssUnit(rrect.blRadiusY)}';
style.borderBottomRightRadius =
'${_borderStrokeToCssUnit(rrect.brRadiusX)} '
'${_borderStrokeToCssUnit(rrect.brRadiusY)}';
}
String _borderStrokeToCssUnit(double value) {
if (value == 0) {
// TODO(ferhat): hairline nees to take into account both dpi and density.
value = 1.0;
}
return '${value.toStringAsFixed(3)}px';
}
SVGSVGElement pathToSvgElement(SurfacePath path, SurfacePaintData paint) {
// In Firefox some SVG typed attributes are returned as null without a
// setter. So we use strings here.
final SVGSVGElement root = createSVGSVGElement()..setAttribute('overflow', 'visible');
final SVGPathElement svgPath = createSVGPathElement();
root.append(svgPath);
if (paint.style == ui.PaintingStyle.stroke ||
(paint.style != ui.PaintingStyle.fill &&
paint.strokeWidth != 0 &&
paint.strokeWidth != null)) {
svgPath.setAttribute('stroke', colorValueToCssString(paint.color));
svgPath.setAttribute('stroke-width', '${paint.strokeWidth ?? 1.0}');
if (paint.strokeCap case final value?) {
svgPath.setAttribute('stroke-linecap', value.name);
}
svgPath.setAttribute('fill', 'none');
} else {
svgPath.setAttribute('fill', colorValueToCssString(paint.color));
}
if (path.fillType == ui.PathFillType.evenOdd) {
svgPath.setAttribute('fill-rule', 'evenodd');
}
svgPath.setAttribute('d', pathToSvg(path.pathRef));
return root;
}

View File

@@ -1,97 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(yjbanov): this file should be deleted as part of https://github.com/flutter/flutter/issues/145954
// because it's only used by the HTML renderer.
List<FrameReference<dynamic>> frameReferences = <FrameReference<dynamic>>[];
/// A temporary reference to a value of type [V].
///
/// The value automatically gets set to null after the current frame is
/// rendered.
///
/// It is useful to think of this as a weak reference that's scoped to a
/// single frame.
class FrameReference<V> {
/// Creates a frame reference to a value.
FrameReference([this.value]) {
frameReferences.add(this);
}
/// The current value of this reference.
V? value;
}
/// Cache where items cached before frame(N) is committed, can be reused in
/// frame(N+1) and are evicted if not.
///
/// A typical use case is image elements. As images are created and added to
/// DOM when painting a scene they are cached and if possible reused on next
/// update. If the next update does not reuse the element, it is evicted.
///
/// Maps are lazily allocated since many pictures don't contain cachable images
/// at all.
class CrossFrameCache<T> {
// Cached items in a scene.
Map<String, List<_CrossFrameCacheItem<T>>>? _cache;
// Cached items that have been committed, ready for reuse on next frame.
Map<String, List<_CrossFrameCacheItem<T>>>? _reusablePool;
// Called when a scene or picture update is committed.
void commitFrame() {
// Evict unused items from prior frame.
if (_reusablePool != null) {
for (final List<_CrossFrameCacheItem<T>> items in _reusablePool!.values) {
for (final _CrossFrameCacheItem<T> item in items) {
item.evict();
}
}
}
// Move cached items to reusable pool.
_reusablePool = _cache;
_cache = null;
}
/// Caches an item for reuse on next update frame.
///
/// Duplicate keys are allowed. For example the same image url may be used
/// to create multiple instances of [ImageElement] to be reused in the future.
void cache(String key, T value, [CrossFrameCacheEvictCallback<T>? callback]) {
_addToCache(key, _CrossFrameCacheItem<T>(value, callback));
}
void _addToCache(String key, _CrossFrameCacheItem<T> item) {
_cache ??= <String, List<_CrossFrameCacheItem<T>>>{};
(_cache![key] ??= <_CrossFrameCacheItem<T>>[]).add(item);
}
/// Given a key, consumes an item that has been cached in a prior frame.
T? reuse(String key) {
if (_reusablePool == null) {
return null;
}
final List<_CrossFrameCacheItem<T>>? items = _reusablePool![key];
if (items == null || items.isEmpty) {
return null;
}
final _CrossFrameCacheItem<T> item = items.removeAt(0);
_addToCache(key, item);
return item.value;
}
}
class _CrossFrameCacheItem<T> {
_CrossFrameCacheItem(this.value, this.evictCallback);
final T value;
final CrossFrameCacheEvictCallback<T>? evictCallback;
void evict() {
if (evictCallback != null) {
evictCallback!(value);
}
}
}
typedef CrossFrameCacheEvictCallback<T> = void Function(T value);

View File

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

View File

@@ -1,122 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import '../color_filter.dart';
import '../dom.dart';
import '../util.dart';
import '../vector_math.dart';
import 'resource_manager.dart';
import 'shaders/shader.dart';
import 'surface.dart';
import 'surface_stats.dart';
/// A surface that applies an [imageFilter] to its children.
class PersistedImageFilter extends PersistedContainerSurface implements ui.ImageFilterEngineLayer {
PersistedImageFilter(PersistedImageFilter? super.oldLayer, this.filter, this.offset);
final ui.ImageFilter filter;
final ui.Offset offset;
@override
void recomputeTransformAndClip() {
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);
}
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);
DomElement? _svgFilter;
@override
DomElement? get childContainer => _childContainer;
DomElement? _childContainer;
@override
void adoptElements(PersistedImageFilter oldSurface) {
super.adoptElements(oldSurface);
_svgFilter = oldSurface._svgFilter;
_childContainer = oldSurface._childContainer;
oldSurface._svgFilter = null;
oldSurface._childContainer = null;
}
@override
void discard() {
super.discard();
ResourceManager.instance.removeResource(_svgFilter);
_svgFilter = null;
_childContainer = null;
}
@override
DomElement createElement() {
final DomElement element = defaultCreateElement('flt-image-filter');
final DomElement container = defaultCreateElement('flt-image-filter-interior');
if (debugExplainSurfaceStats) {
// This creates an additional interior element. Count it too.
surfaceStatsFor(this).allocatedDomNodeCount++;
}
setElementStyle(container, 'position', 'absolute');
setElementStyle(container, 'transform-origin', '0 0 0');
setElementStyle(element, 'position', 'absolute');
setElementStyle(element, 'transform-origin', '0 0 0');
_childContainer = container;
element.appendChild(container);
return element;
}
@override
void apply() {
EngineImageFilter backendFilter;
if (filter is ui.ColorFilter) {
backendFilter = createHtmlColorFilter(filter as EngineColorFilter)!;
} else {
backendFilter = filter as EngineImageFilter;
}
ResourceManager.instance.removeResource(_svgFilter);
_svgFilter = null;
if (backendFilter is ModeHtmlColorFilter) {
_svgFilter = backendFilter.makeSvgFilter(rootElement);
/// Some blendModes do not make an svgFilter. See [EngineHtmlColorFilter.makeSvgFilter()]
if (_svgFilter == null) {
return;
}
} else if (backendFilter is MatrixHtmlColorFilter) {
_svgFilter = backendFilter.makeSvgFilter(rootElement);
}
_childContainer!.style.filter = backendFilter.filterAttribute;
_childContainer!.style.transform = backendFilter.transformAttribute;
rootElement!.style
..left = '${offset.dx}px'
..top = '${offset.dy}px';
}
@override
void update(PersistedImageFilter oldSurface) {
super.update(oldSurface);
if (oldSurface.filter != filter || oldSurface.offset != offset) {
apply();
}
}
}

View File

@@ -1,61 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../util.dart';
import '../vector_math.dart';
import 'surface.dart';
/// A surface that translates its children using CSS transform and translate.
class PersistedOffset extends PersistedContainerSurface implements ui.OffsetEngineLayer {
PersistedOffset(PersistedOffset? super.oldLayer, this.dx, this.dy);
/// Horizontal displacement.
final double dx;
/// Vertical displacement.
final double dy;
@override
void recomputeTransformAndClip() {
transform = parent!.transform;
if (dx != 0.0 || dy != 0.0) {
transform = transform!.clone();
transform!.translate(dx, dy);
}
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);
@override
DomElement createElement() {
final DomElement element = domDocument.createElement('flt-offset');
setElementStyle(element, 'position', 'absolute');
setElementStyle(element, 'transform-origin', '0 0 0');
return element;
}
@override
void apply() {
rootElement!.style.transform = 'translate(${dx}px, ${dy}px)';
}
@override
void update(PersistedOffset oldSurface) {
super.update(oldSurface);
if (oldSurface.dx != dx || oldSurface.dy != dy) {
apply();
}
}
}

View File

@@ -1,63 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../util.dart';
import '../vector_math.dart';
import 'surface.dart';
/// A surface that makes its children transparent.
class PersistedOpacity extends PersistedContainerSurface implements ui.OpacityEngineLayer {
PersistedOpacity(PersistedOpacity? super.oldLayer, this.alpha, this.offset);
final int alpha;
final ui.Offset offset;
@override
void recomputeTransformAndClip() {
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);
}
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);
@override
DomElement createElement() {
final DomElement element = domDocument.createElement('flt-opacity');
setElementStyle(element, 'position', 'absolute');
setElementStyle(element, 'transform-origin', '0 0 0');
return element;
}
@override
void apply() {
final DomElement element = rootElement!;
setElementStyle(element, 'opacity', '${alpha / 255}');
element.style.transform = 'translate(${offset.dx}px, ${offset.dy}px)';
}
@override
void update(PersistedOpacity oldSurface) {
super.update(oldSurface);
if (alpha != oldSurface.alpha || offset != oldSurface.offset) {
apply();
}
}
}

View File

@@ -1,349 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import '../color_filter.dart';
import '../util.dart';
/// Implementation of [ui.Paint] used by the HTML rendering backend.
class SurfacePaint implements ui.Paint {
SurfacePaintData _paintData = SurfacePaintData();
@override
ui.BlendMode get blendMode => _paintData.blendMode ?? ui.BlendMode.srcOver;
@override
set blendMode(ui.BlendMode value) {
if (_frozen) {
_paintData = _paintData.clone();
_frozen = false;
}
_paintData.blendMode = value;
}
@override
ui.PaintingStyle get style => _paintData.style ?? ui.PaintingStyle.fill;
@override
set style(ui.PaintingStyle value) {
if (_frozen) {
_paintData = _paintData.clone();
_frozen = false;
}
_paintData.style = value;
}
@override
double get strokeWidth => _paintData.strokeWidth ?? 0.0;
@override
set strokeWidth(double value) {
if (_frozen) {
_paintData = _paintData.clone();
_frozen = false;
}
_paintData.strokeWidth = value;
}
@override
ui.StrokeCap get strokeCap => _paintData.strokeCap ?? ui.StrokeCap.butt;
@override
set strokeCap(ui.StrokeCap value) {
if (_frozen) {
_paintData = _paintData.clone();
_frozen = false;
}
_paintData.strokeCap = value;
}
@override
ui.StrokeJoin get strokeJoin => _paintData.strokeJoin ?? ui.StrokeJoin.miter;
@override
set strokeJoin(ui.StrokeJoin value) {
if (_frozen) {
_paintData = _paintData.clone();
_frozen = false;
}
_paintData.strokeJoin = value;
}
@override
bool get isAntiAlias => _paintData.isAntiAlias;
@override
set isAntiAlias(bool value) {
if (_frozen) {
_paintData = _paintData.clone();
_frozen = false;
}
_paintData.isAntiAlias = value;
}
@override
ui.Color get color => ui.Color(_paintData.color);
@override
set color(ui.Color value) {
if (_frozen) {
_paintData = _paintData.clone();
_frozen = false;
}
_paintData.color = value.value;
}
@override
bool invertColors = false;
@override
ui.Shader? get shader => _paintData.shader;
@override
set shader(ui.Shader? value) {
if (_frozen) {
_paintData = _paintData.clone();
_frozen = false;
}
_paintData.shader = value;
}
@override
ui.MaskFilter? get maskFilter => _paintData.maskFilter;
@override
set maskFilter(ui.MaskFilter? value) {
if (_frozen) {
_paintData = _paintData.clone();
_frozen = false;
}
_paintData.maskFilter = value;
}
@override
ui.FilterQuality get filterQuality => _paintData.filterQuality ?? ui.FilterQuality.none;
@override
set filterQuality(ui.FilterQuality value) {
if (_frozen) {
_paintData = _paintData.clone();
_frozen = false;
}
_paintData.filterQuality = value;
}
@override
ui.ColorFilter? get colorFilter => _paintData.colorFilter;
@override
set colorFilter(ui.ColorFilter? value) {
if (_frozen) {
_paintData = _paintData.clone();
_frozen = false;
}
_paintData.colorFilter = value as EngineColorFilter?;
}
// TODO(ferhat): see https://github.com/flutter/flutter/issues/33605
@override
double strokeMiterLimit = 4.0;
// TODO(ferhat): Implement ImageFilter, flutter/flutter#35156.
@override
ui.ImageFilter? imageFilter;
// True if Paint instance has used in RecordingCanvas.
bool _frozen = false;
// Marks this paint object as previously used.
SurfacePaintData get paintData {
// Flip bit so next time object gets mutated we create a clone of
// current paint data.
_frozen = true;
return _paintData;
}
// Must be kept in sync with the default in paint.cc.
static const double _kStrokeMiterLimitDefault = 4.0;
// Must be kept in sync with the default in paint.cc.
static const int _kColorDefault = 0xFF000000;
// Must be kept in sync with the default in paint.cc.
static final int _kBlendModeDefault = ui.BlendMode.srcOver.index;
@override
String toString() {
String resultString = 'Paint()';
assert(() {
final StringBuffer result = StringBuffer();
String semicolon = '';
result.write('Paint(');
if (style == ui.PaintingStyle.stroke) {
result.write('$style');
if (strokeWidth != 0.0) {
result.write(' ${strokeWidth.toStringAsFixed(1)}');
} else {
result.write(' hairline');
}
if (strokeCap != ui.StrokeCap.butt) {
result.write(' $strokeCap');
}
if (strokeJoin == ui.StrokeJoin.miter) {
if (strokeMiterLimit != _kStrokeMiterLimitDefault) {
result.write(' $strokeJoin up to ${strokeMiterLimit.toStringAsFixed(1)}');
}
} else {
result.write(' $strokeJoin');
}
semicolon = '; ';
}
if (!isAntiAlias) {
result.write('${semicolon}antialias off');
semicolon = '; ';
}
if (color != const ui.Color(_kColorDefault)) {
result.write('$semicolon$color');
semicolon = '; ';
}
if (blendMode.index != _kBlendModeDefault) {
result.write('$semicolon$blendMode');
semicolon = '; ';
}
if (colorFilter != null) {
result.write('${semicolon}colorFilter: $colorFilter');
semicolon = '; ';
}
if (maskFilter != null) {
result.write('${semicolon}maskFilter: $maskFilter');
semicolon = '; ';
}
if (filterQuality != ui.FilterQuality.none) {
result.write('${semicolon}filterQuality: $filterQuality');
semicolon = '; ';
}
if (shader != null) {
result.write('${semicolon}shader: $shader');
semicolon = '; ';
}
if (imageFilter != null) {
result.write('${semicolon}imageFilter: $imageFilter');
semicolon = '; ';
}
if (invertColors) {
result.write('${semicolon}invert: $invertColors');
}
result.write(')');
resultString = result.toString();
return true;
}());
return resultString;
}
}
/// Private Paint context data used for recording canvas commands allowing
/// Paint to be mutated post canvas draw operations.
class SurfacePaintData {
ui.BlendMode? blendMode;
ui.PaintingStyle? style;
double? strokeWidth;
ui.StrokeCap? strokeCap;
ui.StrokeJoin? strokeJoin;
bool isAntiAlias = true;
int color = 0xFF000000;
ui.Shader? shader;
ui.MaskFilter? maskFilter;
ui.FilterQuality? filterQuality;
EngineColorFilter? colorFilter;
// Internal for recording canvas use.
SurfacePaintData clone() {
return SurfacePaintData()
..blendMode = blendMode
..filterQuality = filterQuality
..maskFilter = maskFilter
..shader = shader
..isAntiAlias = isAntiAlias
..color = color
..colorFilter = colorFilter
..strokeWidth = strokeWidth
..style = style
..strokeJoin = strokeJoin
..strokeCap = strokeCap;
}
@override
String toString() {
String result = super.toString();
assert(() {
final StringBuffer buffer = StringBuffer('SurfacePaintData(');
if (blendMode != null) {
buffer.write('blendMode = $blendMode; ');
}
if (style != null) {
buffer.write('style = $style; ');
}
if (strokeWidth != null) {
buffer.write('strokeWidth = $strokeWidth; ');
}
if (strokeCap != null) {
buffer.write('strokeCap = $strokeCap; ');
}
if (strokeJoin != null) {
buffer.write('strokeJoin = $strokeJoin; ');
}
buffer.write('color = ${ui.Color(color).toCssString()}; ');
if (shader != null) {
buffer.write('shader = $shader; ');
}
if (maskFilter != null) {
buffer.write('maskFilter = $maskFilter; ');
}
if (filterQuality != null) {
buffer.write('filterQuality = $filterQuality; ');
}
if (colorFilter != null) {
buffer.write('colorFilter = $colorFilter; ');
}
buffer.write('isAntiAlias = $isAntiAlias)');
result = buffer.toString();
return true;
}());
return result;
}
}
class HtmlFragmentProgram implements ui.FragmentProgram {
@override
ui.FragmentShader fragmentShader() {
throw UnsupportedError('FragmentProgram is not supported for the HTML renderer.');
}
}
class HtmlFragmentShader implements ui.FragmentShader {
@override
void setFloat(int index, double value) {
throw UnsupportedError('FragmentShader is not supported for the HTML renderer.');
}
@override
void setImageSampler(int index, ui.Image image) {
throw UnsupportedError('FragmentShader is not supported for the HTML renderer.');
}
@override
void dispose() {
throw UnsupportedError('FragmentShader is not supported for the HTML renderer.');
}
@override
bool get debugDisposed {
throw UnsupportedError('FragmentShader is not supported for the HTML renderer.');
}
}

View File

@@ -1,468 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'path_utils.dart';
/// Converts conic curve to a list of quadratic curves for rendering on
/// canvas or conversion to svg.
///
/// See "High order approximation of conic sections by quadratic splines"
/// by Michael Floater, 1993.
/// Skia implementation reference:
/// https://github.com/google/skia/blob/main/src/core/SkGeometry.cpp
class Conic {
Conic(this.p0x, this.p0y, this.p1x, this.p1y, this.p2x, this.p2y, this.fW);
double p0x, p0y, p1x, p1y, p2x, p2y;
final double fW;
static const int _maxSubdivisionCount = 5;
/// Returns array of points for the approximation of the conic as quad(s).
///
/// First offset is start Point. Each pair of offsets after are quadratic
/// control and end points.
List<ui.Offset> toQuads() {
final List<ui.Offset> pointList = <ui.Offset>[];
// This value specifies error bound.
const double conicTolerance = 1.0 / 4.0;
// Based on error bound, compute how many times we should subdivide
final int subdivideCount = _computeSubdivisionCount(conicTolerance);
// Split conic into quads, writes quad coordinates into [_pointList] and
// returns number of quads.
assert(subdivideCount >= 0 && subdivideCount <= _maxSubdivisionCount);
int quadCount = 1 << subdivideCount;
bool skipSubdivide = false;
pointList.add(ui.Offset(p0x, p0y));
if (subdivideCount == _maxSubdivisionCount) {
// We have an extreme number of quads, chop this conic and check if
// it generates a pair of lines, in which case we should not subdivide.
final _ConicPair dst = _ConicPair();
_chop(dst);
final Conic conic0 = dst.first!;
final Conic conic1 = dst.second!;
// If this chop generates pair of lines no need to subdivide.
if (conic0.p1x == conic0.p2x &&
conic0.p1y == conic0.p2y &&
conic1.p0x == conic1.p1x &&
conic1.p0y == conic1.p1y) {
final ui.Offset controlPointOffset = ui.Offset(conic0.p1x, conic0.p1y);
pointList.add(controlPointOffset);
pointList.add(controlPointOffset);
pointList.add(controlPointOffset);
pointList.add(ui.Offset(conic1.p2x, conic1.p2y));
quadCount = 2;
skipSubdivide = true;
}
}
if (!skipSubdivide) {
_subdivide(this, subdivideCount, pointList);
}
// If there are any non-finite generated points, pin to middle of hull.
final int pointCount = 2 * quadCount + 1;
bool hasNonFinitePoints = false;
for (int p = 0; p < pointCount; ++p) {
if (pointList[p].dx.isNaN || pointList[p].dy.isNaN) {
hasNonFinitePoints = true;
break;
}
}
if (hasNonFinitePoints) {
for (int p = 1; p < pointCount - 1; ++p) {
pointList[p] = ui.Offset(p1x, p1y);
}
}
return pointList;
}
// Subdivides a conic and writes to points list.
static void _subdivide(Conic src, int level, List<ui.Offset> pointList) {
assert(level >= 0);
if (0 == level) {
// At lowest subdivision point, copy control point and end point to
// target.
pointList.add(ui.Offset(src.p1x, src.p1y));
pointList.add(ui.Offset(src.p2x, src.p2y));
return;
}
final _ConicPair dst = _ConicPair();
src._chop(dst);
final Conic conic0 = dst.first!;
final Conic conic1 = dst.second!;
final double startY = src.p0y;
final double endY = src.p2y;
final double cpY = src.p1y;
if (SPath.between(startY, cpY, endY)) {
// Ensure that chopped conics maintain their y-order.
final double midY = conic0.p2y;
if (!SPath.between(startY, midY, endY)) {
// The computed midpoint is outside end points, move it to
// closer one.
final double closerY = (midY - startY).abs() < (midY - endY).abs() ? startY : endY;
conic0.p2y = conic1.p0y = closerY;
}
if (!SPath.between(startY, conic0.p1y, conic0.p2y)) {
// First control point not between start and end points, move it
// to start.
conic0.p1y = startY;
}
if (!SPath.between(conic1.p0y, conic1.p1y, endY)) {
// Second control point not between start and end points, move it
// to end.
conic1.p1y = endY;
}
// Verify that conics points are ordered.
assert(SPath.between(startY, conic0.p1y, conic0.p2y));
assert(SPath.between(conic0.p1y, conic0.p2y, conic1.p1y));
assert(SPath.between(conic0.p2y, conic1.p1y, endY));
}
--level;
_subdivide(conic0, level, pointList);
_subdivide(conic1, level, pointList);
}
static double _subdivideWeightValue(double w) {
return math.sqrt(0.5 + w * 0.5);
}
// Splits conic into 2 parts based on weight.
void _chop(_ConicPair pair) {
final double scale = 1.0 / (1.0 + fW);
final double newW = _subdivideWeightValue(fW);
final ui.Offset wp1 = ui.Offset(fW * p1x, fW * p1y);
ui.Offset m = ui.Offset(
(p0x + (2 * wp1.dx) + p2x) * scale * 0.5,
(p0y + 2 * wp1.dy + p2y) * scale * 0.5,
);
if (m.dx.isNaN || m.dy.isNaN) {
final double w2 = fW * 2;
final double scaleHalf = 1.0 / (1 + fW) * 0.5;
m = ui.Offset((p0x + (w2 * p1x) + p2x) * scaleHalf, (p0y + (w2 * p1y) + p2y) * scaleHalf);
}
pair.first = Conic(p0x, p0y, (p0x + wp1.dx) * scale, (p0y + wp1.dy) * scale, m.dx, m.dy, newW);
pair.second = Conic(m.dx, m.dy, (p2x + wp1.dx) * scale, (p2y + wp1.dy) * scale, p2x, p2y, newW);
}
void chopAtYExtrema(List<Conic> dst) {
final double? t = _findYExtrema();
if (t == null) {
dst.add(this);
return;
}
if (!_chopAt(t, dst, cleanupMiddle: true)) {
// If chop can't return finite values, don't chop.
dst.add(this);
return;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// NURB representation for conics. Helpful explanations at:
//
// http://citeseerx.ist.psu.edu/viewdoc/
// download?doi=10.1.1.44.5740&rep=rep1&type=ps
// and
// http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/NURBS/RB-conics.html
//
// F = (A (1 - t)^2 + C t^2 + 2 B (1 - t) t w)
// ------------------------------------------
// ((1 - t)^2 + t^2 + 2 (1 - t) t w)
//
// = {t^2 (P0 + P2 - 2 P1 w), t (-2 P0 + 2 P1 w), P0}
// ------------------------------------------------
// {t^2 (2 - 2 w), t (-2 + 2 w), 1}
//
// F' = 2 (C t (1 + t (-1 + w)) - A (-1 + t) (t (-1 + w) - w) + B (1 - 2 t) w)
//
// t^2 : (2 P0 - 2 P2 - 2 P0 w + 2 P2 w)
// t^1 : (-2 P0 + 2 P2 + 4 P0 w - 4 P1 w)
// t^0 : -2 P0 w + 2 P1 w
//
// We disregard magnitude, so we can freely ignore the denominator of F', and
// divide the numerator by 2
//
// coeff[0] for t^2
// coeff[1] for t^1
// coeff[2] for t^0
//
double? _findYExtrema() {
final double p20 = p2y - p0y;
final double p10 = p1y - p0y;
final double wP10 = fW * p10;
final double coeff0 = fW * p20 - p20;
final double coeff1 = p20 - 2 * wP10;
final double coeff2 = wP10;
final QuadRoots quadRoots = QuadRoots();
final int rootCount = quadRoots.findRoots(coeff0, coeff1, coeff2);
assert(rootCount == 0 || rootCount == 1);
if (rootCount == 1) {
return quadRoots.root0;
}
return null;
}
bool _chopAt(double t, List<Conic> dst, {bool cleanupMiddle = false}) {
// Map conic to 3D.
final double tx0 = p0x;
final double ty0 = p0y;
const double tz0 = 1;
final double tx1 = p1x * fW;
final double ty1 = p1y * fW;
final double tz1 = fW;
final double tx2 = p2x;
final double ty2 = p2y;
const double tz2 = 1;
// Now interpolate each dimension.
final double dx0 = tx0 + (tx1 - tx0) * t;
final double dx2 = tx1 + (tx2 - tx1) * t;
final double dx1 = dx0 + (dx2 - dx0) * t;
final double dy0 = ty0 + (ty1 - ty0) * t;
final double dy2 = ty1 + (ty2 - ty1) * t;
final double dy1 = dy0 + (dy2 - dy0) * t;
final double dz0 = tz0 + (tz1 - tz0) * t;
final double dz2 = tz1 + (tz2 - tz1) * t;
final double dz1 = dz0 + (dz2 - dz0) * t;
// Compute new weights.
final double root = math.sqrt(dz1);
if (SPath.nearlyEqual(root, 0)) {
return false;
}
final double w0 = dz0 / root;
final double w2 = dz2 / root;
if (SPath.nearlyEqual(dz0, 0) || SPath.nearlyEqual(dz1, 0) || SPath.nearlyEqual(dz2, 0)) {
return false;
}
// Now we can construct the 2 conics by projecting 3D down to 2D.
final double chopPointX = dx1 / dz1;
final double chopPointY = dy1 / dz1;
double cp0y = dy0 / dz0;
double cp1y = dy2 / dz2;
if (cleanupMiddle) {
// Clean-up the middle, since we know t was meant to be at
// an Y-extrema.
cp0y = chopPointY;
cp1y = chopPointY;
}
final Conic conic0 = Conic(p0x, p0y, dx0 / dz0, cp0y, chopPointX, chopPointY, w0);
final Conic conic1 = Conic(chopPointX, chopPointY, dx2 / dz2, cp1y, p2x, p2y, w2);
dst.add(conic0);
dst.add(conic1);
return true;
}
/// Computes number of binary subdivisions of the curve given
/// the tolerance.
///
/// The number of subdivisions never exceed [_maxSubdivisionCount].
int _computeSubdivisionCount(double tolerance) {
assert(tolerance.isFinite);
// Expecting finite coordinates.
assert(
p0x.isFinite && p1x.isFinite && p2x.isFinite && p0y.isFinite && p1y.isFinite && p2y.isFinite,
);
if (tolerance < 0) {
return 0;
}
// See "High order approximation of conic sections by quadratic splines"
// by Michael Floater, 1993.
// Error bound e0 = |a| |p0 - 2p1 + p2| / 4(2 + a).
final double a = fW - 1;
final double k = a / (4.0 * (2.0 + a));
final double x = k * (p0x - 2 * p1x + p2x);
final double y = k * (p0y - 2 * p1y + p2y);
double error = math.sqrt(x * x + y * y);
int pow2 = 0;
for (; pow2 < _maxSubdivisionCount; ++pow2) {
if (error <= tolerance) {
break;
}
error *= 0.25;
}
return pow2;
}
ui.Offset evalTangentAt(double t) {
// The derivative equation returns a zero tangent vector when t is 0 or 1,
// and the control point is equal to the end point.
// In this case, use the conic endpoints to compute the tangent.
if ((t == 0 && p0x == p1x && p0y == p1y) || (t == 1 && p1x == p2x && p1y == p2y)) {
return ui.Offset(p2x - p0x, p2y - p0y);
}
final double p20x = p2x - p0x;
final double p20y = p2y - p0y;
final double p10x = p1x - p0x;
final double p10y = p1y - p0y;
final double cx = fW * p10x;
final double cy = fW * p10y;
final double ax = fW * p20x - p20x;
final double ay = fW * p20y - p20y;
final double bx = p20x - cx - cx;
final double by = p20y - cy - cy;
final SkQuadCoefficients quadC = SkQuadCoefficients(ax, ay, bx, by, cx, cy);
return ui.Offset(quadC.evalX(t), quadC.evalY(t));
}
static double evalNumerator(double p0, double p1, double p2, double w, double t) {
assert(t >= 0 && t <= 1);
final double src2w = p1 * w;
final double C = p0;
final double A = p2 - 2 * src2w + C;
final double B = 2 * (src2w - C);
return polyEval(A, B, C, t);
}
static double evalDenominator(double w, double t) {
final double B = 2 * (w - 1);
const double C = 1;
final double A = -B;
return polyEval(A, B, C, t);
}
}
class QuadBounds {
double minX = 0;
double minY = 0;
double maxX = 0;
double maxY = 0;
void calculateBounds(Float32List points, int pointIndex) {
final double x1 = points[pointIndex++];
final double y1 = points[pointIndex++];
final double cpX = points[pointIndex++];
final double cpY = points[pointIndex++];
final double x2 = points[pointIndex++];
final double y2 = points[pointIndex++];
minX = math.min(x1, x2);
minY = math.min(y1, y2);
maxX = math.max(x1, x2);
maxY = math.max(y1, y2);
// At extrema's derivative = 0.
// Solve for
// -2x1+2tx1 + 2cpX + 4tcpX + 2tx2 = 0
// -2x1 + 2cpX +2t(x1 + 2cpX + x2) = 0
// t = (x1 - cpX) / (x1 - 2cpX + x2)
double denom = x1 - (2 * cpX) + x2;
if (denom.abs() > SPath.scalarNearlyZero) {
final double t1 = (x1 - cpX) / denom;
if ((t1 >= 0) && (t1 <= 1.0)) {
// Solve (x,y) for curve at t = tx to find extrema
final double tprime = 1.0 - t1;
final double extremaX = (tprime * tprime * x1) + (2 * t1 * tprime * cpX) + (t1 * t1 * x2);
final double extremaY = (tprime * tprime * y1) + (2 * t1 * tprime * cpY) + (t1 * t1 * y2);
// Expand bounds.
minX = math.min(minX, extremaX);
maxX = math.max(maxX, extremaX);
minY = math.min(minY, extremaY);
maxY = math.max(maxY, extremaY);
}
}
// Now calculate dy/dt = 0
denom = y1 - (2 * cpY) + y2;
if (denom.abs() > SPath.scalarNearlyZero) {
final double t2 = (y1 - cpY) / denom;
if ((t2 >= 0) && (t2 <= 1.0)) {
final double tprime2 = 1.0 - t2;
final double extrema2X =
(tprime2 * tprime2 * x1) + (2 * t2 * tprime2 * cpX) + (t2 * t2 * x2);
final double extrema2Y =
(tprime2 * tprime2 * y1) + (2 * t2 * tprime2 * cpY) + (t2 * t2 * y2);
// Expand bounds.
minX = math.min(minX, extrema2X);
maxX = math.max(maxX, extrema2X);
minY = math.min(minY, extrema2Y);
maxY = math.max(maxY, extrema2Y);
}
}
}
}
class ConicBounds {
double minX = 0;
double minY = 0;
double maxX = 0;
double maxY = 0;
void calculateBounds(Float32List points, double w, int pointIndex) {
final double x1 = points[pointIndex++];
final double y1 = points[pointIndex++];
final double cpX = points[pointIndex++];
final double cpY = points[pointIndex++];
final double x2 = points[pointIndex++];
final double y2 = points[pointIndex++];
minX = math.min(x1, x2);
minY = math.min(y1, y2);
maxX = math.max(x1, x2);
maxY = math.max(y1, y2);
// {t^2 (P0 + P2 - 2 P1 w), t (-2 P0 + 2 P1 w), P0}
// ------------------------------------------------
// {t^2 (2 - 2 w), t (-2 + 2 w), 1}
// Calculate coefficients and solve root.
final QuadRoots roots = QuadRoots();
final double p20x = x2 - x1;
final double p10x = cpX - x1;
final double wP10x = w * p10x;
final double ax = w * p20x - p20x;
final double bx = p20x - 2 * wP10x;
final double cx = wP10x;
int n = roots.findRoots(ax, bx, cx);
if (n != 0) {
final double t1 = roots.root0!;
if ((t1 >= 0) && (t1 <= 1.0)) {
final double denom = Conic.evalDenominator(w, t1);
double numerator = Conic.evalNumerator(x1, cpX, x2, w, t1);
final double extremaX = numerator / denom;
numerator = Conic.evalNumerator(y1, cpY, y2, w, t1);
final double extremaY = numerator / denom;
// Expand bounds.
minX = math.min(minX, extremaX);
maxX = math.max(maxX, extremaX);
minY = math.min(minY, extremaY);
maxY = math.max(maxY, extremaY);
}
}
final double p20y = y2 - y1;
final double p10y = cpY - y1;
final double wP10y = w * p10y;
final double a = w * p20y - p20y;
final double b = p20y - 2 * wP10y;
final double c = wP10y;
n = roots.findRoots(a, b, c);
if (n != 0) {
final double t2 = roots.root0!;
if ((t2 >= 0) && (t2 <= 1.0)) {
final double denom = Conic.evalDenominator(w, t2);
double numerator = Conic.evalNumerator(x1, cpX, x2, w, t2);
final double extrema2X = numerator / denom;
numerator = Conic.evalNumerator(y1, cpY, y2, w, t2);
final double extrema2Y = numerator / denom;
// Expand bounds.
minX = math.min(minX, extrema2X);
maxX = math.max(maxX, extrema2X);
minY = math.min(minY, extrema2Y);
maxY = math.max(maxY, extrema2Y);
}
}
}
}
class _ConicPair {
Conic? first;
Conic? second;
}

View File

@@ -1,417 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:typed_data';
import 'path_utils.dart';
/// Chops cubic at Y extrema points and writes result to [dest].
///
/// [points] and [dest] are allowed to share underlying storage as long.
int chopCubicAtYExtrema(Float32List points, Float32List dest) {
final double y0 = points[1];
final double y1 = points[3];
final double y2 = points[5];
final double y3 = points[7];
final QuadRoots quadRoots = _findCubicExtrema(y0, y1, y2, y3);
final List<double> roots = quadRoots.roots;
if (roots.isEmpty) {
// No roots, just use input cubic.
return 0;
}
_chopCubicAt(roots, points, dest);
final int rootCount = roots.length;
if (rootCount > 0) {
// Cleanup to ensure Y extrema are flat.
dest[5] = dest[9] = dest[7];
if (rootCount == 2) {
dest[11] = dest[15] = dest[13];
}
}
return rootCount;
}
QuadRoots _findCubicExtrema(double a, double b, double c, double d) {
// A,B,C scaled by 1/3 to simplify
final double A = d - a + 3 * (b - c);
final double B = 2 * (a - b - b + c);
final double C = b - a;
return QuadRoots()..findRoots(A, B, C);
}
/// Subdivides cubic curve for a list of t values.
void _chopCubicAt(List<double> tValues, Float32List points, Float32List outPts) {
assert(() {
for (int i = 0; i < tValues.length - 1; i++) {
final double tValue = tValues[i];
assert(tValue > 0 && tValue < 1, 'Not expecting to chop curve at start, end points');
}
for (int i = 0; i < tValues.length - 1; i++) {
final double tValue = tValues[i];
final double nextTValue = tValues[i + 1];
assert(nextTValue > tValue, 'Expecting t value to monotonically increase');
}
return true;
}());
final int rootCount = tValues.length;
if (0 == rootCount) {
for (int i = 0; i < 8; i++) {
outPts[i] = points[i];
}
} else {
// Chop curve at t value and loop through right side of curve
// while normalizing t value based on prior t.
double? t = tValues[0];
int bufferPos = 0;
for (int i = 0; i < rootCount; i++) {
_chopCubicAtT(points, bufferPos, outPts, bufferPos, t!);
if (i == rootCount - 1) {
break;
}
bufferPos += 6;
// watch out in case the renormalized t isn't in range
if ((t = validUnitDivide(tValues[i + 1] - tValues[i], 1.0 - tValues[i])) == null) {
// Can't renormalize last point, just create a degenerate cubic.
outPts[bufferPos + 4] =
outPts[bufferPos + 5] = outPts[bufferPos + 6] = points[bufferPos + 3];
break;
}
}
}
}
/// Subdivides cubic curve at [t] and writes to [outPts] at position [outIndex].
///
/// The cubic points are read from [points] at [bufferPos] offset.
void _chopCubicAtT(Float32List points, int bufferPos, Float32List outPts, int outIndex, double t) {
assert(t > 0 && t < 1);
final double p3y = points[bufferPos + 7];
final double p0x = points[bufferPos + 0];
final double p0y = points[bufferPos + 1];
final double p1x = points[bufferPos + 2];
final double p1y = points[bufferPos + 3];
final double p2x = points[bufferPos + 4];
final double p2y = points[bufferPos + 5];
final double p3x = points[bufferPos + 6];
// If startT == 0 chop at end point and return curve.
final double ab1x = interpolate(p0x, p1x, t);
final double ab1y = interpolate(p0y, p1y, t);
final double bc1x = interpolate(p1x, p2x, t);
final double bc1y = interpolate(p1y, p2y, t);
final double cd1x = interpolate(p2x, p3x, t);
final double cd1y = interpolate(p2y, p3y, t);
final double abc1x = interpolate(ab1x, bc1x, t);
final double abc1y = interpolate(ab1y, bc1y, t);
final double bcd1x = interpolate(bc1x, cd1x, t);
final double bcd1y = interpolate(bc1y, cd1y, t);
final double abcd1x = interpolate(abc1x, bcd1x, t);
final double abcd1y = interpolate(abc1y, bcd1y, t);
// Return left side of curve.
outPts[outIndex++] = p0x;
outPts[outIndex++] = p0y;
outPts[outIndex++] = ab1x;
outPts[outIndex++] = ab1y;
outPts[outIndex++] = abc1x;
outPts[outIndex++] = abc1y;
outPts[outIndex++] = abcd1x;
outPts[outIndex++] = abcd1y;
// Return right side of curve.
outPts[outIndex++] = bcd1x;
outPts[outIndex++] = bcd1y;
outPts[outIndex++] = cd1x;
outPts[outIndex++] = cd1y;
outPts[outIndex++] = p3x;
outPts[outIndex++] = p3y;
}
// Returns t at Y for cubic curve. null if y is out of range.
//
// Options are Newton Raphson (quadratic convergence with typically
// 3 iterations or bisection with 16 iterations.
double? chopMonoAtY(Float32List buffer, int bufferStartPos, double y) {
// Translate curve points relative to y.
final double ycrv0 = buffer[1 + bufferStartPos] - y;
final double ycrv1 = buffer[3 + bufferStartPos] - y;
final double ycrv2 = buffer[5 + bufferStartPos] - y;
final double ycrv3 = buffer[7 + bufferStartPos] - y;
// Positive and negative function parameters.
double tNeg, tPos;
// Set initial t points to converge from.
if (ycrv0 < 0) {
if (ycrv3 < 0) {
// Start and end points out of range.
return null;
}
tNeg = 0;
tPos = 1.0;
} else if (ycrv0 > 0) {
tNeg = 1.0;
tPos = 0;
} else {
// Start is at y.
return 0.0;
}
// Bisection / linear convergance.
const double tolerance = 1.0 / 65536;
do {
final double tMid = (tPos + tNeg) / 2.0;
final double y01 = ycrv0 + (ycrv1 - ycrv0) * tMid;
final double y12 = ycrv1 + (ycrv2 - ycrv1) * tMid;
final double y23 = ycrv2 + (ycrv3 - ycrv2) * tMid;
final double y012 = y01 + (y12 - y01) * tMid;
final double y123 = y12 + (y23 - y12) * tMid;
final double y0123 = y012 + (y123 - y012) * tMid;
if (y0123 == 0) {
return tMid;
}
if (y0123 < 0) {
tNeg = tMid;
} else {
tPos = tMid;
}
} while ((tPos - tNeg).abs() > tolerance);
return (tNeg + tPos) / 2;
}
double evalCubicPts(double c0, double c1, double c2, double c3, double t) {
final double A = c3 + 3 * (c1 - c2) - c0;
final double B = 3 * (c2 - c1 - c1 + c0);
final double C = 3 * (c1 - c0);
final double D = c0;
return polyEval4(A, B, C, D, t);
}
// Reusable class to compute bounds without object allocation.
class CubicBounds {
double minX = 0.0;
double maxX = 0.0;
double minY = 0.0;
double maxY = 0.0;
/// Sets resulting bounds as [minX], [minY], [maxX], [maxY].
///
/// The cubic is defined by 4 points (8 floats) in [points].
void calculateBounds(Float32List points, int pointIndex) {
final double startX = points[pointIndex++];
final double startY = points[pointIndex++];
final double cpX1 = points[pointIndex++];
final double cpY1 = points[pointIndex++];
final double cpX2 = points[pointIndex++];
final double cpY2 = points[pointIndex++];
final double endX = points[pointIndex++];
final double endY = points[pointIndex++];
// Bounding box is defined by all points on the curve where
// monotonicity changes.
minX = math.min(startX, endX);
minY = math.min(startY, endY);
maxX = math.max(startX, endX);
maxY = math.max(startY, endY);
double extremaX;
double extremaY;
double a, b, c;
// Check for simple case of strong ordering before calculating
// extrema
if (!(((startX < cpX1) && (cpX1 < cpX2) && (cpX2 < endX)) ||
((startX > cpX1) && (cpX1 > cpX2) && (cpX2 > endX)))) {
// The extrema point is dx/dt B(t) = 0
// The derivative of B(t) for cubic bezier is a quadratic equation
// with multiple roots
// B'(t) = a*t*t + b*t + c*t
a = -startX + (3 * (cpX1 - cpX2)) + endX;
b = 2 * (startX - (2 * cpX1) + cpX2);
c = -startX + cpX1;
// Now find roots for quadratic equation with known coefficients
// a,b,c
// The roots are (-b+-sqrt(b*b-4*a*c)) / 2a
num s = (b * b) - (4 * a * c);
// If s is negative, we have no real roots
if ((s >= 0.0) && (a.abs() > SPath.scalarNearlyZero)) {
if (s == 0.0) {
// we have only 1 root
final double t = -b / (2 * a);
final double tprime = 1.0 - t;
if ((t >= 0.0) && (t <= 1.0)) {
extremaX =
((tprime * tprime * tprime) * startX) +
((3 * tprime * tprime * t) * cpX1) +
((3 * tprime * t * t) * cpX2) +
(t * t * t * endX);
minX = math.min(extremaX, minX);
maxX = math.max(extremaX, maxX);
}
} else {
// we have 2 roots
s = math.sqrt(s);
double t = (-b - s) / (2 * a);
double tprime = 1.0 - t;
if ((t >= 0.0) && (t <= 1.0)) {
extremaX =
((tprime * tprime * tprime) * startX) +
((3 * tprime * tprime * t) * cpX1) +
((3 * tprime * t * t) * cpX2) +
(t * t * t * endX);
minX = math.min(extremaX, minX);
maxX = math.max(extremaX, maxX);
}
// check 2nd root
t = (-b + s) / (2 * a);
tprime = 1.0 - t;
if ((t >= 0.0) && (t <= 1.0)) {
extremaX =
((tprime * tprime * tprime) * startX) +
((3 * tprime * tprime * t) * cpX1) +
((3 * tprime * t * t) * cpX2) +
(t * t * t * endX);
minX = math.min(extremaX, minX);
maxX = math.max(extremaX, maxX);
}
}
}
}
// Now calc extremes for dy/dt = 0 just like above
if (!(((startY < cpY1) && (cpY1 < cpY2) && (cpY2 < endY)) ||
((startY > cpY1) && (cpY1 > cpY2) && (cpY2 > endY)))) {
// The extrema point is dy/dt B(t) = 0
// The derivative of B(t) for cubic bezier is a quadratic equation
// with multiple roots
// B'(t) = a*t*t + b*t + c*t
a = -startY + (3 * (cpY1 - cpY2)) + endY;
b = 2 * (startY - (2 * cpY1) + cpY2);
c = -startY + cpY1;
// Now find roots for quadratic equation with known coefficients
// a,b,c
// The roots are (-b+-sqrt(b*b-4*a*c)) / 2a
double s = (b * b) - (4 * a * c);
// If s is negative, we have no real roots
if ((s >= 0.0) && (a.abs() > SPath.scalarNearlyZero)) {
if (s == 0.0) {
// we have only 1 root
final double t = -b / (2 * a);
final double tprime = 1.0 - t;
if ((t >= 0.0) && (t <= 1.0)) {
extremaY =
((tprime * tprime * tprime) * startY) +
((3 * tprime * tprime * t) * cpY1) +
((3 * tprime * t * t) * cpY2) +
(t * t * t * endY);
minY = math.min(extremaY, minY);
maxY = math.max(extremaY, maxY);
}
} else {
// we have 2 roots
s = math.sqrt(s);
final double t = (-b - s) / (2 * a);
final double tprime = 1.0 - t;
if ((t >= 0.0) && (t <= 1.0)) {
extremaY =
((tprime * tprime * tprime) * startY) +
((3 * tprime * tprime * t) * cpY1) +
((3 * tprime * t * t) * cpY2) +
(t * t * t * endY);
minY = math.min(extremaY, minY);
maxY = math.max(extremaY, maxY);
}
// check 2nd root
final double t2 = (-b + s) / (2 * a);
final double tprime2 = 1.0 - t2;
if ((t2 >= 0.0) && (t2 <= 1.0)) {
extremaY =
((tprime2 * tprime2 * tprime2) * startY) +
((3 * tprime2 * tprime2 * t2) * cpY1) +
((3 * tprime2 * t2 * t2) * cpY2) +
(t2 * t2 * t2 * endY);
minY = math.min(extremaY, minY);
maxY = math.max(extremaY, maxY);
}
}
}
}
}
}
/// Chops cubic spline at startT and stopT, writes result to buffer.
void chopCubicBetweenT(List<double> points, double startT, double stopT, Float32List buffer) {
assert(startT != 0 || stopT != 0);
final double p3y = points[7];
final double p0x = points[0];
final double p0y = points[1];
final double p1x = points[2];
final double p1y = points[3];
final double p2x = points[4];
final double p2y = points[5];
final double p3x = points[6];
// If startT == 0 chop at end point and return curve.
final bool chopStart = startT != 0;
final double t = chopStart ? startT : stopT;
final double ab1x = interpolate(p0x, p1x, t);
final double ab1y = interpolate(p0y, p1y, t);
final double bc1x = interpolate(p1x, p2x, t);
final double bc1y = interpolate(p1y, p2y, t);
final double cd1x = interpolate(p2x, p3x, t);
final double cd1y = interpolate(p2y, p3y, t);
final double abc1x = interpolate(ab1x, bc1x, t);
final double abc1y = interpolate(ab1y, bc1y, t);
final double bcd1x = interpolate(bc1x, cd1x, t);
final double bcd1y = interpolate(bc1y, cd1y, t);
final double abcd1x = interpolate(abc1x, bcd1x, t);
final double abcd1y = interpolate(abc1y, bcd1y, t);
if (!chopStart) {
// Return left side of curve.
buffer[0] = p0x;
buffer[1] = p0y;
buffer[2] = ab1x;
buffer[3] = ab1y;
buffer[4] = abc1x;
buffer[5] = abc1y;
buffer[6] = abcd1x;
buffer[7] = abcd1y;
return;
}
if (stopT == 1) {
// Return right side of curve.
buffer[0] = abcd1x;
buffer[1] = abcd1y;
buffer[2] = bcd1x;
buffer[3] = bcd1y;
buffer[4] = cd1x;
buffer[5] = cd1y;
buffer[6] = p3x;
buffer[7] = p3y;
return;
}
// We chopped at startT, now the right hand side of curve is at
// abcd1, bcd1, cd1, p3x, p3y. Chop this part using endT;
final double endT = (stopT - startT) / (1 - startT);
final double ab2x = interpolate(abcd1x, bcd1x, endT);
final double ab2y = interpolate(abcd1y, bcd1y, endT);
final double bc2x = interpolate(bcd1x, cd1x, endT);
final double bc2y = interpolate(bcd1y, cd1y, endT);
final double cd2x = interpolate(cd1x, p3x, endT);
final double cd2y = interpolate(cd1y, p3y, endT);
final double abc2x = interpolate(ab2x, bc2x, endT);
final double abc2y = interpolate(ab2y, bc2y, endT);
final double bcd2x = interpolate(bc2x, cd2x, endT);
final double bcd2y = interpolate(bc2y, cd2y, endT);
final double abcd2x = interpolate(abc2x, bcd2x, endT);
final double abcd2y = interpolate(abc2y, bcd2y, endT);
buffer[0] = abcd1x;
buffer[1] = abcd1y;
buffer[2] = ab2x;
buffer[3] = ab2y;
buffer[4] = abc2x;
buffer[5] = abc2y;
buffer[6] = abcd2x;
buffer[7] = abcd2y;
}

View File

@@ -1,209 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'path_ref.dart';
import 'path_utils.dart';
// Iterates through path including generating closing segments.
class PathIterator {
PathIterator(this.pathRef, bool forceClose)
: _forceClose = forceClose,
_verbCount = pathRef.countVerbs() {
_pointIndex = 0;
if (!pathRef.isFinite) {
// Don't allow iteration through non-finite points, prepare to return
// done verb.
_verbIndex = pathRef.countVerbs();
}
}
final PathRef pathRef;
final bool _forceClose;
final int _verbCount;
bool _needClose = false;
int _segmentState = SPathSegmentState.kEmptyContour;
int _conicWeightIndex = -1;
double _lastPointX = 0;
double _lastPointY = 0;
double _moveToX = 0;
double _moveToY = 0;
int _verbIndex = 0;
int _pointIndex = 0;
int get pathVerbIndex => _verbIndex;
int get conicWeightIndex => _conicWeightIndex;
/// Maximum buffer size required for points in [next] calls.
static const int kMaxBufferSize = 8;
/// Returns true if first contour on path is closed.
bool isClosedContour() {
if (_verbCount == 0 || _verbIndex == _verbCount) {
return false;
}
if (_forceClose) {
return true;
}
int verbIndex = 0;
// Skip starting moveTo.
if (pathRef.atVerb(verbIndex) == SPath.kMoveVerb) {
++verbIndex;
}
while (verbIndex < _verbCount) {
final int verb = pathRef.atVerb(verbIndex++);
if (SPath.kMoveVerb == verb) {
break;
}
if (SPath.kCloseVerb == verb) {
return true;
}
}
return false;
}
int _autoClose(Float32List outPts) {
if (_lastPointX != _moveToX || _lastPointY != _moveToY) {
// Handle special case where comparison above will return true for
// NaN != NaN although it should be false.
if (_lastPointX.isNaN || _lastPointY.isNaN || _moveToX.isNaN || _moveToY.isNaN) {
return SPath.kCloseVerb;
}
outPts[0] = _lastPointX;
outPts[1] = _lastPointY;
outPts[2] = _moveToX;
outPts[3] = _moveToY;
_lastPointX = _moveToX;
_lastPointY = _moveToY;
return SPath.kLineVerb;
} else {
outPts[0] = _moveToX;
outPts[1] = _moveToY;
return SPath.kCloseVerb;
}
}
// Returns true if caller should use moveTo, false if last point of
// previous primitive.
ui.Offset _constructMoveTo() {
if (_segmentState == SPathSegmentState.kAfterMove) {
// Set the first return point to move point.
_segmentState = SPathSegmentState.kAfterPrimitive;
return ui.Offset(_moveToX, _moveToY);
}
return ui.Offset(pathRef.points[_pointIndex - 2], pathRef.points[_pointIndex - 1]);
}
int peek() {
if (_verbIndex < pathRef.countVerbs()) {
return pathRef.atVerb(_verbIndex);
}
if (_needClose && _segmentState == SPathSegmentState.kAfterPrimitive) {
return (_lastPointX != _moveToX || _lastPointY != _moveToY)
? SPath.kLineVerb
: SPath.kCloseVerb;
}
return SPath.kDoneVerb;
}
// Returns next verb and reads associated points into [outPts].
int next(Float32List outPts) {
if (_verbIndex == pathRef.countVerbs()) {
// Close the curve if requested and if there is some curve to close
if (_needClose && _segmentState == SPathSegmentState.kAfterPrimitive) {
if (SPath.kLineVerb == _autoClose(outPts)) {
return SPath.kLineVerb;
}
_needClose = false;
return SPath.kCloseVerb;
}
return SPath.kDoneVerb;
}
int verb = pathRef.atVerb(_verbIndex++);
switch (verb) {
case SPath.kMoveVerb:
if (_needClose) {
// Move back one verb.
_verbIndex--;
final int autoVerb = _autoClose(outPts);
if (autoVerb == SPath.kCloseVerb) {
_needClose = false;
}
return autoVerb;
}
if (_verbIndex == _verbCount) {
return SPath.kDoneVerb;
}
final double offsetX = pathRef.points[_pointIndex++];
final double offsetY = pathRef.points[_pointIndex++];
_moveToX = offsetX;
_moveToY = offsetY;
outPts[0] = offsetX;
outPts[1] = offsetY;
_segmentState = SPathSegmentState.kAfterMove;
_lastPointX = _moveToX;
_lastPointY = _moveToY;
_needClose = _forceClose;
case SPath.kLineVerb:
final ui.Offset start = _constructMoveTo();
final double offsetX = pathRef.points[_pointIndex++];
final double offsetY = pathRef.points[_pointIndex++];
outPts[0] = start.dx;
outPts[1] = start.dy;
outPts[2] = offsetX;
outPts[3] = offsetY;
_lastPointX = offsetX;
_lastPointY = offsetY;
case SPath.kConicVerb:
_conicWeightIndex++;
final ui.Offset start = _constructMoveTo();
outPts[0] = start.dx;
outPts[1] = start.dy;
outPts[2] = pathRef.points[_pointIndex++];
outPts[3] = pathRef.points[_pointIndex++];
_lastPointX = outPts[4] = pathRef.points[_pointIndex++];
_lastPointY = outPts[5] = pathRef.points[_pointIndex++];
case SPath.kQuadVerb:
final ui.Offset start = _constructMoveTo();
outPts[0] = start.dx;
outPts[1] = start.dy;
outPts[2] = pathRef.points[_pointIndex++];
outPts[3] = pathRef.points[_pointIndex++];
_lastPointX = outPts[4] = pathRef.points[_pointIndex++];
_lastPointY = outPts[5] = pathRef.points[_pointIndex++];
case SPath.kCubicVerb:
final ui.Offset start = _constructMoveTo();
outPts[0] = start.dx;
outPts[1] = start.dy;
outPts[2] = pathRef.points[_pointIndex++];
outPts[3] = pathRef.points[_pointIndex++];
outPts[4] = pathRef.points[_pointIndex++];
outPts[5] = pathRef.points[_pointIndex++];
_lastPointX = outPts[6] = pathRef.points[_pointIndex++];
_lastPointY = outPts[7] = pathRef.points[_pointIndex++];
case SPath.kCloseVerb:
verb = _autoClose(outPts);
if (verb == SPath.kLineVerb) {
// Move back one verb since we constructed line for this close verb.
_verbIndex--;
} else {
_needClose = false;
_segmentState = SPathSegmentState.kEmptyContour;
}
_lastPointX = _moveToX;
_lastPointY = _moveToY;
case SPath.kDoneVerb:
assert(_verbIndex == pathRef.countVerbs());
default:
throw FormatException('Unsupport Path verb $verb');
}
return verb;
}
double get conicWeight => pathRef.atWeight(_conicWeightIndex);
}

View File

@@ -1,860 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:collection' show IterableBase;
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'conic.dart';
import 'cubic.dart';
import 'path_iterator.dart';
import 'path_ref.dart';
import 'path_utils.dart';
const double kEpsilon = 0.000000001;
/// An iterable collection of [PathMetric] objects describing a [Path].
///
/// A [PathMetrics] object is created by using the [Path.computeMetrics] method,
/// and represents the path as it stood at the time of the call. Subsequent
/// modifications of the path do not affect the [PathMetrics] object.
///
/// Each path metric corresponds to a segment, or contour, of a path.
///
/// For example, a path consisting of a [Path.lineTo], a [Path.moveTo], and
/// another [Path.lineTo] will contain two contours and thus be represented by
/// two [PathMetric] objects.
///
/// When iterating across a [PathMetrics]' contours, the [PathMetric] objects
/// are only valid until the next one is obtained.
class SurfacePathMetrics extends IterableBase<ui.PathMetric> implements ui.PathMetrics {
SurfacePathMetrics(PathRef path, bool forceClosed)
: _iterator = SurfacePathMetricIterator._(
_SurfacePathMeasure(PathRef.shallowCopy(path), forceClosed),
);
final SurfacePathMetricIterator _iterator;
@override
Iterator<ui.PathMetric> get iterator => _iterator;
}
/// Maintains a single instance of computed segments for set of PathMetric
/// objects exposed through iterator.
class _SurfacePathMeasure {
_SurfacePathMeasure(this._path, this.forceClosed)
: // nextContour will increment this to the zero based index.
_currentContourIndex = -1,
_pathIterator = PathIterator(_path, forceClosed);
final PathRef _path;
final PathIterator _pathIterator;
final List<_PathContourMeasure> _contours = <_PathContourMeasure>[];
// If the contour ends with a call to [Path.close] (which may
// have been implied when using [Path.addRect])
final bool forceClosed;
int _currentContourIndex;
int get currentContourIndex => _currentContourIndex;
double length(int contourIndex) {
assert(
contourIndex <= currentContourIndex,
'Iterator must be advanced before index $contourIndex can be used.',
);
return _contours[contourIndex].length;
}
/// Computes the position of hte current contour at the given offset, and the
/// angle of the path at that point.
///
/// For example, calling this method with a distance of 1.41 for a line from
/// 0.0,0.0 to 2.0,2.0 would give a point 1.0,1.0 and the angle 45 degrees
/// (but in radians).
///
/// Returns null if the contour has zero [length].
///
/// The distance is clamped to the [length] of the current contour.
ui.Tangent? getTangentForOffset(int contourIndex, double distance) {
return _contours[contourIndex].getTangentForOffset(distance);
}
bool isClosed(int contourIndex) => _contours[contourIndex].isClosed;
// Move to the next contour in the path.
//
// A path can have a next contour if [Path.moveTo] was called after drawing began.
// Return true if one exists, or false.
bool _nextContour() {
final bool next = _nativeNextContour();
if (next) {
_currentContourIndex++;
}
return next;
}
// Iterator index into next contour.
int _verbIterIndex = 0;
// Move to the next contour in the path.
//
// A path can have a next contour if [Path.moveTo] was called after drawing
// began. Return true if one exists, or false.
//
// This is not exactly congruent with a regular [Iterator.moveNext].
// Typically, [Iterator.moveNext] should be called before accessing the
// [Iterator.current]. In this case, the [PathMetric] is valid before
// calling `_moveNext` - `_moveNext` should be called after the first
// iteration is done instead of before.
bool _nativeNextContour() {
if (_verbIterIndex == _path.countVerbs()) {
return false;
}
final _PathContourMeasure measure = _PathContourMeasure(_path, _pathIterator, forceClosed);
_verbIterIndex = measure.verbEndIndex;
_contours.add(measure);
return true;
}
ui.Path extractPath(int contourIndex, double start, double end, {bool startWithMoveTo = true}) {
return _contours[contourIndex].extractPath(start, end, startWithMoveTo);
}
}
/// Builds segments for a single contour to measure distance, compute tangent
/// and extract a sub path.
class _PathContourMeasure {
_PathContourMeasure(this.pathRef, PathIterator iter, this.forceClosed) {
_verbEndIndex = _buildSegments(iter);
}
final PathRef pathRef;
int _verbEndIndex = 0;
final List<_PathSegment> _segments = <_PathSegment>[];
// Allocate buffer large enough for returning cubic curve chop result.
// 2 floats for each coordinate x (start, end & control point 1 & 2).
static final Float32List _buffer = Float32List(8);
final bool forceClosed;
double get length => _contourLength;
bool get isClosed => _isClosed;
int get verbEndIndex => _verbEndIndex;
double _contourLength = 0.0;
bool _isClosed = false;
ui.Tangent? getTangentForOffset(double distance) {
final int segmentIndex = _segmentIndexAtDistance(distance);
if (segmentIndex == -1) {
return null;
}
return _getPosTan(segmentIndex, distance);
}
// Returns segment at [distance].
int _segmentIndexAtDistance(double distance) {
if (distance.isNaN) {
return -1;
}
// Pin distance to legal range.
if (distance < 0.0) {
distance = 0.0;
} else if (distance > _contourLength) {
distance = _contourLength;
}
// Binary search through segments to find segment at distance.
if (_segments.isEmpty) {
return -1;
}
int lo = 0;
int hi = _segments.length - 1;
while (lo < hi) {
final int mid = (lo + hi) >> 1;
if (_segments[mid].distance < distance) {
lo = mid + 1;
} else {
hi = mid;
}
}
if (_segments[hi].distance < distance) {
hi++;
}
return hi;
}
_SurfaceTangent _getPosTan(int segmentIndex, double distance) {
final _PathSegment segment = _segments[segmentIndex];
// Compute distance to segment. Since distance is cumulative to find
// t = 0..1 on the segment, we need to calculate start distance using prior
// segment.
final double startDistance = segmentIndex == 0 ? 0 : _segments[segmentIndex - 1].distance;
final double totalDistance = segment.distance - startDistance;
final double t = totalDistance < kEpsilon ? 0 : (distance - startDistance) / totalDistance;
return segment.computeTangent(t);
}
ui.Path extractPath(double startDistance, double stopDistance, bool startWithMoveTo) {
if (startDistance < 0) {
startDistance = 0;
}
if (stopDistance > _contourLength) {
stopDistance = _contourLength;
}
final ui.Path path = ui.Path();
if (startDistance > stopDistance || _segments.isEmpty) {
return path;
}
final int startSegmentIndex = _segmentIndexAtDistance(startDistance);
final int stopSegmentIndex = _segmentIndexAtDistance(stopDistance);
if (startSegmentIndex == -1 || stopSegmentIndex == -1) {
return path;
}
int currentSegmentIndex = startSegmentIndex;
_PathSegment seg = _segments[currentSegmentIndex];
final _SurfaceTangent startTangent = _getPosTan(startSegmentIndex, startDistance);
if (startWithMoveTo) {
final ui.Offset startPosition = startTangent.position;
path.moveTo(startPosition.dx, startPosition.dy);
}
final _SurfaceTangent stopTangent = _getPosTan(stopSegmentIndex, stopDistance);
double startT = startTangent.t;
final double stopT = stopTangent.t;
if (startSegmentIndex == stopSegmentIndex) {
// We only have a single segment that covers the complete distance.
_outputSegmentTo(seg, startT, stopT, path);
} else {
do {
// Write this segment from startT to end (t = 1.0).
_outputSegmentTo(seg, startT, 1.0, path);
// Move to next segment until we hit stop segment.
++currentSegmentIndex;
seg = _segments[currentSegmentIndex];
startT = 0;
} while (currentSegmentIndex != stopSegmentIndex);
// Final write last segment from t=0.0 to t=stopT.
_outputSegmentTo(seg, 0.0, stopT, path);
}
return path;
}
// Chops the segment at startT and endT and writes it to output [path].
void _outputSegmentTo(_PathSegment segment, double startT, double stopT, ui.Path path) {
final List<double> points = segment.points;
switch (segment.segmentType) {
case SPath.kLineVerb:
final double toX = (points[2] * stopT) + (points[0] * (1.0 - stopT));
final double toY = (points[3] * stopT) + (points[1] * (1.0 - stopT));
path.lineTo(toX, toY);
case SPath.kCubicVerb:
chopCubicBetweenT(points, startT, stopT, _buffer);
path.cubicTo(_buffer[2], _buffer[3], _buffer[4], _buffer[5], _buffer[6], _buffer[7]);
case SPath.kQuadVerb:
_chopQuadBetweenT(points, startT, stopT, _buffer);
path.quadraticBezierTo(_buffer[2], _buffer[3], _buffer[4], _buffer[5]);
case SPath.kConicVerb:
// Implement this once we start writing out conic segments.
throw UnimplementedError();
default:
throw UnsupportedError('Invalid segment type');
}
}
/// Builds segments from contour starting at verb [_verbStartIndex] and
/// returns next contour verb index.
int _buildSegments(PathIterator iter) {
assert(_segments.isEmpty, '_buildSegments should be called once');
_isClosed = false;
double distance = 0.0;
bool haveSeenMoveTo = false;
void lineToHandler(double fromX, double fromY, double x, double y) {
final double dx = fromX - x;
final double dy = fromY - y;
final double prevDistance = distance;
distance += math.sqrt(dx * dx + dy * dy);
// As we accumulate distance, we have to check that the result of +=
// actually made it larger, since a very small delta might be > 0, but
// still have no effect on distance (if distance >>> delta).
if (distance > prevDistance) {
_segments.add(_PathSegment(SPath.kLineVerb, distance, <double>[fromX, fromY, x, y]));
}
}
int verb = 0;
final Float32List points = Float32List(PathRefIterator.kMaxBufferSize);
do {
if (iter.peek() == SPath.kMoveVerb && haveSeenMoveTo) {
break;
}
verb = iter.next(points);
switch (verb) {
case SPath.kMoveVerb:
haveSeenMoveTo = true;
case SPath.kLineVerb:
assert(haveSeenMoveTo);
lineToHandler(points[0], points[1], points[2], points[3]);
case SPath.kCubicVerb:
assert(haveSeenMoveTo);
// Compute cubic curve distance.
distance = _computeCubicSegments(
points[0],
points[1],
points[2],
points[3],
points[4],
points[5],
points[6],
points[7],
distance,
0,
_kMaxTValue,
_segments,
);
case SPath.kConicVerb:
assert(haveSeenMoveTo);
final double w = iter.conicWeight;
final Conic conic = Conic(
points[0],
points[1],
points[2],
points[3],
points[4],
points[5],
w,
);
final List<ui.Offset> conicPoints = conic.toQuads();
final int len = conicPoints.length;
double startX = conicPoints[0].dx;
double startY = conicPoints[0].dy;
for (int i = 1; i < len; i += 2) {
final double p1x = conicPoints[i].dx;
final double p1y = conicPoints[i].dy;
final double p2x = conicPoints[i + 1].dx;
final double p2y = conicPoints[i + 1].dy;
distance = _computeQuadSegments(
startX,
startY,
p1x,
p1y,
p2x,
p2y,
distance,
0,
_kMaxTValue,
);
startX = p2x;
startY = p2y;
}
case SPath.kQuadVerb:
assert(haveSeenMoveTo);
// Compute quad curve distance.
distance = _computeQuadSegments(
points[0],
points[1],
points[2],
points[3],
points[4],
points[5],
distance,
0,
_kMaxTValue,
);
case SPath.kCloseVerb:
_contourLength = distance;
return iter.pathVerbIndex;
default:
break;
}
} while (verb != SPath.kDoneVerb);
_contourLength = distance;
return iter.pathVerbIndex;
}
static bool _tspanBigEnough(int tSpan) => (tSpan >> 10) != 0;
static bool _cubicTooCurvy(
double x0,
double y0,
double x1,
double y1,
double x2,
double y2,
double x3,
double y3,
) {
// Measure distance from start-end line at 1/3 and 2/3rds to control
// points. If distance is less than _fTolerance we should continue
// subdividing curve. Uses approx distance for speed.
//
// p1 = point 1/3rd between start,end points.
final double p1x = (x0 * 2 / 3) + (x3 / 3);
final double p1y = (y0 * 2 / 3) + (y3 / 3);
if ((p1x - x1).abs() > _fTolerance) {
return true;
}
if ((p1y - y1).abs() > _fTolerance) {
return true;
}
// p2 = point 2/3rd between start,end points.
final double p2x = (x0 / 3) + (x3 * 2 / 3);
final double p2y = (y0 / 3) + (y3 * 2 / 3);
if ((p2x - x2).abs() > _fTolerance) {
return true;
}
if ((p2y - y2).abs() > _fTolerance) {
return true;
}
return false;
}
// Recursively subdivides cubic and adds segments.
static double _computeCubicSegments(
double x0,
double y0,
double x1,
double y1,
double x2,
double y2,
double x3,
double y3,
double distance,
int tMin,
int tMax,
List<_PathSegment> segments,
) {
if (_tspanBigEnough(tMax - tMin) && _cubicTooCurvy(x0, y0, x1, y1, x2, y2, x3, y3)) {
// Chop cubic into two halves (De Cateljau's algorithm)
// See https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm
final double abX = (x0 + x1) / 2;
final double abY = (y0 + y1) / 2;
final double bcX = (x1 + x2) / 2;
final double bcY = (y1 + y2) / 2;
final double cdX = (x2 + x3) / 2;
final double cdY = (y2 + y3) / 2;
final double abcX = (abX + bcX) / 2;
final double abcY = (abY + bcY) / 2;
final double bcdX = (bcX + cdX) / 2;
final double bcdY = (bcY + cdY) / 2;
final double abcdX = (abcX + bcdX) / 2;
final double abcdY = (abcY + bcdY) / 2;
final int tHalf = (tMin + tMax) >> 1;
distance = _computeCubicSegments(
x0,
y0,
abX,
abY,
abcX,
abcY,
abcdX,
abcdY,
distance,
tMin,
tHalf,
segments,
);
distance = _computeCubicSegments(
abcdX,
abcdY,
bcdX,
bcdY,
cdX,
cdY,
x3,
y3,
distance,
tHalf,
tMax,
segments,
);
} else {
final double dx = x0 - x3;
final double dy = y0 - y3;
final double startToEndDistance = math.sqrt(dx * dx + dy * dy);
final double prevDistance = distance;
distance += startToEndDistance;
if (distance > prevDistance) {
segments.add(
_PathSegment(SPath.kCubicVerb, distance, <double>[x0, y0, x1, y1, x2, y2, x3, y3]),
);
}
}
return distance;
}
static bool _quadTooCurvy(double x0, double y0, double x1, double y1, double x2, double y2) {
// (a/4 + b/2 + c/4) - (a/2 + c/2) = -a/4 + b/2 - c/4
final double dx = (x1 / 2) - (x0 + x2) / 4;
if (dx.abs() > _fTolerance) {
return true;
}
final double dy = (y1 / 2) - (y0 + y2) / 4;
if (dy.abs() > _fTolerance) {
return true;
}
return false;
}
double _computeQuadSegments(
double x0,
double y0,
double x1,
double y1,
double x2,
double y2,
double distance,
int tMin,
int tMax,
) {
if (_tspanBigEnough(tMax - tMin) && _quadTooCurvy(x0, y0, x1, y1, x2, y2)) {
final double p01x = (x0 + x1) / 2;
final double p01y = (y0 + y1) / 2;
final double p12x = (x1 + x2) / 2;
final double p12y = (y1 + y2) / 2;
final double p012x = (p01x + p12x) / 2;
final double p012y = (p01y + p12y) / 2;
final int tHalf = (tMin + tMax) >> 1;
distance = _computeQuadSegments(x0, y0, p01x, p01y, p012x, p012y, distance, tMin, tHalf);
distance = _computeQuadSegments(p012x, p012y, p12x, p12y, x2, y2, distance, tMin, tHalf);
} else {
final double dx = x0 - x2;
final double dy = y0 - y2;
final double startToEndDistance = math.sqrt(dx * dx + dy * dy);
final double prevDistance = distance;
distance += startToEndDistance;
if (distance > prevDistance) {
_segments.add(_PathSegment(SPath.kQuadVerb, distance, <double>[x0, y0, x1, y1, x2, y2]));
}
}
return distance;
}
}
/// Tracks iteration from one segment of a path to the next for measurement.
class SurfacePathMetricIterator implements Iterator<ui.PathMetric> {
SurfacePathMetricIterator._(this._pathMeasure);
SurfacePathMetric? _pathMetric;
final _SurfacePathMeasure _pathMeasure;
@override
SurfacePathMetric get current {
if (_pathMetric == null) {
throw RangeError(
'PathMetricIterator is not pointing to a PathMetric. This can happen in two situations:\n'
'- The iteration has not started yet. If so, call "moveNext" to start iteration.\n'
'- The iterator ran out of elements. If so, check that "moveNext" returns true prior to calling "current".',
);
}
return _pathMetric!;
}
@override
bool moveNext() {
if (_pathMeasure._nextContour()) {
_pathMetric = SurfacePathMetric._(_pathMeasure);
return true;
}
_pathMetric = null;
return false;
}
}
// Maximum range value used in curve subdivision using Casteljau algorithm.
const int _kMaxTValue = 0x3FFFFFFF;
// Distance at which we stop subdividing cubic and quadratic curves.
const double _fTolerance = 0.5;
/// Utilities for measuring a [Path] and extracting sub-paths.
///
/// Iterate over the object returned by [Path.computeMetrics] to obtain
/// [PathMetric] objects. Callers that want to randomly access elements or
/// iterate multiple times should use `path.computeMetrics().toList()`, since
/// [PathMetrics] does not memoize.
///
/// Once created, the metrics are only valid for the path as it was specified
/// when [Path.computeMetrics] was called. If additional contours are added or
/// any contours are updated, the metrics need to be recomputed. Previously
/// created metrics will still refer to a snapshot of the path at the time they
/// were computed, rather than to the actual metrics for the new mutations to
/// the path.
///
/// Implementation is based on
/// https://github.com/google/skia/blob/main/src/core/SkContourMeasure.cpp
/// to maintain consistency with native platforms.
class SurfacePathMetric implements ui.PathMetric {
SurfacePathMetric._(this._measure)
: length = _measure.length(_measure.currentContourIndex),
isClosed = _measure.isClosed(_measure.currentContourIndex),
contourIndex = _measure.currentContourIndex;
/// Return the total length of the current contour.
@override
final double length;
/// Whether the contour is closed.
///
/// Returns true if the contour ends with a call to [Path.close] (which may
/// have been implied when using methods like [Path.addRect]) or if
/// `forceClosed` was specified as true in the call to [Path.computeMetrics].
/// Returns false otherwise.
@override
final bool isClosed;
/// The zero-based index of the contour.
///
/// [Path] objects are made up of zero or more contours. The first contour is
/// created once a drawing command (e.g. [Path.lineTo]) is issued. A
/// [Path.moveTo] command after a drawing command may create a new contour,
/// although it may not if optimizations are applied that determine the move
/// command did not actually result in moving the pen.
///
/// This property is only valid with reference to its original iterator and
/// the contours of the path at the time the path's metrics were computed. If
/// additional contours were added or existing contours updated, this metric
/// will be invalid for the current state of the path.
@override
final int contourIndex;
final _SurfacePathMeasure _measure;
/// Computes the position of the current contour at the given offset, and the
/// angle of the path at that point.
///
/// For example, calling this method with a distance of 1.41 for a line from
/// 0.0,0.0 to 2.0,2.0 would give a point 1.0,1.0 and the angle 45 degrees
/// (but in radians).
///
/// Returns null if the contour has zero [length].
///
/// The distance is clamped to the [length] of the current contour.
@override
ui.Tangent? getTangentForOffset(double distance) {
return _measure.getTangentForOffset(contourIndex, distance);
}
/// Given a start and end distance, return the intervening segment(s).
///
/// `start` and `end` are pinned to legal values (0..[length])
/// Begin the segment with a moveTo if `startWithMoveTo` is true.
@override
ui.Path extractPath(double start, double end, {bool startWithMoveTo = true}) {
return _measure.extractPath(contourIndex, start, end, startWithMoveTo: startWithMoveTo);
}
@override
String toString() => 'PathMetric';
}
// Given a vector dx, dy representing slope, normalize and return as [ui.Offset].
ui.Offset _normalizeSlope(double dx, double dy) {
final double length = math.sqrt(dx * dx + dy * dy);
return length < kEpsilon ? ui.Offset.zero : ui.Offset(dx / length, dy / length);
}
class _SurfaceTangent extends ui.Tangent {
const _SurfaceTangent(super.position, super.vector, this.t);
// Normalized distance of tangent point from start of a contour.
final double t;
}
class _PathSegment {
_PathSegment(this.segmentType, this.distance, this.points);
final int segmentType;
final double distance;
final List<double> points;
_SurfaceTangent computeTangent(double t) {
switch (segmentType) {
case SPath.kLineVerb:
// Simple line. Position is simple interpolation from start to end point.
final double xAtDistance = (points[2] * t) + (points[0] * (1.0 - t));
final double yAtDistance = (points[3] * t) + (points[1] * (1.0 - t));
return _SurfaceTangent(
ui.Offset(xAtDistance, yAtDistance),
_normalizeSlope(points[2] - points[0], points[3] - points[1]),
t,
);
case SPath.kCubicVerb:
return tangentForCubicAt(
t,
points[0],
points[1],
points[2],
points[3],
points[4],
points[5],
points[6],
points[7],
);
case SPath.kQuadVerb:
return tangentForQuadAt(
t,
points[0],
points[1],
points[2],
points[3],
points[4],
points[5],
);
default:
throw UnsupportedError('Invalid segment type');
}
}
_SurfaceTangent tangentForQuadAt(
double t,
double x0,
double y0,
double x1,
double y1,
double x2,
double y2,
) {
assert(t >= 0 && t <= 1);
final SkQuadCoefficients quadEval = SkQuadCoefficients(x0, y0, x1, y1, x2, y2);
final ui.Offset pos = ui.Offset(quadEval.evalX(t), quadEval.evalY(t));
// Derivative of quad curve is 2(b - a + (a - 2b + c)t).
// If control point is at start or end point, this yields 0 for t = 0 and
// t = 1. In that case use the quad end points to compute tangent instead
// of derivative.
final ui.Offset tangentVector =
((t == 0 && x0 == x1 && y0 == y1) || (t == 1 && x1 == x2 && y1 == y2))
? _normalizeSlope(x2 - x0, y2 - y0)
: _normalizeSlope(2 * ((x2 - x0) * t + (x1 - x0)), 2 * ((y2 - y0) * t + (y1 - y0)));
return _SurfaceTangent(pos, tangentVector, t);
}
_SurfaceTangent tangentForCubicAt(
double t,
double x0,
double y0,
double x1,
double y1,
double x2,
double y2,
double x3,
double y3,
) {
assert(t >= 0 && t <= 1);
final _SkCubicCoefficients cubicEval = _SkCubicCoefficients(x0, y0, x1, y1, x2, y2, x3, y3);
final ui.Offset pos = ui.Offset(cubicEval.evalX(t), cubicEval.evalY(t));
// Derivative of cubic is zero when t = 0 or 1 and adjacent control point
// is on the start or end point of curve. Use the other control point
// to compute the tangent or if both control points are on end points
// use end points for tangent.
final bool tAtZero = t == 0;
ui.Offset tangentVector;
if ((tAtZero && x0 == x1 && y0 == y1) || (t == 1 && x2 == x3 && y2 == y3)) {
double dx = tAtZero ? x2 - x0 : x3 - x1;
double dy = tAtZero ? y2 - y0 : y3 - y1;
if (dx == 0 && dy == 0) {
dx = x3 - x0;
dy = y3 - y0;
}
tangentVector = _normalizeSlope(dx, dy);
} else {
final double ax = x3 + (3 * (x1 - x2)) - x0;
final double ay = y3 + (3 * (y1 - y2)) - y0;
final double bx = 2 * (x2 - (2 * x1) + x0);
final double by = 2 * (y2 - (2 * y1) + y0);
final double cx = x1 - x0;
final double cy = y1 - y0;
final double tx = (ax * t + bx) * t + cx;
final double ty = (ay * t + by) * t + cy;
tangentVector = _normalizeSlope(tx, ty);
}
return _SurfaceTangent(pos, tangentVector, t);
}
}
// Evaluates A * t^3 + B * t^2 + Ct + D = 0 for cubic curve.
class _SkCubicCoefficients {
_SkCubicCoefficients(
double x0,
double y0,
double x1,
double y1,
double x2,
double y2,
double x3,
double y3,
) : ax = x3 + (3 * (x1 - x2)) - x0,
ay = y3 + (3 * (y1 - y2)) - y0,
bx = 3 * (x2 - (2 * x1) + x0),
by = 3 * (y2 - (2 * y1) + y0),
cx = 3 * (x1 - x0),
cy = 3 * (y1 - y0),
dx = x0,
dy = y0;
final double ax, ay, bx, by, cx, cy, dx, dy;
double evalX(double t) => (((ax * t + bx) * t) + cx) * t + dx;
double evalY(double t) => (((ay * t + by) * t) + cy) * t + dy;
}
/// Chops quadratic curve at startT and stopT and writes result to buffer.
void _chopQuadBetweenT(List<double> points, double startT, double stopT, Float32List buffer) {
assert(startT != 0 || stopT != 0);
final double p2y = points[5];
final double p0x = points[0];
final double p0y = points[1];
final double p1x = points[2];
final double p1y = points[3];
final double p2x = points[4];
// If startT == 0 chop at end point and return curve.
final bool chopStart = startT != 0;
final double t = chopStart ? startT : stopT;
final double ab1x = interpolate(p0x, p1x, t);
final double ab1y = interpolate(p0y, p1y, t);
final double bc1x = interpolate(p1x, p2x, t);
final double bc1y = interpolate(p1y, p2y, t);
final double abc1x = interpolate(ab1x, bc1x, t);
final double abc1y = interpolate(ab1y, bc1y, t);
if (!chopStart) {
// Return left side of curve.
buffer[0] = p0x;
buffer[1] = p0y;
buffer[2] = ab1x;
buffer[3] = ab1y;
buffer[4] = abc1x;
buffer[5] = abc1y;
return;
}
if (stopT == 1) {
// Return right side of curve.
buffer[0] = abc1x;
buffer[1] = abc1y;
buffer[2] = bc1x;
buffer[3] = bc1y;
buffer[4] = p2x;
buffer[5] = p2y;
return;
}
// We chopped at startT, now the right hand side of curve is at
// abc1x, abc1y, bc1x, bc1y, p2x, p2y
final double endT = (stopT - startT) / (1 - startT);
final double ab2x = interpolate(abc1x, bc1x, endT);
final double ab2y = interpolate(abc1y, bc1y, endT);
final double bc2x = interpolate(bc1x, p2x, endT);
final double bc2y = interpolate(bc1y, p2y, endT);
final double abc2x = interpolate(ab2x, bc2x, endT);
final double abc2y = interpolate(ab2y, bc2y, endT);
buffer[0] = abc1x;
buffer[1] = abc1y;
buffer[2] = ab2x;
buffer[3] = ab2y;
buffer[4] = abc2x;
buffer[5] = abc2y;
}

View File

@@ -1,66 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'conic.dart';
import 'path_ref.dart';
import 'path_utils.dart';
/// Converts [path] to SVG path syntax to be used as "d" attribute in path
/// element.
String pathToSvg(PathRef pathRef, {double offsetX = 0, double offsetY = 0}) {
final StringBuffer buffer = StringBuffer();
final PathRefIterator iter = PathRefIterator(pathRef);
int verb = 0;
final Float32List outPts = Float32List(PathRefIterator.kMaxBufferSize);
while ((verb = iter.next(outPts)) != SPath.kDoneVerb) {
switch (verb) {
case SPath.kMoveVerb:
buffer.write('M ${outPts[0] + offsetX} ${outPts[1] + offsetY}');
case SPath.kLineVerb:
buffer.write('L ${outPts[2] + offsetX} ${outPts[3] + offsetY}');
case SPath.kCubicVerb:
buffer.write(
'C ${outPts[2] + offsetX} ${outPts[3] + offsetY} '
'${outPts[4] + offsetX} ${outPts[5] + offsetY} ${outPts[6] + offsetX} ${outPts[7] + offsetY}',
);
case SPath.kQuadVerb:
buffer.write(
'Q ${outPts[2] + offsetX} ${outPts[3] + offsetY} '
'${outPts[4] + offsetX} ${outPts[5] + offsetY}',
);
case SPath.kConicVerb:
final double w = iter.conicWeight;
final Conic conic = Conic(
outPts[0],
outPts[1],
outPts[2],
outPts[3],
outPts[4],
outPts[5],
w,
);
final List<ui.Offset> points = conic.toQuads();
final int len = points.length;
for (int i = 1; i < len; i += 2) {
final double p1x = points[i].dx;
final double p1y = points[i].dy;
final double p2x = points[i + 1].dx;
final double p2y = points[i + 1].dy;
buffer.write(
'Q ${p1x + offsetX} ${p1y + offsetY} '
'${p2x + offsetX} ${p2y + offsetY}',
);
}
case SPath.kCloseVerb:
buffer.write('Z');
default:
throw UnimplementedError('Unknown path verb $verb');
}
}
return buffer.toString();
}

View File

@@ -1,432 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:ui/ui.dart' as ui;
import 'path_ref.dart';
/// Mask used to keep track of types of verbs used in a path segment.
class SPathSegmentMask {
static const int kLine_SkPathSegmentMask = 1 << 0;
static const int kQuad_SkPathSegmentMask = 1 << 1;
static const int kConic_SkPathSegmentMask = 1 << 2;
static const int kCubic_SkPathSegmentMask = 1 << 3;
}
/// Types of path operations.
class SPathVerb {
static const int kMove = 0; // 1 point
static const int kLine = 1; // 2 points
static const int kQuad = 2; // 3 points
static const int kConic = 3; // 3 points + 1 weight
static const int kCubic = 4; // 4 points
static const int kClose = 5; // 0 points
}
abstract final class SPath {
static const int kMoveVerb = SPathVerb.kMove;
static const int kLineVerb = SPathVerb.kLine;
static const int kQuadVerb = SPathVerb.kQuad;
static const int kConicVerb = SPathVerb.kConic;
static const int kCubicVerb = SPathVerb.kCubic;
static const int kCloseVerb = SPathVerb.kClose;
static const int kDoneVerb = SPathVerb.kClose + 1;
static const int kLineSegmentMask = SPathSegmentMask.kLine_SkPathSegmentMask;
static const int kQuadSegmentMask = SPathSegmentMask.kQuad_SkPathSegmentMask;
static const int kConicSegmentMask = SPathSegmentMask.kConic_SkPathSegmentMask;
static const int kCubicSegmentMask = SPathSegmentMask.kCubic_SkPathSegmentMask;
static const double scalarNearlyZero = 1.0 / (1 << 12);
/// Square root of 2 divided by 2. Useful for sin45 = cos45 = 1/sqrt(2).
static const double scalarRoot2Over2 = 0.707106781;
/// True if (a <= b <= c) || (a >= b >= c)
static bool between(double a, double b, double c) {
return (a - b) * (c - b) <= 0;
}
/// Returns -1 || 0 || 1 depending on the sign of value:
/// -1 if x < 0
/// 0 if x == 0
/// 1 if x > 0
static int scalarSignedAsInt(double x) {
return x < 0 ? -1 : ((x > 0) ? 1 : 0);
}
static bool nearlyEqual(double value1, double value2) =>
(value1 - value2).abs() < SPath.scalarNearlyZero;
// Snaps a value to zero if almost zero (within tolerance).
static double snapToZero(double value) => SPath.nearlyEqual(value, 0.0) ? 0.0 : value;
static bool isInteger(double value) => value.floor() == value;
}
class SPathAddPathMode {
// Append to destination unaltered.
static const int kAppend = 0;
// Add line if prior contour is not closed.
static const int kExtend = 1;
}
class SPathDirection {
/// Uninitialized value for empty paths.
static const int kUnknown = -1;
/// clockwise direction for adding closed contours.
static const int kCW = 0;
/// counter-clockwise direction for adding closed contours.
static const int kCCW = 1;
}
class SPathConvexityType {
static const int kUnknown = -1;
static const int kConvex = 0;
static const int kConcave = 1;
}
class SPathSegmentState {
/// The current contour is empty. Starting processing or have just closed
/// a contour.
static const int kEmptyContour = 0;
/// Have seen a move, but nothing else.
static const int kAfterMove = 1;
/// Have seen a primitive but not yet closed the path. Also the initial state.
static const int kAfterPrimitive = 2;
}
/// Quadratic roots. See Numerical Recipes in C.
///
/// Q = -1/2 (B + sign(B) sqrt[B*B - 4*A*C])
/// x1 = Q / A
/// x2 = C / Q
class QuadRoots {
QuadRoots();
double? root0;
double? root1;
/// Returns roots as list.
List<double> get roots =>
(root0 == null) ? <double>[] : (root1 == null ? <double>[root0!] : <double>[root0!, root1!]);
int findRoots(double a, double b, double c) {
int rootCount = 0;
if (a == 0) {
root0 = validUnitDivide(-c, b);
return root0 == null ? 0 : 1;
}
double dr = b * b - 4 * a * c;
if (dr < 0) {
return 0;
}
dr = math.sqrt(dr);
if (!dr.isFinite) {
return 0;
}
final double q = (b < 0) ? -(b - dr) / 2 : -(b + dr) / 2;
double? res = validUnitDivide(q, a);
if (res != null) {
root0 = res;
++rootCount;
}
res = validUnitDivide(c, q);
if (res != null) {
if (rootCount == 0) {
root0 = res;
++rootCount;
} else {
root1 = res;
++rootCount;
}
}
if (rootCount == 2) {
if (root0! > root1!) {
final double swap = root0!;
root0 = root1;
root1 = swap;
} else if (root0 == root1) {
return 1; // skip the double root
}
}
return rootCount;
}
}
double? validUnitDivide(double numer, double denom) {
if (numer < 0) {
numer = -numer;
denom = -denom;
}
if (denom == 0 || numer == 0 || numer >= denom) {
return null;
}
final double r = numer / denom;
if (r.isNaN) {
return null;
}
if (r == 0) {
// catch underflow if numer <<<< denom
return null;
}
return r;
}
bool isRRectOval(ui.RRect rrect) {
if ((rrect.tlRadiusX + rrect.trRadiusX) != rrect.width) {
return false;
}
if ((rrect.tlRadiusY + rrect.trRadiusY) != rrect.height) {
return false;
}
if (rrect.tlRadiusX != rrect.blRadiusX ||
rrect.trRadiusX != rrect.brRadiusX ||
rrect.tlRadiusY != rrect.blRadiusY ||
rrect.trRadiusY != rrect.brRadiusY) {
return false;
}
return true;
}
/// Evaluates degree 2 polynomial (quadratic).
double polyEval(double A, double B, double C, double t) => (A * t + B) * t + C;
/// Evaluates degree 3 polynomial (cubic).
double polyEval4(double A, double B, double C, double D, double t) => ((A * t + B) * t + C) * t + D;
// Interpolate between two doubles (Not using lerpDouble here since it null
// checks and treats values as 0).
double interpolate(double startValue, double endValue, double t) =>
(startValue * (1 - t)) + endValue * t;
double dotProduct(double x0, double y0, double x1, double y1) {
return x0 * x1 + y0 * y1;
}
// Helper class for computing convexity for a single contour.
//
// Iteratively looks at angle (using cross product) between consecutive vectors
// formed by path.
class Convexicator {
static const int kValueNeverReturnedBySign = 2;
// Second point of contour start that forms a vector.
// Used to handle close operator to compute angle between last vector and
// first.
double? firstVectorEndPointX;
double? firstVectorEndPointY;
double? priorX;
double? priorY;
double? lastX;
double? lastY;
double? currX;
double? currY;
// Last vector to use to compute angle.
double? lastVecX;
double? lastVecY;
bool _isFinite = true;
int _firstDirection = SPathDirection.kUnknown;
int _reversals = 0;
/// SPathDirection of contour.
int get firstDirection => _firstDirection;
DirChange _expectedDirection = DirChange.kInvalid;
void setMovePt(double x, double y) {
currX = priorX = lastX = x;
currY = priorY = lastY = y;
}
bool addPoint(double x, double y) {
if (x == currX && y == currY) {
// Skip zero length vector.
return true;
}
currX = x;
currY = y;
final double vecX = currX! - lastX!;
final double vecY = currY! - lastY!;
if (priorX == lastX && priorY == lastY) {
// First non-zero vector.
lastVecX = vecX;
lastVecY = vecY;
firstVectorEndPointX = x;
firstVectorEndPointY = y;
} else if (!_addVector(vecX, vecY)) {
return false;
}
priorX = lastX;
priorY = lastY;
lastX = x;
lastY = y;
return true;
}
bool close() {
// Add another point from path closing point to end of first vector.
return addPoint(firstVectorEndPointX!, firstVectorEndPointY!);
}
bool get isFinite => _isFinite;
int get reversals => _reversals;
DirChange _directionChange(double curVecX, double curVecY) {
// Cross product = ||lastVec|| * ||curVec|| * sin(theta) * N
// sin(theta) angle between two vectors is positive for angles 0..180 and
// negative for greater, providing left or right direction.
final double lastX = lastVecX!;
final double lastY = lastVecY!;
final double cross = lastX * curVecY - lastY * curVecX;
if (!cross.isFinite) {
return DirChange.kUnknown;
}
// Detect straight and backwards direction change.
// Instead of comparing absolute crossproduct size, compare
// largest component double+crossproduct.
final double smallest = math.min(curVecX, math.min(curVecY, math.min(lastX, lastY)));
final double largest = math.max(
math.max(curVecX, math.max(curVecY, math.max(lastX, lastY))),
-smallest,
);
if (SPath.nearlyEqual(largest, largest + cross)) {
const double nearlyZeroSquared = SPath.scalarNearlyZero * SPath.scalarNearlyZero;
if (SPath.nearlyEqual(lengthSquared(lastX, lastY), nearlyZeroSquared) ||
SPath.nearlyEqual(lengthSquared(curVecX, curVecY), nearlyZeroSquared)) {
// Length of either vector is smaller than tolerance to be able
// to compute direction.
return DirChange.kUnknown;
}
// The vectors are parallel, sign of dot product gives us direction.
// cosine is positive for straight -90 < Theta < 90
return dotProduct(lastX, lastY, curVecX, curVecY) < 0
? DirChange.kBackwards
: DirChange.kStraight;
}
return cross > 0 ? DirChange.kRight : DirChange.kLeft;
}
bool _addVector(double curVecX, double curVecY) {
final DirChange dir = _directionChange(curVecX, curVecY);
final bool isDirectionRight = dir == DirChange.kRight;
if (dir == DirChange.kLeft || isDirectionRight) {
if (_expectedDirection == DirChange.kInvalid) {
// First valid direction. From this point on expect always left.
_expectedDirection = dir;
_firstDirection = isDirectionRight ? SPathDirection.kCW : SPathDirection.kCCW;
} else if (dir != _expectedDirection) {
_firstDirection = SPathDirection.kUnknown;
return false;
}
lastVecX = curVecX;
lastVecY = curVecY;
} else {
switch (dir) {
case DirChange.kBackwards:
// Allow path to reverse direction twice.
// Given path.moveTo(0,0) lineTo(1,1)
// - First reversal: direction change formed by line (0,0 1,1),
// line (1,1 0,0)
// - Second reversal: direction change formed by line (1,1 0,0),
// line (0,0 1,1)
lastVecX = curVecX;
lastVecY = curVecY;
return ++_reversals < 3;
case DirChange.kUnknown:
return _isFinite = false;
default:
break;
}
}
return true;
}
// Quick test to detect concave by looking at number of changes in direction
// of vectors formed by path points (excluding control points).
static int bySign(PathRef pathRef, int pointIndex, int numPoints) {
final int lastPointIndex = pointIndex + numPoints;
int currentPoint = pointIndex++;
final int firstPointIndex = currentPoint;
int signChangeCountX = 0;
int signChangeCountY = 0;
int lastSx = kValueNeverReturnedBySign;
int lastSy = kValueNeverReturnedBySign;
for (int outerLoop = 0; outerLoop < 2; ++outerLoop) {
while (pointIndex != lastPointIndex) {
final double vecX = pathRef.pointXAt(pointIndex) - pathRef.pointXAt(currentPoint);
final double vecY = pathRef.pointYAt(pointIndex) - pathRef.pointYAt(currentPoint);
if (!(vecX == 0 && vecY == 0)) {
// Give up if vector construction failed.
// give up if vector construction failed
if (!(vecX.isFinite && vecY.isFinite)) {
return SPathConvexityType.kUnknown;
}
final int sx = vecX < 0 ? 1 : 0;
final int sy = vecY < 0 ? 1 : 0;
signChangeCountX += (sx != lastSx) ? 1 : 0;
signChangeCountY += (sy != lastSy) ? 1 : 0;
if (signChangeCountX > 3 || signChangeCountY > 3) {
return SPathConvexityType.kConcave;
}
lastSx = sx;
lastSy = sy;
}
currentPoint = pointIndex++;
if (outerLoop != 0) {
break;
}
}
pointIndex = firstPointIndex;
}
return SPathConvexityType.kConvex;
}
}
enum DirChange {
kUnknown,
kLeft,
kRight,
kStraight,
kBackwards, // if double back, allow simple lines to be convex
kInvalid,
}
double lengthSquaredOffset(ui.Offset offset) {
final double dx = offset.dx;
final double dy = offset.dy;
return dx * dx + dy * dy;
}
double lengthSquared(double dx, double dy) => dx * dx + dy * dy;
/// Evaluates A * t^2 + B * t + C = 0 for quadratic curve.
class SkQuadCoefficients {
SkQuadCoefficients(double x0, double y0, double x1, double y1, double x2, double y2)
: cx = x0,
cy = y0,
bx = 2 * (x1 - x0),
by = 2 * (y1 - y0),
ax = x2 - (2 * x1) + x0,
ay = y2 - (2 * y1) + y0;
final double ax, ay, bx, by, cx, cy;
double evalX(double t) => (ax * t + bx) * t + cx;
double evalY(double t) => (ay * t + by) * t + cy;
}

View File

@@ -1,377 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:typed_data';
import 'conic.dart';
import 'cubic.dart';
import 'path_iterator.dart';
import 'path_ref.dart';
import 'path_utils.dart';
/// Computes winding number and onCurveCount for a path and point.
class PathWinding {
PathWinding(this.pathRef, this.x, this.y) {
_walkPath();
}
final PathRef pathRef;
final double x;
final double y;
int _w = 0;
int _onCurveCount = 0;
int get w => _w;
int get onCurveCount => _onCurveCount;
/// Buffer used for max(iterator result, chopped 3 cubics).
final Float32List _buffer = Float32List(8 + 10);
/// Iterates through path and computes winding.
void _walkPath() {
final PathIterator iter = PathIterator(pathRef, true);
int verb;
while ((verb = iter.next(_buffer)) != SPath.kDoneVerb) {
switch (verb) {
case SPath.kMoveVerb:
case SPath.kCloseVerb:
break;
case SPath.kLineVerb:
_computeLineWinding();
case SPath.kQuadVerb:
_computeQuadWinding();
case SPath.kConicVerb:
_computeConicWinding(pathRef.conicWeights![iter.conicWeightIndex]);
case SPath.kCubicVerb:
_computeCubicWinding();
}
}
}
void _computeLineWinding() {
final double x0 = _buffer[0];
final double startY = _buffer[1];
double y0 = startY;
final double x1 = _buffer[2];
final double endY = _buffer[3];
double y1 = endY;
final double dy = y1 - y0;
int dir = 1;
// Swap so that y0 <= y1 holds.
if (y0 > y1) {
final double temp = y0;
y0 = y1;
y1 = temp;
dir = -1;
}
// If point is outside top/bottom bounds, winding is 0.
if (y < y0 || y > y1) {
return;
}
if (_checkOnCurve(x, y, x0, startY, x1, endY)) {
_onCurveCount++;
return;
}
if (y == y1) {
return;
}
// c = ax*by − ay*bx where a is the line and b is line formed from start
// to the given point(x,y).
final double crossProduct = (x1 - x0) * (y - startY) - dy * (x - x0);
if (crossProduct == 0) {
// zero cross means the point is on the line, and since the case where
// y of the query point is at the end point is handled above, we can be
// sure that we're on the line (excluding the end point) here.
if (x != x1 || y != endY) {
_onCurveCount++;
}
dir = 0;
} else if (SPath.scalarSignedAsInt(crossProduct) == dir) {
// Direction of cross product and line the same.
dir = 0;
}
_w += dir;
}
// Check if point starts the line, handle special case for horizontal lines
// where and point except the end point is considered on curve.
static bool _checkOnCurve(
double x,
double y,
double startX,
double startY,
double endX,
double endY,
) {
if (startY == endY) {
// Horizontal line.
return SPath.between(startX, x, endX) && x != endX;
} else {
return x == startX && y == startY;
}
}
void _computeQuadWinding() {
// Check if we need to chop quadratic at extrema to compute 2 separate
// windings.
int n = 0;
if (!_isQuadMonotonic(_buffer)) {
n = _chopQuadAtExtrema(_buffer);
}
int winding = _computeMonoQuadWinding(
_buffer[0],
_buffer[1],
_buffer[2],
_buffer[3],
_buffer[4],
_buffer[5],
);
if (n > 0) {
winding += _computeMonoQuadWinding(
_buffer[4],
_buffer[5],
_buffer[6],
_buffer[7],
_buffer[8],
_buffer[9],
);
}
_w += winding;
}
int _computeMonoQuadWinding(double x0, double y0, double x1, double y1, double x2, double y2) {
int dir = 1;
final double startY = y0;
final double endY = y2;
if (y0 > y2) {
final double temp = y0;
y0 = y2;
y2 = temp;
dir = -1;
}
if (y < y0 || y > y2) {
return 0;
}
if (_checkOnCurve(x, y, x0, startY, x2, endY)) {
_onCurveCount++;
return 0;
}
if (y == y2) {
return 0;
}
final QuadRoots quadRoots = QuadRoots();
final int n = quadRoots.findRoots(startY - 2 * y1 + endY, 2 * (y1 - startY), startY - y);
assert(n <= 1);
double xt;
if (0 == n) {
// zero roots are returned only when y0 == y
xt = dir == 1 ? x0 : x2;
} else {
final double t = quadRoots.root0!;
final double C = x0;
final double A = x2 - 2 * x1 + C;
final double B = 2 * (x1 - C);
xt = polyEval(A, B, C, t);
}
if (SPath.nearlyEqual(xt, x)) {
if (x != x2 || y != endY) {
// don't test end points; they're start points
_onCurveCount += 1;
return 0;
}
}
return xt < x ? dir : 0;
}
/// Chops a non-monotonic quadratic curve, returns subdivisions and writes
/// result into [buffer].
static int _chopQuadAtExtrema(Float32List buffer) {
final double x0 = buffer[0];
final double y0 = buffer[1];
final double x1 = buffer[2];
final double y1 = buffer[3];
final double x2 = buffer[4];
final double y2 = buffer[5];
final double? tValueAtExtrema = validUnitDivide(y0 - y1, y0 - y1 - y1 + y2);
if (tValueAtExtrema != null) {
// Chop quad at t value by interpolating along p0-p1 and p1-p2.
final double p01x = x0 + (tValueAtExtrema * (x1 - x0));
final double p01y = y0 + (tValueAtExtrema * (y1 - y0));
final double p12x = x1 + (tValueAtExtrema * (x2 - x1));
final double p12y = y1 + (tValueAtExtrema * (y2 - y1));
final double cx = p01x + (tValueAtExtrema * (p12x - p01x));
final double cy = p01y + (tValueAtExtrema * (p12y - p01y));
buffer[2] = p01x;
buffer[3] = p01y;
buffer[4] = cx;
buffer[5] = cy;
buffer[6] = p12x;
buffer[7] = p12y;
buffer[8] = x2;
buffer[9] = y2;
return 1;
}
// if we get here, we need to force output to be monotonic, even though
// we couldn't compute a unit divide value (probably underflow).
buffer[3] = (y0 - y1).abs() < (y1 - y2).abs() ? y0 : y2;
return 0;
}
static bool _isQuadMonotonic(Float32List quad) {
final double y0 = quad[1];
final double y1 = quad[3];
final double y2 = quad[5];
if (y0 == y1) {
return true;
}
if (y0 < y1) {
return y1 <= y2;
} else {
return y1 >= y2;
}
}
void _computeConicWinding(double weight) {
final Conic conic = Conic(
_buffer[0],
_buffer[1],
_buffer[2],
_buffer[3],
_buffer[4],
_buffer[5],
weight,
);
// If the data points are very large, the conic may not be monotonic but may also
// fail to chop. Then, the chopper does not split the original conic in two.
final bool isMono = _isQuadMonotonic(_buffer);
final List<Conic> conics = <Conic>[];
conic.chopAtYExtrema(conics);
_computeMonoConicWinding(conics[0]);
if (!isMono && conics.length == 2) {
_computeMonoConicWinding(conics[1]);
}
}
void _computeMonoConicWinding(Conic conic) {
double y0 = conic.p0y;
double y2 = conic.p2y;
int dir = 1;
if (y0 > y2) {
final double swap = y0;
y0 = y2;
y2 = swap;
dir = -1;
}
if (y < y0 || y > y2) {
return;
}
if (_checkOnCurve(x, y, conic.p0x, conic.p0y, conic.p2x, conic.p2y)) {
_onCurveCount += 1;
return;
}
if (y == y2) {
return;
}
double A = conic.p2y;
double B = conic.p1y * conic.fW - y * conic.fW + y;
double C = conic.p0y;
// A = a + c - 2*(b*w - yCept*w + yCept)
A += C - 2 * B;
// B = b*w - w * yCept + yCept - a
B -= C;
C -= y;
final QuadRoots quadRoots = QuadRoots();
final int n = quadRoots.findRoots(A, 2 * B, C);
assert(n <= 1);
double xt;
if (0 == n) {
// zero roots are returned only when y0 == y
// Need [0] if dir == 1
// and [2] if dir == -1
xt = dir == 1 ? conic.p0x : conic.p2x;
} else {
final double root = quadRoots.root0!;
xt =
Conic.evalNumerator(conic.p0x, conic.p1x, conic.p2x, conic.fW, root) /
Conic.evalDenominator(conic.fW, root);
}
if (SPath.nearlyEqual(xt, x)) {
if (x != conic.p2x || y != conic.p2y) {
// don't test end points; they're start points
_onCurveCount += 1;
return;
}
}
_w += xt < x ? dir : 0;
}
void _computeCubicWinding() {
final int n = chopCubicAtYExtrema(_buffer, _buffer);
for (int i = 0; i <= n; ++i) {
_windingMonoCubic(i * 3 * 2);
}
}
void _windingMonoCubic(int bufferIndex) {
final int bufferStartPos = bufferIndex;
final double px0 = _buffer[bufferIndex++];
final double py0 = _buffer[bufferIndex++];
final double px1 = _buffer[bufferIndex++];
bufferIndex++;
final double px2 = _buffer[bufferIndex++];
bufferIndex++;
final double px3 = _buffer[bufferIndex++];
final double py3 = _buffer[bufferIndex++];
double y0 = py0;
double y3 = py3;
int dir = 1;
if (y0 > y3) {
final double swap = y0;
y0 = y3;
y3 = swap;
dir = -1;
}
if (y < y0 || y > y3) {
return;
}
if (_checkOnCurve(x, y, px0, py0, px3, py3)) {
_onCurveCount += 1;
return;
}
if (y == y3) {
return;
}
// Quickly reject or accept
final double min = math.min(px0, math.min(px1, math.min(px2, px3)));
final double max = math.max(px0, math.max(px1, math.max(px2, px3)));
if (x < min) {
return;
}
if (x > max) {
_w += dir;
return;
}
// Compute the actual x(t) value.
final double? t = chopMonoAtY(_buffer, bufferStartPos, y);
if (t == null) {
return;
}
final double xt = evalCubicPts(px0, px1, px2, px3, t);
if (SPath.nearlyEqual(xt, x)) {
if (x != px3 || y != py3) {
// don't test end points; they're start points
_onCurveCount += 1;
return;
}
}
_w += xt < x ? dir : 0;
}
}

View File

@@ -1,216 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'conic.dart';
import 'cubic.dart';
import 'path_utils.dart';
/// Computes tangent at point x,y on a line.
void tangentLine(Float32List pts, double x, double y, List<ui.Offset> tangents) {
final double y0 = pts[1];
final double y1 = pts[3];
if (!SPath.between(y0, y, y1)) {
return;
}
final double x0 = pts[0];
final double x1 = pts[2];
if (!SPath.between(x0, x, x1)) {
return;
}
final double dx = x1 - x0;
final double dy = y1 - y0;
if (!SPath.nearlyEqual((x - x0) * dy, dx * (y - y0))) {
return;
}
tangents.add(ui.Offset(dx, dy));
}
/// Computes tangent at point x,y on a quadratic curve.
void tangentQuad(Float32List pts, double x, double y, List<ui.Offset> tangents) {
final double y0 = pts[1];
final double y1 = pts[3];
final double y2 = pts[5];
if (!SPath.between(y0, y, y1) && !SPath.between(y1, y, y2)) {
return;
}
final double x0 = pts[0];
final double x1 = pts[2];
final double x2 = pts[4];
if (!SPath.between(x0, x, x1) && !SPath.between(x1, x, x2)) {
return;
}
final QuadRoots roots = QuadRoots();
final int n = roots.findRoots(y0 - 2 * y1 + y2, 2 * (y1 - y0), y0 - y);
for (int index = 0; index < n; ++index) {
final double t = index == 0 ? roots.root0! : roots.root1!;
final double C = x0;
final double A = x2 - 2 * x1 + C;
final double B = 2 * (x1 - C);
final double xt = polyEval(A, B, C, t);
if (!SPath.nearlyEqual(x, xt)) {
continue;
}
tangents.add(_evalQuadTangentAt(x0, y0, x1, y1, x2, y2, t));
}
}
ui.Offset _evalQuadTangentAt(
double x0,
double y0,
double x1,
double y1,
double x2,
double y2,
double t,
) {
// The derivative of a quad equation is 2(b - a +(a - 2b +c)t).
// This returns a zero tangent vector when t is 0 or 1, and the control
// point is equal to the end point. In this case, use the quad end points to
// compute the tangent.
if ((t == 0 && x0 == x1 && y0 == y1) || (t == 1 && x1 == x2 && y1 == y2)) {
return ui.Offset(x2 - x0, y2 - y0);
}
assert(t >= 0 && t <= 1.0);
final double bx = x1 - x0;
final double by = y1 - y0;
final double ax = x2 - x1 - bx;
final double ay = y2 - y1 - by;
final double tx = ax * t + bx;
final double ty = ay * t + by;
return ui.Offset(tx * 2, ty * 2);
}
/// Computes tangent at point x,y on a conic curve.
void tangentConic(Float32List pts, double x, double y, double weight, List<ui.Offset> tangents) {
final double y0 = pts[1];
final double y1 = pts[3];
final double y2 = pts[5];
if (!SPath.between(y0, y, y1) && !SPath.between(y1, y, y2)) {
return;
}
final double x0 = pts[0];
final double x1 = pts[2];
final double x2 = pts[4];
if (!SPath.between(x0, x, x1) && !SPath.between(x1, x, x2)) {
return;
}
// Check extrema.
double A = y2;
double B = y1 * weight - y * weight + y;
double C = y0;
// A = a + c - 2*(b*w - yCept*w + yCept)
A += C - 2 * B;
// B = b*w - w * yCept + yCept - a
B -= C;
C -= y;
final QuadRoots quadRoots = QuadRoots();
final int n = quadRoots.findRoots(A, 2 * B, C);
for (int index = 0; index < n; ++index) {
final double t = index == 0 ? quadRoots.root0! : quadRoots.root1!;
final double xt = Conic.evalNumerator(x0, x1, x2, weight, t) / Conic.evalDenominator(weight, t);
if (!SPath.nearlyEqual(x, xt)) {
continue;
}
final Conic conic = Conic(x0, y0, x1, y1, x2, y2, weight);
tangents.add(conic.evalTangentAt(t));
}
}
/// Computes tangent at point x,y on a cubic curve.
void tangentCubic(Float32List pts, double x, double y, List<ui.Offset> tangents) {
final double y3 = pts[7];
final double y0 = pts[1];
final double y1 = pts[3];
final double y2 = pts[5];
if (!SPath.between(y0, y, y1) && !SPath.between(y1, y, y2) && !SPath.between(y2, y, y3)) {
return;
}
final double x0 = pts[0];
final double x1 = pts[2];
final double x2 = pts[4];
final double x3 = pts[6];
if (!SPath.between(x0, x, x1) && !SPath.between(x1, x, x2) && !SPath.between(x2, x, x3)) {
return;
}
final Float32List dst = Float32List(20);
final int n = chopCubicAtYExtrema(pts, dst);
for (int i = 0; i <= n; ++i) {
final int bufferPos = i * 6;
final double? t = chopMonoAtY(dst, i * 6, y);
if (t == null) {
continue;
}
final double xt = evalCubicPts(
dst[bufferPos],
dst[bufferPos + 2],
dst[bufferPos + 4],
dst[bufferPos + 6],
t,
);
if (!SPath.nearlyEqual(x, xt)) {
continue;
}
tangents.add(_evalCubicTangentAt(dst, bufferPos, t));
}
}
ui.Offset _evalCubicTangentAt(Float32List points, int bufferPos, double t) {
assert(t >= 0 && t <= 1.0);
final double y3 = points[7 + bufferPos];
final double y0 = points[1 + bufferPos];
final double y1 = points[3 + bufferPos];
final double y2 = points[5 + bufferPos];
final double x0 = points[0 + bufferPos];
final double x1 = points[2 + bufferPos];
final double x2 = points[4 + bufferPos];
final double x3 = points[6 + bufferPos];
// The derivative equation returns a zero tangent vector when t is 0 or 1,
// and the adjacent control point is equal to the end point. In this case,
// use the next control point or the end points to compute the tangent.
if ((t == 0 && x0 == x1 && y0 == y1) || (t == 1 && x2 == x3 && y2 == y3)) {
double dx, dy;
if (t == 0) {
dx = x2 - x0;
dy = y2 - y0;
} else {
dx = x3 - x1;
dy = y3 - y1;
}
if (dx == 0 && dy == 0) {
dx = x3 - x0;
dy = y3 - y0;
}
return ui.Offset(dx, dy);
} else {
return _evalCubicDerivative(x0, y0, x1, y1, x2, y2, x3, y3, t);
}
}
ui.Offset _evalCubicDerivative(
double x0,
double y0,
double x1,
double y1,
double x2,
double y2,
double x3,
double y3,
double t,
) {
final SkQuadCoefficients coeff = SkQuadCoefficients(
x3 + 3 * (x1 - x2) - x0,
y3 + 3 * (y1 - y2) - y0,
2 * (x2 - (2 * x1) + x0),
2 * (y2 - (2 * y1) + y0),
x1 - x0,
y1 - y0,
);
return ui.Offset(coeff.evalX(t), coeff.evalY(t));
}

View File

@@ -1,74 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../dom.dart';
import '../svg.dart';
import 'path/path.dart';
import 'path/path_to_svg.dart';
/// Counter used for generating clip path id inside an svg <defs> tag.
int _clipIdCounter = 0;
/// Used for clipping and filter svg resources.
///
/// Position needs to be absolute since these svgs are sandwiched between
/// canvas elements and can cause layout shifts otherwise.
final SVGSVGElement kSvgResourceHeader =
createSVGSVGElement()
..setAttribute('width', 0)
..setAttribute('height', 0)
..style.position = 'absolute';
/// Converts Path to svg element that contains a clip-path definition.
///
/// Calling this method updates [_clipIdCounter]. The HTML id of the generated
/// clip is set to "svgClip${_clipIdCounter}", e.g. "svgClip123".
SVGSVGElement pathToSvgClipPath(
ui.Path path, {
double offsetX = 0,
double offsetY = 0,
double scaleX = 1.0,
double scaleY = 1.0,
}) {
_clipIdCounter += 1;
final SVGSVGElement root = kSvgResourceHeader.cloneNode(false) as SVGSVGElement;
final SVGDefsElement defs = createSVGDefsElement();
root.append(defs);
final String clipId = 'svgClip$_clipIdCounter';
final SVGClipPathElement clipPath = createSVGClipPathElement();
defs.append(clipPath);
clipPath.id = clipId;
final SVGPathElement svgPath = createSVGPathElement();
clipPath.append(svgPath);
svgPath.setAttribute('fill', '#FFFFFF');
// Firefox objectBoundingBox fails to scale to 1x1 units, instead use
// no clipPathUnits but write the path in target units.
if (ui_web.browser.browserEngine != ui_web.BrowserEngine.firefox) {
clipPath.setAttribute('clipPathUnits', 'objectBoundingBox');
svgPath.setAttribute('transform', 'scale($scaleX, $scaleY)');
}
if (path.fillType == ui.PathFillType.evenOdd) {
svgPath.setAttribute('clip-rule', 'evenodd');
} else {
svgPath.setAttribute('clip-rule', 'nonzero');
}
svgPath.setAttribute(
'd',
pathToSvg((path as SurfacePath).pathRef, offsetX: offsetX, offsetY: offsetY),
);
return root;
}
String createSvgClipUrl() => 'url(#svgClip$_clipIdCounter)';
/// Resets clip ids. Used for testing by [debugForgetFrameScene] API.
void resetSvgClipIds() {
_clipIdCounter = 0;
}

View File

@@ -1,834 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../engine_canvas.dart';
import '../util.dart';
import '../vector_math.dart';
import 'bitmap_canvas.dart';
import 'debug_canvas_reuse_overlay.dart';
import 'dom_canvas.dart';
import 'frame_reference.dart';
import 'image.dart';
import 'path/path_metrics.dart';
import 'recording_canvas.dart';
import 'surface.dart';
import 'surface_stats.dart';
class EnginePictureRecorder implements ui.PictureRecorder {
EnginePictureRecorder();
RecordingCanvas? _canvas;
late ui.Rect cullRect;
bool _isRecording = false;
RecordingCanvas beginRecording(ui.Rect bounds) {
assert(!_isRecording);
cullRect = bounds;
_isRecording = true;
return _canvas = RecordingCanvas(cullRect);
}
@override
bool get isRecording => _isRecording;
@override
EnginePicture endRecording() {
if (!_isRecording) {
// The mobile version returns an empty picture in this case. To match the
// behavior we produce a blank picture too.
beginRecording(ui.Rect.largest);
}
_isRecording = false;
_canvas!.endRecording();
final EnginePicture result = EnginePicture(_canvas, cullRect);
// We invoke the handler here, not in the Picture constructor, because we want
// [result.approximateBytesUsed] to be available for the handler.
ui.Picture.onCreate?.call(result);
return result;
}
}
/// An implementation of [ui.Picture] which is backed by a [RecordingCanvas].
class EnginePicture implements ui.Picture {
/// This class is created by the engine, and should not be instantiated
/// or extended directly.
///
/// To create a [Picture], use a [PictureRecorder].
EnginePicture(this.recordingCanvas, this.cullRect);
@override
Future<ui.Image> toImage(int width, int height) async {
final ui.Rect imageRect = ui.Rect.fromLTRB(0, 0, width.toDouble(), height.toDouble());
final BitmapCanvas canvas = BitmapCanvas.imageData(imageRect);
recordingCanvas!.apply(canvas, imageRect);
final String imageDataUrl = canvas.toDataUrl();
final DomHTMLImageElement imageElement =
createDomHTMLImageElement()
..src = imageDataUrl
..width = width.toDouble()
..height = height.toDouble();
// The image loads asynchronously. We need to wait before returning,
// otherwise the returned HtmlImage will be temporarily unusable.
final Completer<ui.Image> onImageLoaded = Completer<ui.Image>.sync();
// Ignoring the returned futures from onError and onLoad because we're
// communicating through the `onImageLoaded` completer.
late final DomEventListener errorListener;
errorListener = createDomEventListener((DomEvent event) {
onImageLoaded.completeError(event);
imageElement.removeEventListener('error', errorListener);
});
imageElement.addEventListener('error', errorListener);
late final DomEventListener loadListener;
loadListener = createDomEventListener((DomEvent event) {
onImageLoaded.complete(HtmlImage(imageElement, width, height));
imageElement.removeEventListener('load', loadListener);
});
imageElement.addEventListener('load', loadListener);
return onImageLoaded.future;
}
@override
ui.Image toImageSync(int width, int height) {
throw UnsupportedError(
'toImageSync is not supported on the HTML backend. Use drawPicture instead, or toImage.',
);
}
bool _disposed = false;
@override
void dispose() {
ui.Picture.onDispose?.call(this);
_disposed = true;
}
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _disposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError('Picture.debugDisposed is only available when asserts are enabled.');
}
@override
int get approximateBytesUsed => 0;
final RecordingCanvas? recordingCanvas;
final ui.Rect? cullRect;
}
// TODO(yjbanov): this is currently very naive. We probably want to cache
// fewer large canvases than small canvases. We could also
// improve cache hit count if we did not require exact canvas
// size match, but instead could choose a canvas that's big
// enough. The optimal heuristic will need to be figured out.
// For example, we probably don't want to pick a full-screen
// canvas to draw a 10x10 picture. Let's revisit this after
// Harry's layer merging refactor.
/// The maximum number canvases cached.
const int _kCanvasCacheSize = 30;
/// Canvases available for reuse, capped at [_kCanvasCacheSize].
List<BitmapCanvas> get recycledCanvases => _recycledCanvases;
final List<BitmapCanvas> _recycledCanvases = <BitmapCanvas>[];
/// Reduces recycled canvas list by 50% to reduce bitmap canvas memory use.
void reduceCanvasMemoryUsage() {
final int canvasCount = _recycledCanvases.length;
for (int i = 0; i < canvasCount; i++) {
_recycledCanvases[i].dispose();
}
_recycledCanvases.clear();
}
/// A request to repaint a canvas.
///
/// Paint requests are prioritized such that the larger pictures go first. This
/// 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({required this.canvasSize, required this.paintCallback});
final ui.Size canvasSize;
final ui.VoidCallback paintCallback;
}
/// 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>[];
void _recycleCanvas(EngineCanvas? canvas) {
// If a canvas is in the paint queue it maybe be recycled. To
// prevent subsequent dispose recycling again check.
if (canvas != null && _recycledCanvases.contains(canvas)) {
return;
}
if (canvas is BitmapCanvas) {
canvas.setElementCache(null);
if (canvas.isReusable()) {
_recycledCanvases.add(canvas);
if (_recycledCanvases.length > _kCanvasCacheSize) {
final BitmapCanvas removedCanvas = _recycledCanvases.removeAt(0);
removedCanvas.dispose();
if (debugShowCanvasReuseStats) {
DebugCanvasReuseOverlay.instance.disposedCount++;
}
}
if (debugShowCanvasReuseStats) {
DebugCanvasReuseOverlay.instance.inRecycleCount = _recycledCanvases.length;
}
} else {
canvas.dispose();
}
}
}
/// A surface that uses a combination of `<canvas>`, `<div>` and `<p>` elements
/// to draw shapes and text.
class PersistedPicture extends PersistedLeafSurface {
PersistedPicture(this.dx, this.dy, this.picture, this.hints)
: localPaintBounds = picture.recordingCanvas!.pictureBounds;
EngineCanvas? _canvas;
/// Returns the canvas used by this picture layer.
EngineCanvas? get canvas => _canvas;
final double dx;
final double dy;
final EnginePicture picture;
final ui.Rect? localPaintBounds;
final int hints;
double _density = 1.0;
/// Cull rect changes and density changes due to transforms should
/// call applyPaint for picture when retain() or update() is called after
/// preroll is complete.
bool _requiresRepaint = false;
/// Cache for reusing elements such as images across picture updates.
CrossFrameCache<DomHTMLElement>? _elementCache = CrossFrameCache<DomHTMLElement>();
@override
DomElement createElement() {
final DomElement element = defaultCreateElement('flt-picture');
// The DOM elements used to render pictures are used purely to put pixels on
// the screen. They have no semantic information. If an assistive technology
// attempts to scan picture content it will look like garbage and confuse
// users. UI semantics are exported as a separate DOM tree rendered parallel
// to pictures.
//
// Why are layer and scene elements not hidden from ARIA? Because those
// elements may contain platform views, and platform views must be
// accessible.
element.setAttribute('aria-hidden', 'true');
return element;
}
@override
void preroll(PrerollSurfaceContext prerollContext) {
if (prerollContext.activeShaderMaskCount != 0 || prerollContext.activeColorFilterCount != 0) {
picture.recordingCanvas?.renderStrategy.isInsideSvgFilterTree = true;
}
super.preroll(prerollContext);
}
@override
void recomputeTransformAndClip() {
transform = parent!.transform;
if (dx != 0.0 || dy != 0.0) {
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);
if (newDensity != _density) {
_density = newDensity;
_requiresRepaint = true;
}
_computeExactCullRects();
}
/// The rectangle that contains all visible pixels drawn by [picture] inside
/// the current layer hierarchy in local coordinates.
///
/// This value is a conservative estimate, i.e. it must be big enough to
/// contain everything that's visible, but it may be bigger than necessary.
/// Therefore it should not be used for clipping. It is meant to be used for
/// optimizing canvas allocation.
ui.Rect? get optimalLocalCullRect => _optimalLocalCullRect;
ui.Rect? _optimalLocalCullRect;
/// Same as [optimalLocalCullRect] but in screen coordinate system.
ui.Rect? get debugExactGlobalCullRect => _exactGlobalCullRect;
ui.Rect? _exactGlobalCullRect;
ui.Rect? _exactLocalCullRect;
/// Computes the canvas paint bounds based on the estimated paint bounds and
/// the scaling produced by transformations.
///
/// Return `true` if the local cull rect changed, indicating that a repaint
/// may be required. Returns `false` otherwise. Global cull rect changes do
/// not necessarily incur repaints. For example, if the layer sub-tree was
/// translated from one frame to another we may not need to repaint, just
/// translate the canvas.
void _computeExactCullRects() {
assert(transform != null);
assert(localPaintBounds != 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.
ui.Rect? bounds;
PersistedSurface? parentSurface = parent;
final Matrix4 clipTransform = Matrix4.identity();
while (parentSurface != null) {
final ui.Rect? localClipBounds = parentSurface.localClipBounds;
if (localClipBounds != null) {
if (bounds == null) {
bounds = clipTransform.transformRect(localClipBounds);
} else {
bounds = bounds.intersect(clipTransform.transformRect(localClipBounds));
}
}
final Matrix4? localInverse = parentSurface.localTransformInverse;
if (localInverse != null && !localInverse.isIdentity()) {
clipTransform.multiply(localInverse);
}
parentSurface = parentSurface.parent;
}
if (bounds != null && (bounds.width <= 0 || bounds.height <= 0)) {
bounds = ui.Rect.zero;
}
// Cache projected clip on parent.
parent!.projectedClip = bounds;
}
// Intersect localPaintBounds with parent projected clip to calculate
// and cache [_exactLocalCullRect].
if (parent!.projectedClip == null) {
_exactLocalCullRect = localPaintBounds;
} else {
_exactLocalCullRect = localPaintBounds!.intersect(parent!.projectedClip!);
}
if (_exactLocalCullRect!.width <= 0 || _exactLocalCullRect!.height <= 0) {
_exactLocalCullRect = ui.Rect.zero;
_exactGlobalCullRect = ui.Rect.zero;
} else {
assert(() {
_exactGlobalCullRect = transform!.transformRect(_exactLocalCullRect!);
return true;
}());
}
}
void _computeOptimalCullRect(PersistedPicture? oldSurface) {
assert(_exactLocalCullRect != null);
if (oldSurface == null || !oldSurface.picture.recordingCanvas!.didDraw) {
// First useful paint.
_optimalLocalCullRect = _exactLocalCullRect;
_requiresRepaint = true;
return;
}
assert(oldSurface._optimalLocalCullRect != null);
final bool surfaceBeingRetained = identical(oldSurface, this);
final ui.Rect? oldOptimalLocalCullRect =
surfaceBeingRetained ? _optimalLocalCullRect : oldSurface._optimalLocalCullRect;
if (_exactLocalCullRect == ui.Rect.zero) {
// The clip collapsed into a zero-sized rectangle. If it was already zero,
// no need to signal cull rect change.
_optimalLocalCullRect = ui.Rect.zero;
if (oldOptimalLocalCullRect != ui.Rect.zero) {
_requiresRepaint = true;
}
return;
}
if (rectContainsOther(oldOptimalLocalCullRect!, _exactLocalCullRect!)) {
// The cull rect we computed in the past contains the newly computed cull
// rect. This can happen, for example, when the picture is being shrunk by
// a clip when it is scrolled out of the screen. In this case we do not
// repaint the picture. We just let it be shrunk by the outer clip.
_optimalLocalCullRect = oldOptimalLocalCullRect;
return;
}
// The new cull rect contains area not covered by a previous rect. Perhaps
// the clip is growing, moving around the picture, or both. In this case
// a part of the picture may not have been painted. We will need to
// request a new canvas and paint the picture on it. However, this is also
// a strong signal that the clip will continue growing as typically
// Flutter uses animated transitions. So instead of allocating the canvas
// the size of the currently visible area, we try to allocate a canvas of
// a bigger size. This will prevent any further repaints as future frames
// will hit the above case where the new cull rect is fully contained
// within the cull rect we compute now.
// Compute the delta, by which each of the side of the clip rect has "moved"
// since the last time we updated the cull rect.
final double leftwardDelta = oldOptimalLocalCullRect.left - _exactLocalCullRect!.left;
final double upwardDelta = oldOptimalLocalCullRect.top - _exactLocalCullRect!.top;
final double rightwardDelta = _exactLocalCullRect!.right - oldOptimalLocalCullRect.right;
final double bottomwardDelta = _exactLocalCullRect!.bottom - oldOptimalLocalCullRect.bottom;
// Compute the new optimal rect to paint into.
final ui.Rect newLocalCullRect = ui.Rect.fromLTRB(
_exactLocalCullRect!.left - _predictTrend(leftwardDelta, _exactLocalCullRect!.width),
_exactLocalCullRect!.top - _predictTrend(upwardDelta, _exactLocalCullRect!.height),
_exactLocalCullRect!.right + _predictTrend(rightwardDelta, _exactLocalCullRect!.width),
_exactLocalCullRect!.bottom + _predictTrend(bottomwardDelta, _exactLocalCullRect!.height),
).intersect(localPaintBounds!);
_requiresRepaint = _optimalLocalCullRect != newLocalCullRect;
_optimalLocalCullRect = newLocalCullRect;
}
/// Predicts the delta a particular side of a clip rect will move given the
/// [delta] it moved by last, and the respective [extent] (width or height)
/// of the clip.
static double _predictTrend(double delta, double extent) {
if (delta <= 0.0) {
// Shrinking. Give it 10% of the extent in case the trend is reversed.
return extent * 0.1;
} else {
// Growing. Predict 10 more frames of similar deltas. Give it at least
// 50% of the extent (protect from extremely slow growth trend such as
// slow scrolling). Give no more than the full extent (protects from
// fast scrolling that could lead to overallocation).
return math.min(math.max(extent * 0.5, delta * 10.0), extent);
}
}
/// Number of bitmap pixel painted by this picture.
///
/// If the implementation does not paint onto a bitmap canvas, it should
/// return zero.
int get bitmapPixelCount {
if (_canvas is! BitmapCanvas) {
return 0;
}
final BitmapCanvas bitmapCanvas = _canvas! as BitmapCanvas;
return bitmapCanvas.bitmapPixelCount;
}
void _applyPaint(PersistedPicture? oldSurface) {
final EngineCanvas? oldCanvas = oldSurface?._canvas;
_requiresRepaint = false;
if (!picture.recordingCanvas!.didDraw || _optimalLocalCullRect!.isEmpty) {
// The picture is empty, or it has been completely clipped out. Skip
// painting. This removes all the setup work and scaffolding objects
// that won't be useful for anything anyway.
_recycleCanvas(oldCanvas);
if (oldSurface != null) {
// Make sure it doesn't get reused/recycled again.
oldSurface._canvas = null;
}
if (rootElement != null) {
removeAllChildren(rootElement!);
}
if (_canvas != null && _canvas != oldCanvas) {
_recycleCanvas(_canvas);
}
_canvas = null;
return;
}
if (debugExplainSurfaceStats) {
surfaceStatsFor(this).paintCount++;
}
assert(_optimalLocalCullRect != null);
applyPaint(oldCanvas);
}
@override
double matchForUpdate(PersistedPicture existingSurface) {
if (existingSurface.picture == picture) {
// Picture is the same, return perfect score.
return 0.0;
}
if (!existingSurface.picture.recordingCanvas!.didDraw) {
// The previous surface didn't draw anything and therefore has no
// resources to reuse.
return 1.0;
}
final bool didRequireBitmap =
existingSurface.picture.recordingCanvas!.renderStrategy.hasArbitraryPaint;
final bool requiresBitmap = picture.recordingCanvas!.renderStrategy.hasArbitraryPaint;
if (didRequireBitmap != requiresBitmap) {
// Switching canvas types is always expensive.
return 1.0;
} else if (!requiresBitmap) {
// Currently DomCanvas is always expensive to repaint, as we always throw
// out all the DOM we rendered before. This may change in the future, at
// which point we may return other values here.
return 1.0;
} else {
final BitmapCanvas? oldCanvas = existingSurface._canvas as BitmapCanvas?;
if (oldCanvas == null) {
// We did not allocate a canvas last time. This can happen when the
// picture is completely clipped out of the view.
return 1.0;
} else if (!oldCanvas.doesFitBounds(_exactLocalCullRect!, _density)) {
// The canvas needs to be resized before painting.
return 1.0;
} else {
final int newPixelCount =
BitmapCanvas.widthToPhysical(_exactLocalCullRect!.width) *
BitmapCanvas.heightToPhysical(_exactLocalCullRect!.height);
final int oldPixelCount = oldCanvas.widthInBitmapPixels * oldCanvas.heightInBitmapPixels;
if (oldPixelCount == 0) {
return 1.0;
}
final double pixelCountRatio = newPixelCount / oldPixelCount;
assert(
0 <= pixelCountRatio && pixelCountRatio <= 1.0,
'Invalid pixel count ratio $pixelCountRatio',
);
return 1.0 - pixelCountRatio;
}
}
}
void applyPaint(EngineCanvas? oldCanvas) {
if (picture.recordingCanvas!.renderStrategy.hasArbitraryPaint) {
_applyBitmapPaint(oldCanvas);
} else {
_applyDomPaint(oldCanvas);
}
}
void _applyDomPaint(EngineCanvas? oldCanvas) {
_recycleCanvas(_canvas);
final DomCanvas domCanvas = DomCanvas(rootElement!);
_canvas = domCanvas;
removeAllChildren(rootElement!);
picture.recordingCanvas!.apply(domCanvas, _optimalLocalCullRect!);
}
void _applyBitmapPaint(EngineCanvas? oldCanvas) {
if (oldCanvas is BitmapCanvas &&
oldCanvas.doesFitBounds(_optimalLocalCullRect!, _density) &&
oldCanvas.isReusable()) {
final BitmapCanvas reusedCanvas = oldCanvas;
if (debugShowCanvasReuseStats) {
DebugCanvasReuseOverlay.instance.keptCount++;
}
// Re-use old bitmap canvas.
reusedCanvas.bounds = _optimalLocalCullRect!;
_canvas = reusedCanvas;
reusedCanvas.setElementCache(_elementCache);
reusedCanvas.clear();
picture.recordingCanvas!.apply(reusedCanvas, _optimalLocalCullRect!);
} else {
// We can't use the old canvas because the size has changed, so we put
// it in a cache for later reuse.
_recycleCanvas(oldCanvas);
if (_canvas is BitmapCanvas) {
(_canvas! as BitmapCanvas).setElementCache(null);
}
_canvas = null;
// We cannot paint immediately because not all canvases that we may be
// 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(
canvasSize: _optimalLocalCullRect!.size,
paintCallback: () {
final BitmapCanvas bitmapCanvas = _findOrCreateCanvas(_optimalLocalCullRect!);
_canvas = bitmapCanvas;
bitmapCanvas.setElementCache(_elementCache);
if (debugExplainSurfaceStats) {
surfaceStatsFor(this).paintPixelCount += bitmapCanvas.bitmapPixelCount;
}
removeAllChildren(rootElement!);
rootElement!.append(bitmapCanvas.rootElement);
bitmapCanvas.clear();
picture.recordingCanvas!.apply(bitmapCanvas, _optimalLocalCullRect!);
},
),
);
}
}
/// Attempts to reuse a canvas from the [_recycledCanvases]. Allocates a new
/// one if unable to reuse.
///
/// The best recycled canvas is one that:
///
/// - Fits the requested [canvasSize]. This is a hard requirement. Otherwise
/// we risk clipping the picture.
/// - Is the smallest among all possible reusable canvases. This makes canvas
/// reuse more efficient.
/// - Contains no more than twice the number of requested pixels. This makes
/// sure we do not use too much memory for small canvases.
BitmapCanvas _findOrCreateCanvas(ui.Rect bounds) {
final ui.Size canvasSize = bounds.size;
BitmapCanvas? bestRecycledCanvas;
double lastPixelCount = double.infinity;
for (int i = 0; i < _recycledCanvases.length; i++) {
final BitmapCanvas candidate = _recycledCanvases[i];
if (!candidate.isReusable()) {
continue;
}
final ui.Size candidateSize = candidate.size;
final double candidatePixelCount = candidateSize.width * candidateSize.height;
final bool fits = candidate.doesFitBounds(bounds, _density);
final bool isSmaller = candidatePixelCount < lastPixelCount;
if (fits && isSmaller) {
// [isTooSmall] is used to make sure that a small picture doesn't
// reuse and hold onto memory of a large canvas.
final double requestedPixelCount = bounds.width * bounds.height;
final bool isTooSmall =
isSmaller && requestedPixelCount > 1 && (candidatePixelCount / requestedPixelCount) > 4;
if (!isTooSmall) {
bestRecycledCanvas = candidate;
lastPixelCount = candidatePixelCount;
final bool fitsExactly =
candidateSize.width == canvasSize.width && candidateSize.height == canvasSize.height;
if (fitsExactly) {
// No need to keep looking any more.
break;
}
}
}
}
if (bestRecycledCanvas != null) {
if (debugExplainSurfaceStats) {
surfaceStatsFor(this).reuseCanvasCount++;
}
_recycledCanvases.remove(bestRecycledCanvas);
if (debugShowCanvasReuseStats) {
DebugCanvasReuseOverlay.instance.inRecycleCount = _recycledCanvases.length;
}
if (debugShowCanvasReuseStats) {
DebugCanvasReuseOverlay.instance.reusedCount++;
}
bestRecycledCanvas.bounds = bounds;
bestRecycledCanvas.setElementCache(_elementCache);
return bestRecycledCanvas;
}
if (debugShowCanvasReuseStats) {
DebugCanvasReuseOverlay.instance.createdCount++;
}
final BitmapCanvas canvas = BitmapCanvas(
bounds,
picture.recordingCanvas!.renderStrategy,
density: _density,
);
canvas.setElementCache(_elementCache);
if (debugExplainSurfaceStats) {
surfaceStatsFor(this)
..allocateBitmapCanvasCount += 1
..allocatedBitmapSizeInPixels = canvas.widthInBitmapPixels * canvas.heightInBitmapPixels;
}
return canvas;
}
void _applyTranslate() {
rootElement!.style.transform = 'translate(${dx}px, ${dy}px)';
}
@override
void apply() {
_applyTranslate();
_applyPaint(null);
}
@override
void build() {
_computeOptimalCullRect(null);
_requiresRepaint = true;
super.build();
}
@override
void update(PersistedPicture oldSurface) {
super.update(oldSurface);
// Transfer element cache over.
_elementCache = oldSurface._elementCache;
if (oldSurface != this) {
oldSurface._elementCache = null;
}
if (dx != oldSurface.dx || dy != oldSurface.dy) {
_applyTranslate();
}
_computeOptimalCullRect(oldSurface);
if (identical(picture, oldSurface.picture)) {
final bool densityChanged =
_canvas is BitmapCanvas && _density != (_canvas! as BitmapCanvas).density;
// The picture is the same. Attempt to avoid repaint.
if (_requiresRepaint || densityChanged) {
// Cull rect changed such that a repaint is still necessary.
_applyPaint(oldSurface);
} else {
// Cull rect did not change, or changed such in a way that does not
// require a repaint (e.g. it shrunk).
_canvas = oldSurface._canvas;
}
} else {
// We have a new picture. Repaint.
_applyPaint(oldSurface);
}
}
@override
void retain() {
super.retain();
_computeOptimalCullRect(this);
if (_requiresRepaint) {
_applyPaint(this);
}
}
@override
void discard() {
_recycleCanvas(_canvas);
_canvas = null;
super.discard();
}
@override
void debugPrintChildren(StringBuffer buffer, int indent) {
super.debugPrintChildren(buffer, indent);
if (rootElement != null && rootElement!.firstChild != null) {
final DomElement firstChild = rootElement!.firstChild! as DomElement;
final String canvasTag = firstChild.tagName.toLowerCase();
final int canvasHash = firstChild.hashCode;
buffer.writeln('${' ' * (indent + 1)}<$canvasTag @$canvasHash />');
} else if (rootElement != null) {
buffer.writeln('${' ' * (indent + 1)}<${rootElement!.tagName.toLowerCase()} @$hashCode />');
} else {
buffer.writeln('${' ' * (indent + 1)}<recycled-canvas />');
}
}
@override
void debugValidate(List<String> validationErrors) {
super.debugValidate(validationErrors);
if (picture.recordingCanvas!.didDraw) {
if (!_optimalLocalCullRect!.isEmpty && canvas == null) {
validationErrors.add('$runtimeType has non-trivial picture but it has null canvas');
}
if (_optimalLocalCullRect == null) {
validationErrors.add('$runtimeType has null _optimalLocalCullRect');
}
if (_exactGlobalCullRect == null) {
validationErrors.add('$runtimeType has null _exactGlobalCullRect');
}
if (_exactLocalCullRect == null) {
validationErrors.add('$runtimeType has null _exactLocalCullRect');
}
}
}
}
/// Given size of a rectangle and transform, computes pixel density
/// (scale factor).
double _computePixelDensity(Matrix4? transform, double width, double height) {
if (transform == null || transform.isIdentityOrTranslation()) {
return 1.0;
}
final Float32List m = transform.storage;
// Apply perspective transform to all 4 corners. Can't use left,top, bottom,
// right since for example rotating 45 degrees would yield inaccurate size.
double minX = m[12] * m[15];
double minY = m[13] * m[15];
double maxX = minX;
double maxY = minY;
double x = width;
double y = height;
double wp = 1.0 / ((m[3] * x) + (m[7] * y) + m[15]);
double xp = ((m[0] * x) + (m[4] * y) + m[12]) * wp;
double yp = ((m[1] * x) + (m[5] * y) + m[13]) * wp;
minX = math.min(minX, xp);
maxX = math.max(maxX, xp);
minY = math.min(minY, yp);
maxY = math.max(maxY, yp);
x = 0;
wp = 1.0 / ((m[3] * x) + (m[7] * y) + m[15]);
xp = ((m[0] * x) + (m[4] * y) + m[12]) * wp;
yp = ((m[1] * x) + (m[5] * y) + m[13]) * wp;
minX = math.min(minX, xp);
maxX = math.max(maxX, xp);
minY = math.min(minY, yp);
maxY = math.max(maxY, yp);
x = width;
y = 0;
wp = 1.0 / ((m[3] * x) + (m[7] * y) + m[15]);
xp = ((m[0] * x) + (m[4] * y) + m[12]) * wp;
yp = ((m[1] * x) + (m[5] * y) + m[13]) * wp;
minX = math.min(minX, xp);
maxX = math.max(maxX, xp);
minY = math.min(minY, yp);
maxY = math.max(maxY, yp);
final double scaleX = (maxX - minX) / width;
final double scaleY = (maxY - minY) / height;
double scale = math.min(scaleX, scaleY);
// kEpsilon guards against divide by zero below.
if (scale < kEpsilon || scale == 1) {
// Handle local paint bounds scaled to 0, typical when using
// transform animations and nothing is drawn.
return 1.0;
}
if (scale > 1) {
// Normalize scale to multiples of 2: 1x, 2x, 4x, 6x, 8x.
// This is to prevent frequent rescaling of canvas during animations.
//
// On a fullscreen high dpi device dpi*density*resolution will demand
// too much memory, so clamp at 4.
scale = math.min(4.0, (scale / 2.0).ceil() * 2.0);
// Guard against webkit absolute limit.
const double kPixelLimit = 1024 * 1024 * 4;
if ((width * height * scale * scale) > kPixelLimit && scale > 2) {
scale = (kPixelLimit * 0.8) / (width * height);
}
} else {
scale = math.max(2.0 / (2.0 / scale).floor(), 0.0001);
}
return scale;
}

View File

@@ -1,72 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../dom.dart';
import '../platform_dispatcher.dart';
import '../platform_views/slots.dart';
import '../window.dart';
import 'surface.dart';
/// A surface containing a platform view, which is an HTML element.
class PersistedPlatformView extends PersistedLeafSurface {
PersistedPlatformView(this.platformViewId, this.dx, this.dy, this.width, this.height) {
// Ensure platform view with `viewId` is injected into the `implicitView`
// before rendering its shadow DOM `slot`.
final EngineFlutterView implicitView = EnginePlatformDispatcher.instance.implicitView!;
implicitView.dom.injectPlatformView(platformViewId);
}
final int platformViewId;
final double dx;
final double dy;
final double width;
final double height;
@override
DomElement createElement() {
return createPlatformViewSlot(platformViewId);
}
@override
void apply() {
// See `_compositeWithParams` in the HtmlViewEmbedder for the canvaskit equivalent.
rootElement!.style
..transform = 'translate(${dx}px, ${dy}px)'
..width = '${width}px'
..height = '${height}px'
..position = 'absolute';
}
// Platform Views can only be updated if their viewId matches.
@override
bool canUpdateAsMatch(PersistedSurface oldSurface) {
if (super.canUpdateAsMatch(oldSurface)) {
// super checks the runtimeType of the surface, so we can just cast...
return platformViewId == ((oldSurface as PersistedPlatformView).platformViewId);
}
return false;
}
@override
double matchForUpdate(PersistedPlatformView existingSurface) {
return existingSurface.platformViewId == platformViewId ? 0.0 : 1.0;
}
@override
void update(PersistedPlatformView oldSurface) {
assert(
platformViewId == oldSurface.platformViewId,
'PersistedPlatformView with different platformViewId should never be updated. Check the canUpdateAsMatch method.',
);
super.update(oldSurface);
// Only update if the view has been resized
if (dx != oldSurface.dx ||
dy != oldSurface.dy ||
width != oldSurface.width ||
height != oldSurface.height) {
// A change in any of the dimensions is performed by calling apply.
apply();
}
}
}

View File

@@ -1,602 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../browser_detection.dart';
import '../dom.dart';
import '../safe_browser_api.dart';
import '../util.dart';
import '../vector_math.dart';
import 'painting.dart';
import 'shaders/image_shader.dart';
import 'shaders/normalized_gradient.dart';
import 'shaders/shader_builder.dart';
import 'shaders/vertex_shaders.dart';
GlRenderer? glRenderer;
class SurfaceVertices implements ui.Vertices {
SurfaceVertices(
this.mode,
List<ui.Offset> positions, {
List<ui.Color>? colors,
List<int>? indices,
}) : colors = colors != null ? _int32ListFromColors(colors) : null,
indices = indices != null ? Uint16List.fromList(indices) : null,
positions = offsetListToFloat32List(positions) {
initWebGl();
}
SurfaceVertices.raw(this.mode, this.positions, {this.colors, this.indices}) {
initWebGl();
}
final ui.VertexMode mode;
final Float32List positions;
final Int32List? colors;
final Uint16List? indices;
static Int32List _int32ListFromColors(List<ui.Color> colors) {
final Int32List list = Int32List(colors.length);
final int len = colors.length;
for (int i = 0; i < len; i++) {
list[i] = colors[i].value;
}
return list;
}
bool get hasNoPoints => positions.isEmpty;
bool _disposed = false;
@override
void dispose() {
_disposed = true;
}
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _disposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError('Vertices.debugDisposed is only available when asserts are enabled.');
}
}
/// Lazily initializes web gl.
///
/// Used to treeshake WebGlRenderer when user doesn't create Vertices object
/// to use the API.
void initWebGl() {
glRenderer ??= _WebGlRenderer();
}
abstract class GlRenderer {
void drawVertices(
DomCanvasRenderingContext2D? context,
int canvasWidthInPixels,
int canvasHeightInPixels,
Matrix4 transform,
SurfaceVertices vertices,
ui.BlendMode blendMode,
SurfacePaintData paint,
);
Object? drawRect(
ui.Rect targetRect,
GlContext gl,
GlProgram glProgram,
NormalizedGradient gradient,
int widthInPixels,
int heightInPixels,
);
String drawRectToImageUrl(
ui.Rect targetRect,
GlContext gl,
GlProgram glProgram,
NormalizedGradient gradient,
int widthInPixels,
int heightInPixels,
);
void drawHairline(DomCanvasRenderingContext2D? ctx, Float32List positions);
}
/// Treeshakeable backend for rendering webgl on canvas.
///
/// This class gets instantiated on demand by Vertices constructor. For apps
/// that don't use Vertices WebGlRenderer will be removed from release binary.
class _WebGlRenderer implements GlRenderer {
@override
void drawVertices(
DomCanvasRenderingContext2D? context,
int canvasWidthInPixels,
int canvasHeightInPixels,
Matrix4 transform,
SurfaceVertices vertices,
ui.BlendMode blendMode,
SurfacePaintData paint,
) {
// Compute bounds of vertices.
final Float32List positions = vertices.positions;
if (positions.isEmpty) {
// Drawing empty vertices is a no-op.
return;
}
final ui.Rect bounds = _computeVerticesBounds(positions, transform);
final double minValueX = bounds.left;
final double minValueY = bounds.top;
final double maxValueX = bounds.right;
final double maxValueY = bounds.bottom;
double offsetX = 0;
double offsetY = 0;
int widthInPixels = canvasWidthInPixels;
int heightInPixels = canvasHeightInPixels;
// If vertices fall outside the bitmap area, cull.
if (maxValueX < 0 || maxValueY < 0) {
return;
}
if (minValueX > widthInPixels || minValueY > heightInPixels) {
return;
}
// If Vertices are is smaller than hosting canvas, allocate minimal
// offscreen canvas to reduce readPixels data size.
if ((maxValueX - minValueX) < widthInPixels && (maxValueY - minValueY) < heightInPixels) {
widthInPixels = maxValueX.ceil() - minValueX.floor();
heightInPixels = maxValueY.ceil() - minValueY.floor();
offsetX = minValueX.floor().toDouble();
offsetY = minValueY.floor().toDouble();
}
if (widthInPixels == 0 || heightInPixels == 0) {
return;
}
final bool isWebGl2 = webGLVersion == WebGLVersion.webgl2;
final EngineImageShader? imageShader =
paint.shader == null ? null : paint.shader! as EngineImageShader;
final String vertexShader =
imageShader == null
? VertexShaders.writeBaseVertexShader()
: VertexShaders.writeTextureVertexShader();
final String fragmentShader =
imageShader == null
? _writeVerticesFragmentShader()
: FragmentShaders.writeTextureFragmentShader(
isWebGl2,
imageShader.tileModeX,
imageShader.tileModeY,
);
final GlContext gl = GlContextCache.createGlContext(widthInPixels, heightInPixels)!;
final GlProgram glProgram = gl.cacheProgram(vertexShader, fragmentShader);
gl.useProgram(glProgram);
final Object positionAttributeLocation = gl.getAttributeLocation(glProgram.program, 'position');
setupVertexTransforms(
gl,
glProgram,
offsetX,
offsetY,
widthInPixels.toDouble(),
heightInPixels.toDouble(),
transform,
);
if (imageShader != null) {
/// To map from vertex position to texture coordinate in 0..1 range,
/// we setup scalar to be used in vertex shader.
setupTextureTransform(
gl,
glProgram,
0.0,
0.0,
1.0 / imageShader.image.width.toDouble(),
1.0 / imageShader.image.height.toDouble(),
);
}
// Setup geometry.
//
// Create buffer for vertex coordinates.
final Object positionsBuffer = gl.createBuffer()!;
Object? vao;
if (imageShader != null) {
if (isWebGl2) {
// Create a vertex array object.
vao = gl.createVertexArray();
// Set vertex array object as active one.
gl.bindVertexArray(vao!);
}
}
// Turn on position attribute.
gl.enableVertexAttribArray(positionAttributeLocation);
// Bind buffer as position buffer and transfer data.
gl.bindArrayBuffer(positionsBuffer);
bufferVertexData(gl, positions, 1.0);
// Setup data format for attribute.
vertexAttribPointerGlContext(
gl.glContext,
positionAttributeLocation,
2,
gl.kFloat,
false,
0,
0,
);
final int vertexCount = positions.length ~/ 2;
Object? texture;
if (imageShader == null) {
// Setup color buffer.
final Object? colorsBuffer = gl.createBuffer();
gl.bindArrayBuffer(colorsBuffer);
// Buffer kBGRA_8888.
if (vertices.colors == null) {
final Uint32List vertexColors = Uint32List(vertexCount);
for (int i = 0; i < vertexCount; i++) {
vertexColors[i] = paint.color;
}
gl.bufferData(vertexColors, gl.kStaticDraw);
} else {
gl.bufferData(vertices.colors, gl.kStaticDraw);
}
final Object colorLoc = gl.getAttributeLocation(glProgram.program, 'color');
vertexAttribPointerGlContext(gl.glContext, colorLoc, 4, gl.kUnsignedByte, true, 0, 0);
gl.enableVertexAttribArray(colorLoc);
} else {
// Copy image it to the texture.
texture = gl.createTexture();
// Texture units are a global array of references to the textures.
// By setting activeTexture, we associate the bound texture to a unit.
// Every time we call a texture function such as texImage2D with a target
// like TEXTURE_2D, it looks up texture by using the currently active
// unit.
// In our case we have a single texture unit 0.
gl.activeTexture(gl.kTexture0);
gl.bindTexture(gl.kTexture2D, texture);
gl.texImage2D(
gl.kTexture2D,
0,
gl.kRGBA,
gl.kRGBA,
gl.kUnsignedByte,
imageShader.image.imgElement,
);
if (isWebGl2) {
// Texture REPEAT and MIRROR is only supported in WebGL 2, for
// WebGL 1.0 we let shader compute correct uv coordinates.
gl.texParameteri(
gl.kTexture2D,
gl.kTextureWrapS,
tileModeToGlWrapping(gl, imageShader.tileModeX),
);
gl.texParameteri(
gl.kTexture2D,
gl.kTextureWrapT,
tileModeToGlWrapping(gl, imageShader.tileModeY),
);
// Mipmapping saves your texture in different resolutions
// so the graphics card can choose which resolution is optimal
// without artifacts.
gl.generateMipmap(gl.kTexture2D);
} else {
// For webgl1, if a texture is not mipmap complete, then the return
// value of a texel fetch is (0, 0, 0, 1), so we have to set
// minifying function to filter.
// See https://www.khronos.org/registry/webgl/specs/1.0.0/#5.13.8.
gl.texParameteri(gl.kTexture2D, gl.kTextureWrapS, gl.kClampToEdge);
gl.texParameteri(gl.kTexture2D, gl.kTextureWrapT, gl.kClampToEdge);
gl.texParameteri(gl.kTexture2D, gl.kTextureMinFilter, gl.kLinear);
}
}
// Finally render triangles.
gl.clear();
final Uint16List? indices = vertices.indices;
if (indices == null) {
gl.drawTriangles(vertexCount, vertices.mode);
} else {
/// If indices are specified to use shared vertices to reduce vertex
/// data transfer, use drawElements to map from vertex indices to
/// triangles.
final Object? indexBuffer = gl.createBuffer();
gl.bindElementArrayBuffer(indexBuffer);
gl.bufferElementData(indices, gl.kStaticDraw);
gl.drawElements(gl.kTriangles, indices.length, gl.kUnsignedShort);
}
if (vao != null) {
gl.unbindVertexArray();
}
context!.save();
context.resetTransform();
gl.drawImage(context, offsetX, offsetY);
context.restore();
}
/// Renders a rectangle using given program into an image resource.
///
/// Browsers that support OffscreenCanvas and the transferToImageBitmap api
/// will return ImageBitmap, otherwise will return CanvasElement.
@override
Object? drawRect(
ui.Rect targetRect,
GlContext gl,
GlProgram glProgram,
NormalizedGradient gradient,
int widthInPixels,
int heightInPixels,
) {
drawRectToGl(targetRect, gl, glProgram, gradient, widthInPixels, heightInPixels);
final Object? image = gl.readPatternData(gradient.isOpaque);
gl.bindArrayBuffer(null);
gl.bindElementArrayBuffer(null);
return image;
}
/// Renders a rectangle using given program into an image resource and returns
/// url.
@override
String drawRectToImageUrl(
ui.Rect targetRect,
GlContext gl,
GlProgram glProgram,
NormalizedGradient gradient,
int widthInPixels,
int heightInPixels,
) {
drawRectToGl(targetRect, gl, glProgram, gradient, widthInPixels, heightInPixels);
final String imageUrl = gl.toImageUrl();
// Cleanup buffers.
gl.bindArrayBuffer(null);
gl.bindElementArrayBuffer(null);
return imageUrl;
}
/// Renders a rectangle using given program into [GlContext].
///
/// Caller has to cleanup gl array and element array buffers.
void drawRectToGl(
ui.Rect targetRect,
GlContext gl,
GlProgram glProgram,
NormalizedGradient gradient,
int widthInPixels,
int heightInPixels,
) {
// Setup rectangle coordinates.
final double left = targetRect.left;
final double top = targetRect.top;
final double right = targetRect.right;
final double bottom = targetRect.bottom;
// Form 2 triangles for rectangle.
final Float32List vertices = Float32List(8);
vertices[0] = left;
vertices[1] = top;
vertices[2] = right;
vertices[3] = top;
vertices[4] = right;
vertices[5] = bottom;
vertices[6] = left;
vertices[7] = bottom;
final Object transformUniform = gl.getUniformLocation(glProgram.program, 'u_ctransform');
gl.setUniformMatrix4fv(transformUniform, false, Matrix4.identity().storage);
// Set uniform to scale 0..width/height pixels coordinates to -1..1
// clipspace range and flip the Y axis.
final Object resolution = gl.getUniformLocation(glProgram.program, 'u_scale');
gl.setUniform4f(
resolution,
2.0 / widthInPixels.toDouble(),
-2.0 / heightInPixels.toDouble(),
1,
1,
);
final Object shift = gl.getUniformLocation(glProgram.program, 'u_shift');
gl.setUniform4f(shift, -1, 1, 0, 0);
// Setup geometry.
final Object positionsBuffer = gl.createBuffer()!;
gl.bindArrayBuffer(positionsBuffer);
gl.bufferData(vertices, gl.kStaticDraw);
// Point an attribute to the currently bound vertex buffer object.
vertexAttribPointerGlContext(gl.glContext, 0, 2, gl.kFloat, false, 0, 0);
gl.enableVertexAttribArray(0);
// Setup color buffer.
final Object? colorsBuffer = gl.createBuffer();
gl.bindArrayBuffer(colorsBuffer);
// Buffer kBGRA_8888.
final Int32List colors = Int32List.fromList(<int>[
0xFF00FF00,
0xFF0000FF,
0xFFFFFF00,
0xFF00FFFF,
]);
gl.bufferData(colors, gl.kStaticDraw);
vertexAttribPointerGlContext(gl.glContext, 1, 4, gl.kUnsignedByte, true, 0, 0);
gl.enableVertexAttribArray(1);
final Object? indexBuffer = gl.createBuffer();
gl.bindElementArrayBuffer(indexBuffer);
gl.bufferElementData(VertexShaders.vertexIndicesForRect, gl.kStaticDraw);
if (gl.containsUniform(glProgram.program, 'u_resolution')) {
final Object uRes = gl.getUniformLocation(glProgram.program, 'u_resolution');
gl.setUniform2f(uRes, widthInPixels.toDouble(), heightInPixels.toDouble());
}
gl.clear();
gl.viewport(0, 0, widthInPixels.toDouble(), heightInPixels.toDouble());
gl.drawElements(gl.kTriangles, VertexShaders.vertexIndicesForRect.length, gl.kUnsignedShort);
}
/// This fragment shader enables Int32List of colors to be passed directly
/// to gl context buffer for rendering by decoding RGBA8888.
/// #version 300 es
/// precision mediump float;
/// in vec4 vColor;
/// out vec4 fragColor;
/// void main() {
/// fragColor = vColor;
/// }
String _writeVerticesFragmentShader() {
final ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion);
builder.floatPrecision = ShaderPrecision.kMedium;
builder.addIn(ShaderType.kVec4, name: 'v_color');
final ShaderMethod method = builder.addMethod('main');
method.addStatement('${builder.fragmentColor.name} = v_color;');
return builder.build();
}
@override
void drawHairline(DomCanvasRenderingContext2D? ctx, Float32List positions) {
final int pointCount = positions.length ~/ 2;
ctx!.lineWidth = 1.0;
ctx.beginPath();
final int len = pointCount * 2;
for (int i = 0; i < len;) {
for (int triangleVertexIndex = 0; triangleVertexIndex < 3; triangleVertexIndex++, i += 2) {
final double dx = positions[i];
final double dy = positions[i + 1];
switch (triangleVertexIndex) {
case 0:
ctx.moveTo(dx, dy);
case 1:
ctx.lineTo(dx, dy);
case 2:
ctx.lineTo(dx, dy);
ctx.closePath();
ctx.stroke();
}
}
}
}
}
ui.Rect _computeVerticesBounds(Float32List positions, Matrix4 transform) {
double minValueX, maxValueX, minValueY, maxValueY;
minValueX = maxValueX = positions[0];
minValueY = maxValueY = positions[1];
final int len = positions.length;
for (int i = 2; i < len; i += 2) {
final double x = positions[i];
final double y = positions[i + 1];
if (x.isNaN || y.isNaN) {
// Follows skia implementation that sets bounds to empty
// and aborts.
return ui.Rect.zero;
}
minValueX = math.min(minValueX, x);
maxValueX = math.max(maxValueX, x);
minValueY = math.min(minValueY, y);
maxValueY = math.max(maxValueY, y);
}
return _transformBounds(transform, minValueX, minValueY, maxValueX, maxValueY);
}
ui.Rect _transformBounds(Matrix4 transform, double left, double top, double right, double bottom) {
final Float32List storage = transform.storage;
final double m0 = storage[0];
final double m1 = storage[1];
final double m4 = storage[4];
final double m5 = storage[5];
final double m12 = storage[12];
final double m13 = storage[13];
final double x0 = (m0 * left) + (m4 * top) + m12;
final double y0 = (m1 * left) + (m5 * top) + m13;
final double x1 = (m0 * right) + (m4 * top) + m12;
final double y1 = (m1 * right) + (m5 * top) + m13;
final double x2 = (m0 * right) + (m4 * bottom) + m12;
final double y2 = (m1 * right) + (m5 * bottom) + m13;
final double x3 = (m0 * left) + (m4 * bottom) + m12;
final double y3 = (m1 * left) + (m5 * bottom) + m13;
return ui.Rect.fromLTRB(
math.min(x0, math.min(x1, math.min(x2, x3))),
math.min(y0, math.min(y1, math.min(y2, y3))),
math.max(x0, math.max(x1, math.max(x2, x3))),
math.max(y0, math.max(y1, math.max(y2, y3))),
);
}
/// Converts from [VertexMode] triangleFan and triangleStrip to triangles.
Float32List convertVertexPositions(ui.VertexMode mode, Float32List positions) {
assert(mode != ui.VertexMode.triangles);
if (mode == ui.VertexMode.triangleFan) {
final int coordinateCount = positions.length ~/ 2;
final int triangleCount = coordinateCount - 2;
final Float32List triangleList = Float32List(triangleCount * 3 * 2);
final double centerX = positions[0];
final double centerY = positions[1];
int destIndex = 0;
int positionIndex = 2;
for (
int triangleIndex = 0;
triangleIndex < triangleCount;
triangleIndex++, positionIndex += 2
) {
triangleList[destIndex++] = centerX;
triangleList[destIndex++] = centerY;
triangleList[destIndex++] = positions[positionIndex];
triangleList[destIndex++] = positions[positionIndex + 1];
triangleList[destIndex++] = positions[positionIndex + 2];
triangleList[destIndex++] = positions[positionIndex + 3];
}
return triangleList;
} else {
assert(mode == ui.VertexMode.triangleStrip);
// Set of connected triangles. Each triangle shares 2 last vertices.
final int vertexCount = positions.length ~/ 2;
final int triangleCount = vertexCount - 2;
double x0 = positions[0];
double y0 = positions[1];
double x1 = positions[2];
double y1 = positions[3];
final Float32List triangleList = Float32List(triangleCount * 3 * 2);
int destIndex = 0;
for (int i = 0, positionIndex = 4; i < triangleCount; i++) {
final double x2 = positions[positionIndex++];
final double y2 = positions[positionIndex++];
triangleList[destIndex++] = x0;
triangleList[destIndex++] = y0;
triangleList[destIndex++] = x1;
triangleList[destIndex++] = y1;
triangleList[destIndex++] = x2;
triangleList[destIndex++] = y2;
x0 = x1;
y0 = y1;
x1 = x2;
y1 = y2;
}
return triangleList;
}
}

View File

@@ -1,387 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:js_interop';
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
class HtmlRenderer implements Renderer {
static HtmlRenderer get instance => _instance;
static late HtmlRenderer _instance;
@override
String get rendererTag => 'html';
late final HtmlFontCollection _fontCollection = HtmlFontCollection();
@override
HtmlFontCollection get fontCollection => _fontCollection;
@override
void initialize() {
scheduleMicrotask(() {
// Access [lineLookup] to force the lazy unpacking of line break data
// now. Removing this line won't break anything. It's just an optimization
// to make the unpacking happen while we are waiting for network requests.
lineLookup;
});
_instance = this;
}
@override
ui.Paint createPaint() => SurfacePaint();
@override
ui.Vertices createVertices(
ui.VertexMode mode,
List<ui.Offset> positions, {
List<ui.Offset>? textureCoordinates,
List<ui.Color>? colors,
List<int>? indices,
}) => SurfaceVertices(mode, positions, colors: colors, indices: indices);
@override
ui.Vertices createVerticesRaw(
ui.VertexMode mode,
Float32List positions, {
Float32List? textureCoordinates,
Int32List? colors,
Uint16List? indices,
}) => SurfaceVertices.raw(mode, positions, colors: colors, indices: indices);
@override
ui.Canvas createCanvas(ui.PictureRecorder recorder, [ui.Rect? cullRect]) =>
SurfaceCanvas(recorder as EnginePictureRecorder, cullRect);
@override
ui.Gradient createLinearGradient(
ui.Offset from,
ui.Offset to,
List<ui.Color> colors, [
List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
Float32List? matrix4,
]) => GradientLinear(from, to, colors, colorStops, tileMode, matrix4);
@override
ui.Gradient createRadialGradient(
ui.Offset center,
double radius,
List<ui.Color> colors, [
List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
Float32List? matrix4,
]) => GradientRadial(center, radius, colors, colorStops, tileMode, matrix4);
@override
ui.Gradient createConicalGradient(
ui.Offset focal,
double focalRadius,
ui.Offset center,
double radius,
List<ui.Color> colors, [
List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
Float32List? matrix,
]) => GradientConical(focal, focalRadius, center, radius, colors, colorStops, tileMode, matrix);
@override
ui.Gradient createSweepGradient(
ui.Offset center,
List<ui.Color> colors, [
List<double>? colorStops,
ui.TileMode tileMode = ui.TileMode.clamp,
double startAngle = 0.0,
double endAngle = math.pi * 2,
Float32List? matrix4,
]) => GradientSweep(center, colors, colorStops, tileMode, startAngle, endAngle, matrix4);
@override
ui.PictureRecorder createPictureRecorder() => EnginePictureRecorder();
@override
ui.SceneBuilder createSceneBuilder() => SurfaceSceneBuilder();
// TODO(ferhat): implement TileMode.
@override
ui.ImageFilter createBlurImageFilter({
double sigmaX = 0.0,
double sigmaY = 0.0,
ui.TileMode? tileMode,
}) => EngineImageFilter.blur(sigmaX: sigmaX, sigmaY: sigmaY, tileMode: tileMode);
@override
ui.ImageFilter createDilateImageFilter({double radiusX = 0.0, double radiusY = 0.0}) {
// TODO(fzyzcjy): implement dilate. https://github.com/flutter/flutter/issues/101085
throw UnimplementedError('ImageFilter.dilate not implemented for HTML renderer.');
}
@override
ui.ImageFilter createErodeImageFilter({double radiusX = 0.0, double radiusY = 0.0}) {
// TODO(fzyzcjy): implement erode. https://github.com/flutter/flutter/issues/101085
throw UnimplementedError('ImageFilter.erode not implemented for HTML renderer.');
}
@override
ui.ImageFilter createMatrixImageFilter(
Float64List matrix4, {
ui.FilterQuality filterQuality = ui.FilterQuality.low,
}) => EngineImageFilter.matrix(matrix: matrix4, filterQuality: filterQuality);
@override
ui.ImageFilter composeImageFilters({
required ui.ImageFilter outer,
required ui.ImageFilter inner,
}) {
// TODO(ferhat): add implementation.
throw UnimplementedError('ImageFilter.erode not implemented for HTML renderer.');
}
@override
Future<ui.Codec> instantiateImageCodec(
Uint8List list, {
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true,
}) async {
final DomBlob blob = createDomBlob(<dynamic>[list.buffer]);
return HtmlRendererBlobCodec(blob);
}
@override
Future<ui.Codec> instantiateImageCodecFromUrl(
Uri uri, {
ui_web.ImageCodecChunkCallback? chunkCallback,
}) async {
return HtmlRendererImageCodec(uri.toString(), chunkCallback: chunkCallback);
}
@override
void decodeImageFromPixels(
Uint8List pixels,
int width,
int height,
ui.PixelFormat format,
ui.ImageDecoderCallback callback, {
int? rowBytes,
int? targetWidth,
int? targetHeight,
bool allowUpscaling = true,
}) {
void executeCallback(ui.Codec codec) {
codec.getNextFrame().then((ui.FrameInfo frameInfo) {
callback(frameInfo.image);
});
}
ui.createBmp(pixels, width, height, rowBytes ?? width, format).then(executeCallback);
}
@override
ui.ImageShader createImageShader(
ui.Image image,
ui.TileMode tmx,
ui.TileMode tmy,
Float64List matrix4,
ui.FilterQuality? filterQuality,
) => EngineImageShader(image, tmx, tmy, matrix4, filterQuality);
@override
ui.Path createPath() => SurfacePath();
@override
ui.Path copyPath(ui.Path src) => SurfacePath.from(src as SurfacePath);
@override
ui.Path combinePaths(ui.PathOperation op, ui.Path path1, ui.Path path2) {
throw UnimplementedError('combinePaths not implemented in HTML renderer.');
}
@override
ui.TextStyle createTextStyle({
ui.Color? color,
ui.TextDecoration? decoration,
ui.Color? decorationColor,
ui.TextDecorationStyle? decorationStyle,
double? decorationThickness,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
ui.TextBaseline? textBaseline,
String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
double? letterSpacing,
double? wordSpacing,
double? height,
ui.TextLeadingDistribution? leadingDistribution,
ui.Locale? locale,
ui.Paint? background,
ui.Paint? foreground,
List<ui.Shadow>? shadows,
List<ui.FontFeature>? fontFeatures,
List<ui.FontVariation>? fontVariations,
}) => EngineTextStyle(
color: color,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
decorationThickness: decorationThickness,
fontWeight: fontWeight,
fontStyle: fontStyle,
textBaseline: textBaseline,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSize: fontSize,
letterSpacing: letterSpacing,
wordSpacing: wordSpacing,
height: height,
leadingDistribution: leadingDistribution,
locale: locale,
background: background,
foreground: foreground,
shadows: shadows,
fontFeatures: fontFeatures,
fontVariations: fontVariations,
);
@override
ui.ParagraphStyle createParagraphStyle({
ui.TextAlign? textAlign,
ui.TextDirection? textDirection,
int? maxLines,
String? fontFamily,
double? fontSize,
double? height,
ui.TextHeightBehavior? textHeightBehavior,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
ui.StrutStyle? strutStyle,
String? ellipsis,
ui.Locale? locale,
}) => EngineParagraphStyle(
textAlign: textAlign,
textDirection: textDirection,
maxLines: maxLines,
fontFamily: fontFamily,
fontSize: fontSize,
height: height,
textHeightBehavior: textHeightBehavior,
fontWeight: fontWeight,
fontStyle: fontStyle,
strutStyle: strutStyle,
ellipsis: ellipsis,
locale: locale,
);
@override
ui.StrutStyle createStrutStyle({
String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
double? height,
ui.TextLeadingDistribution? leadingDistribution,
double? leading,
ui.FontWeight? fontWeight,
ui.FontStyle? fontStyle,
bool? forceStrutHeight,
}) => EngineStrutStyle(
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSize: fontSize,
height: height,
leadingDistribution: leadingDistribution,
leading: leading,
fontWeight: fontWeight,
fontStyle: fontStyle,
forceStrutHeight: forceStrutHeight,
);
@override
ui.ParagraphBuilder createParagraphBuilder(ui.ParagraphStyle style) =>
CanvasParagraphBuilder(style as EngineParagraphStyle);
@override
Future<void> renderScene(ui.Scene scene, EngineFlutterView view) async {
final EngineFlutterView implicitView = EnginePlatformDispatcher.instance.implicitView!;
scene as SurfaceScene;
implicitView.dom.setScene(scene.webOnlyRootElement!);
final FrameTimingRecorder? recorder = scene.timingRecorder;
recorder?.recordRasterFinish();
recorder?.submitTimings();
}
@override
void clearFragmentProgramCache() {}
@override
Future<ui.FragmentProgram> createFragmentProgram(String assetKey) {
return Future<HtmlFragmentProgram>.value(HtmlFragmentProgram());
}
@override
ui.LineMetrics createLineMetrics({
required bool hardBreak,
required double ascent,
required double descent,
required double unscaledAscent,
required double height,
required double width,
required double left,
required double baseline,
required int lineNumber,
}) => EngineLineMetrics(
hardBreak: hardBreak,
ascent: ascent,
descent: descent,
unscaledAscent: unscaledAscent,
height: height,
width: width,
left: left,
baseline: baseline,
lineNumber: lineNumber,
);
@override
Future<ui.Image> createImageFromImageBitmap(DomImageBitmap imageSource) async {
final int width = imageSource.width.toDartInt;
final int height = imageSource.height.toDartInt;
final OffScreenCanvas canvas = OffScreenCanvas(width, height);
final DomCanvasRenderingContextBitmapRenderer context = canvas.getBitmapRendererContext()!;
context.transferFromImageBitmap(imageSource);
final DomHTMLImageElement imageElement = createDomHTMLImageElement();
late final DomEventListener loadListener;
late final DomEventListener errorListener;
final Completer<HtmlImage> completer = Completer<HtmlImage>();
loadListener = createDomEventListener((DomEvent event) {
completer.complete(HtmlImage(imageElement, width, height));
imageElement.removeEventListener('load', loadListener);
imageElement.removeEventListener('error', errorListener);
});
errorListener = createDomEventListener((DomEvent event) {
completer.completeError(Exception('Failed to create image from image bitmap.'));
imageElement.removeEventListener('load', loadListener);
imageElement.removeEventListener('error', errorListener);
});
imageElement.addEventListener('load', loadListener);
imageElement.addEventListener('error', errorListener);
imageElement.src = await canvas.toDataUrl();
return completer.future;
}
@override
FutureOr<ui.Image> createImageFromTextureSource(
JSAny object, {
required int width,
required int height,
required bool transferOwnership,
}) {
throw Exception('Not implemented for HTML renderer');
}
}

View File

@@ -1,79 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../dom.dart';
import '../view_embedder/dom_manager.dart';
import '../window.dart';
/// Manages global resources for the singleton Flutter Window in the HTML
/// renderer.
///
/// It's used for resources that are referenced by CSS, such as svg filters.
class ResourceManager {
ResourceManager(this._domManager);
final DomManager _domManager;
static const String resourcesHostTagName = 'flt-svg-filters';
static ResourceManager? _instance;
static ResourceManager get instance {
assert(_instance != null, 'ResourceManager has not been initialized.');
return _instance!;
}
/// A child element of body outside the shadowroot that hosts
/// global resources such svg filters and clip paths when using webkit.
DomElement? _resourcesHost;
/// Add an element as a global resource to be referenced by CSS.
///
/// Creates a global resource host element on demand and either places it as
/// first element of body(webkit), or as a child of the implicit view element
/// for other browsers to make sure url resolution works correctly when
/// content is inside a shadow root.
void addResource(DomElement element) {
_getOrCreateResourcesHost().append(element);
}
DomElement _getOrCreateResourcesHost() {
if (_resourcesHost != null) {
return _resourcesHost!;
}
final DomElement resourcesHost = domDocument.createElement(resourcesHostTagName);
resourcesHost.style.visibility = 'hidden';
_resourcesHost = resourcesHost;
if (ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit) {
final DomElement rootElement = _domManager.rootElement;
// The resourcesHost *must* be a sibling of the rootElement.
rootElement.parent!.prepend(resourcesHost);
} else {
final DomShadowRoot renderingHost = _domManager.renderingHost;
renderingHost.prepend(resourcesHost);
}
return resourcesHost;
}
/// Removes a global resource element.
void removeResource(DomElement? element) {
if (element == null) {
return;
}
assert(element.parentNode == _resourcesHost);
element.remove();
}
}
/// Initializes the [ResourceManager.instance] singleton if it hasn't been
/// initialized yet.
void ensureResourceManagerInitialized(EngineFlutterWindow implicitView) {
if (ResourceManager._instance != null) {
return;
}
ResourceManager._instance = ResourceManager(implicitView.dom);
}

View File

@@ -1,74 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
class SurfaceScene implements ui.Scene {
/// This class is created by the engine, and should not be instantiated
/// or extended directly.
///
/// To create a Scene object, use a [SceneBuilder].
SurfaceScene(this.webOnlyRootElement, {required this.timingRecorder});
final DomElement? webOnlyRootElement;
final FrameTimingRecorder? timingRecorder;
/// Creates a raster image representation of the current state of the scene.
/// This is a slow operation that is performed on a background thread.
@override
Future<ui.Image> toImage(int width, int height) {
throw UnsupportedError('toImage is not supported on the Web');
}
@override
ui.Image toImageSync(int width, int height) {
throw UnsupportedError('toImageSync is not supported on the Web');
}
/// Releases the resources used by this scene.
///
/// After calling this function, the scene is cannot be used further.
@override
void dispose() {}
}
/// A surface that creates a DOM element for whole app.
class PersistedScene extends PersistedContainerSurface {
PersistedScene(PersistedScene? super.oldLayer) {
transform = Matrix4.identity();
}
@override
void recomputeTransformAndClip() {
// Must be the true DPR from the browser, nothing overridable.
// See: https://github.com/flutter/flutter/issues/143124
final double browserDpr = EngineFlutterDisplay.instance.browserDevicePixelRatio;
// The scene clip is the size of the entire window **in Logical pixels**.
//
// Even though the majority of the engine uses `physicalSize`, there are some
// bits (like the HTML renderer, or dynamic view sizing) that are implemented
// using CSS, and CSS operates in logical pixels.
//
// See also: [EngineFlutterView.resize].
final ui.Size bounds = window.physicalSize / browserDpr;
localClipBounds = ui.Rect.fromLTRB(0, 0, bounds.width, bounds.height);
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.identity();
@override
DomElement createElement() {
return defaultCreateElement('flt-scene');
}
@override
void apply() {}
}

View File

@@ -1,535 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../../engine.dart' show FrameTimingRecorder, kProfileApplyFrame, kProfilePrerollFrame;
import '../display.dart';
import '../dom.dart';
import '../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_to_svg_clip.dart';
import 'picture.dart';
import 'platform_view.dart';
import 'scene.dart';
import 'shader_mask.dart';
import 'surface.dart';
import 'transform.dart';
class SurfaceSceneBuilder implements ui.SceneBuilder {
SurfaceSceneBuilder() {
_surfaceStack.add(PersistedScene(_lastFrameScene));
}
final List<PersistedContainerSurface> _surfaceStack = <PersistedContainerSurface>[];
/// The scene built by this scene builder.
///
/// This getter should only be called after all surfaces are built.
PersistedScene get _persistedScene {
return _surfaceStack.first as PersistedScene;
}
/// The surface currently being built.
PersistedContainerSurface get _currentSurface => _surfaceStack.last;
T _pushSurface<T extends PersistedContainerSurface>(T surface) {
// Only attempt to update if the update is requested and the surface is in
// the live tree.
if (surface.oldLayer != null) {
assert(surface.oldLayer!.runtimeType == surface.runtimeType);
assert(debugAssertSurfaceState(surface.oldLayer!, PersistedSurfaceState.active));
surface.oldLayer!.state = PersistedSurfaceState.pendingUpdate;
}
_adoptSurface(surface);
_surfaceStack.add(surface);
return surface;
}
/// Adds [surface] to the surface tree.
///
/// This is used by tests.
void debugAddSurface(PersistedSurface surface) {
assert(() {
_addSurface(surface);
return true;
}());
}
void _addSurface(PersistedSurface surface) {
_adoptSurface(surface);
}
void _adoptSurface(PersistedSurface surface) {
_currentSurface.appendChild(surface);
}
/// Pushes an offset operation onto the operation stack.
///
/// This is equivalent to [pushTransform] with a matrix with only translation.
///
/// See [pop] for details about the operation stack.
@override
ui.OffsetEngineLayer pushOffset(double dx, double dy, {ui.OffsetEngineLayer? oldLayer}) {
return _pushSurface<PersistedOffset>(PersistedOffset(oldLayer as PersistedOffset?, dx, dy));
}
/// Pushes a transform operation onto the operation stack.
///
/// The objects are transformed by the given matrix before rasterization.
///
/// See [pop] for details about the operation stack.
@override
ui.TransformEngineLayer pushTransform(Float64List matrix4, {ui.TransformEngineLayer? oldLayer}) {
if (matrix4.length != 16) {
throw ArgumentError('"matrix4" must have 16 entries.');
}
final Float32List matrix;
if (_surfaceStack.length == 1) {
// Top level transform contains view configuration to scale
// scene to devicepixelratio. Use identity instead since CSS uses
// logical device pixels.
if (!ui_web.debugEmulateFlutterTesterEnvironment) {
assert(
matrix4[0] == EngineFlutterDisplay.instance.devicePixelRatio &&
matrix4[5] == EngineFlutterDisplay.instance.devicePixelRatio,
);
}
matrix = Matrix4.identity().storage;
} else {
matrix = toMatrix32(matrix4);
}
return _pushSurface<PersistedTransform>(
PersistedTransform(oldLayer as PersistedTransform?, matrix),
);
}
/// Pushes a rectangular clip operation onto the operation stack.
///
/// Rasterization outside the given rectangle is discarded.
///
/// See [pop] for details about the operation stack, and [Clip] for different clip modes.
/// By default, the clip will be anti-aliased (clip = [Clip.antiAlias]).
@override
ui.ClipRectEngineLayer pushClipRect(
ui.Rect rect, {
ui.Clip clipBehavior = ui.Clip.antiAlias,
ui.ClipRectEngineLayer? oldLayer,
}) {
return _pushSurface<PersistedClipRect>(
PersistedClipRect(oldLayer as PersistedClipRect?, rect, clipBehavior),
);
}
/// Pushes a rounded-rectangular clip operation onto the operation stack.
///
/// Rasterization outside the given rounded rectangle is discarded.
///
/// See [pop] for details about the operation stack.
@override
ui.ClipRRectEngineLayer pushClipRRect(
ui.RRect rrect, {
ui.Clip? clipBehavior,
ui.ClipRRectEngineLayer? oldLayer,
}) {
return _pushSurface<PersistedClipRRect>(PersistedClipRRect(oldLayer, rrect, clipBehavior));
}
/// Pushes a rounded-superellipse clip operation onto the operation stack.
///
/// Rasterization outside the given rounded rectangle is discarded.
///
/// See [pop] for details about the operation stack.
@override
ui.ClipRSuperellipseEngineLayer pushClipRSuperellipse(
ui.RSuperellipse rse, {
ui.Clip? clipBehavior,
ui.ClipRSuperellipseEngineLayer? oldLayer,
}) {
return _pushSurface<PersistedClipRSuperellipse>(
PersistedClipRSuperellipse(oldLayer, rse, clipBehavior),
);
}
/// Pushes a path clip operation onto the operation stack.
///
/// Rasterization outside the given path is discarded.
///
/// See [pop] for details about the operation stack.
@override
ui.ClipPathEngineLayer pushClipPath(
ui.Path path, {
ui.Clip clipBehavior = ui.Clip.antiAlias,
ui.ClipPathEngineLayer? oldLayer,
}) {
return _pushSurface<PersistedClipPath>(
PersistedClipPath(oldLayer as PersistedClipPath?, path, clipBehavior),
);
}
/// Pushes an opacity operation onto the operation stack.
///
/// The given alpha value is blended into the alpha value of the objects'
/// rasterization. An alpha value of 0 makes the objects entirely invisible.
/// An alpha value of 255 has no effect (i.e., the objects retain the current
/// opacity).
///
/// See [pop] for details about the operation stack.
@override
ui.OpacityEngineLayer pushOpacity(
int alpha, {
ui.Offset offset = ui.Offset.zero,
ui.OpacityEngineLayer? oldLayer,
}) {
return _pushSurface<PersistedOpacity>(
PersistedOpacity(oldLayer as PersistedOpacity?, alpha, offset),
);
}
/// Pushes a color filter operation onto the operation stack.
///
/// The given color is applied to the objects' rasterization using the given
/// blend mode.
///
/// {@macro dart.ui.sceneBuilder.oldLayer}
///
/// {@macro dart.ui.sceneBuilder.oldLayerVsRetained}
///
/// See [pop] for details about the operation stack.
@override
ui.ColorFilterEngineLayer pushColorFilter(
ui.ColorFilter filter, {
ui.ColorFilterEngineLayer? oldLayer,
}) {
return _pushSurface<PersistedColorFilter>(
PersistedColorFilter(oldLayer as PersistedColorFilter?, filter),
);
}
/// Pushes an image filter operation onto the operation stack.
///
/// The given filter is applied to the children's rasterization before compositing them into
/// the scene.
///
/// {@macro dart.ui.sceneBuilder.oldLayer}
///
/// {@macro dart.ui.sceneBuilder.oldLayerVsRetained}
///
/// See [pop] for details about the operation stack.
@override
ui.ImageFilterEngineLayer pushImageFilter(
ui.ImageFilter filter, {
ui.Offset offset = ui.Offset.zero,
ui.ImageFilterEngineLayer? oldLayer,
}) {
return _pushSurface<PersistedImageFilter>(
PersistedImageFilter(oldLayer as PersistedImageFilter?, filter, offset),
);
}
/// Pushes a backdrop filter operation onto the operation stack.
///
/// The given filter is applied to the current contents of the scene prior to
/// rasterizing the child layers.
///
/// The [blendMode] argument is required for [ui.SceneBuilder] compatibility, but is
/// ignored by the DOM renderer.
///
/// See [pop] for details about the operation stack.
@override
ui.BackdropFilterEngineLayer pushBackdropFilter(
ui.ImageFilter filter, {
ui.BlendMode blendMode = ui.BlendMode.srcOver,
ui.BackdropFilterEngineLayer? oldLayer,
int? backdropId,
}) {
return _pushSurface<PersistedBackdropFilter>(
PersistedBackdropFilter(oldLayer as PersistedBackdropFilter?, filter),
);
}
/// Pushes a shader mask operation onto the operation stack.
///
/// The given shader is applied to the object's rasterization in the given
/// rectangle using the given blend mode.
///
/// See [pop] for details about the operation stack.
@override
ui.ShaderMaskEngineLayer pushShaderMask(
ui.Shader shader,
ui.Rect maskRect,
ui.BlendMode blendMode, {
ui.ShaderMaskEngineLayer? oldLayer,
ui.FilterQuality filterQuality = ui.FilterQuality.low,
}) {
return _pushSurface<PersistedShaderMask>(
PersistedShaderMask(
oldLayer as PersistedShaderMask?,
shader,
maskRect,
blendMode,
filterQuality,
),
);
}
/// Add a retained engine layer subtree from previous frames.
///
/// All the engine layers that are in the subtree of the retained layer will
/// be automatically appended to the current engine layer tree.
///
/// Therefore, when implementing a subclass of the [Layer] concept defined in
/// the rendering layer of Flutter's framework, once this is called, there's
/// no need to call [addToScene] for its children layers.
@override
void addRetained(ui.EngineLayer retainedLayer) {
final PersistedContainerSurface retainedSurface = retainedLayer as PersistedContainerSurface;
assert(
debugAssertSurfaceState(
retainedSurface,
PersistedSurfaceState.active,
PersistedSurfaceState.released,
),
);
retainedSurface.tryRetain();
_adoptSurface(retainedSurface);
}
/// Ends the effect of the most recently pushed operation.
///
/// Internally the scene builder maintains a stack of operations. Each of the
/// operations in the stack applies to each of the objects added to the scene.
/// Calling this function removes the most recently added operation from the
/// stack.
@override
void pop() {
assert(_surfaceStack.isNotEmpty);
_surfaceStack.removeLast();
}
/// Adds an object to the scene that displays performance statistics.
///
/// Useful during development to assess the performance of the application.
/// The enabledOptions controls which statistics are displayed. The bounds
/// controls where the statistics are displayed.
///
/// enabledOptions is a bit field with the following bits defined:
/// - 0x01: displayRasterizerStatistics - show raster thread frame time
/// - 0x02: visualizeRasterizerStatistics - graph raster thread frame times
/// - 0x04: displayEngineStatistics - show UI thread frame time
/// - 0x08: visualizeEngineStatistics - graph UI thread frame times
/// Set enabledOptions to 0x0F to enable all the currently defined features.
///
/// The "UI thread" is the thread that includes all the execution of the main
/// Dart isolate (the isolate that can call [FlutterView.render]). The UI
/// thread frame time is the total time spent executing the
/// [FlutterView.onBeginFrame] callback. The "raster thread" is the thread
/// (running on the CPU) that subsequently processes the [Scene] provided by
/// the Dart code to turn it into GPU commands and send it to the GPU.
///
/// See also the [PerformanceOverlayOption] enum in the rendering library.
/// for more details.
@override
void addPerformanceOverlay(int enabledOptions, ui.Rect bounds) {
_addPerformanceOverlay(enabledOptions, bounds.left, bounds.right, bounds.top, bounds.bottom);
}
/// Whether we've already warned the user about the lack of the performance
/// overlay or not.
///
/// We use this to avoid spamming the console with redundant warning messages.
static bool _didWarnAboutPerformanceOverlay = false;
void _addPerformanceOverlay(
int enabledOptions,
double left,
double right,
double top,
double bottom,
) {
if (!_didWarnAboutPerformanceOverlay) {
_didWarnAboutPerformanceOverlay = true;
printWarning("The performance overlay isn't supported on the web");
}
}
/// Adds a [Picture] to the scene.
///
/// The picture is rasterized at the given offset.
@override
void addPicture(
ui.Offset offset,
ui.Picture picture, {
bool isComplexHint = false,
bool willChangeHint = false,
}) {
int hints = 0;
if (isComplexHint) {
hints |= 1;
}
if (willChangeHint) {
hints |= 2;
}
_addSurface(PersistedPicture(offset.dx, offset.dy, picture as EnginePicture, hints));
}
/// Adds a backend texture to the scene.
///
/// The texture is scaled to the given size and rasterized at the given
/// offset.
@override
void addTexture(
int textureId, {
ui.Offset offset = ui.Offset.zero,
double width = 0.0,
double height = 0.0,
bool freeze = false,
ui.FilterQuality filterQuality = ui.FilterQuality.low,
}) {
_addTexture(offset.dx, offset.dy, width, height, textureId, filterQuality);
}
void _addTexture(
double dx,
double dy,
double width,
double height,
int textureId,
ui.FilterQuality filterQuality,
) {
// In test mode, allow this to be a no-op.
if (!ui_web.debugEmulateFlutterTesterEnvironment) {
throw UnimplementedError('Textures are not supported in Flutter Web');
}
}
/// Adds a platform view (e.g an iOS UIView) to the scene.
///
/// Only supported on iOS, this is currently a no-op on other platforms.
///
/// On iOS this layer splits the current output surface into two surfaces, one for the scene nodes
/// preceding the platform view, and one for the scene nodes following the platform view.
///
/// ## Performance impact
///
/// Adding an additional surface doubles the amount of graphics memory directly used by Flutter
/// for output buffers. Quartz might allocated extra buffers for compositing the Flutter surfaces
/// and the platform view.
///
/// With a platform view in the scene, Quartz has to composite the two Flutter surfaces and the
/// embedded UIView. In addition to that, on iOS versions greater than 9, the Flutter frames are
/// synchronized with the UIView frames adding additional performance overhead.
@override
void addPlatformView(
int viewId, {
ui.Offset offset = ui.Offset.zero,
double width = 0.0,
double height = 0.0,
}) {
_addPlatformView(offset.dx, offset.dy, width, height, viewId);
}
void _addPlatformView(double dx, double dy, double width, double height, int viewId) {
_addSurface(PersistedPlatformView(viewId, dx, dy, width, height));
}
/// The scene recorded in the last frame.
///
/// This is a surface tree that holds onto the DOM elements that can be reused
/// on the next frame.
static PersistedScene? _lastFrameScene;
/// Returns the computed persisted scene graph recorded in the last frame.
///
/// This is only available in debug mode. It returns `null` in profile and
/// release modes.
static PersistedScene? get debugLastFrameScene {
PersistedScene? result;
assert(() {
result = _lastFrameScene;
return true;
}());
return result;
}
/// Discards information about previously rendered frames, including DOM
/// elements and cached canvases.
///
/// After calling this function new canvases will be created for the
/// subsequent scene. This is useful when tests need predictable canvas
/// sizes. If the cache is not cleared, then canvases allocated in one test
/// may be reused in another test.
static void debugForgetFrameScene() {
_lastFrameScene?.rootElement?.remove();
_lastFrameScene = null;
resetSvgClipIds();
recycledCanvases.clear();
}
/// Finishes building the scene.
///
/// Returns a [Scene] containing the objects that have been added to
/// this scene builder. The [Scene] can then be displayed on the
/// screen with [FlutterView.render].
///
/// After calling this function, the scene builder object is invalid and
/// cannot be used further.
@override
SurfaceScene build() {
// "Build finish" and "raster start" happen back-to-back because we
// render on the same thread, so there's no overhead from hopping to
// another thread.
//
// In the HTML renderer we time the beginning of the rasterization phase
// (counter-intuitively) in SceneBuilder.build because DOM updates happen
// here. This is different from CanvasKit.
final FrameTimingRecorder? recorder =
FrameTimingRecorder.frameTimingsEnabled ? FrameTimingRecorder() : null;
recorder?.recordBuildFinish();
recorder?.recordRasterStart();
timeAction<void>(kProfilePrerollFrame, () {
while (_surfaceStack.length > 1) {
// Auto-pop layers that were pushed without a corresponding pop.
pop();
}
_persistedScene.preroll(PrerollSurfaceContext());
});
return timeAction<SurfaceScene>(kProfileApplyFrame, () {
if (_lastFrameScene == null) {
_persistedScene.build();
} else {
_persistedScene.update(_lastFrameScene!);
}
commitScene(_persistedScene);
_lastFrameScene = _persistedScene;
return SurfaceScene(_persistedScene.rootElement, timingRecorder: recorder);
});
}
/// Set properties on the linked scene. These properties include its bounds,
/// as well as whether it can be the target of focus events or not.
@override
void setProperties(
double width,
double height,
double insetTop,
double insetRight,
double insetBottom,
double insetLeft,
bool focusable,
) {
throw UnimplementedError();
}
}

View File

@@ -1,398 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../dom.dart';
import 'bitmap_canvas.dart';
import 'color_filter.dart';
import 'resource_manager.dart';
import 'shaders/shader.dart';
import 'surface.dart';
/// A surface that applies a shader to its children.
///
/// Currently there are 2 types of shaders:
/// - Gradients
/// - ImageShader
///
/// Gradients
/// The gradients can be applied to the child tree by rendering the gradient
/// into an image and referencing the image in an svg filter to apply
/// to DOM tree.
///
class PersistedShaderMask extends PersistedContainerSurface implements ui.ShaderMaskEngineLayer {
PersistedShaderMask(
PersistedShaderMask? super.oldLayer,
this.shader,
this.maskRect,
this.blendMode,
this.filterQuality,
);
DomElement? _childContainer;
final ui.Shader shader;
final ui.Rect maskRect;
final ui.BlendMode blendMode;
final ui.FilterQuality filterQuality;
DomElement? _shaderElement;
final bool isWebKit = ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit;
@override
void adoptElements(PersistedShaderMask oldSurface) {
super.adoptElements(oldSurface);
_childContainer = oldSurface._childContainer;
_shaderElement = oldSurface._shaderElement;
oldSurface._childContainer = null;
oldSurface._shaderElement = null;
}
@override
DomElement? get childContainer => _childContainer;
@override
void discard() {
super.discard();
ResourceManager.instance.removeResource(_shaderElement);
_shaderElement = null;
// Do not detach the child container from the root. It is permanently
// attached. The elements are reused together and are detached from the DOM
// together.
_childContainer = null;
}
@override
void preroll(PrerollSurfaceContext prerollContext) {
++prerollContext.activeShaderMaskCount;
super.preroll(prerollContext);
--prerollContext.activeShaderMaskCount;
}
@override
DomElement createElement() {
final DomElement element = defaultCreateElement('flt-shader-mask');
final DomElement container = createDomElement('flt-mask-interior');
container.style.position = 'absolute';
_childContainer = container;
element.append(_childContainer!);
return element;
}
@override
void apply() {
ResourceManager.instance.removeResource(_shaderElement);
_shaderElement = null;
if (shader is ui.Gradient) {
rootElement!.style
..left = '${maskRect.left}px'
..top = '${maskRect.top}px'
..width = '${maskRect.width}px'
..height = '${maskRect.height}px';
_childContainer!.style
..left = '${-maskRect.left}px'
..top = '${-maskRect.top}px';
// Prevent ShaderMask from failing inside animations that size
// area to empty.
if (maskRect.width > 0 && maskRect.height > 0) {
_applyGradientShader();
}
return;
}
// TODO(ferhat): Implement _applyImageShader();
throw Exception('Shader type not supported for ShaderMask');
}
void _applyGradientShader() {
if (shader is EngineGradient) {
final EngineGradient gradientShader = shader as EngineGradient;
// The gradient shader's bounds are in the context of the element itself,
// rather than the global position, so translate it back to the origin.
final ui.Rect translatedRect = maskRect.translate(-maskRect.left, -maskRect.top);
final String imageUrl = gradientShader.createImageBitmap(translatedRect, 1, true) as String;
ui.BlendMode blendModeTemp = blendMode;
switch (blendModeTemp) {
case ui.BlendMode.clear:
case ui.BlendMode.dstOut:
case ui.BlendMode.srcOut:
childContainer?.style.visibility = 'hidden';
return;
case ui.BlendMode.dst:
case ui.BlendMode.dstIn:
// Noop. Should render existing destination.
rootElement!.style.filter = '';
return;
case ui.BlendMode.srcOver:
// Uses source filter color.
// Since we don't have a size, we can't use background color.
// Use svg filter srcIn instead.
blendModeTemp = ui.BlendMode.srcIn;
case ui.BlendMode.src:
case ui.BlendMode.dstOver:
case ui.BlendMode.srcIn:
case ui.BlendMode.srcATop:
case ui.BlendMode.dstATop:
case ui.BlendMode.xor:
case ui.BlendMode.plus:
case ui.BlendMode.modulate:
case ui.BlendMode.screen:
case ui.BlendMode.overlay:
case ui.BlendMode.darken:
case ui.BlendMode.lighten:
case ui.BlendMode.colorDodge:
case ui.BlendMode.colorBurn:
case ui.BlendMode.hardLight:
case ui.BlendMode.softLight:
case ui.BlendMode.difference:
case ui.BlendMode.exclusion:
case ui.BlendMode.multiply:
case ui.BlendMode.hue:
case ui.BlendMode.saturation:
case ui.BlendMode.color:
case ui.BlendMode.luminosity:
break;
}
final SvgFilter svgFilter = svgMaskFilterFromImageAndBlendMode(
imageUrl,
blendModeTemp,
maskRect.width,
maskRect.height,
);
_shaderElement = svgFilter.element;
if (isWebKit) {
_childContainer!.style.filter = 'url(#${svgFilter.id})';
} else {
rootElement!.style.filter = 'url(#${svgFilter.id})';
}
ResourceManager.instance.addResource(_shaderElement!);
}
}
@override
void update(PersistedShaderMask oldSurface) {
super.update(oldSurface);
if (shader != oldSurface.shader ||
maskRect != oldSurface.maskRect ||
blendMode != oldSurface.blendMode) {
apply();
}
}
}
SvgFilter svgMaskFilterFromImageAndBlendMode(
String imageUrl,
ui.BlendMode blendMode,
double width,
double height,
) {
final SvgFilter svgFilter;
switch (blendMode) {
case ui.BlendMode.src:
svgFilter = _srcImageToSvg(imageUrl, width, height);
case ui.BlendMode.srcIn:
case ui.BlendMode.srcATop:
svgFilter = _srcInImageToSvg(imageUrl, width, height);
case ui.BlendMode.srcOut:
svgFilter = _srcOutImageToSvg(imageUrl, width, height);
case ui.BlendMode.xor:
svgFilter = _xorImageToSvg(imageUrl, width, height);
case ui.BlendMode.plus:
// Porter duff source + destination.
svgFilter = _compositeImageToSvg(imageUrl, 0, 1, 1, 0, width, height);
case ui.BlendMode.modulate:
// Porter duff source * destination but preserves alpha.
svgFilter = _modulateImageToSvg(imageUrl, width, height);
case ui.BlendMode.overlay:
// Since overlay is the same as hard-light by swapping layers,
// pass hard-light blend function.
svgFilter = _blendImageToSvg(
imageUrl,
blendModeToSvgEnum(ui.BlendMode.hardLight)!,
width,
height,
swapLayers: true,
);
// Several of the filters below (although supported) do not render the
// same (close but not exact) as native flutter when used as blend mode
// for a background-image with a background color. They only look
// identical when feBlend is used within an svg filter definition.
//
// Saturation filter uses destination when source is transparent.
// cMax = math.max(r, math.max(b, g));
// cMin = math.min(r, math.min(b, g));
// delta = cMax - cMin;
// lightness = (cMax + cMin) / 2.0;
// saturation = delta / (1.0 - (2 * lightness - 1.0).abs());
case ui.BlendMode.saturation:
case ui.BlendMode.colorDodge:
case ui.BlendMode.colorBurn:
case ui.BlendMode.hue:
case ui.BlendMode.color:
case ui.BlendMode.luminosity:
case ui.BlendMode.multiply:
case ui.BlendMode.screen:
case ui.BlendMode.darken:
case ui.BlendMode.lighten:
case ui.BlendMode.hardLight:
case ui.BlendMode.softLight:
case ui.BlendMode.difference:
case ui.BlendMode.exclusion:
svgFilter = _blendImageToSvg(imageUrl, blendModeToSvgEnum(blendMode)!, width, height);
case ui.BlendMode.dst:
case ui.BlendMode.dstATop:
case ui.BlendMode.dstIn:
case ui.BlendMode.dstOut:
case ui.BlendMode.dstOver:
case ui.BlendMode.clear:
case ui.BlendMode.srcOver:
throw UnsupportedError('Invalid svg filter request for blend-mode $blendMode');
}
return svgFilter;
}
// The color matrix for feColorMatrix element changes colors based on
// the following:
//
// | R' | | r1 r2 r3 r4 r5 | | R |
// | G' | | g1 g2 g3 g4 g5 | | G |
// | B' | = | b1 b2 b3 b4 b5 | * | B |
// | A' | | a1 a2 a3 a4 a5 | | A |
// | 1 | | 0 0 0 0 1 | | 1 |
//
// R' = r1*R + r2*G + r3*B + r4*A + r5
// G' = g1*R + g2*G + g3*B + g4*A + g5
// B' = b1*R + b2*G + b3*B + b4*A + b5
// A' = a1*R + a2*G + a3*B + a4*A + a5
SvgFilter _srcInImageToSvg(String imageUrl, double width, double height) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeColorMatrix(const <double>[
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
1,
0,
], result: 'destalpha');
builder.setFeImage(href: imageUrl, result: 'image', width: width, height: height);
builder.setFeComposite(
in1: 'image',
in2: 'destalpha',
operator: kOperatorArithmetic,
k1: 1,
k2: 0,
k3: 0,
k4: 0,
result: 'comp',
);
return builder.build();
}
SvgFilter _srcImageToSvg(String imageUrl, double width, double height) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(href: imageUrl, result: 'comp', width: width, height: height);
return builder.build();
}
SvgFilter _srcOutImageToSvg(String imageUrl, double width, double height) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(href: imageUrl, result: 'image', width: width, height: height);
builder.setFeComposite(
in1: 'image',
in2: 'SourceGraphic',
operator: kOperatorOut,
result: 'comp',
);
return builder.build();
}
SvgFilter _xorImageToSvg(String imageUrl, double width, double height) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(href: imageUrl, result: 'image', width: width, height: height);
builder.setFeComposite(
in1: 'image',
in2: 'SourceGraphic',
operator: kOperatorXor,
result: 'comp',
);
return builder.build();
}
// The source image and color are composited using :
// result = k1 *in*in2 + k2*in + k3*in2 + k4.
SvgFilter _compositeImageToSvg(
String imageUrl,
double k1,
double k2,
double k3,
double k4,
double width,
double height,
) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(href: imageUrl, result: 'image', width: width, height: height);
builder.setFeComposite(
in1: 'image',
in2: 'SourceGraphic',
operator: kOperatorArithmetic,
k1: k1,
k2: k2,
k3: k3,
k4: k4,
result: 'comp',
);
return builder.build();
}
// Porter duff source * destination , keep source alpha.
// First apply color filter to source to change it to [color], then
// composite using multiplication.
SvgFilter _modulateImageToSvg(String imageUrl, double width, double height) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(href: imageUrl, result: 'image', width: width, height: height);
builder.setFeComposite(
in1: 'image',
in2: 'SourceGraphic',
operator: kOperatorArithmetic,
k1: 1,
k2: 0,
k3: 0,
k4: 0,
result: 'comp',
);
return builder.build();
}
// Uses feBlend element to blend source image with a color.
SvgFilter _blendImageToSvg(
String imageUrl,
SvgBlendMode svgBlendMode,
double width,
double height, {
bool swapLayers = false,
}) {
final SvgFilterBuilder builder = SvgFilterBuilder();
builder.setFeImage(href: imageUrl, result: 'image', width: width, height: height);
if (swapLayers) {
builder.setFeBlend(in1: 'SourceGraphic', in2: 'image', mode: svgBlendMode.blendMode);
} else {
builder.setFeBlend(in1: 'image', in2: 'SourceGraphic', mode: svgBlendMode.blendMode);
}
return builder.build();
}

View File

@@ -1,300 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../../browser_detection.dart';
import '../../dom.dart';
import '../../safe_browser_api.dart';
import '../../vector_math.dart';
import '../image.dart';
import '../render_vertices.dart';
import 'vertex_shaders.dart';
class EngineImageShader implements ui.ImageShader {
EngineImageShader(
ui.Image image,
this.tileModeX,
this.tileModeY,
Float64List matrix4,
this.filterQuality,
) : image = image as HtmlImage,
matrix4 = Float32List.fromList(matrix4);
final ui.TileMode tileModeX;
final ui.TileMode tileModeY;
final Float32List matrix4;
final ui.FilterQuality? filterQuality;
final HtmlImage image;
/// Whether fill pattern requires transform to shift tiling offset.
bool requiresTileOffset = false;
Object createPaintStyle(
DomCanvasRenderingContext2D context,
ui.Rect? shaderBounds,
double density,
) {
/// Creates a canvas rendering context pattern based on image and tile modes.
final ui.TileMode tileX = tileModeX;
final ui.TileMode tileY = tileModeY;
if (tileX != ui.TileMode.clamp && tileY != ui.TileMode.clamp) {
return context.createPattern(
_resolveTiledImageSource(image, tileX, tileY)!,
_tileModeToHtmlRepeatAttribute(tileX, tileY),
)!;
} else {
initWebGl();
return _createGlShader(context, shaderBounds!, density);
}
}
/// Converts tilemode to CSS repeat attribute.
///
/// CSS and Canvas2D createPattern apis only support repeated tiles.
/// For mirroring we create a new image with mirror builtin so both
/// repeated and mirrored modes can be supported when applied to
/// html element background-image or used by createPattern api.
String _tileModeToHtmlRepeatAttribute(ui.TileMode tileModeX, ui.TileMode tileModeY) {
final bool repeatX = tileModeX == ui.TileMode.repeated || tileModeX == ui.TileMode.mirror;
final bool repeatY = tileModeY == ui.TileMode.repeated || tileModeY == ui.TileMode.mirror;
return repeatX ? (repeatY ? 'repeat' : 'repeat-x') : (repeatY ? 'repeat-y' : 'no-repeat');
}
/// Tiles the image and returns an image or canvas element to be used as
/// source for a repeated pattern.
///
/// Other alternative was to create a webgl shader for the area and
/// tile in the shader, but that will generate a much larger image footprint
/// when the pattern is small. So we opt here for mirroring by
/// redrawing the image 2 or 4 times into a new bitmap.
Object? _resolveTiledImageSource(HtmlImage image, ui.TileMode tileX, ui.TileMode tileY) {
final int mirrorX = tileX == ui.TileMode.mirror ? 2 : 1;
final int mirrorY = tileY == ui.TileMode.mirror ? 2 : 1;
/// If we have no mirror, we can use image directly as pattern.
if (mirrorX == 1 && mirrorY == 1) {
return image.imgElement;
}
/// Create a new image by mirroring.
final int imageWidth = image.width;
final int imageHeight = image.height;
final int newWidth = imageWidth * mirrorX;
final int newHeight = imageHeight * mirrorY;
final OffScreenCanvas offscreenCanvas = OffScreenCanvas(newWidth, newHeight);
final Object renderContext = offscreenCanvas.getContext2d()!;
for (int y = 0; y < mirrorY; y++) {
for (int x = 0; x < mirrorX; x++) {
final int flipX = x != 0 ? -1 : 1;
final int flipY = y != 0 ? -1 : 1;
/// To draw image flipped we set translate and scale and pass
/// negative width/height to drawImage.
if (flipX != 1 || flipY != 1) {
scaleCanvas2D(renderContext, flipX, flipY);
}
drawImageCanvas2D(
renderContext,
image.imgElement,
x == 0 ? 0 : -2 * imageWidth,
y == 0 ? 0 : -2 * imageHeight,
);
if (flipX != 1 || flipY != 1) {
/// Restore transform. This is faster than save/restore on context.
scaleCanvas2D(renderContext, flipX, flipY);
}
}
}
// When using OffscreenCanvas and transferToImageBitmap is supported by
// browser create ImageBitmap otherwise use more expensive canvas
// allocation.
if (OffScreenCanvas.supported && offscreenCanvas.transferToImageBitmapSupported) {
return offscreenCanvas.transferToImageBitmap();
} else {
final DomCanvasElement canvas = createDomCanvasElement(width: newWidth, height: newHeight);
final DomCanvasRenderingContext2D ctx = canvas.context2D;
offscreenCanvas.transferImage(ctx);
return canvas;
}
}
/// Creates an image with tiled/transformed images.
DomCanvasPattern _createGlShader(
DomCanvasRenderingContext2D? context,
ui.Rect shaderBounds,
double density,
) {
final Matrix4 transform = Matrix4.fromFloat32List(matrix4);
final double dpr = ui.window.devicePixelRatio;
final int widthInPixels = (shaderBounds.width * dpr).ceil();
final int heightInPixels = (shaderBounds.height * dpr).ceil();
assert(widthInPixels > 0 && heightInPixels > 0);
/// Render tiles into a bitmap and create a canvas pattern.
final bool isWebGl2 = webGLVersion == WebGLVersion.webgl2;
final String vertexShader = VertexShaders.writeTextureVertexShader();
final String fragmentShader = FragmentShaders.writeTextureFragmentShader(
isWebGl2,
tileModeX,
tileModeY,
);
/// Render gradient into a bitmap and create a canvas pattern.
final OffScreenCanvas offScreenCanvas = OffScreenCanvas(widthInPixels, heightInPixels);
final GlContext gl = GlContext(offScreenCanvas);
gl.setViewportSize(widthInPixels, heightInPixels);
final GlProgram glProgram = gl.cacheProgram(vertexShader, fragmentShader);
gl.useProgram(glProgram);
const int vertexCount = 6;
final Float32List vertices = Float32List(vertexCount * 2);
final ui.Rect vRect = shaderBounds.translate(-shaderBounds.left, -shaderBounds.top);
vertices[0] = vRect.left;
vertices[1] = vRect.top;
vertices[2] = vRect.right;
vertices[3] = vRect.top;
vertices[4] = vRect.right;
vertices[5] = vRect.bottom;
vertices[6] = vRect.right;
vertices[7] = vRect.bottom;
vertices[8] = vRect.left;
vertices[9] = vRect.bottom;
vertices[10] = vRect.left;
vertices[11] = vRect.top;
final Object positionAttributeLocation = gl.getAttributeLocation(glProgram.program, 'position');
setupVertexTransforms(
gl,
glProgram,
0,
0,
widthInPixels.toDouble(),
heightInPixels.toDouble(),
transform,
);
requiresTileOffset = shaderBounds.left != 0 || shaderBounds.top != 0;
/// To map from vertex position to texture coordinate in 0..1 range,
/// we setup scalar to be used in vertex shader.
setupTextureTransform(
gl,
glProgram,
shaderBounds.left,
shaderBounds.top,
1.0 / image.width.toDouble(),
1.0 / image.height.toDouble(),
);
/// Setup geometry.
///
/// Create buffer for vertex coordinates.
final Object positionsBuffer = gl.createBuffer()!;
Object? vao;
if (isWebGl2) {
/// Create a vertex array object.
vao = gl.createVertexArray();
/// Set vertex array object as active one.
gl.bindVertexArray(vao!);
}
/// Turn on position attribute.
gl.enableVertexAttribArray(positionAttributeLocation);
/// Bind buffer as position buffer and transfer data.
gl.bindArrayBuffer(positionsBuffer);
bufferVertexData(gl, vertices, ui.window.devicePixelRatio);
/// Setup data format for attribute.
vertexAttribPointerGlContext(
gl.glContext,
positionAttributeLocation,
2,
gl.kFloat,
false,
0,
0,
);
/// Copy image to the texture.
final Object? texture = gl.createTexture();
/// Texture units are a global array of references to the textures.
/// By setting activeTexture, we associate the bound texture to a unit.
/// Every time we call a texture function such as texImage2D with a target
/// like TEXTURE_2D, it looks up texture by using the currently active
/// unit.
/// In our case we have a single texture unit 0.
gl.activeTexture(gl.kTexture0);
gl.bindTexture(gl.kTexture2D, texture);
gl.texImage2D(gl.kTexture2D, 0, gl.kRGBA, gl.kRGBA, gl.kUnsignedByte, image.imgElement);
if (isWebGl2) {
/// Texture REPEAT and MIRROR is only supported in WebGL 2, for
/// WebGL 1.0 we let shader compute correct uv coordinates.
gl.texParameteri(gl.kTexture2D, gl.kTextureWrapS, tileModeToGlWrapping(gl, tileModeX));
gl.texParameteri(gl.kTexture2D, gl.kTextureWrapT, tileModeToGlWrapping(gl, tileModeY));
/// Mipmapping saves your texture in different resolutions
/// so the graphics card can choose which resolution is optimal
/// without artifacts.
gl.generateMipmap(gl.kTexture2D);
} else {
/// For webgl1, if a texture is not mipmap complete, then the return
/// value of a texel fetch is (0, 0, 0, 1), so we have to set
/// minifying function to filter.
/// See https://www.khronos.org/registry/webgl/specs/1.0.0/#5.13.8.
gl.texParameteri(gl.kTexture2D, gl.kTextureWrapS, gl.kClampToEdge);
gl.texParameteri(gl.kTexture2D, gl.kTextureWrapT, gl.kClampToEdge);
gl.texParameteri(gl.kTexture2D, gl.kTextureMinFilter, gl.kLinear);
}
/// Finally render triangles.
gl.clear();
gl.drawTriangles(vertexCount, ui.VertexMode.triangles);
if (vao != null) {
gl.unbindVertexArray();
}
final Object? bitmapImage = gl.readPatternData(false);
gl.bindArrayBuffer(null);
gl.bindElementArrayBuffer(null);
return context!.createPattern(bitmapImage!, 'no-repeat')!;
}
bool _disposed = false;
@override
bool get debugDisposed {
late bool disposed;
assert(() {
disposed = _disposed;
return true;
}());
return disposed;
}
@override
void dispose() {
assert(() {
_disposed = true;
return true;
}());
image.dispose();
}
}

View File

@@ -1,202 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../../safe_browser_api.dart';
import 'shader_builder.dart';
/// Converts colors and stops to typed array of bias, scale and threshold to use
/// in shaders.
///
/// A color is generated by taking a t value [0..1] and computing
/// t * scale + bias.
///
/// Example: For stops 0.0 t1, t2, 1.0 and colors c0, c1, c2, c3
/// Given t1<t<t2 outputColor = t * scale + bias.
/// = c1 + (t - t1)/(t2 - t1) * (c2 - c1)
/// = t * (c2 - c1)/(t2 - t1) + c1 - t1/(t2 - t1) * (c2 - c1)
/// scale = (c2 - c1) / (t2 - t1)
/// bias = c1 - t1 / (t2 - t1) * (c2 - c1)
class NormalizedGradient {
factory NormalizedGradient(List<ui.Color> colors, {List<double>? stops}) {
// If colorStops is not provided, then only two stops, at 0.0 and 1.0,
// are implied (and colors must therefore only have two entries).
assert(stops != null || colors.length == 2);
stops ??= const <double>[0.0, 1.0];
final int colorCount = colors.length;
int normalizedCount = colorCount;
final bool isOpaque = !colors.any((ui.Color c) => c.alpha < 1.0);
final bool addFirst = stops[0] != 0.0;
final bool addLast = stops.last != 1.0;
if (addFirst) {
normalizedCount++;
}
if (addLast) {
normalizedCount++;
}
final Float32List bias = Float32List(normalizedCount * 4);
final Float32List scale = Float32List(normalizedCount * 4);
final Float32List thresholds = Float32List(4 * ((normalizedCount - 1) ~/ 4 + 1));
int targetIndex = 0;
int thresholdIndex = 0;
if (addFirst) {
final ui.Color c = colors[0];
bias[targetIndex++] = c.red / 255.0;
bias[targetIndex++] = c.green / 255.0;
bias[targetIndex++] = c.blue / 255.0;
bias[targetIndex++] = c.alpha / 255.0;
thresholds[thresholdIndex++] = 0.0;
}
for (final ui.Color c in colors) {
bias[targetIndex++] = c.red / 255.0;
bias[targetIndex++] = c.green / 255.0;
bias[targetIndex++] = c.blue / 255.0;
bias[targetIndex++] = c.alpha / 255.0;
}
for (final double stop in stops) {
thresholds[thresholdIndex++] = stop;
}
if (addLast) {
final ui.Color c = colors.last;
bias[targetIndex++] = c.red / 255.0;
bias[targetIndex++] = c.green / 255.0;
bias[targetIndex++] = c.blue / 255.0;
bias[targetIndex++] = c.alpha / 255.0;
thresholds[thresholdIndex++] = 1.0;
}
// Now that we have bias for each color stop, we can compute scale based
// on delta between colors.
final int lastColorIndex = 4 * (normalizedCount - 1);
for (int i = 0; i < lastColorIndex; i++) {
final int thresholdIndex = i >> 2;
scale[i] =
(bias[i + 4] - bias[i]) / (thresholds[thresholdIndex + 1] - thresholds[thresholdIndex]);
}
scale[lastColorIndex] = 0.0;
scale[lastColorIndex + 1] = 0.0;
scale[lastColorIndex + 2] = 0.0;
scale[lastColorIndex + 3] = 0.0;
// Compute bias = colorAtStop - stopValue * (scale).
for (int i = 0; i < normalizedCount; i++) {
final double t = thresholds[i];
final int colorIndex = i * 4;
bias[colorIndex] -= t * scale[colorIndex];
bias[colorIndex + 1] -= t * scale[colorIndex + 1];
bias[colorIndex + 2] -= t * scale[colorIndex + 2];
bias[colorIndex + 3] -= t * scale[colorIndex + 3];
}
return NormalizedGradient._(normalizedCount, thresholds, scale, bias, isOpaque);
}
NormalizedGradient._(
this.thresholdCount,
this._thresholds,
this._scale,
this._bias,
this.isOpaque,
);
final Float32List _thresholds;
final Float32List _bias;
final Float32List _scale;
final int thresholdCount;
final bool isOpaque;
/// Sets uniforms for threshold, bias and scale for program.
void setupUniforms(GlContext gl, GlProgram glProgram) {
for (int i = 0; i < thresholdCount; i++) {
final Object biasId = gl.getUniformLocation(glProgram.program, 'bias_$i');
gl.setUniform4f(biasId, _bias[i * 4], _bias[i * 4 + 1], _bias[i * 4 + 2], _bias[i * 4 + 3]);
final Object scaleId = gl.getUniformLocation(glProgram.program, 'scale_$i');
gl.setUniform4f(
scaleId,
_scale[i * 4],
_scale[i * 4 + 1],
_scale[i * 4 + 2],
_scale[i * 4 + 3],
);
}
for (int i = 0; i < _thresholds.length; i += 4) {
final Object thresId = gl.getUniformLocation(glProgram.program, 'threshold_${i ~/ 4}');
gl.setUniform4f(
thresId,
_thresholds[i],
_thresholds[i + 1],
_thresholds[i + 2],
_thresholds[i + 3],
);
}
}
/// Returns bias component at index.
double biasAt(int index) => _bias[index];
/// Returns scale component at index.
double scaleAt(int index) => _scale[index];
/// Returns threshold at index.
double thresholdAt(int index) => _thresholds[index];
}
/// Writes fragment shader code to search for probe value in source data and set
/// bias and scale to be used for computation.
///
/// Source data for thresholds is provided using ceil(count/4) packed vec4
/// uniforms.
///
/// Bias and scale data are vec4 uniforms that hold color data.
void writeUnrolledBinarySearch(
ShaderMethod method,
int start,
int end, {
required String probe,
required String sourcePrefix,
required String biasName,
required String scaleName,
}) {
if (start == end) {
final String biasSource = '${biasName}_$start';
method.addStatement('$biasName = $biasSource;');
final String scaleSource = '${scaleName}_$start';
method.addStatement('$scaleName = $scaleSource;');
} else {
// Add probe check.
final int mid = (start + end) ~/ 2;
String thresholdAtMid = '${sourcePrefix}_${(mid + 1) ~/ 4}';
thresholdAtMid += '.${vectorComponentIndexToName((mid + 1) % 4)}';
method.addStatement('if ($probe < $thresholdAtMid) {');
method.indent();
writeUnrolledBinarySearch(
method,
start,
mid,
probe: probe,
sourcePrefix: sourcePrefix,
biasName: biasName,
scaleName: scaleName,
);
method.unindent();
method.addStatement('} else {');
method.indent();
writeUnrolledBinarySearch(
method,
mid + 1,
end,
probe: probe,
sourcePrefix: sourcePrefix,
biasName: biasName,
scaleName: scaleName,
);
method.unindent();
method.addStatement('}');
}
}
String vectorComponentIndexToName(int index) {
assert(index >= 0 && index <= 4);
return 'xyzw'[index];
}

View File

@@ -1,947 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../../browser_detection.dart';
import '../../color_filter.dart';
import '../../dom.dart';
import '../../safe_browser_api.dart';
import '../../util.dart';
import '../../validators.dart';
import '../../vector_math.dart';
import '../color_filter.dart';
import '../path/path_utils.dart';
import '../render_vertices.dart';
import '../resource_manager.dart';
import 'normalized_gradient.dart';
import 'shader_builder.dart';
import 'vertex_shaders.dart';
const double kFltEpsilon = 1.19209290E-07; // == 1 / (2 ^ 23)
const double kFltEpsilonSquared = 1.19209290E-07 * 1.19209290E-07;
class SharedCanvas {
OffScreenCanvas? _canvas;
bool _checkedOut = false;
GlContext checkOutContext(int width, int height) {
assert(!_checkedOut);
_checkedOut = true;
if (_canvas == null) {
_canvas = OffScreenCanvas(width, height);
} else {
_canvas!.resize(width, height);
}
return GlContext(_canvas!);
}
void checkInContext() {
assert(_checkedOut);
_checkedOut = false;
}
}
SharedCanvas _sharedCanvas = SharedCanvas();
abstract class EngineGradient implements ui.Gradient {
/// Hidden constructor to prevent subclassing.
EngineGradient._();
/// Creates a fill style to be used in painting.
Object createPaintStyle(DomCanvasRenderingContext2D? ctx, ui.Rect? shaderBounds, double density);
/// Creates a CanvasImageSource to paint gradient.
Object createImageBitmap(ui.Rect? shaderBounds, double density, bool createDataUrl);
@override
bool debugDisposed = false;
@override
void dispose() {}
@override
String toString() => 'Gradient()';
}
class GradientSweep extends EngineGradient {
GradientSweep(
this.center,
this.colors,
this.colorStops,
this.tileMode,
this.startAngle,
this.endAngle,
this.matrix4,
) : assert(offsetIsValid(center)),
super._() {
validateColorStops(colors, colorStops);
}
@override
Object createImageBitmap(ui.Rect? shaderBounds, double density, bool createDataUrl) {
assert(shaderBounds != null);
final int widthInPixels = shaderBounds!.width.ceil();
final int heightInPixels = shaderBounds.height.ceil();
assert(widthInPixels > 0 && heightInPixels > 0);
initWebGl();
// Render gradient into a bitmap and create a canvas pattern.
final GlContext gl = _sharedCanvas.checkOutContext(widthInPixels, heightInPixels);
gl.setViewportSize(widthInPixels, heightInPixels);
final NormalizedGradient normalizedGradient = NormalizedGradient(colors, stops: colorStops);
final GlProgram glProgram = gl.cacheProgram(
VertexShaders.writeBaseVertexShader(),
_createSweepFragmentShader(normalizedGradient, tileMode),
);
gl.useProgram(glProgram);
final Object tileOffset = gl.getUniformLocation(glProgram.program, 'u_tile_offset');
final double centerX = (center.dx - shaderBounds.left) / (shaderBounds.width);
final double centerY = (center.dy - shaderBounds.top) / (shaderBounds.height);
gl.setUniform2f(
tileOffset,
2 * (shaderBounds.width * (centerX - 0.5)),
2 * (shaderBounds.height * (0.5 - centerY)),
);
final Object angleRange = gl.getUniformLocation(glProgram.program, 'angle_range');
gl.setUniform2f(angleRange, startAngle, endAngle);
normalizedGradient.setupUniforms(gl, glProgram);
final Object gradientMatrix = gl.getUniformLocation(glProgram.program, 'm_gradient');
final Matrix4 gradientTransform = Matrix4.identity();
if (matrix4 != null) {
final Matrix4 m4 = Matrix4.zero()..copyInverse(Matrix4.fromFloat32List(matrix4!));
gradientTransform.translate(-center.dx, -center.dy);
gradientTransform.multiply(m4);
gradientTransform.translate(center.dx, center.dy);
}
gl.setUniformMatrix4fv(gradientMatrix, false, gradientTransform.storage);
final Object result = () {
if (createDataUrl) {
return glRenderer!.drawRectToImageUrl(
ui.Rect.fromLTWH(0, 0, shaderBounds.width, shaderBounds.height),
gl,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels,
);
} else {
return glRenderer!.drawRect(
ui.Rect.fromLTWH(0, 0, shaderBounds.width, shaderBounds.height),
gl,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels,
)!;
}
}();
_sharedCanvas.checkInContext();
return result;
}
@override
Object createPaintStyle(DomCanvasRenderingContext2D? ctx, ui.Rect? shaderBounds, double density) {
final Object imageBitmap = createImageBitmap(shaderBounds, density, false);
return ctx!.createPattern(imageBitmap, 'no-repeat')!;
}
String _createSweepFragmentShader(NormalizedGradient gradient, ui.TileMode tileMode) {
final ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion);
builder.floatPrecision = ShaderPrecision.kMedium;
builder.addIn(ShaderType.kVec4, name: 'v_color');
builder.addUniform(ShaderType.kVec2, name: 'u_resolution');
builder.addUniform(ShaderType.kVec2, name: 'u_tile_offset');
builder.addUniform(ShaderType.kVec2, name: 'angle_range');
builder.addUniform(ShaderType.kMat4, name: 'm_gradient');
final ShaderDeclaration fragColor = builder.fragmentColor;
final ShaderMethod method = builder.addMethod('main');
// Sweep gradient
method.addStatement('vec2 center = 0.5 * (u_resolution + u_tile_offset);');
method.addStatement(
'vec4 localCoord = m_gradient * vec4(gl_FragCoord.x - center.x, center.y - gl_FragCoord.y, 0, 1);',
);
method.addStatement('float angle = atan(-localCoord.y, -localCoord.x) + ${math.pi};');
method.addStatement('float sweep = angle_range.y - angle_range.x;');
method.addStatement('angle = (angle - angle_range.x) / sweep;');
method.addStatement('float st = angle;');
final String probeName = _writeSharedGradientShader(builder, method, gradient, tileMode);
method.addStatement('${fragColor.name} = $probeName * scale + bias;');
final String shader = builder.build();
return shader;
}
final ui.Offset center;
final List<ui.Color> colors;
final List<double>? colorStops;
final ui.TileMode tileMode;
final double startAngle;
final double endAngle;
final Float32List? matrix4;
}
class GradientLinear extends EngineGradient {
GradientLinear(
this.from,
this.to,
this.colors,
this.colorStops,
this.tileMode,
Float32List? matrix,
) : assert(offsetIsValid(from)),
assert(offsetIsValid(to)),
matrix4 = matrix == null ? null : FastMatrix32(matrix),
super._() {
// ignore: prefer_asserts_in_initializer_lists
assert(() {
validateColorStops(colors, colorStops);
return true;
}());
}
final ui.Offset from;
final ui.Offset to;
final List<ui.Color> colors;
final List<double>? colorStops;
final ui.TileMode tileMode;
final FastMatrix32? matrix4;
@override
Object createPaintStyle(DomCanvasRenderingContext2D? ctx, ui.Rect? shaderBounds, double density) {
if (tileMode == ui.TileMode.clamp || tileMode == ui.TileMode.decal) {
return _createCanvasGradient(ctx, shaderBounds, density);
} else {
return _createGlGradient(ctx, shaderBounds, density);
}
}
DomCanvasGradient _createCanvasGradient(
DomCanvasRenderingContext2D? ctx,
ui.Rect? shaderBounds,
double density,
) {
final FastMatrix32? matrix4 = this.matrix4;
DomCanvasGradient gradient;
final double offsetX = shaderBounds!.left;
final double offsetY = shaderBounds.top;
if (matrix4 != null) {
// The matrix is relative to shaderBounds so we shift center by
// shaderBounds top-left origin.
final double centerX = (from.dx + to.dx) / 2.0 - shaderBounds.left;
final double centerY = (from.dy + to.dy) / 2.0 - shaderBounds.top;
matrix4.transform(from.dx - centerX, from.dy - centerY);
final double fromX = matrix4.transformedX + centerX;
final double fromY = matrix4.transformedY + centerY;
matrix4.transform(to.dx - centerX, to.dy - centerY);
gradient = ctx!.createLinearGradient(
fromX - offsetX,
fromY - offsetY,
matrix4.transformedX + centerX - offsetX,
matrix4.transformedY + centerY - offsetY,
);
} else {
gradient = ctx!.createLinearGradient(
from.dx - offsetX,
from.dy - offsetY,
to.dx - offsetX,
to.dy - offsetY,
);
}
_addColorStopsToCanvasGradient(gradient, colors, colorStops, tileMode == ui.TileMode.decal);
return gradient;
}
@override
Object createImageBitmap(ui.Rect? shaderBounds, double density, bool createDataUrl) {
assert(shaderBounds != null);
final int widthInPixels = shaderBounds!.width.ceil();
final int heightInPixels = shaderBounds.height.ceil();
assert(widthInPixels > 0 && heightInPixels > 0);
initWebGl();
// Render gradient into a bitmap and create a canvas pattern.
final GlContext gl = _sharedCanvas.checkOutContext(widthInPixels, heightInPixels);
gl.setViewportSize(widthInPixels, heightInPixels);
final NormalizedGradient normalizedGradient = NormalizedGradient(colors, stops: colorStops);
final GlProgram glProgram = gl.cacheProgram(
VertexShaders.writeBaseVertexShader(),
_createLinearFragmentShader(normalizedGradient, tileMode),
);
gl.useProgram(glProgram);
// Setup from/to uniforms.
//
// From/to is relative to shaderBounds.
//
// To compute t value between 0..1 for any point on the screen,
// we need to use from,to point pair to construct a matrix that will
// take any fragment coordinate and transform it to a t value.
//
// We compute the matrix by:
// 1- Shift from,to vector to origin.
// 2- Rotate the vector to align with x axis.
// 3- Scale it to unit vector.
final double fromX = from.dx;
final double fromY = from.dy;
final double toX = to.dx;
final double toY = to.dy;
final double dx = toX - fromX;
final double dy = toY - fromY;
final double length = math.sqrt(dx * dx + dy * dy);
// sin(theta) = dy / length.
// cos(theta) = dx / length.
// Flip dy for gl flip.
final double sinVal = length < kFltEpsilon ? 0 : -dy / length;
final double cosVal = length < kFltEpsilon ? 1 : dx / length;
// If tile mode is repeated we need to shift the center of from->to
// vector to the center of shader bounds.
final bool isRepeated = tileMode != ui.TileMode.clamp;
final double originX =
isRepeated ? (shaderBounds.width / 2) : (fromX + toX) / 2.0 - shaderBounds.left;
final double originY =
isRepeated ? (shaderBounds.height / 2) : (fromY + toY) / 2.0 - shaderBounds.top;
final Matrix4 originTranslation = Matrix4.translationValues(-originX, -originY, 0);
// Rotate around Z axis.
final Matrix4 rotationZ = Matrix4.identity();
final Float32List storage = rotationZ.storage;
storage[0] = cosVal;
// Sign is flipped since gl coordinate system is flipped around y axis.
storage[1] = sinVal;
storage[4] = -sinVal;
storage[5] = cosVal;
final Matrix4 gradientTransform = Matrix4.identity();
// We compute location based on gl_FragCoord to center distance which
// returns 0.0 at center. To make sure we align center of gradient to this
// point, we shift by 0.5 to get st value for center of gradient.
gradientTransform.translate(0.5);
if (length > kFltEpsilon) {
gradientTransform.scale(1.0 / length);
}
if (matrix4 != null) {
// Flutter GradientTransform is defined in shaderBounds coordinate system
// with flipped y axis.
// We flip y axis, translate to center, multiply matrix and translate
// and flip back so it is applied correctly.
final Matrix4 m4 = Matrix4.zero()..copyInverse(Matrix4.fromFloat32List(matrix4!.matrix));
final ui.Offset center = shaderBounds.center;
gradientTransform.translate(-center.dx, -center.dy);
gradientTransform.multiply(m4);
gradientTransform.translate(center.dx, center.dy);
}
gradientTransform.multiply(rotationZ);
gradientTransform.multiply(originTranslation);
// Setup gradient uniforms for t search.
normalizedGradient.setupUniforms(gl, glProgram);
// Setup matrix transform uniform.
final Object gradientMatrix = gl.getUniformLocation(glProgram.program, 'm_gradient');
gl.setUniformMatrix4fv(gradientMatrix, false, gradientTransform.storage);
final Object uRes = gl.getUniformLocation(glProgram.program, 'u_resolution');
gl.setUniform2f(uRes, widthInPixels.toDouble(), heightInPixels.toDouble());
final Object result = () {
if (createDataUrl) {
return glRenderer!.drawRectToImageUrl(
ui.Rect.fromLTWH(0, 0, shaderBounds.width, shaderBounds.height) /* !! shaderBounds */,
gl,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels,
);
} else {
return glRenderer!.drawRect(
ui.Rect.fromLTWH(0, 0, shaderBounds.width, shaderBounds.height) /* !! shaderBounds */,
gl,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels,
)!;
}
}();
_sharedCanvas.checkInContext();
return result;
}
/// Creates a linear gradient with tiling repeat or mirror.
DomCanvasPattern _createGlGradient(
DomCanvasRenderingContext2D? ctx,
ui.Rect? shaderBounds,
double density,
) {
final Object imageBitmap = createImageBitmap(shaderBounds, density, false);
return ctx!.createPattern(imageBitmap, 'no-repeat')!;
}
String _createLinearFragmentShader(NormalizedGradient gradient, ui.TileMode tileMode) {
final ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion);
builder.floatPrecision = ShaderPrecision.kMedium;
builder.addIn(ShaderType.kVec4, name: 'v_color');
builder.addUniform(ShaderType.kVec2, name: 'u_resolution');
builder.addUniform(ShaderType.kMat4, name: 'm_gradient');
final ShaderDeclaration fragColor = builder.fragmentColor;
final ShaderMethod method = builder.addMethod('main');
// Linear gradient.
// Multiply with m_gradient transform to convert from fragment coordinate to
// distance on the from-to line.
method.addStatement(
'vec4 localCoord = m_gradient * vec4(gl_FragCoord.x, '
'u_resolution.y - gl_FragCoord.y, 0, 1);',
);
method.addStatement('float st = localCoord.x;');
final String probeName = _writeSharedGradientShader(builder, method, gradient, tileMode);
method.addStatement('${fragColor.name} = $probeName * scale + bias;');
final String shader = builder.build();
return shader;
}
}
void _addColorStopsToCanvasGradient(
DomCanvasGradient gradient,
List<ui.Color> colors,
List<double>? colorStops,
bool isDecal,
) {
double scale, offset;
if (isDecal) {
scale = 0.999;
offset = (1.0 - scale) / 2.0;
gradient.addColorStop(0, '#00000000');
} else {
scale = 1.0;
offset = 0.0;
}
if (colorStops == null) {
assert(colors.length == 2);
gradient.addColorStop(offset, colors[0].toCssString());
gradient.addColorStop(1 - offset, colors[1].toCssString());
} else {
for (int i = 0; i < colors.length; i++) {
final double colorStop = colorStops[i].clamp(0.0, 1.0);
gradient.addColorStop(colorStop * scale + offset, colors[i].toCssString());
}
}
if (isDecal) {
gradient.addColorStop(1, '#00000000');
}
}
/// Writes shader code to map fragment value to gradient color.
///
/// Returns name of gradient treshold variable to use to compute color.
String _writeSharedGradientShader(
ShaderBuilder builder,
ShaderMethod method,
NormalizedGradient gradient,
ui.TileMode tileMode,
) {
method.addStatement('vec4 bias;');
method.addStatement('vec4 scale;');
// Write uniforms for each threshold, bias and scale.
for (int i = 0; i < (gradient.thresholdCount - 1) ~/ 4 + 1; i++) {
builder.addUniform(ShaderType.kVec4, name: 'threshold_$i');
}
for (int i = 0; i < gradient.thresholdCount; i++) {
builder.addUniform(ShaderType.kVec4, name: 'bias_$i');
builder.addUniform(ShaderType.kVec4, name: 'scale_$i');
}
// Use st variable name if clamped or decaled, otherwise write code to compute
// tiled_st.
String probeName = 'st';
switch (tileMode) {
case ui.TileMode.clamp:
method.addStatement('float tiled_st = clamp(st, 0.0, 1.0);');
probeName = 'tiled_st';
case ui.TileMode.decal:
break;
case ui.TileMode.repeated:
// st represents our distance from center. Flutter maps the center to
// center of gradient ramp so we need to add 0.5 to make sure repeated
// pattern center is at origin.
method.addStatement('float tiled_st = fract(st);');
probeName = 'tiled_st';
case ui.TileMode.mirror:
method.addStatement('float t_1 = (st - 1.0);');
method.addStatement('float tiled_st = abs((t_1 - 2.0 * floor(t_1 * 0.5)) - 1.0);');
probeName = 'tiled_st';
}
writeUnrolledBinarySearch(
method,
0,
gradient.thresholdCount - 1,
probe: probeName,
sourcePrefix: 'threshold',
biasName: 'bias',
scaleName: 'scale',
);
if (tileMode == ui.TileMode.decal) {
method.addStatement('if (st < 0.0 || st > 1.0) {');
method.addStatement(' ${builder.fragmentColor.name} = vec4(0, 0, 0, 0);');
method.addStatement(' return;');
method.addStatement('}');
}
return probeName;
}
class GradientRadial extends EngineGradient {
GradientRadial(
this.center,
this.radius,
this.colors,
this.colorStops,
this.tileMode,
this.matrix4,
) : super._();
final ui.Offset center;
final double radius;
final List<ui.Color> colors;
final List<double>? colorStops;
final ui.TileMode tileMode;
final Float32List? matrix4;
@override
Object createPaintStyle(DomCanvasRenderingContext2D? ctx, ui.Rect? shaderBounds, double density) {
if (matrix4 == null && (tileMode == ui.TileMode.clamp || tileMode == ui.TileMode.decal)) {
return _createCanvasGradient(ctx, shaderBounds, density);
} else {
return _createGlGradient(ctx, shaderBounds, density);
}
}
Object _createCanvasGradient(
DomCanvasRenderingContext2D? ctx,
ui.Rect? shaderBounds,
double density,
) {
final double offsetX = shaderBounds!.left;
final double offsetY = shaderBounds.top;
final DomCanvasGradient gradient = ctx!.createRadialGradient(
center.dx - offsetX,
center.dy - offsetY,
0,
center.dx - offsetX,
center.dy - offsetY,
radius,
);
_addColorStopsToCanvasGradient(gradient, colors, colorStops, tileMode == ui.TileMode.decal);
return gradient;
}
@override
Object createImageBitmap(ui.Rect? shaderBounds, double density, bool createDataUrl) {
assert(shaderBounds != null);
final int widthInPixels = shaderBounds!.width.ceil();
final int heightInPixels = shaderBounds.height.ceil();
assert(widthInPixels > 0 && heightInPixels > 0);
initWebGl();
// Render gradient into a bitmap and create a canvas pattern.
final GlContext gl = _sharedCanvas.checkOutContext(widthInPixels, heightInPixels);
gl.setViewportSize(widthInPixels, heightInPixels);
final NormalizedGradient normalizedGradient = NormalizedGradient(colors, stops: colorStops);
final GlProgram glProgram = gl.cacheProgram(
VertexShaders.writeBaseVertexShader(),
_createRadialFragmentShader(normalizedGradient, shaderBounds, tileMode),
);
gl.useProgram(glProgram);
final Object tileOffset = gl.getUniformLocation(glProgram.program, 'u_tile_offset');
final double centerX = (center.dx - shaderBounds.left) / (shaderBounds.width);
final double centerY = (center.dy - shaderBounds.top) / (shaderBounds.height);
gl.setUniform2f(
tileOffset,
2 * (shaderBounds.width * (centerX - 0.5)),
2 * (shaderBounds.height * (0.5 - centerY)),
);
final Object radiusUniform = gl.getUniformLocation(glProgram.program, 'u_radius');
gl.setUniform1f(radiusUniform, radius);
normalizedGradient.setupUniforms(gl, glProgram);
final Object gradientMatrix = gl.getUniformLocation(glProgram.program, 'm_gradient');
final Matrix4 gradientTransform = Matrix4.identity();
if (matrix4 != null) {
final Matrix4 m4 = Matrix4.zero()..copyInverse(Matrix4.fromFloat32List(matrix4!));
gradientTransform.translate(-center.dx, -center.dy);
gradientTransform.multiply(m4);
gradientTransform.translate(center.dx, center.dy);
}
gl.setUniformMatrix4fv(gradientMatrix, false, gradientTransform.storage);
final Object result = () {
if (createDataUrl) {
return glRenderer!.drawRectToImageUrl(
ui.Rect.fromLTWH(0, 0, shaderBounds.width, shaderBounds.height),
gl,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels,
);
} else {
return glRenderer!.drawRect(
ui.Rect.fromLTWH(0, 0, shaderBounds.width, shaderBounds.height),
gl,
glProgram,
normalizedGradient,
widthInPixels,
heightInPixels,
)!;
}
}();
_sharedCanvas.checkInContext();
return result;
}
/// Creates a radial gradient with tiling repeat or mirror.
DomCanvasPattern _createGlGradient(
DomCanvasRenderingContext2D? ctx,
ui.Rect? shaderBounds,
double density,
) {
final Object imageBitmap = createImageBitmap(shaderBounds, density, false);
return ctx!.createPattern(imageBitmap, 'no-repeat')!;
}
String _createRadialFragmentShader(
NormalizedGradient gradient,
ui.Rect shaderBounds,
ui.TileMode tileMode,
) {
final ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion);
builder.floatPrecision = ShaderPrecision.kMedium;
builder.addIn(ShaderType.kVec4, name: 'v_color');
builder.addUniform(ShaderType.kVec2, name: 'u_resolution');
builder.addUniform(ShaderType.kVec2, name: 'u_tile_offset');
builder.addUniform(ShaderType.kFloat, name: 'u_radius');
builder.addUniform(ShaderType.kMat4, name: 'm_gradient');
final ShaderDeclaration fragColor = builder.fragmentColor;
final ShaderMethod method = builder.addMethod('main');
// Sweep gradient
method.addStatement('vec2 center = 0.5 * (u_resolution + u_tile_offset);');
method.addStatement(
'vec4 localCoord = m_gradient * vec4(gl_FragCoord.x - center.x, center.y - gl_FragCoord.y, 0, 1);',
);
method.addStatement('float dist = length(localCoord);');
method.addStatement('float st = abs(dist / u_radius);');
final String probeName = _writeSharedGradientShader(builder, method, gradient, tileMode);
method.addStatement('${fragColor.name} = $probeName * scale + bias;');
final String shader = builder.build();
return shader;
}
}
// TODO(ferhat): Implement focal https://github.com/flutter/flutter/issues/76643.
class GradientConical extends GradientRadial {
GradientConical(
this.focal,
this.focalRadius,
ui.Offset center,
double radius,
List<ui.Color> colors,
List<double>? colorStops,
ui.TileMode tileMode,
Float32List? matrix4,
) : super(center, radius, colors, colorStops, tileMode, matrix4);
final ui.Offset focal;
final double focalRadius;
@override
Object createPaintStyle(DomCanvasRenderingContext2D? ctx, ui.Rect? shaderBounds, double density) {
if ((tileMode == ui.TileMode.clamp || tileMode == ui.TileMode.decal) &&
focalRadius == 0.0 &&
focal == ui.Offset.zero) {
return _createCanvasGradient(ctx, shaderBounds, density);
} else {
initWebGl();
return _createGlGradient(ctx, shaderBounds, density);
}
}
@override
String _createRadialFragmentShader(
NormalizedGradient gradient,
ui.Rect shaderBounds,
ui.TileMode tileMode,
) {
/// If distance between centers is nearly zero we can pretend we're radial
/// to prevent divide by zero in computing gradient.
final double centerDistanceX = center.dx - focal.dx;
final double centerDistanceY = center.dy - focal.dy;
final double centerDistanceSq =
centerDistanceX * centerDistanceX + centerDistanceY * centerDistanceY;
if (centerDistanceSq < kFltEpsilonSquared) {
return super._createRadialFragmentShader(gradient, shaderBounds, tileMode);
}
final double centerDistance = math.sqrt(centerDistanceSq);
double r0 = focalRadius / centerDistance;
double r1 = radius / centerDistance;
double fFocalX = r0 / (r0 - r1);
if ((fFocalX - 1).abs() < SPath.scalarNearlyZero) {
// swap r0, r1
final double temp = r0;
r0 = r1;
r1 = temp;
fFocalX = 0.0; // because r0 is now 0
}
final ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion);
builder.floatPrecision = ShaderPrecision.kMedium;
builder.addIn(ShaderType.kVec4, name: 'v_color');
builder.addUniform(ShaderType.kVec2, name: 'u_resolution');
builder.addUniform(ShaderType.kVec2, name: 'u_tile_offset');
builder.addUniform(ShaderType.kFloat, name: 'u_radius');
builder.addUniform(ShaderType.kMat4, name: 'm_gradient');
final ShaderDeclaration fragColor = builder.fragmentColor;
final ShaderMethod method = builder.addMethod('main');
// Sweep gradient
method.addStatement('vec2 center = 0.5 * (u_resolution + u_tile_offset);');
method.addStatement(
'vec4 localCoord = m_gradient * vec4(gl_FragCoord.x - center.x, center.y - gl_FragCoord.y, 0, 1);',
);
method.addStatement('float dist = length(localCoord);');
final String f = (focalRadius / (math.min(shaderBounds.width, shaderBounds.height) / 2.0))
.toStringAsPrecision(8);
method.addStatement(
focalRadius == 0.0
? 'float st = dist / u_radius;'
: 'float st = ((dist / u_radius) - $f) / (1.0 - $f);',
);
if (tileMode == ui.TileMode.clamp) {
method.addStatement('if (st < 0.0) { st = -1.0; }');
}
final String probeName = _writeSharedGradientShader(builder, method, gradient, tileMode);
method.addStatement('${fragColor.name} = $probeName * scale + bias;');
return builder.build();
}
}
/// Backend implementation of [ui.ImageFilter].
///
/// Currently only `blur` and `matrix` are supported.
abstract class EngineImageFilter implements ui.ImageFilter {
factory EngineImageFilter.blur({
required double sigmaX,
required double sigmaY,
required ui.TileMode? tileMode,
}) = _BlurEngineImageFilter;
factory EngineImageFilter.matrix({
required Float64List matrix,
required ui.FilterQuality filterQuality,
}) = _MatrixEngineImageFilter;
EngineImageFilter._();
String get filterAttribute => '';
String get transformAttribute => '';
}
class _BlurEngineImageFilter extends EngineImageFilter {
_BlurEngineImageFilter({this.sigmaX = 0.0, this.sigmaY = 0.0, this.tileMode}) : super._();
final double sigmaX;
final double sigmaY;
final ui.TileMode? tileMode;
// TODO(ferhat): implement TileMode.
@override
String get filterAttribute => blurSigmasToCssString(sigmaX, sigmaY);
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is _BlurEngineImageFilter &&
other.tileMode == tileMode &&
other.sigmaX == sigmaX &&
other.sigmaY == sigmaY;
}
@override
int get hashCode => Object.hash(sigmaX, sigmaY, tileMode);
@override
String toString() {
return 'ImageFilter.blur($sigmaX, $sigmaY, ${tileModeString(tileMode)})';
}
}
class _MatrixEngineImageFilter extends EngineImageFilter {
_MatrixEngineImageFilter({required Float64List matrix, required this.filterQuality})
: webMatrix = Float64List.fromList(matrix),
super._();
final Float64List webMatrix;
final ui.FilterQuality filterQuality;
// TODO(yjbanov): implement FilterQuality.
@override
String get transformAttribute => float64ListToCssTransform(webMatrix);
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is _MatrixEngineImageFilter &&
other.filterQuality == filterQuality &&
listEquals<double>(other.webMatrix, webMatrix);
}
@override
int get hashCode => Object.hash(Object.hashAll(webMatrix), filterQuality);
@override
String toString() {
return 'ImageFilter.matrix($webMatrix, $filterQuality)';
}
}
/// The backend implementation of [ui.ColorFilter]
///
/// Currently only 'mode' and 'matrix' are supported.
abstract class EngineHtmlColorFilter implements EngineImageFilter {
EngineHtmlColorFilter();
String? filterId;
@override
String get filterAttribute => (filterId != null) ? 'url(#$filterId)' : '';
@override
String get transformAttribute => '';
/// Make an [SvgFilter] and add it as a globabl resource using [ResourceManager]
/// The [DomElement] from the made [SvgFilter] is returned so it can be managed
/// by the surface calling it.
DomElement? makeSvgFilter(DomElement? filterElement);
}
class ModeHtmlColorFilter extends EngineHtmlColorFilter {
ModeHtmlColorFilter(this.color, this.blendMode);
final ui.Color color;
ui.BlendMode blendMode;
@override
DomElement? makeSvgFilter(DomElement? filterElement) {
switch (blendMode) {
case ui.BlendMode.clear:
case ui.BlendMode.dstOut:
case ui.BlendMode.srcOut:
filterElement!.style.visibility = 'hidden';
return null;
case ui.BlendMode.dst:
case ui.BlendMode.dstIn:
// Noop.
return null;
case ui.BlendMode.src:
case ui.BlendMode.srcOver:
// Uses source filter color.
// Since we don't have a size, we can't use background color.
// Use svg filter srcIn instead.
blendMode = ui.BlendMode.srcIn;
case ui.BlendMode.dstOver:
case ui.BlendMode.srcIn:
case ui.BlendMode.srcATop:
case ui.BlendMode.dstATop:
case ui.BlendMode.xor:
case ui.BlendMode.plus:
case ui.BlendMode.modulate:
case ui.BlendMode.screen:
case ui.BlendMode.overlay:
case ui.BlendMode.darken:
case ui.BlendMode.lighten:
case ui.BlendMode.colorDodge:
case ui.BlendMode.colorBurn:
case ui.BlendMode.hardLight:
case ui.BlendMode.softLight:
case ui.BlendMode.difference:
case ui.BlendMode.exclusion:
case ui.BlendMode.multiply:
case ui.BlendMode.hue:
case ui.BlendMode.saturation:
case ui.BlendMode.color:
case ui.BlendMode.luminosity:
break;
}
final SvgFilter svgFilter = svgFilterFromBlendMode(color, blendMode);
ResourceManager.instance.addResource(svgFilter.element);
filterId = svgFilter.id;
if (blendMode == ui.BlendMode.saturation ||
blendMode == ui.BlendMode.multiply ||
blendMode == ui.BlendMode.modulate) {
filterElement!.style.backgroundColor = color.toCssString();
}
return svgFilter.element;
}
}
class MatrixHtmlColorFilter extends EngineHtmlColorFilter {
MatrixHtmlColorFilter(this.matrix);
final List<double> matrix;
@override
DomElement? makeSvgFilter(DomNode? filterElement) {
final SvgFilter svgFilter = svgFilterFromColorMatrix(matrix);
ResourceManager.instance.addResource(svgFilter.element);
filterId = svgFilter.id;
return svgFilter.element;
}
}
/// Convert the current [ColorFilter] to an EngineHtmlColorFilter
///
/// This workaround allows ColorFilter to be const constructible and
/// efficiently comparable, so that widgets can check for COlorFIlter equality to
/// avoid repainting.
EngineHtmlColorFilter? createHtmlColorFilter(EngineColorFilter? colorFilter) {
if (colorFilter == null) {
return null;
}
switch (colorFilter.type) {
case ColorFilterType.mode:
if (colorFilter.color == null || colorFilter.blendMode == null) {
return null;
}
return ModeHtmlColorFilter(colorFilter.color!, colorFilter.blendMode!);
case ColorFilterType.matrix:
if (colorFilter.matrix == null) {
return null;
}
assert(colorFilter.matrix!.length == 20, 'Color Matrix must have 20 entries.');
return MatrixHtmlColorFilter(colorFilter.matrix!);
case ColorFilterType.linearToSrgbGamma:
throw UnimplementedError('ColorFilter.linearToSrgbGamma not implemented for HTML renderer');
case ColorFilterType.srgbToLinearGamma:
throw UnimplementedError('ColorFilter.srgbToLinearGamma not implemented for HTML renderer.');
}
}

View File

@@ -1,433 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import '../../browser_detection.dart';
/// Creates shader program for target webgl version.
///
/// See spec at https://www.khronos.org/registry/webgl/specs/latest/1.0/.
///
/// Differences in WebGL2 vs WebGL1.
/// - WebGL2 needs '#version 300 es' to enable the new shading language
/// - vertex attributes have the qualifier 'in' instead of 'attribute'
/// - GLSL 3.00 defines texture and other new and future reserved words.
/// - varying is now called `in`.
/// - GLSL 1.00 has a predefined variable gl_FragColor which now needs to be
/// defined as `out vec4 fragmentColor`.
/// - Texture lookup functions texture2D and textureCube have now been
/// replaced with texture.
///
/// Example usage:
/// ShaderBuilder builder = ShaderBuilder(WebGlVersion.webgl2);
/// ShaderDeclaration u1 = builder.addUniform(ShaderType.kVec4);
/// ShaderMethod method = builder.addMethod('main');
/// method.addStatement('${u1.name} = vec4(1.0, 1.0, 1.0, 0.0);');
/// source = builder.build();
class ShaderBuilder {
ShaderBuilder(this.version)
: isWebGl2 = version == WebGLVersion.webgl2,
_isFragmentShader = false;
ShaderBuilder.fragment(this.version)
: isWebGl2 = version == WebGLVersion.webgl2,
_isFragmentShader = true;
/// WebGL version.
final int version;
final List<ShaderDeclaration> declarations = <ShaderDeclaration>[];
final List<ShaderMethod> _methods = <ShaderMethod>[];
/// Precision for integer variables.
int? integerPrecision;
/// Precision floating point variables.
int? floatPrecision;
/// Counter for generating unique name if name is not specified for attribute.
int _attribCounter = 0;
/// Counter for generating unique name if name is not specified for varying.
int _varyingCounter = 0;
/// Counter for generating unique name if name is not specified for uniform.
int _uniformCounter = 0;
/// Counter for generating unique name if name is not specified for constant.
int _constCounter = 0;
final bool isWebGl2;
final bool _isFragmentShader;
static const String kOpenGlEs3Header = '#version 300 es';
/// Lazily allocated fragment color output.
ShaderDeclaration? _fragmentColorDeclaration;
/// Returns fragment color declaration for fragment shader.
///
/// This is hard coded for webgl1 as gl_FragColor.
ShaderDeclaration get fragmentColor {
_fragmentColorDeclaration ??= ShaderDeclaration(
isWebGl2 ? 'gFragColor' : 'gl_FragColor',
ShaderType.kVec4,
ShaderStorageQualifier.kVarying,
);
return _fragmentColorDeclaration!;
}
/// Adds an attribute.
///
/// The attribute variable is assigned a value from a object buffer as a
/// series of graphics primitives are rendered. The value is only accessible
/// in the vertex shader.
ShaderDeclaration addIn(int dataType, {String? name}) {
final ShaderDeclaration attrib = ShaderDeclaration(
name ?? 'attr_${_attribCounter++}',
dataType,
ShaderStorageQualifier.kAttribute,
);
declarations.add(attrib);
return attrib;
}
/// Adds a constant.
ShaderDeclaration addConst(int dataType, String value, {String? name}) {
final ShaderDeclaration declaration = ShaderDeclaration.constant(
name ?? 'c_${_constCounter++}',
dataType,
value,
);
declarations.add(declaration);
return declaration;
}
/// Adds a uniform variable.
///
/// The variable is assigned a value before a gl.draw call.
/// It is accessible in both the vertex and fragment shaders.
///
ShaderDeclaration addUniform(int dataType, {String? name}) {
final ShaderDeclaration uniform = ShaderDeclaration(
name ?? 'uni_${_uniformCounter++}',
dataType,
ShaderStorageQualifier.kUniform,
);
declarations.add(uniform);
return uniform;
}
/// Adds a varying variable.
///
/// The variable is assigned a value by a vertex shader and
/// interpolated across the surface of a graphics primitive for each
/// input to a fragment shader.
/// It can be used in a fragment shader, but not changed.
ShaderDeclaration addOut(int dataType, {String? name}) {
final ShaderDeclaration varying = ShaderDeclaration(
name ?? 'output_${_varyingCounter++}',
dataType,
ShaderStorageQualifier.kVarying,
);
declarations.add(varying);
return varying;
}
void _writeVariableDeclaration(StringBuffer sb, ShaderDeclaration variable) {
switch (variable.storage) {
case ShaderStorageQualifier.kConst:
_buffer.write('const ');
case ShaderStorageQualifier.kAttribute:
_buffer.write(
isWebGl2
? 'in '
: _isFragmentShader
? 'varying '
: 'attribute ',
);
case ShaderStorageQualifier.kUniform:
_buffer.write('uniform ');
case ShaderStorageQualifier.kVarying:
_buffer.write(isWebGl2 ? 'out ' : 'varying ');
}
_buffer.write('${typeToString(variable.dataType)} ${variable.name}');
if (variable.storage == ShaderStorageQualifier.kConst) {
_buffer.write(' = ${variable.constValue}');
}
_buffer.writeln(';');
}
final StringBuffer _buffer = StringBuffer();
static String typeToString(int dataType) {
switch (dataType) {
case ShaderType.kBool:
return 'bool';
case ShaderType.kInt:
return 'int';
case ShaderType.kFloat:
return 'float';
case ShaderType.kBVec2:
return 'bvec2';
case ShaderType.kBVec3:
return 'bvec3';
case ShaderType.kBVec4:
return 'bvec4';
case ShaderType.kIVec2:
return 'ivec2';
case ShaderType.kIVec3:
return 'ivec3';
case ShaderType.kIVec4:
return 'ivec4';
case ShaderType.kVec2:
return 'vec2';
case ShaderType.kVec3:
return 'vec3';
case ShaderType.kVec4:
return 'vec4';
case ShaderType.kMat2:
return 'mat2';
case ShaderType.kMat3:
return 'mat3';
case ShaderType.kMat4:
return 'mat4';
case ShaderType.kSampler1D:
return 'sampler1D';
case ShaderType.kSampler2D:
return 'sampler2D';
case ShaderType.kSampler3D:
return 'sampler3D';
case ShaderType.kVoid:
return 'void';
}
throw ArgumentError();
}
ShaderMethod addMethod(String name) {
final ShaderMethod method = ShaderMethod(name);
_methods.add(method);
return method;
}
String build() {
// Write header.
if (isWebGl2) {
_buffer.writeln(kOpenGlEs3Header);
}
// Write optional precision.
if (integerPrecision != null) {
_buffer.writeln('precision ${_precisionToString(integerPrecision!)} int;');
}
if (floatPrecision != null) {
_buffer.writeln('precision ${_precisionToString(floatPrecision!)} float;');
}
if (isWebGl2 && _fragmentColorDeclaration != null) {
_writeVariableDeclaration(_buffer, _fragmentColorDeclaration!);
}
for (final ShaderDeclaration decl in declarations) {
_writeVariableDeclaration(_buffer, decl);
}
for (final ShaderMethod method in _methods) {
method.write(_buffer);
}
return _buffer.toString();
}
String _precisionToString(int precision) =>
precision == ShaderPrecision.kLow
? 'lowp'
: precision == ShaderPrecision.kMedium
? 'mediump'
: 'highp';
String get texture2DFunction => isWebGl2 ? 'texture' : 'texture2D';
}
class ShaderMethod {
ShaderMethod(this.name);
final String returnType = 'void';
final String name;
final List<String> _statements = <String>[];
int _indentLevel = 1;
void indent() {
++_indentLevel;
}
void unindent() {
assert(_indentLevel != 1);
--_indentLevel;
}
void addStatement(String statement) {
String itemToAdd = statement;
assert(() {
itemToAdd = ' ' * _indentLevel + statement;
return true;
}());
_statements.add(itemToAdd);
}
/// Adds statements to compute tiling in 0..1 coordinate space.
///
/// For clamp we simply assign source value to destination.
///
/// For repeat, we use fractional part of source value.
/// float destination = fract(source);
///
/// For mirror, we repeat every 2 units, by scaling and measuring distance
/// from floor.
/// float destination = 1.0 - source;
/// destination = abs((destination - 2.0 * floor(destination * 0.5)) - 1.0);
void addTileStatements(String source, String destination, ui.TileMode tileMode) {
switch (tileMode) {
case ui.TileMode.repeated:
addStatement('float $destination = fract($source);');
case ui.TileMode.mirror:
addStatement('float $destination = ($source - 1.0);');
addStatement(
'$destination = '
'abs(($destination - 2.0 * floor($destination * 0.5)) - 1.0);',
);
case ui.TileMode.clamp:
case ui.TileMode.decal:
addStatement('float $destination = $source;');
}
}
void write(StringBuffer buffer) {
buffer.writeln('$returnType $name() {');
_statements.forEach(buffer.writeln);
buffer.writeln('}');
}
}
/// WebGl Shader data types.
abstract class ShaderType {
// Basic types.
static const int kBool = 0;
static const int kInt = 1;
static const int kFloat = 2;
// Vector types.
static const int kBVec2 = 3;
static const int kBVec3 = 4;
static const int kBVec4 = 5;
static const int kIVec2 = 6;
static const int kIVec3 = 7;
static const int kIVec4 = 8;
static const int kVec2 = 9;
static const int kVec3 = 10;
static const int kVec4 = 11;
static const int kMat2 = 12;
static const int kMat3 = 13;
static const int kMat4 = 14;
// Textures.
static const int kSampler1D = 15;
static const int kSampler2D = 16;
static const int kSampler3D = 17;
// Other.
static const int kVoid = 18;
}
/// Precision of int and float types.
///
/// Integers: 8 bit, 10 bit and 16 bits.
/// Float: 8 bit. 14 bit and 62 bits.
abstract class ShaderPrecision {
static const int kLow = 0;
static const int kMedium = 1;
static const int kHigh = 2;
}
/// GL Variable storage qualifiers.
abstract class ShaderStorageQualifier {
static const int kConst = 0;
static const int kAttribute = 1;
static const int kUniform = 2;
static const int kVarying = 3;
}
/// Shader variable and constant declaration.
class ShaderDeclaration {
ShaderDeclaration(this.name, this.dataType, this.storage)
: assert(!_isGLSLReservedWord(name)),
constValue = '';
/// Constructs a constant.
ShaderDeclaration.constant(this.name, this.dataType, this.constValue)
: storage = ShaderStorageQualifier.kConst;
final String name;
final int dataType;
final int storage;
final String constValue;
}
// These are used only in debug mode to assert if used as variable name.
// https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.10.pdf
const List<String> _kReservedWords = <String>[
'attribute',
'const',
'uniform',
'varying',
'layout',
'centroid',
'flat',
'smooth',
'noperspective',
'patch', 'sample',
'break', 'continue',
'do', 'for', 'while', 'switch', 'case', 'default', 'if', 'else',
'subroutine',
'in', 'out', 'inout', 'float', 'double', 'int',
'void',
'bool', 'true', 'false',
'invariant',
'discard', 'return',
'mat2', 'mat3', 'mat4', 'dmat2', 'dmat3', 'dmat4',
'mat2x2', 'mat2x3', 'mat2x4', 'dmat2x2', 'dmat2x3', 'dmat2x4',
'mat3x2', 'mat3x3', 'mat3x4', 'dmat3x2', 'dmat3x3', 'dmat3x4',
'mat4x2', 'mat4x3', 'mat4x4', 'dmat4x2', 'dmat4x3', 'dmat4x4',
'vec2', 'vec3', 'vec4', 'ivec2', 'ivec3', 'ivec4', 'bvec2', 'bvec3', 'bvec4',
'dvec2', 'dvec3', 'dvec4',
'uint', 'uvec2', 'uvec3', 'uvec4',
'lowp', 'mediump', 'highp', 'precision',
'sampler1D', 'sampler2D', 'sampler3D', 'samplerCube',
'sampler1DShadow', 'sampler2DShadow', 'samplerCubeShadow',
'sampler1DArray', 'sampler2DArray',
'sampler1DArrayShadow', 'sampler2DArrayShadow',
'isampler1D', 'isampler2D', 'isampler3D', 'isamplerCube',
'isampler1DArray', 'isampler2DArray',
'usampler1D', 'usampler2D', 'usampler3D', 'usamplerCube',
'usampler1DArray', 'usampler2DArray',
'sampler2DRect', 'sampler2DRectShadow', 'isampler2DRect', 'usampler2DRect',
'samplerBuffer', 'isamplerBuffer', 'usamplerBuffer',
'sampler2DMS', 'isampler2DMS', 'usampler2DMS',
'sampler2DMSArray', 'isampler2DMSArray', 'usampler2DMSArray',
'samplerCubeArray', 'samplerCubeArrayShadow', 'isamplerCubeArray',
'usamplerCubeArray',
'struct',
'texture',
// Reserved for future use, see
// https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.10.pdf
'active', 'asm', 'cast', 'class', 'common', 'enum', 'extern', 'external',
'filter', 'fixed', 'fvec2', 'fvec3', 'fvec4', 'goto', 'half', 'hvec2',
'hvec3', 'hvec4', 'iimage1D', 'iimage1DArray', 'iimage2D', 'iimage2DArray',
'iimage3D', 'iimageBuffer', 'iimageCube', 'image1D', 'image1DArray',
'image1DArrayShadow', 'image1DShadow', 'image2D', 'image2DArray',
'image2DArrayShadow', 'image2DShadow', 'image3D', 'imageBuffer',
'imageCube', 'inline', 'input', 'interface', 'long',
'namespace', 'noinline', 'output', 'packed', 'partition', 'public',
'row_major', 'sampler3DRect', 'short', 'sizeof', 'static', 'superp', 'template', 'this',
'typedef', 'uimage1D', 'uimage1DArray', 'uimage2D', 'uimage2DArray',
'uimage3D', 'uimageBuffer', 'uimageCube', 'union', 'unsigned',
'using', 'volatile',
];
bool _isGLSLReservedWord(String name) {
return _kReservedWords.contains(name);
}

View File

@@ -1,106 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../../browser_detection.dart';
import 'shader_builder.dart';
/// Provides common shaders used for gradients and drawVertices APIs.
abstract final class VertexShaders {
static final Uint16List vertexIndicesForRect = Uint16List.fromList(<int>[0, 1, 2, 2, 3, 0]);
/// Cached vertex shaders.
static String? _baseVertexShader;
static String? _textureVertexShader;
/// Creates a vertex shader transforms pixel space [Vertices.positions] to
/// final clipSpace -1..1 coordinates with inverted Y Axis.
/// #version 300 es
/// layout (location=0) in vec4 position;
/// layout (location=1) in vec4 color;
/// uniform mat4 u_ctransform;
/// uniform vec4 u_scale;
/// uniform vec4 u_shift;
/// out vec4 vColor;
/// void main() {
/// gl_Position = ((u_ctransform * position) * u_scale) + u_shift;
/// v_color = color.zyxw;
/// }
static String writeBaseVertexShader() {
if (_baseVertexShader == null) {
final ShaderBuilder builder = ShaderBuilder(webGLVersion);
builder.addIn(ShaderType.kVec4, name: 'position');
builder.addIn(ShaderType.kVec4, name: 'color');
builder.addUniform(ShaderType.kMat4, name: 'u_ctransform');
builder.addUniform(ShaderType.kVec4, name: 'u_scale');
builder.addUniform(ShaderType.kVec4, name: 'u_shift');
builder.addOut(ShaderType.kVec4, name: 'v_color');
final ShaderMethod method = builder.addMethod('main');
method.addStatement('gl_Position = ((u_ctransform * position) * u_scale) + u_shift;');
method.addStatement('v_color = color.zyxw;');
_baseVertexShader = builder.build();
}
return _baseVertexShader!;
}
static String writeTextureVertexShader() {
if (_textureVertexShader == null) {
final ShaderBuilder builder = ShaderBuilder(webGLVersion);
builder.addIn(ShaderType.kVec4, name: 'position');
builder.addUniform(ShaderType.kMat4, name: 'u_ctransform');
builder.addUniform(ShaderType.kVec4, name: 'u_scale');
builder.addUniform(ShaderType.kVec4, name: 'u_textransform');
builder.addUniform(ShaderType.kVec4, name: 'u_shift');
builder.addOut(ShaderType.kVec2, name: 'v_texcoord');
final ShaderMethod method = builder.addMethod('main');
method.addStatement('gl_Position = ((u_ctransform * position) * u_scale) + u_shift;');
method.addStatement(
'v_texcoord = vec2((u_textransform.z + position.x) * u_textransform.x, '
'((u_textransform.w + position.y) * u_textransform.y));',
);
_textureVertexShader = builder.build();
}
return _textureVertexShader!;
}
}
abstract final class FragmentShaders {
static String writeTextureFragmentShader(
bool isWebGl2,
ui.TileMode? tileModeX,
ui.TileMode? tileModeY,
) {
final ShaderBuilder builder = ShaderBuilder.fragment(webGLVersion);
builder.floatPrecision = ShaderPrecision.kMedium;
builder.addIn(ShaderType.kVec2, name: 'v_texcoord');
builder.addUniform(ShaderType.kSampler2D, name: 'u_texture');
final ShaderMethod method = builder.addMethod('main');
if (isWebGl2 ||
tileModeX == null ||
tileModeY == null ||
(tileModeX == ui.TileMode.clamp && tileModeY == ui.TileMode.clamp)) {
method.addStatement(
'${builder.fragmentColor.name} = '
'${builder.texture2DFunction}(u_texture, v_texcoord);',
);
} else {
// Repeat and mirror are not supported for webgl1. Write code to
// adjust texture coordinate.
//
// This will write u and v floats, clamp/repeat and mirror the value and
// pass it to sampler.
method.addTileStatements('v_texcoord.x', 'u', tileModeX);
method.addTileStatements('v_texcoord.y', 'v', tileModeY);
method.addStatement('vec2 uv = vec2(u, v);');
method.addStatement(
'${builder.fragmentColor.name} = '
'${builder.texture2DFunction}(u_texture, uv);',
);
}
return builder.build();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,319 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import '../display.dart';
import '../dom.dart';
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<PersistedSurface> retainedSurfaces = <PersistedSurface>[];
/// Maps every surface currently active on the screen to debug statistics.
Map<PersistedSurface, DebugSurfaceStats> surfaceStats = <PersistedSurface, DebugSurfaceStats>{};
List<Map<PersistedSurface, DebugSurfaceStats>> _surfaceStatsTimeline =
<Map<PersistedSurface, DebugSurfaceStats>>[];
/// Returns debug statistics for the given [surface].
DebugSurfaceStats surfaceStatsFor(PersistedSurface surface) {
if (!debugExplainSurfaceStats) {
throw Exception(
'surfaceStatsFor is only available when debugExplainSurfaceStats is set to true.',
);
}
return surfaceStats.putIfAbsent(surface, () => DebugSurfaceStats(surface));
}
/// Compositor information collected for one frame useful for assessing the
/// efficiency of constructing the frame.
///
/// This information is only available in debug mode.
///
/// 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);
/// The surface these stats are for, or `null` if these are aggregated stats.
final PersistedSurface? surface;
/// How many times a surface was retained from a previously rendered frame.
int retainSurfaceCount = 0;
/// How many times a surface reused an HTML element from a previously rendered
/// surface.
int reuseElementCount = 0;
/// If a surface is a [PersistedPicture], how many times it painted.
int paintCount = 0;
/// If a surface is a [PersistedPicture], how many pixels it painted.
int paintPixelCount = 0;
/// If a surface is a [PersistedPicture], how many times it reused a
/// previously allocated `<canvas>` element when it painted.
int reuseCanvasCount = 0;
/// If a surface is a [PersistedPicture], how many times it allocated a new
/// bitmap canvas.
int allocateBitmapCanvasCount = 0;
/// If a surface is a [PersistedPicture], how many pixels it allocated for
/// the bitmap.
///
/// For aggregated stats, this is the total sum of all pixels across all
/// canvases.
int allocatedBitmapSizeInPixels = 0;
/// The number of HTML DOM nodes a surface allocated.
///
/// For aggregated stats, this is the total sum of all DOM nodes across all
/// surfaces.
int allocatedDomNodeCount = 0;
/// Adds all counters of [oneSurfaceStats] into this object.
void aggregate(DebugSurfaceStats oneSurfaceStats) {
retainSurfaceCount += oneSurfaceStats.retainSurfaceCount;
reuseElementCount += oneSurfaceStats.reuseElementCount;
paintCount += oneSurfaceStats.paintCount;
paintPixelCount += oneSurfaceStats.paintPixelCount;
reuseCanvasCount += oneSurfaceStats.reuseCanvasCount;
allocateBitmapCanvasCount += oneSurfaceStats.allocateBitmapCanvasCount;
allocatedBitmapSizeInPixels += oneSurfaceStats.allocatedBitmapSizeInPixels;
allocatedDomNodeCount += oneSurfaceStats.allocatedDomNodeCount;
}
}
DomCanvasRenderingContext2D? _debugSurfaceStatsOverlayCtx;
void debugRepaintSurfaceStatsOverlay(PersistedScene scene) {
final int overlayWidth = domWindow.innerWidth!.toInt();
const int rowHeight = 30;
const int rowCount = 4;
const int overlayHeight = rowHeight * rowCount;
const int strokeWidth = 2;
_surfaceStatsTimeline.add(surfaceStats);
while (_surfaceStatsTimeline.length > (overlayWidth / strokeWidth)) {
_surfaceStatsTimeline.removeAt(0);
}
if (_debugSurfaceStatsOverlayCtx == null) {
final DomCanvasElement debugSurfaceStatsOverlay = createDomCanvasElement(
width: overlayWidth,
height: overlayHeight,
);
debugSurfaceStatsOverlay.style
..position = 'fixed'
..left = '0'
..top = '0'
..zIndex = '1000'
..opacity = '0.8';
_debugSurfaceStatsOverlayCtx = debugSurfaceStatsOverlay.context2D;
domDocument.body!.append(debugSurfaceStatsOverlay);
}
_debugSurfaceStatsOverlayCtx!
..fillStyle = 'black'
..beginPath()
..rect(0, 0, overlayWidth, overlayHeight)
..fill();
final double physicalScreenWidth =
domWindow.innerWidth! * EngineFlutterDisplay.instance.browserDevicePixelRatio;
final double physicalScreenHeight =
domWindow.innerHeight! * EngineFlutterDisplay.instance.browserDevicePixelRatio;
final double physicsScreenPixelCount = physicalScreenWidth * physicalScreenHeight;
final int totalDomNodeCount = scene.rootElement!.querySelectorAll('*').length;
for (int i = 0; i < _surfaceStatsTimeline.length; i++) {
final Map<PersistedSurface, DebugSurfaceStats> statsMap = _surfaceStatsTimeline[i];
final DebugSurfaceStats totals = DebugSurfaceStats(null);
int pixelCount = 0;
for (final DebugSurfaceStats oneSurfaceStats in statsMap.values) {
totals.aggregate(oneSurfaceStats);
if (oneSurfaceStats.surface is PersistedPicture) {
final PersistedPicture picture = oneSurfaceStats.surface! as PersistedPicture;
pixelCount += picture.bitmapPixelCount;
}
}
final double repaintRate = totals.paintPixelCount / pixelCount;
final double domAllocationRate = totals.allocatedDomNodeCount / totalDomNodeCount;
final double bitmapAllocationRate =
totals.allocatedBitmapSizeInPixels / physicsScreenPixelCount;
final double surfaceRetainRate = totals.retainSurfaceCount / _surfaceStatsTimeline[i].length;
// Repaints
_debugSurfaceStatsOverlayCtx!
..lineWidth = strokeWidth
..strokeStyle = 'red'
..beginPath()
..moveTo(strokeWidth * i, rowHeight)
..lineTo(strokeWidth * i, rowHeight * (1 - repaintRate))
..stroke();
// DOM allocations
_debugSurfaceStatsOverlayCtx!
..lineWidth = strokeWidth
..strokeStyle = 'red'
..beginPath()
..moveTo(strokeWidth * i, 2 * rowHeight)
..lineTo(strokeWidth * i, rowHeight * (2 - domAllocationRate))
..stroke();
// Bitmap allocations
_debugSurfaceStatsOverlayCtx!
..lineWidth = strokeWidth
..strokeStyle = 'red'
..beginPath()
..moveTo(strokeWidth * i, 3 * rowHeight)
..lineTo(strokeWidth * i, rowHeight * (3 - bitmapAllocationRate))
..stroke();
// Surface retentions
_debugSurfaceStatsOverlayCtx!
..lineWidth = strokeWidth
..strokeStyle = 'green'
..beginPath()
..moveTo(strokeWidth * i, 4 * rowHeight)
..lineTo(strokeWidth * i, rowHeight * (4 - surfaceRetainRate))
..stroke();
}
_debugSurfaceStatsOverlayCtx!
..font = 'normal normal 14px sans-serif'
..fillStyle = 'white'
..fillText('Repaint rate', 5, rowHeight - 5)
..fillText('DOM alloc rate', 5, 2 * rowHeight - 5)
..fillText('Bitmap alloc rate', 5, 3 * rowHeight - 5)
..fillText('Retain rate', 5, 4 * rowHeight - 5);
for (int i = 1; i <= rowCount; i++) {
_debugSurfaceStatsOverlayCtx!
..lineWidth = 1
..strokeStyle = 'blue'
..beginPath()
..moveTo(0, overlayHeight - rowHeight * i)
..lineTo(overlayWidth, overlayHeight - rowHeight * i)
..stroke();
}
}
/// Prints debug statistics for the current frame to the console.
void debugPrintSurfaceStats(PersistedScene scene, int frameNumber) {
int pictureCount = 0;
int paintCount = 0;
int bitmapCanvasCount = 0;
int bitmapReuseCount = 0;
int bitmapAllocationCount = 0;
int bitmapPaintCount = 0;
int bitmapPixelsAllocated = 0;
int domCanvasCount = 0;
int domPaintCount = 0;
int surfaceRetainCount = 0;
int elementReuseCount = 0;
int totalAllocatedDomNodeCount = 0;
void countReusesRecursively(PersistedSurface surface) {
final DebugSurfaceStats stats = surfaceStatsFor(surface);
surfaceRetainCount += stats.retainSurfaceCount;
elementReuseCount += stats.reuseElementCount;
totalAllocatedDomNodeCount += stats.allocatedDomNodeCount;
if (surface is PersistedPicture) {
pictureCount += 1;
paintCount += stats.paintCount;
if (surface.canvas is DomCanvas) {
domCanvasCount++;
domPaintCount += stats.paintCount;
}
if (surface.canvas is BitmapCanvas) {
bitmapCanvasCount++;
bitmapPaintCount += stats.paintCount;
}
bitmapReuseCount += stats.reuseCanvasCount;
bitmapAllocationCount += stats.allocateBitmapCanvasCount;
bitmapPixelsAllocated += stats.allocatedBitmapSizeInPixels;
}
surface.visitChildren(countReusesRecursively);
}
scene.visitChildren(countReusesRecursively);
final StringBuffer buf = StringBuffer();
buf
..writeln('---------------------- FRAME #$frameNumber -------------------------')
..writeln('Surfaces retained: $surfaceRetainCount')
..writeln('Elements reused: $elementReuseCount')
..writeln('Elements allocated: $totalAllocatedDomNodeCount')
..writeln('Pictures: $pictureCount')
..writeln(' Painted: $paintCount')
..writeln(' Skipped painting: ${pictureCount - paintCount}')
..writeln('DOM canvases:')
..writeln(' Painted: $domPaintCount')
..writeln(' Skipped painting: ${domCanvasCount - domPaintCount}')
..writeln('Bitmap canvases: $bitmapCanvasCount')
..writeln(' Painted: $bitmapPaintCount')
..writeln(' Skipped painting: ${bitmapCanvasCount - bitmapPaintCount}')
..writeln(' Reused: $bitmapReuseCount')
..writeln(' Allocated: $bitmapAllocationCount')
..writeln(' Allocated pixels: $bitmapPixelsAllocated')
..writeln(' Available for reuse: ${recycledCanvases.length}');
// A microtask will fire after the DOM is flushed, letting us probe into
// actual <canvas> tags.
scheduleMicrotask(() {
final Iterable<DomElement> canvasElements = domDocument.querySelectorAll('canvas');
final StringBuffer canvasInfo = StringBuffer();
final int pixelCount = canvasElements
.cast<DomCanvasElement>()
.map<int>((DomCanvasElement e) {
final int pixels = (e.width! * e.height!).toInt();
canvasInfo.writeln(' - ${e.width!} x ${e.height!} = $pixels pixels');
return pixels;
})
.fold(0, (int total, int pixels) => total + pixels);
final double physicalScreenWidth =
domWindow.innerWidth! * EngineFlutterDisplay.instance.browserDevicePixelRatio;
final double physicalScreenHeight =
domWindow.innerHeight! * EngineFlutterDisplay.instance.browserDevicePixelRatio;
final double physicsScreenPixelCount = physicalScreenWidth * physicalScreenHeight;
final double screenPixelRatio = pixelCount / physicsScreenPixelCount;
final String screenDescription =
'1 screen is $physicalScreenWidth x $physicalScreenHeight = $physicsScreenPixelCount pixels';
final String canvasPixelDescription =
'$pixelCount (${screenPixelRatio.toStringAsFixed(2)} x screens';
buf
..writeln(' Elements: ${canvasElements.length}')
..writeln(canvasInfo)
..writeln(' Pixels: $canvasPixelDescription; $screenDescription)')
..writeln('-----------------------------------------------------------');
final bool screenPixelRatioTooHigh = screenPixelRatio > kScreenPixelRatioWarningThreshold;
if (screenPixelRatioTooHigh) {
print('WARNING: pixel/screen ratio too high (${screenPixelRatio.toStringAsFixed(2)}x)');
}
print(buf);
});
}

View File

@@ -1,83 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import '../dom.dart';
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? super.oldLayer, this._matrixStorage);
/// 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);
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);
return _localTransformInverse;
}
@override
DomElement createElement() {
final DomElement element = domDocument.createElement('flt-transform');
setElementStyle(element, 'position', 'absolute');
setElementStyle(element, 'transform-origin', '0 0 0');
return element;
}
@override
void apply() {
rootElement!.style.transform = float64ListToCssTransform(_matrixStorage);
}
@override
void update(PersistedTransform oldSurface) {
super.update(oldSurface);
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 < _matrixStorage.length; i++) {
if (_matrixStorage[i] != oldSurface._matrixStorage[i]) {
matrixChanged = true;
break;
}
}
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;
}
}
}

View File

@@ -1,737 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import '../dom.dart';
import '../html/bitmap_canvas.dart';
import '../profiler.dart';
import '../view_embedder/style_manager.dart';
import 'layout_fragmenter.dart';
import 'layout_service.dart';
import 'paint_service.dart';
import 'paragraph.dart';
import 'word_breaker.dart';
final String placeholderChar = String.fromCharCode(0xFFFC);
/// A paragraph made up of a flat list of text spans and placeholders.
///
/// [CanvasParagraph] doesn't use a DOM element to represent the structure of
/// its spans and styles. Instead it uses a flat list of [ParagraphSpan]
/// objects.
class CanvasParagraph implements ui.Paragraph {
/// This class is created by the engine, and should not be instantiated
/// or extended directly.
///
/// To create a [CanvasParagraph] object, use a [CanvasParagraphBuilder].
CanvasParagraph(
this.spans, {
required this.paragraphStyle,
required this.plainText,
required this.canDrawOnCanvas,
}) : assert(spans.isNotEmpty);
/// The flat list of spans that make up this paragraph.
final List<ParagraphSpan> spans;
/// General styling information for this paragraph.
final EngineParagraphStyle paragraphStyle;
/// The full textual content of the paragraph.
final String plainText;
/// Whether this paragraph can be drawn on a bitmap canvas.
///
/// Some text features cannot be rendered into a 2D canvas and must use HTML,
/// such as font features and text decorations.
final bool canDrawOnCanvas;
@override
double get width => _layoutService.width;
@override
double get height => _layoutService.height;
@override
double get longestLine => _layoutService.longestLine?.width ?? 0.0;
@override
double get minIntrinsicWidth => _layoutService.minIntrinsicWidth;
@override
double get maxIntrinsicWidth => _layoutService.maxIntrinsicWidth;
@override
double get alphabeticBaseline => _layoutService.alphabeticBaseline;
@override
double get ideographicBaseline => _layoutService.ideographicBaseline;
@override
bool get didExceedMaxLines => _layoutService.didExceedMaxLines;
List<ParagraphLine> get lines => _layoutService.lines;
/// The bounds that contain the text painted inside this paragraph.
ui.Rect get paintBounds => _layoutService.paintBounds;
/// Whether this paragraph has been laid out or not.
bool isLaidOut = false;
ui.ParagraphConstraints? _lastUsedConstraints;
late final TextLayoutService _layoutService = TextLayoutService(this);
late final TextPaintService _paintService = TextPaintService(this);
@override
void layout(ui.ParagraphConstraints constraints) {
if (constraints == _lastUsedConstraints) {
return;
}
late Stopwatch stopwatch;
if (Profiler.isBenchmarkMode) {
stopwatch = Stopwatch()..start();
}
_layoutService.performLayout(constraints);
if (Profiler.isBenchmarkMode) {
stopwatch.stop();
Profiler.instance.benchmark('text_layout', stopwatch.elapsedMicroseconds.toDouble());
}
isLaidOut = true;
_lastUsedConstraints = constraints;
_cachedDomElement = null;
}
// TODO(mdebbar): Returning true means we always require a bitmap canvas. Revisit
// this decision once `CanvasParagraph` is fully implemented.
/// Whether this paragraph is doing arbitrary paint operations that require
/// a bitmap canvas, and can't be expressed in a DOM canvas.
bool get hasArbitraryPaint => true;
/// Paints this paragraph instance on a [canvas] at the given [offset].
void paint(BitmapCanvas canvas, ui.Offset offset) {
_paintService.paint(canvas, offset);
}
DomElement? _cachedDomElement;
/// Returns a DOM element that represents the entire paragraph and its
/// children.
///
/// Generates a new DOM element on every invocation.
DomElement toDomElement() {
assert(isLaidOut);
final DomElement? domElement = _cachedDomElement;
if (domElement == null) {
return _cachedDomElement ??= _createDomElement();
}
return domElement.cloneNode(true) as DomElement;
}
DomElement _createDomElement() {
final DomElement rootElement = domDocument.createElement('flt-paragraph');
// 1. Set paragraph-level styles.
final DomCSSStyleDeclaration cssStyle = rootElement.style;
cssStyle
..position = 'absolute'
// Prevent the browser from doing any line breaks in the paragraph. We want
// to have full control of the paragraph layout.
..whiteSpace = 'pre';
// 2. Append all spans to the paragraph.
for (int i = 0; i < lines.length; i++) {
final ParagraphLine line = lines[i];
for (final LayoutFragment fragment in line.fragments) {
if (fragment.isPlaceholder) {
continue;
}
final String text = fragment.getText(this);
if (text.isEmpty) {
continue;
}
final DomElement spanElement = domDocument.createElement('flt-span');
if (fragment.textDirection == ui.TextDirection.rtl) {
spanElement.setAttribute('dir', 'rtl');
}
applyTextStyleToElement(element: spanElement, style: fragment.style);
_positionSpanElement(spanElement, line, fragment);
spanElement.appendText(text);
rootElement.append(spanElement);
}
}
return rootElement;
}
@override
List<ui.TextBox> getBoxesForPlaceholders() {
return _layoutService.getBoxesForPlaceholders();
}
@override
List<ui.TextBox> getBoxesForRange(
int start,
int end, {
ui.BoxHeightStyle boxHeightStyle = ui.BoxHeightStyle.tight,
ui.BoxWidthStyle boxWidthStyle = ui.BoxWidthStyle.tight,
}) {
return _layoutService.getBoxesForRange(start, end, boxHeightStyle, boxWidthStyle);
}
@override
ui.TextPosition getPositionForOffset(ui.Offset offset) {
return _layoutService.getPositionForOffset(offset);
}
@override
ui.GlyphInfo? getClosestGlyphInfoForOffset(ui.Offset offset) =>
_layoutService.getClosestGlyphInfo(offset);
@override
ui.GlyphInfo? getGlyphInfoAt(int codeUnitOffset) {
final int? lineNumber = _findLine(codeUnitOffset, 0, numberOfLines);
if (lineNumber == null) {
return null;
}
final ParagraphLine line = lines[lineNumber];
final ui.TextRange? range = line.getCharacterRangeAt(codeUnitOffset);
if (range == null) {
return null;
}
assert(line.overlapsWith(range.start, range.end));
for (final LayoutFragment fragment in line.fragments) {
if (fragment.overlapsWith(range.start, range.end)) {
// If the grapheme cluster is split into multiple fragments (which really
// shouldn't happen but currently if they are in different TextSpans they
// don't combine), use the layout box of the first base character as its
// layout box has a better chance to be not that far-off.
final ui.TextBox textBox = fragment.toTextBox(start: range.start, end: range.end);
return ui.GlyphInfo(textBox.toRect(), range, textBox.direction);
}
}
assert(false, 'This should not be reachable.');
return null;
}
@override
ui.TextRange getWordBoundary(ui.TextPosition position) {
final int characterPosition = switch (position.affinity) {
ui.TextAffinity.upstream => position.offset - 1,
ui.TextAffinity.downstream => position.offset,
};
final int start = WordBreaker.prevBreakIndex(plainText, characterPosition + 1);
final int end = WordBreaker.nextBreakIndex(plainText, characterPosition);
return ui.TextRange(start: start, end: end);
}
@override
ui.TextRange getLineBoundary(ui.TextPosition position) {
if (lines.isEmpty) {
return ui.TextRange.empty;
}
final int? lineNumber = getLineNumberAt(position.offset);
// Fallback to the last line for backward compatibility.
final ParagraphLine line = lineNumber != null ? lines[lineNumber] : lines.last;
return ui.TextRange(start: line.startIndex, end: line.endIndex - line.trailingNewlines);
}
@override
List<EngineLineMetrics> computeLineMetrics() {
return lines.map((ParagraphLine line) => line.lineMetrics).toList();
}
@override
EngineLineMetrics? getLineMetricsAt(int lineNumber) {
return 0 <= lineNumber && lineNumber < lines.length ? lines[lineNumber].lineMetrics : null;
}
@override
int get numberOfLines => lines.length;
@override
int? getLineNumberAt(int codeUnitOffset) => _findLine(codeUnitOffset, 0, lines.length);
int? _findLine(int codeUnitOffset, int startLine, int endLine) {
assert(endLine <= lines.length);
final bool isOutOfBounds =
endLine <= startLine ||
codeUnitOffset < lines[startLine].startIndex ||
(endLine < numberOfLines && lines[endLine].startIndex <= codeUnitOffset);
if (isOutOfBounds) {
return null;
}
if (endLine == startLine + 1) {
assert(lines[startLine].startIndex <= codeUnitOffset);
assert(endLine == numberOfLines || codeUnitOffset < lines[endLine].startIndex);
return codeUnitOffset >= lines[startLine].visibleEndIndex ? null : startLine;
}
// endLine >= startLine + 2 thus we have
// startLine + 1 <= midIndex <= endLine - 1
final int midIndex = (startLine + endLine) ~/ 2;
return _findLine(codeUnitOffset, midIndex, endLine) ??
_findLine(codeUnitOffset, startLine, midIndex);
}
bool _disposed = false;
@override
void dispose() {
// TODO(dnfield): It should be possible to clear resources here, but would
// need refcounting done on any surfaces/pictures holding references to this
// object.
_disposed = true;
}
@override
bool get debugDisposed {
bool? result;
assert(() {
result = _disposed;
return true;
}());
if (result != null) {
return result!;
}
throw StateError('Paragraph.debugDisposed is only avialalbe when asserts are enabled.');
}
}
void _positionSpanElement(DomElement element, ParagraphLine line, LayoutFragment fragment) {
final ui.Rect boxRect = fragment.toPaintingTextBox().toRect();
element.style
..position = 'absolute'
..top = '${boxRect.top}px'
..left = '${boxRect.left}px'
// This is needed for space-only spans that are used to justify the paragraph.
..width = '${boxRect.width}px'
// Makes sure the baseline of each span is positioned as expected.
..lineHeight = '${boxRect.height}px';
}
/// Represents a span in the paragraph.
///
/// Instead of keeping spans and styles in a tree hierarchy like the framework
/// does, we flatten the structure and resolve/merge all the styles from parent
/// nodes.
///
/// These spans are stored as a flat list in the paragraph object.
class ParagraphSpan {
/// Creates a [ParagraphSpan] with the given [style], representing the span of
/// text in the range between [start] and [end].
ParagraphSpan({required this.style, required this.start, required this.end});
/// The resolved style of the span.
final EngineTextStyle style;
/// The index of the beginning of the range of text represented by this span.
final int start;
/// The index of the end of the range of text represented by this span.
final int end;
}
class PlaceholderSpan extends ParagraphPlaceholder implements ParagraphSpan {
PlaceholderSpan(
this.style,
this.start,
this.end,
double width,
double height,
ui.PlaceholderAlignment alignment, {
required double baselineOffset,
required ui.TextBaseline baseline,
}) : super(width, height, alignment, baselineOffset: baselineOffset, baseline: baseline);
@override
final EngineTextStyle style;
@override
final int start;
@override
final int end;
}
/// Represents a node in the tree of text styles pushed to [ui.ParagraphBuilder].
///
/// The [ui.ParagraphBuilder.pushText] and [ui.ParagraphBuilder.pop] operations
/// represent the entire tree of styles in the paragraph. In our implementation,
/// we don't need to keep the entire tree structure in memory. At any point in
/// time, we only need a stack of nodes that represent the current branch in the
/// tree. The items in the stack are [StyleNode] objects.
abstract class StyleNode {
/// Create a child for this style node.
///
/// We are not creating a tree structure, hence there's no need to keep track
/// of the children.
ChildStyleNode createChild(EngineTextStyle style) {
return ChildStyleNode(parent: this, style: style);
}
EngineTextStyle? _cachedStyle;
/// Generates the final text style to be applied to the text span.
///
/// The resolved text style is equivalent to the entire ascendent chain of
/// parent style nodes.
EngineTextStyle resolveStyle() {
return _cachedStyle ??= EngineTextStyle(
color: _color,
decoration: _decoration,
decorationColor: _decorationColor,
decorationStyle: _decorationStyle,
decorationThickness: _decorationThickness,
fontWeight: _fontWeight,
fontStyle: _fontStyle,
textBaseline: _textBaseline,
fontFamily: _fontFamily,
fontFamilyFallback: _fontFamilyFallback,
fontFeatures: _fontFeatures,
fontVariations: _fontVariations,
fontSize: _fontSize,
letterSpacing: _letterSpacing,
wordSpacing: _wordSpacing,
height: _height,
leadingDistribution: _leadingDistribution,
locale: _locale,
background: _background,
foreground: _foreground,
shadows: _shadows,
);
}
ui.Color? get _color;
ui.TextDecoration? get _decoration;
ui.Color? get _decorationColor;
ui.TextDecorationStyle? get _decorationStyle;
double? get _decorationThickness;
ui.FontWeight? get _fontWeight;
ui.FontStyle? get _fontStyle;
ui.TextBaseline? get _textBaseline;
String get _fontFamily;
List<String>? get _fontFamilyFallback;
List<ui.FontFeature>? get _fontFeatures;
List<ui.FontVariation>? get _fontVariations;
double get _fontSize;
double? get _letterSpacing;
double? get _wordSpacing;
double? get _height;
ui.TextLeadingDistribution? get _leadingDistribution;
ui.Locale? get _locale;
ui.Paint? get _background;
ui.Paint? get _foreground;
List<ui.Shadow>? get _shadows;
}
/// Represents a non-root [StyleNode].
class ChildStyleNode extends StyleNode {
/// Creates a [ChildStyleNode] with the given [parent] and [style].
ChildStyleNode({required this.parent, required this.style});
/// The parent node to be used when resolving text styles.
final StyleNode parent;
/// The text style associated with the current node.
final EngineTextStyle style;
// Read these properties from the TextStyle associated with this node. If the
// property isn't defined, go to the parent node.
@override
ui.Color? get _color => style.color ?? (_foreground == null ? parent._color : null);
@override
ui.TextDecoration? get _decoration => style.decoration ?? parent._decoration;
@override
ui.Color? get _decorationColor => style.decorationColor ?? parent._decorationColor;
@override
ui.TextDecorationStyle? get _decorationStyle => style.decorationStyle ?? parent._decorationStyle;
@override
double? get _decorationThickness => style.decorationThickness ?? parent._decorationThickness;
@override
ui.FontWeight? get _fontWeight => style.fontWeight ?? parent._fontWeight;
@override
ui.FontStyle? get _fontStyle => style.fontStyle ?? parent._fontStyle;
@override
ui.TextBaseline? get _textBaseline => style.textBaseline ?? parent._textBaseline;
@override
List<String>? get _fontFamilyFallback => style.fontFamilyFallback ?? parent._fontFamilyFallback;
@override
List<ui.FontFeature>? get _fontFeatures => style.fontFeatures ?? parent._fontFeatures;
@override
List<ui.FontVariation>? get _fontVariations => style.fontVariations ?? parent._fontVariations;
@override
double get _fontSize => style.fontSize ?? parent._fontSize;
@override
double? get _letterSpacing => style.letterSpacing ?? parent._letterSpacing;
@override
double? get _wordSpacing => style.wordSpacing ?? parent._wordSpacing;
@override
double? get _height {
return style.height == ui.kTextHeightNone ? null : (style.height ?? parent._height);
}
@override
ui.TextLeadingDistribution? get _leadingDistribution =>
style.leadingDistribution ?? parent._leadingDistribution;
@override
ui.Locale? get _locale => style.locale ?? parent._locale;
@override
ui.Paint? get _background => style.background ?? parent._background;
@override
ui.Paint? get _foreground => style.foreground ?? parent._foreground;
@override
List<ui.Shadow>? get _shadows => style.shadows ?? parent._shadows;
// Font family is slightly different from the other properties above. It's
// never null on the TextStyle object, so we use `isFontFamilyProvided` to
// check if font family is defined or not.
@override
String get _fontFamily => style.isFontFamilyProvided ? style.fontFamily : parent._fontFamily;
}
/// The root style node for the paragraph.
///
/// The style of the root is derived from a [ui.ParagraphStyle] and is the root
/// style for all spans in the paragraph.
class RootStyleNode extends StyleNode {
/// Creates a [RootStyleNode] from [paragraphStyle].
RootStyleNode(this.paragraphStyle);
/// The style of the paragraph being built.
final EngineParagraphStyle paragraphStyle;
@override
ui.Color? get _color => null;
@override
ui.TextDecoration? get _decoration => null;
@override
ui.Color? get _decorationColor => null;
@override
ui.TextDecorationStyle? get _decorationStyle => null;
@override
double? get _decorationThickness => null;
@override
ui.FontWeight? get _fontWeight => paragraphStyle.fontWeight;
@override
ui.FontStyle? get _fontStyle => paragraphStyle.fontStyle;
@override
ui.TextBaseline? get _textBaseline => null;
@override
String get _fontFamily => paragraphStyle.fontFamily ?? StyleManager.defaultFontFamily;
@override
List<String>? get _fontFamilyFallback => null;
@override
List<ui.FontFeature>? get _fontFeatures => null;
@override
List<ui.FontVariation>? get _fontVariations => null;
@override
double get _fontSize => paragraphStyle.fontSize ?? StyleManager.defaultFontSize;
@override
double? get _letterSpacing => null;
@override
double? get _wordSpacing => null;
@override
double? get _height => paragraphStyle.height;
@override
ui.TextLeadingDistribution? get _leadingDistribution => null;
@override
ui.Locale? get _locale => paragraphStyle.locale;
@override
ui.Paint? get _background => null;
@override
ui.Paint? get _foreground => null;
@override
List<ui.Shadow>? get _shadows => null;
}
/// Builds a [CanvasParagraph] containing text with the given styling
/// information.
class CanvasParagraphBuilder implements ui.ParagraphBuilder {
/// Creates a [CanvasParagraphBuilder] object, which is used to create a
/// [CanvasParagraph].
CanvasParagraphBuilder(EngineParagraphStyle style)
: _paragraphStyle = style,
_rootStyleNode = RootStyleNode(style);
final StringBuffer _plainTextBuffer = StringBuffer();
final EngineParagraphStyle _paragraphStyle;
final List<ParagraphSpan> _spans = <ParagraphSpan>[];
final List<StyleNode> _styleStack = <StyleNode>[];
final RootStyleNode _rootStyleNode;
StyleNode get _currentStyleNode =>
_styleStack.isEmpty ? _rootStyleNode : _styleStack[_styleStack.length - 1];
@override
int get placeholderCount => _placeholderCount;
int _placeholderCount = 0;
@override
List<double> get placeholderScales => _placeholderScales;
final List<double> _placeholderScales = <double>[];
@override
void addPlaceholder(
double width,
double height,
ui.PlaceholderAlignment alignment, {
double scale = 1.0,
double? baselineOffset,
ui.TextBaseline? baseline,
}) {
// Require a baseline to be specified if using a baseline-based alignment.
assert(
!(alignment == ui.PlaceholderAlignment.aboveBaseline ||
alignment == ui.PlaceholderAlignment.belowBaseline ||
alignment == ui.PlaceholderAlignment.baseline) ||
baseline != null,
);
final int start = _plainTextBuffer.length;
_plainTextBuffer.write(placeholderChar);
final int end = _plainTextBuffer.length;
final EngineTextStyle style = _currentStyleNode.resolveStyle();
_updateCanDrawOnCanvas(style);
_placeholderCount++;
_placeholderScales.add(scale);
_spans.add(
PlaceholderSpan(
style,
start,
end,
width * scale,
height * scale,
alignment,
baselineOffset: (baselineOffset ?? height) * scale,
baseline: baseline ?? ui.TextBaseline.alphabetic,
),
);
}
@override
void pushStyle(ui.TextStyle style) {
_styleStack.add(_currentStyleNode.createChild(style as EngineTextStyle));
}
@override
void pop() {
if (_styleStack.isNotEmpty) {
_styleStack.removeLast();
}
}
bool _canDrawOnCanvas = true;
@override
void addText(String text) {
final int start = _plainTextBuffer.length;
_plainTextBuffer.write(text);
final int end = _plainTextBuffer.length;
final EngineTextStyle style = _currentStyleNode.resolveStyle();
_updateCanDrawOnCanvas(style);
_spans.add(ParagraphSpan(style: style, start: start, end: end));
}
void _updateCanDrawOnCanvas(EngineTextStyle style) {
if (!_canDrawOnCanvas) {
return;
}
final double? letterSpacing = style.letterSpacing;
if (letterSpacing != null && letterSpacing != 0.0) {
_canDrawOnCanvas = false;
return;
}
final ui.TextDecoration? decoration = style.decoration;
if (decoration != null && decoration != ui.TextDecoration.none) {
_canDrawOnCanvas = false;
return;
}
final List<ui.FontFeature>? fontFeatures = style.fontFeatures;
if (fontFeatures != null && fontFeatures.isNotEmpty) {
_canDrawOnCanvas = false;
return;
}
final List<ui.FontVariation>? fontVariations = style.fontVariations;
if (fontVariations != null && fontVariations.isNotEmpty) {
_canDrawOnCanvas = false;
return;
}
}
@override
CanvasParagraph build() {
if (_spans.isEmpty) {
// In case `addText` and `addPlaceholder` were never called.
//
// We want the paragraph to always have a non-empty list of spans to match
// the expectations of the [LayoutFragmenter].
_spans.add(ParagraphSpan(style: _rootStyleNode.resolveStyle(), start: 0, end: 0));
}
return CanvasParagraph(
_spans,
paragraphStyle: _paragraphStyle,
plainText: _plainTextBuffer.toString(),
canDrawOnCanvas: _canDrawOnCanvas,
);
}
}

View File

@@ -1,189 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
/// This class is responsible for registering and loading fonts.
///
/// Once an asset manager has been set in the framework, call
/// [downloadAssetFonts] with it to register fonts declared in the
/// font manifest. If test fonts are enabled, then call
/// [debugDownloadTestFonts] as well.
class HtmlFontCollection implements FlutterFontCollection {
/// Reads the font manifest using the [ui_web.assetManager] and downloads all of the
/// fonts declared within.
@override
Future<AssetFontsResult> loadAssetFonts(FontManifest manifest) async {
final List<Future<(String, FontLoadError?)>> pendingFonts =
<Future<(String, FontLoadError?)>>[];
for (final FontFamily family in manifest.families) {
for (final FontAsset fontAsset in family.fontAssets) {
pendingFonts.add(() async {
return (
fontAsset.asset,
await _loadFontAsset(family.name, fontAsset.asset, fontAsset.descriptors),
);
}());
}
}
final List<String> loadedFonts = <String>[];
final Map<String, FontLoadError> fontFailures = <String, FontLoadError>{};
for (final (String asset, FontLoadError? error) in await Future.wait(pendingFonts)) {
if (error == null) {
loadedFonts.add(asset);
} else {
fontFailures[asset] = error;
}
}
return AssetFontsResult(loadedFonts, fontFailures);
}
@override
Future<bool> loadFontFromList(Uint8List list, {String? fontFamily}) async {
if (fontFamily == null) {
printWarning('Font family must be provided to HtmlFontCollection.');
return false;
}
return _loadFontFaceBytes(fontFamily, list);
}
@override
Null get fontFallbackManager => null;
/// Unregister all fonts that have been registered.
@override
void clear() {
domDocument.fonts!.clear();
}
// Regular expression to detect a string with no punctuations.
// For example font family 'Ahem!' does not fall into this category
// so the family name will be wrapped in quotes.
static final RegExp notPunctuation = RegExp(r'[a-z0-9\s]+', caseSensitive: false);
// Regular expression to detect tokens starting with a digit.
// For example font family 'Goudy Bookletter 1911' falls into this
// category.
static final RegExp startWithDigit = RegExp(r'\b\d');
/// Registers assets to Flutter Web Engine.
///
/// Browsers and browsers versions differ significantly on how a valid font
/// family name should be formatted. Notable issues are:
///
/// Safari 12 and Firefox crash if you create a [DomFontFace] with a font
/// family that is not correct CSS syntax. Font family names with invalid
/// characters are accepted on these browsers, when wrapped it in
/// quotes.
///
/// Additionally, for Safari 12 to work [DomFontFace] name should be
/// loaded correctly on the first try.
///
/// A font in Chrome is not usable other than inside a '<p>' tag, if a
/// [DomFontFace] is loaded wrapped with quotes. Unlike Safari 12 if a
/// valid version of the font is also loaded afterwards it will show
/// that font normally.
///
/// In Safari 13 the [DomFontFace] should be loaded with unquoted family
/// names.
///
/// In order to avoid all these browser compatibility issues this method:
/// * Detects the family names that might cause a conflict.
/// * Loads it with the quotes.
/// * Loads it again without the quotes.
/// * For all the other family names [DomFontFace] is loaded only once.
///
/// See also:
///
/// * https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#Valid_family_names
/// * https://drafts.csswg.org/css-fonts-3/#font-family-prop
Future<FontLoadError?> _loadFontAsset(
String family,
String asset,
Map<String, String> descriptors,
) async {
final List<DomFontFace> fontFaces = <DomFontFace>[];
final List<FontLoadError> errors = <FontLoadError>[];
try {
if (startWithDigit.hasMatch(family) || notPunctuation.stringMatch(family) != family) {
// Load a font family name with special characters once here wrapped in
// quotes.
fontFaces.add(await _loadFontFace("'$family'", asset, descriptors));
}
} on FontLoadError catch (error) {
errors.add(error);
}
try {
// Load all fonts, without quoted family names.
fontFaces.add(await _loadFontFace(family, asset, descriptors));
} on FontLoadError catch (error) {
errors.add(error);
}
if (fontFaces.isEmpty) {
// We failed to load either font face. Return the first error.
return errors.first;
}
try {
// Since we can't use tear-offs for interop members, this code is faster
// and easier to read with a for loop instead of forEach.
// ignore: prefer_foreach
for (final DomFontFace font in fontFaces) {
domDocument.fonts!.add(font);
}
} catch (e) {
return FontInvalidDataError(asset);
}
return null;
}
Future<DomFontFace> _loadFontFace(
String family,
String asset,
Map<String, String> descriptors,
) async {
// try/catch because `new FontFace` can crash with an improper font family.
try {
final DomFontFace fontFace = createDomFontFace(
family,
'url(${ui_web.assetManager.getAssetUrl(asset)})',
descriptors,
);
return await fontFace.load();
} catch (e) {
printWarning('Error while loading font family "$family":\n$e');
throw FontDownloadError(asset, e);
}
}
// Loads a font from bytes, surfacing errors through the future.
Future<bool> _loadFontFaceBytes(String family, Uint8List list) async {
// Since these fonts are loaded by user code, surface the error
// through the returned future.
try {
final DomFontFace fontFace = createDomFontFace(family, list);
if (fontFace.status == 'error') {
// Font failed to load.
return false;
}
domDocument.fonts!.add(fontFace);
// There might be paragraph measurements for this new font before it is
// loaded. They were measured using fallback font, so we should clear the
// cache.
Spanometer.clearRulersCache();
} catch (exception) {
// Failures here will throw an DomException. Return false.
return false;
}
return true;
}
@override
void debugResetFallbackFonts() {}
}

View File

@@ -1,34 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Splits [text] into a list of [TextFragment]s.
///
/// Various subclasses can perform the fragmenting based on their own criteria.
///
/// See:
///
/// - [LineBreakFragmenter]: Fragments text based on line break opportunities.
/// - [BidiFragmenter]: Fragments text based on directionality.
abstract class TextFragmenter {
const TextFragmenter(this.text);
/// The text to be fragmented.
final String text;
/// Performs the fragmenting of [text] and returns a list of [TextFragment]s.
List<TextFragment> fragment();
}
/// Represents a fragment produced by [TextFragmenter].
abstract class TextFragment {
const TextFragment(this.start, this.end);
final int start;
final int end;
/// Whether this fragment's range overlaps with the range from [start] to [end].
bool overlapsWith(int start, int end) {
return start < this.end && this.start < end;
}
}

View File

@@ -1,730 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:ui/ui.dart' as ui;
import '../util.dart';
import 'canvas_paragraph.dart';
import 'fragmenter.dart';
import 'layout_service.dart';
import 'line_breaker.dart';
import 'paragraph.dart';
import 'text_direction.dart';
/// Splits [text] into fragments that are ready to be laid out by
/// [TextLayoutService].
///
/// This fragmenter takes into account line breaks, directionality and styles.
class LayoutFragmenter extends TextFragmenter {
const LayoutFragmenter(super.text, this.paragraphSpans);
final List<ParagraphSpan> paragraphSpans;
@override
List<LayoutFragment> fragment() {
final List<LayoutFragment> fragments = <LayoutFragment>[];
int fragmentStart = 0;
final Iterator<LineBreakFragment> lineBreakFragments =
LineBreakFragmenter(text).fragment().iterator..moveNext();
final Iterator<BidiFragment> bidiFragments =
BidiFragmenter(text).fragment().iterator..moveNext();
final Iterator<ParagraphSpan> spans = paragraphSpans.iterator..moveNext();
LineBreakFragment currentLineBreakFragment = lineBreakFragments.current;
BidiFragment currentBidiFragment = bidiFragments.current;
ParagraphSpan currentSpan = spans.current;
while (true) {
final int fragmentEnd = math.min(
currentLineBreakFragment.end,
math.min(currentBidiFragment.end, currentSpan.end),
);
final int distanceFromLineBreak = currentLineBreakFragment.end - fragmentEnd;
final LineBreakType lineBreakType =
distanceFromLineBreak == 0 ? currentLineBreakFragment.type : LineBreakType.prohibited;
final int trailingNewlines =
currentLineBreakFragment.trailingNewlines - distanceFromLineBreak;
final int trailingSpaces = currentLineBreakFragment.trailingSpaces - distanceFromLineBreak;
final int fragmentLength = fragmentEnd - fragmentStart;
fragments.add(
LayoutFragment(
fragmentStart,
fragmentEnd,
lineBreakType,
currentBidiFragment.textDirection,
currentBidiFragment.fragmentFlow,
currentSpan,
trailingNewlines: clampInt(trailingNewlines, 0, fragmentLength),
trailingSpaces: clampInt(trailingSpaces, 0, fragmentLength),
),
);
fragmentStart = fragmentEnd;
bool moved = false;
if (currentLineBreakFragment.end == fragmentEnd) {
if (lineBreakFragments.moveNext()) {
moved = true;
currentLineBreakFragment = lineBreakFragments.current;
}
}
if (currentBidiFragment.end == fragmentEnd) {
if (bidiFragments.moveNext()) {
moved = true;
currentBidiFragment = bidiFragments.current;
}
}
if (currentSpan.end == fragmentEnd) {
if (spans.moveNext()) {
moved = true;
currentSpan = spans.current;
}
}
// Once we reached the end of all fragments, exit the loop.
if (!moved) {
break;
}
}
return fragments;
}
}
abstract class _CombinedFragment extends TextFragment {
_CombinedFragment(
super.start,
super.end,
this.type,
this._textDirection,
this.fragmentFlow,
this.span, {
required this.trailingNewlines,
required this.trailingSpaces,
}) : assert(trailingNewlines >= 0),
assert(trailingSpaces >= trailingNewlines);
final LineBreakType type;
ui.TextDirection? get textDirection => _textDirection;
ui.TextDirection? _textDirection;
final FragmentFlow fragmentFlow;
final ParagraphSpan span;
final int trailingNewlines;
final int trailingSpaces;
@override
int get hashCode => Object.hash(
start,
end,
type,
textDirection,
fragmentFlow,
span,
trailingNewlines,
trailingSpaces,
);
@override
bool operator ==(Object other) {
return other is LayoutFragment &&
other.start == start &&
other.end == end &&
other.type == type &&
other.textDirection == textDirection &&
other.fragmentFlow == fragmentFlow &&
other.span == span &&
other.trailingNewlines == trailingNewlines &&
other.trailingSpaces == trailingSpaces;
}
}
class LayoutFragment extends _CombinedFragment
with _FragmentMetrics, _FragmentPosition, _FragmentBox {
LayoutFragment(
super.start,
super.end,
super.type,
super.textDirection,
super.fragmentFlow,
super.span, {
required super.trailingNewlines,
required super.trailingSpaces,
});
int get length => end - start;
bool get isSpaceOnly => length == trailingSpaces;
bool get isPlaceholder => span is PlaceholderSpan;
bool get isBreak => type != LineBreakType.prohibited;
bool get isHardBreak => type == LineBreakType.mandatory || type == LineBreakType.endOfText;
EngineTextStyle get style => span.style;
/// Returns the substring from [paragraph] that corresponds to this fragment,
/// excluding new line characters.
String getText(CanvasParagraph paragraph) {
return paragraph.plainText.substring(start, end - trailingNewlines);
}
/// Splits this fragment into two fragments with the split point being the
/// given [index].
// TODO(mdebbar): If we ever get multiple return values in Dart, we should use it!
// See: https://github.com/dart-lang/language/issues/68
List<LayoutFragment?> split(int index) {
assert(start <= index);
assert(index <= end);
if (start == index) {
return <LayoutFragment?>[null, this];
}
if (end == index) {
return <LayoutFragment?>[this, null];
}
// The length of the second fragment after the split.
final int secondLength = end - index;
// Trailing spaces/new lines go to the second fragment. Any left over goes
// to the first fragment.
final int secondTrailingNewlines = math.min(trailingNewlines, secondLength);
final int secondTrailingSpaces = math.min(trailingSpaces, secondLength);
return <LayoutFragment>[
LayoutFragment(
start,
index,
LineBreakType.prohibited,
textDirection,
fragmentFlow,
span,
trailingNewlines: trailingNewlines - secondTrailingNewlines,
trailingSpaces: trailingSpaces - secondTrailingSpaces,
),
LayoutFragment(
index,
end,
type,
textDirection,
fragmentFlow,
span,
trailingNewlines: secondTrailingNewlines,
trailingSpaces: secondTrailingSpaces,
),
];
}
@override
String toString() {
return '$LayoutFragment($start, $end, $type, $textDirection)';
}
}
mixin _FragmentMetrics on _CombinedFragment {
late Spanometer _spanometer;
/// The rise from the baseline as calculated from the font and style for this text.
double get ascent => _ascent;
late double _ascent;
/// The drop from the baseline as calculated from the font and style for this text.
double get descent => _descent;
late double _descent;
/// The width of the measured text, not including trailing spaces.
double get widthExcludingTrailingSpaces => _widthExcludingTrailingSpaces;
late double _widthExcludingTrailingSpaces;
/// The width of the measured text, including any trailing spaces.
double get widthIncludingTrailingSpaces =>
_widthIncludingTrailingSpaces + _extraWidthForJustification;
late double _widthIncludingTrailingSpaces;
double _extraWidthForJustification = 0.0;
/// The total height as calculated from the font and style for this text.
double get height => ascent + descent;
double get widthOfTrailingSpaces => widthIncludingTrailingSpaces - widthExcludingTrailingSpaces;
/// Set measurement values for the fragment.
void setMetrics(
Spanometer spanometer, {
required double ascent,
required double descent,
required double widthExcludingTrailingSpaces,
required double widthIncludingTrailingSpaces,
}) {
_spanometer = spanometer;
_ascent = ascent;
_descent = descent;
_widthExcludingTrailingSpaces = widthExcludingTrailingSpaces;
_widthIncludingTrailingSpaces = widthIncludingTrailingSpaces;
}
}
/// Encapsulates positioning of the fragment relative to the line.
///
/// The coordinates are all relative to the line it belongs to. For example,
/// [left] is the distance from the left edge of the line to the left edge of
/// the fragment.
///
/// This is what the various measurements/coordinates look like for a fragment
/// in an LTR paragraph:
///
/// *------------------------line.width-----------------*
/// *---width----*
/// ┌─────────────────┬────────────┬────────────────────┐
/// │ │--FRAGMENT--│ │
/// └─────────────────┴────────────┴────────────────────┘
/// *---startOffset---*
/// *------left-------*
/// *--------endOffset-------------*
/// *----------right---------------*
///
///
/// And in an RTL paragraph, [startOffset] and [endOffset] are flipped because
/// the line starts from the right. Here's what they look like:
///
/// *------------------------line.width-----------------*
/// *---width----*
/// ┌─────────────────┬────────────┬────────────────────┐
/// │ │--FRAGMENT--│ │
/// └─────────────────┴────────────┴────────────────────┘
/// *----startOffset-----*
/// *------left-------*
/// *-----------endOffset-------------*
/// *----------right---------------*
///
mixin _FragmentPosition on _CombinedFragment, _FragmentMetrics {
/// The distance from the beginning of the line to the beginning of the fragment.
double get startOffset => _startOffset;
late double _startOffset;
/// The width of the line that contains this fragment.
late ParagraphLine line;
/// The distance from the beginning of the line to the end of the fragment.
double get endOffset => startOffset + widthIncludingTrailingSpaces;
/// The distance from the left edge of the line to the left edge of the fragment.
double get left =>
line.textDirection == ui.TextDirection.ltr ? startOffset : line.width - endOffset;
/// The distance from the left edge of the line to the right edge of the fragment.
double get right =>
line.textDirection == ui.TextDirection.ltr ? endOffset : line.width - startOffset;
/// Set the horizontal position of this fragment relative to the [line] that
/// contains it.
void setPosition({required double startOffset, required ui.TextDirection textDirection}) {
_startOffset = startOffset;
_textDirection ??= textDirection;
}
/// Adjust the width of this fragment for paragraph justification.
void justifyTo({required double paragraphWidth}) {
// Only justify this fragment if it's not a trailing space in the line.
if (end > line.endIndex - line.trailingSpaces) {
// Don't justify fragments that are part of trailing spaces of the line.
return;
}
if (trailingSpaces == 0) {
// If this fragment has no spaces, there's nothing to justify.
return;
}
final double justificationTotal = paragraphWidth - line.width;
final double justificationPerSpace = justificationTotal / line.nonTrailingSpaces;
_extraWidthForJustification = justificationPerSpace * trailingSpaces;
}
}
/// Encapsulates calculations related to the bounding box of the fragment
/// relative to the paragraph.
mixin _FragmentBox on _CombinedFragment, _FragmentMetrics, _FragmentPosition {
double get top => line.baseline - ascent;
double get bottom => line.baseline + descent;
late final ui.TextBox _textBoxIncludingTrailingSpaces = ui.TextBox.fromLTRBD(
line.left + left,
top,
line.left + right,
bottom,
textDirection!,
);
/// Whether or not the trailing spaces of this fragment are part of trailing
/// spaces of the line containing the fragment.
bool get _isPartOfTrailingSpacesInLine => end > line.endIndex - line.trailingSpaces;
/// Returns a [ui.TextBox] for the purpose of painting this fragment.
///
/// The coordinates of the resulting [ui.TextBox] are relative to the
/// paragraph, not to the line.
///
/// Trailing spaces in each line aren't painted on the screen, so they are
/// excluded from the resulting text box.
ui.TextBox toPaintingTextBox() {
if (_isPartOfTrailingSpacesInLine) {
// For painting, we exclude the width of trailing spaces from the box.
return textDirection! == ui.TextDirection.ltr
? ui.TextBox.fromLTRBD(
line.left + left,
top,
line.left + right - widthOfTrailingSpaces,
bottom,
textDirection!,
)
: ui.TextBox.fromLTRBD(
line.left + left + widthOfTrailingSpaces,
top,
line.left + right,
bottom,
textDirection!,
);
}
return _textBoxIncludingTrailingSpaces;
}
/// Returns a [ui.TextBox] representing this fragment.
///
/// The coordinates of the resulting [ui.TextBox] are relative to the
/// paragraph, not to the line.
///
/// As opposed to [toPaintingTextBox], the resulting text box from this method
/// includes trailing spaces of the fragment.
ui.TextBox toTextBox({int? start, int? end}) {
start ??= this.start;
end ??= this.end;
if (start <= this.start && end >= this.end - trailingNewlines) {
return _textBoxIncludingTrailingSpaces;
}
return _intersect(start, end);
}
/// Performs the intersection of this fragment with the range given by [start] and
/// [end] indices, and returns a [ui.TextBox] representing that intersection.
///
/// The coordinates of the resulting [ui.TextBox] are relative to the
/// paragraph, not to the line.
ui.TextBox _intersect(int start, int end) {
// `_intersect` should only be called when there's an actual intersection.
assert(start > this.start || end < this.end);
final double before;
if (start <= this.start) {
before = 0.0;
} else {
_spanometer.currentSpan = span;
before = _spanometer.measureRange(this.start, start);
}
final double after;
if (end >= this.end - trailingNewlines) {
after = 0.0;
} else {
_spanometer.currentSpan = span;
after = _spanometer.measureRange(end, this.end - trailingNewlines);
}
final double left, right;
if (textDirection! == ui.TextDirection.ltr) {
// Example: let's say the text is "Loremipsum" and we want to get the box
// for "rem". In this case, `before` is the width of "Lo", and `after`
// is the width of "ipsum".
//
// Here's how the measurements/coordinates look like:
//
// before after
// |----| |----------|
// +---------------------+
// | L o r e m i p s u m |
// +---------------------+
// this.left ^ ^ this.right
left = this.left + before;
right = this.right - after;
} else {
// Example: let's say the text is "txet_werbeH" ("Hebrew_text" flowing from
// right to left). Say we want to get the box for "brew". The `before` is
// the width of "He", and `after` is the width of "_text".
//
// after before
// |----------| |----|
// +-----------------------+
// | t x e t _ w e r b e H |
// +-----------------------+
// this.left ^ ^ this.right
//
// Notice how `before` and `after` are reversed in the RTL example. That's
// because the text flows from right to left.
left = this.left + after;
right = this.right - before;
}
// The fragment's left and right edges are relative to the line. In order
// to make them relative to the paragraph, we need to add the left edge of
// the line.
return ui.TextBox.fromLTRBD(line.left + left, top, line.left + right, bottom, textDirection!);
}
/// Returns the text position within this fragment's range that's closest to
/// the given [x] offset.
///
/// The [x] offset is expected to be relative to the left edge of the fragment.
ui.TextPosition getPositionForX(double x) {
x = _makeXDirectionAgnostic(x);
final int startIndex = start;
final int endIndex = end - trailingNewlines;
// Check some special cases to return the result quicker.
final int length = endIndex - startIndex;
if (length == 0) {
return ui.TextPosition(offset: startIndex);
}
if (length == 1) {
// Find out if `x` is closer to `startIndex` or `endIndex`.
final double distanceFromStart = x;
final double distanceFromEnd = widthIncludingTrailingSpaces - x;
return distanceFromStart < distanceFromEnd
? ui.TextPosition(offset: startIndex)
: ui.TextPosition(offset: endIndex, affinity: ui.TextAffinity.upstream);
}
_spanometer.currentSpan = span;
// The resulting `cutoff` is the index of the character where the `x` offset
// falls. We should return the text position of either `cutoff` or
// `cutoff + 1` depending on which one `x` is closer to.
//
// offset x
// ↓
// "A B C D E F"
// ↑
// cutoff
final int cutoff = _spanometer.forceBreak(
startIndex,
endIndex,
availableWidth: x,
allowEmpty: true,
);
if (cutoff == endIndex) {
return ui.TextPosition(offset: cutoff, affinity: ui.TextAffinity.upstream);
}
final double lowWidth = _spanometer.measureRange(startIndex, cutoff);
final double highWidth = _spanometer.measureRange(startIndex, cutoff + 1);
// See if `x` is closer to `cutoff` or `cutoff + 1`.
if (x - lowWidth < highWidth - x) {
// The offset is closer to cutoff.
return ui.TextPosition(offset: cutoff);
} else {
// The offset is closer to cutoff + 1.
return ui.TextPosition(offset: cutoff + 1, affinity: ui.TextAffinity.upstream);
}
}
/// Transforms the [x] coordinate to be direction-agnostic.
///
/// The X (input) is relative to the [left] edge of the fragment, and this
/// method returns an X' (output) that's relative to beginning of the text.
///
/// Here's how it looks for a fragment with LTR content:
///
/// *------------------------line width------------------*
/// *-----X (input)
/// ┌───────────┬────────────────────────┬───────────────┐
/// │ │ ---text-direction----> │ │
/// └───────────┴────────────────────────┴───────────────┘
/// *-----X' (output)
/// *---left----*
/// *---------------right----------------*
///
///
/// And here's how it looks for a fragment with RTL content:
///
/// *------------------------line width------------------*
/// *-----X (input)
/// ┌───────────┬────────────────────────┬───────────────┐
/// │ │ <---text-direction---- │ │
/// └───────────┴────────────────────────┴───────────────┘
/// (output) X'-----------------*
/// *---left----*
/// *---------------right----------------*
///
double _makeXDirectionAgnostic(double x) {
if (textDirection == ui.TextDirection.rtl) {
return widthIncludingTrailingSpaces - x;
}
return x;
}
// [start, end).map((index) => line.graphemeStarts[index]) gives an ascending
// list of UTF16 offsets of graphemes that start in this fragment.
//
// Returns null if this fragment contains no grapheme starts.
late final (int, int)? graphemeStartIndexRange = _getBreaksRange();
(int, int)? _getBreaksRange() {
if (end == start) {
return null;
}
final List<int> lineGraphemeBreaks = line.graphemeStarts;
assert(end > start);
assert(line.graphemeStarts.isNotEmpty);
final int startIndex = line.graphemeStartIndexBefore(start, 0, lineGraphemeBreaks.length);
final int endIndex =
end == start + 1
? startIndex + 1
: line.graphemeStartIndexBefore(end - 1, startIndex, lineGraphemeBreaks.length) + 1;
final int firstGraphemeStart = lineGraphemeBreaks[startIndex];
return firstGraphemeStart > start
? (endIndex == startIndex + 1 ? null : (startIndex + 1, endIndex))
: (startIndex, endIndex);
}
/// Whether the first codepoints of this fragment is not a valid grapheme start,
/// and belongs in the the previous fragment.
///
/// This is the result of a known bug: in rare circumstances, a grapheme is
/// split into different fragments. To workaround this we ignore the trailing
/// part of the grapheme during hit-testing, by adjusting the leading offset of
/// a fragment to the leading edge of the first grapheme start in that fragment.
//
// TODO(LongCatIsLooong): Grapheme clusters should not be separately even
// when they are in different runs. Also document the recommendation to use
// U+25CC or U+00A0 for showing nonspacing marks in isolation.
bool get hasLeadingBrokenGrapheme {
final int? graphemeStartIndexRangeStart = graphemeStartIndexRange?.$1;
return graphemeStartIndexRangeStart == null ||
line.graphemeStarts[graphemeStartIndexRangeStart] != start;
}
/// Returns the GlyphInfo within the range [line.graphemeStarts[startIndex], line.graphemeStarts[endIndex]),
/// that's visually closeset to the given horizontal offset `x` (in the paragraph's coordinates).
ui.GlyphInfo _getClosestCharacterInRange(double x, int startIndex, int endIndex) {
final List<int> graphemeStartIndices = line.graphemeStarts;
final ui.TextRange fullRange = ui.TextRange(
start: graphemeStartIndices[startIndex],
end: graphemeStartIndices[endIndex],
);
final ui.TextBox fullBox = toTextBox(start: fullRange.start, end: fullRange.end);
if (startIndex + 1 == endIndex) {
return ui.GlyphInfo(fullBox.toRect(), fullRange, fullBox.direction);
}
assert(startIndex + 1 < endIndex);
final ui.TextBox(:double left, :double right) = fullBox;
// The toTextBox call is potentially expensive so we'll try reducing the
// search steps with a binary search.
//
// x ∈ (left, right),
if (left < x && x < right) {
final int midIndex = (startIndex + endIndex) ~/ 2;
// endIndex >= startIndex + 2, so midIndex >= start + 1
final ui.GlyphInfo firstHalf = _getClosestCharacterInRange(x, startIndex, midIndex);
if (firstHalf.graphemeClusterLayoutBounds.left < x &&
x < firstHalf.graphemeClusterLayoutBounds.right) {
return firstHalf;
}
// startIndex <= endIndex - 2, so midIndex <= endIndex - 1
final ui.GlyphInfo secondHalf = _getClosestCharacterInRange(x, midIndex, endIndex);
if (secondHalf.graphemeClusterLayoutBounds.left < x &&
x < secondHalf.graphemeClusterLayoutBounds.right) {
return secondHalf;
}
// Neither box clips the given x. This is supposed to be rare.
final double distanceToFirst =
(x -
x.clamp(
firstHalf.graphemeClusterLayoutBounds.left,
firstHalf.graphemeClusterLayoutBounds.right,
))
.abs();
final double distanceToSecond =
(x -
x.clamp(
secondHalf.graphemeClusterLayoutBounds.left,
secondHalf.graphemeClusterLayoutBounds.right,
))
.abs();
return distanceToFirst > distanceToSecond ? firstHalf : secondHalf;
}
// x ∉ (left, right), it's either the first character or the last, since
// there can only be one writing direction in the fragment.
final ui.TextRange range = switch ((fullBox.direction, x <= left)) {
(ui.TextDirection.ltr, true) || (ui.TextDirection.rtl, false) => ui.TextRange(
start: graphemeStartIndices[startIndex],
end: graphemeStartIndices[startIndex + 1],
),
(ui.TextDirection.ltr, false) || (ui.TextDirection.rtl, true) => ui.TextRange(
start: graphemeStartIndices[endIndex - 1],
end: graphemeStartIndices[endIndex],
),
};
assert(!range.isCollapsed);
final ui.TextBox box = toTextBox(start: range.start, end: range.end);
return ui.GlyphInfo(box.toRect(), range, box.direction);
}
/// Returns the GlyphInfo of the character in the fragment that is closest to
/// the given offset x.
ui.GlyphInfo getClosestCharacterBox(double x) {
assert(end > start);
assert(graphemeStartIndexRange != null);
// The force ! is safe here because this method is only called by
// LayoutService.getClosestGlyphInfo which checks this fragment has at least
// one grapheme start before calling this method.
final (int rangeStart, int rangeEnd) = graphemeStartIndexRange!;
return _getClosestCharacterInRange(x, rangeStart, rangeEnd);
}
}
class EllipsisFragment extends LayoutFragment {
EllipsisFragment(int index, ParagraphSpan span)
: super(
index,
index,
LineBreakType.endOfText,
null,
// The ellipsis is always at the end of the line, so it can't be
// sandwiched. This means it'll always follow the paragraph direction.
FragmentFlow.sandwich,
span,
trailingNewlines: 0,
trailingSpaces: 0,
);
@override
bool get isSpaceOnly => false;
@override
bool get isPlaceholder => false;
@override
String getText(CanvasParagraph paragraph) {
return paragraph.paragraphStyle.ellipsis!;
}
@override
List<LayoutFragment> split(int index) {
throw Exception('Cannot split an EllipsisFragment');
}
}

View File

@@ -1,28 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:web_unicode/web_unicode.dart';
import 'unicode_range.dart';
export 'package:web_unicode/web_unicode.dart' show LineCharProperty;
UnicodePropertyLookup<LineCharProperty> get lineLookup => ensureLineLookupInitialized();
/// Initializes [lineLookup], if it's not already initialized.
///
/// Use this function to trigger the initialization before [lineLookup] is
/// actually used. For example, triggering it before the first application
/// frame is rendered will reduce jank by moving the initialization out of
/// the frame.
UnicodePropertyLookup<LineCharProperty> ensureLineLookupInitialized() {
return _lineLookup ??= UnicodePropertyLookup<LineCharProperty>.fromPackedData(
packedLineBreakProperties,
singleLineBreakRangesCount,
LineCharProperty.values,
defaultLineCharProperty,
);
}
UnicodePropertyLookup<LineCharProperty>? _lineLookup;

View File

@@ -5,9 +5,6 @@
import 'dart:js_interop';
import '../dom.dart';
import 'fragmenter.dart';
import 'line_break_properties.dart';
import 'unicode_range.dart';
const Set<int> _kNewlines = <int>{
0x000A, // LF
@@ -41,42 +38,6 @@ enum LineBreakType {
endOfText,
}
/// Splits [text] into fragments based on line breaks.
abstract class LineBreakFragmenter extends TextFragmenter {
factory LineBreakFragmenter(String text) {
if (domIntl.v8BreakIterator != null) {
return V8LineBreakFragmenter(text);
}
return FWLineBreakFragmenter(text);
}
@override
List<LineBreakFragment> fragment();
}
/// Flutter web's custom implementation of [LineBreakFragmenter].
class FWLineBreakFragmenter extends TextFragmenter implements LineBreakFragmenter {
FWLineBreakFragmenter(super.text);
@override
List<LineBreakFragment> fragment() {
return _computeLineBreakFragments(text);
}
}
/// An implementation of [LineBreakFragmenter] that uses V8's
/// `v8BreakIterator` API to find line breaks in the given [text].
class V8LineBreakFragmenter extends TextFragmenter implements LineBreakFragmenter {
V8LineBreakFragmenter(super.text) : assert(domIntl.v8BreakIterator != null);
final DomV8BreakIterator _v8BreakIterator = createV8BreakIterator();
@override
List<LineBreakFragment> fragment() {
return breakLinesUsingV8BreakIterator(text, text.toJS, _v8BreakIterator);
}
}
List<LineBreakFragment> breakLinesUsingV8BreakIterator(
String text,
JSString jsText,
@@ -155,15 +116,17 @@ List<LineBreakFragment> breakLinesUsingV8BreakIterator(
return breaks;
}
class LineBreakFragment extends TextFragment {
class LineBreakFragment {
const LineBreakFragment(
super.start,
super.end,
this.start,
this.end,
this.type, {
required this.trailingNewlines,
required this.trailingSpaces,
});
final int start;
final int end;
final LineBreakType type;
final int trailingNewlines;
final int trailingSpaces;
@@ -186,569 +149,3 @@ class LineBreakFragment extends TextFragment {
return 'LineBreakFragment($start, $end, $type)';
}
}
bool _isHardBreak(LineCharProperty? prop) {
// No need to check for NL because it's already normalized to BK.
return prop == LineCharProperty.LF || prop == LineCharProperty.BK;
}
bool _isALorHL(LineCharProperty? prop) {
return prop == LineCharProperty.AL || prop == LineCharProperty.HL;
}
/// Whether the given property is part of a Korean Syllable block.
///
/// See:
/// - https://unicode.org/reports/tr14/tr14-45.html#LB27
bool _isKoreanSyllable(LineCharProperty? prop) {
return prop == LineCharProperty.JL ||
prop == LineCharProperty.JV ||
prop == LineCharProperty.JT ||
prop == LineCharProperty.H2 ||
prop == LineCharProperty.H3;
}
/// Whether the given char code has an Eastern Asian width property of F, W or H.
///
/// See:
/// - https://www.unicode.org/reports/tr14/tr14-45.html#LB30
/// - https://www.unicode.org/Public/13.0.0/ucd/EastAsianWidth.txt
bool _hasEastAsianWidthFWH(int charCode) {
return charCode == 0x2329 ||
(charCode >= 0x3008 && charCode <= 0x301D) ||
(charCode >= 0xFE17 && charCode <= 0xFF62);
}
bool _isSurrogatePair(int? codePoint) {
return codePoint != null && codePoint > 0xFFFF;
}
/// Finds the next line break in the given [text] starting from [index].
///
/// We think about indices as pointing between characters, and they go all the
/// way from 0 to the string length. For example, here are the indices for the
/// string "foo bar":
///
/// ```none
/// f o o b a r
/// ^ ^ ^ ^ ^ ^ ^ ^
/// 0 1 2 3 4 5 6 7
/// ```
///
/// This way the indices work well with [String.substring].
///
/// Useful resources:
///
/// * https://www.unicode.org/reports/tr14/tr14-45.html#Algorithm
/// * https://www.unicode.org/Public/11.0.0/ucd/LineBreak.txt
List<LineBreakFragment> _computeLineBreakFragments(String text) {
final List<LineBreakFragment> fragments = <LineBreakFragment>[];
// Keeps track of the character two positions behind.
LineCharProperty? prev2;
LineCharProperty? prev1;
int? codePoint = getCodePoint(text, 0);
LineCharProperty? curr = lineLookup.findForChar(codePoint);
// When there's a sequence of combining marks, this variable contains the base
// property i.e. the property of the character preceding the sequence.
LineCharProperty baseOfCombiningMarks = LineCharProperty.AL;
int index = 0;
int trailingNewlines = 0;
int trailingSpaces = 0;
int fragmentStart = 0;
void setBreak(LineBreakType type, int debugRuleNumber) {
final int fragmentEnd = type == LineBreakType.endOfText ? text.length : index;
assert(fragmentEnd >= fragmentStart);
// Uncomment the following line to help debug line breaking.
// print('{$fragmentStart:$fragmentEnd} [$debugRuleNumber] -- $type');
if (prev1 == LineCharProperty.SP) {
trailingSpaces++;
} else if (_isHardBreak(prev1) || prev1 == LineCharProperty.CR) {
trailingNewlines++;
trailingSpaces++;
}
if (type == LineBreakType.prohibited) {
// Don't create a fragment.
return;
}
fragments.add(
LineBreakFragment(
fragmentStart,
fragmentEnd,
type,
trailingNewlines: trailingNewlines,
trailingSpaces: trailingSpaces,
),
);
fragmentStart = index;
// Reset trailing spaces/newlines counter after a new fragment.
trailingNewlines = 0;
trailingSpaces = 0;
prev1 = prev2 = null;
}
// Never break at the start of text.
// LB2: sot ×
setBreak(LineBreakType.prohibited, 2);
// Never break at the start of text.
// LB2: sot ×
//
// Skip index 0 because a line break can't exist at the start of text.
index++;
int regionalIndicatorCount = 0;
// We need to go until `text.length` in order to handle the case where the
// paragraph ends with a hard break. In this case, there will be an empty line
// at the end.
for (; index <= text.length; index++) {
prev2 = prev1;
prev1 = curr;
if (_isSurrogatePair(codePoint)) {
// Can't break in the middle of a surrogate pair.
setBreak(LineBreakType.prohibited, -1);
// Advance `index` one extra step to skip the tail of the surrogate pair.
index++;
}
codePoint = getCodePoint(text, index);
curr = lineLookup.findForChar(codePoint);
// Keep count of the RI (regional indicator) sequence.
if (prev1 == LineCharProperty.RI) {
regionalIndicatorCount++;
} else {
regionalIndicatorCount = 0;
}
// Always break after hard line breaks.
// LB4: BK !
//
// Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks.
// LB5: LF !
// NL !
if (_isHardBreak(prev1)) {
setBreak(LineBreakType.mandatory, 5);
continue;
}
if (prev1 == LineCharProperty.CR) {
if (curr == LineCharProperty.LF) {
// LB5: CR × LF
setBreak(LineBreakType.prohibited, 5);
} else {
// LB5: CR !
setBreak(LineBreakType.mandatory, 5);
}
continue;
}
// Do not break before hard line breaks.
// LB6: × ( BK | CR | LF | NL )
if (_isHardBreak(curr) || curr == LineCharProperty.CR) {
setBreak(LineBreakType.prohibited, 6);
continue;
}
if (index >= text.length) {
break;
}
// Do not break before spaces or zero width space.
// LB7: × SP
// × ZW
if (curr == LineCharProperty.SP || curr == LineCharProperty.ZW) {
setBreak(LineBreakType.prohibited, 7);
continue;
}
// Break after spaces.
// LB18: SP ÷
if (prev1 == LineCharProperty.SP) {
setBreak(LineBreakType.opportunity, 18);
continue;
}
// Break before any character following a zero-width space, even if one or
// more spaces intervene.
// LB8: ZW SP* ÷
if (prev1 == LineCharProperty.ZW) {
setBreak(LineBreakType.opportunity, 8);
continue;
}
// Do not break after a zero width joiner.
// LB8a: ZWJ ×
if (prev1 == LineCharProperty.ZWJ) {
setBreak(LineBreakType.prohibited, 8);
continue;
}
// Establish the base for the sequences of combining marks.
if (prev1 != LineCharProperty.CM && prev1 != LineCharProperty.ZWJ) {
baseOfCombiningMarks = prev1 ?? LineCharProperty.AL;
}
// Do not break a combining character sequence; treat it as if it has the
// line breaking class of the base character in all of the following rules.
// Treat ZWJ as if it were CM.
if (curr == LineCharProperty.CM || curr == LineCharProperty.ZWJ) {
if (baseOfCombiningMarks == LineCharProperty.SP) {
// LB10: Treat any remaining combining mark or ZWJ as AL.
curr = LineCharProperty.AL;
} else {
// LB9: Treat X (CM | ZWJ)* as if it were X
// where X is any line break class except BK, NL, LF, CR, SP, or ZW.
curr = baseOfCombiningMarks;
if (curr == LineCharProperty.RI) {
// Prevent the previous RI from being double-counted.
regionalIndicatorCount--;
}
setBreak(LineBreakType.prohibited, 9);
continue;
}
}
// In certain situations (e.g. CM immediately following a hard break), we
// need to also check if the previous character was CM/ZWJ. That's because
// hard breaks caused the previous iteration to short-circuit, which leads
// to `baseOfCombiningMarks` not being updated properly.
if (prev1 == LineCharProperty.CM || prev1 == LineCharProperty.ZWJ) {
prev1 = baseOfCombiningMarks;
}
// Do not break before or after Word joiner and related characters.
// LB11: × WJ
// WJ ×
if (curr == LineCharProperty.WJ || prev1 == LineCharProperty.WJ) {
setBreak(LineBreakType.prohibited, 11);
continue;
}
// Do not break after NBSP and related characters.
// LB12: GL ×
if (prev1 == LineCharProperty.GL) {
setBreak(LineBreakType.prohibited, 12);
continue;
}
// Do not break before NBSP and related characters, except after spaces and
// hyphens.
// LB12a: [^SP BA HY] × GL
if (!(prev1 == LineCharProperty.SP ||
prev1 == LineCharProperty.BA ||
prev1 == LineCharProperty.HY) &&
curr == LineCharProperty.GL) {
setBreak(LineBreakType.prohibited, 12);
continue;
}
// Do not break before ‘]’ or ‘!’ or ‘;’ or ‘/’, even after spaces.
// LB13: × CL
// × CP
// × EX
// × IS
// × SY
//
// The above is a quote from unicode.org. In our implementation, we did the
// following modification: When there are spaces present, we consider it a
// line break opportunity.
//
// We made this modification to match the browser behavior.
if (prev1 != LineCharProperty.SP &&
(curr == LineCharProperty.CL ||
curr == LineCharProperty.CP ||
curr == LineCharProperty.EX ||
curr == LineCharProperty.IS ||
curr == LineCharProperty.SY)) {
setBreak(LineBreakType.prohibited, 13);
continue;
}
// Do not break after ‘[’, even after spaces.
// LB14: OP SP* ×
//
// The above is a quote from unicode.org. In our implementation, we did the
// following modification: Allow breaks when there are spaces.
//
// We made this modification to match the browser behavior.
if (prev1 == LineCharProperty.OP) {
setBreak(LineBreakType.prohibited, 14);
continue;
}
// Do not break within ‘”[’, even with intervening spaces.
// LB15: QU SP* × OP
//
// The above is a quote from unicode.org. In our implementation, we did the
// following modification: Allow breaks when there are spaces.
//
// We made this modification to match the browser behavior.
if (prev1 == LineCharProperty.QU && curr == LineCharProperty.OP) {
setBreak(LineBreakType.prohibited, 15);
continue;
}
// Do not break between closing punctuation and a nonstarter, even with
// intervening spaces.
// LB16: (CL | CP) SP* × NS
//
// The above is a quote from unicode.org. In our implementation, we did the
// following modification: Allow breaks when there are spaces.
//
// We made this modification to match the browser behavior.
if ((prev1 == LineCharProperty.CL || prev1 == LineCharProperty.CP) &&
curr == LineCharProperty.NS) {
setBreak(LineBreakType.prohibited, 16);
continue;
}
// Do not break within ‘——’, even with intervening spaces.
// LB17: B2 SP* × B2
//
// The above is a quote from unicode.org. In our implementation, we did the
// following modification: Allow breaks when there are spaces.
//
// We made this modification to match the browser behavior.
if (prev1 == LineCharProperty.B2 && curr == LineCharProperty.B2) {
setBreak(LineBreakType.prohibited, 17);
continue;
}
// Do not break before or after quotation marks, such as ‘”’.
// LB19: × QU
// QU ×
if (prev1 == LineCharProperty.QU || curr == LineCharProperty.QU) {
setBreak(LineBreakType.prohibited, 19);
continue;
}
// Break before and after unresolved CB.
// LB20: ÷ CB
// CB ÷
//
// In flutter web, we use this as an object-replacement character for
// placeholders.
if (prev1 == LineCharProperty.CB || curr == LineCharProperty.CB) {
setBreak(LineBreakType.opportunity, 20);
continue;
}
// Do not break before hyphen-minus, other hyphens, fixed-width spaces,
// small kana, and other non-starters, or after acute accents.
// LB21: × BA
// × HY
// × NS
// BB ×
if (curr == LineCharProperty.BA ||
curr == LineCharProperty.HY ||
curr == LineCharProperty.NS ||
prev1 == LineCharProperty.BB) {
setBreak(LineBreakType.prohibited, 21);
continue;
}
// Don't break after Hebrew + Hyphen.
// LB21a: HL (HY | BA) ×
if (prev2 == LineCharProperty.HL &&
(prev1 == LineCharProperty.HY || prev1 == LineCharProperty.BA)) {
setBreak(LineBreakType.prohibited, 21);
continue;
}
// Don’t break between Solidus and Hebrew letters.
// LB21b: SY × HL
if (prev1 == LineCharProperty.SY && curr == LineCharProperty.HL) {
setBreak(LineBreakType.prohibited, 21);
continue;
}
// Do not break before ellipses.
// LB22: × IN
if (curr == LineCharProperty.IN) {
setBreak(LineBreakType.prohibited, 22);
continue;
}
// Do not break between digits and letters.
// LB23: (AL | HL) × NU
// NU × (AL | HL)
if ((_isALorHL(prev1) && curr == LineCharProperty.NU) ||
(prev1 == LineCharProperty.NU && _isALorHL(curr))) {
setBreak(LineBreakType.prohibited, 23);
continue;
}
// Do not break between numeric prefixes and ideographs, or between
// ideographs and numeric postfixes.
// LB23a: PR × (ID | EB | EM)
if (prev1 == LineCharProperty.PR &&
(curr == LineCharProperty.ID ||
curr == LineCharProperty.EB ||
curr == LineCharProperty.EM)) {
setBreak(LineBreakType.prohibited, 23);
continue;
}
// LB23a: (ID | EB | EM) × PO
if ((prev1 == LineCharProperty.ID ||
prev1 == LineCharProperty.EB ||
prev1 == LineCharProperty.EM) &&
curr == LineCharProperty.PO) {
setBreak(LineBreakType.prohibited, 23);
continue;
}
// Do not break between numeric prefix/postfix and letters, or between
// letters and prefix/postfix.
// LB24: (PR | PO) × (AL | HL)
if ((prev1 == LineCharProperty.PR || prev1 == LineCharProperty.PO) && _isALorHL(curr)) {
setBreak(LineBreakType.prohibited, 24);
continue;
}
// LB24: (AL | HL) × (PR | PO)
if (_isALorHL(prev1) && (curr == LineCharProperty.PR || curr == LineCharProperty.PO)) {
setBreak(LineBreakType.prohibited, 24);
continue;
}
// Do not break between the following pairs of classes relevant to numbers.
// LB25: (CL | CP | NU) × (PO | PR)
if ((prev1 == LineCharProperty.CL ||
prev1 == LineCharProperty.CP ||
prev1 == LineCharProperty.NU) &&
(curr == LineCharProperty.PO || curr == LineCharProperty.PR)) {
setBreak(LineBreakType.prohibited, 25);
continue;
}
// LB25: (PO | PR) × OP
if ((prev1 == LineCharProperty.PO || prev1 == LineCharProperty.PR) &&
curr == LineCharProperty.OP) {
setBreak(LineBreakType.prohibited, 25);
continue;
}
// LB25: (PO | PR | HY | IS | NU | SY) × NU
if ((prev1 == LineCharProperty.PO ||
prev1 == LineCharProperty.PR ||
prev1 == LineCharProperty.HY ||
prev1 == LineCharProperty.IS ||
prev1 == LineCharProperty.NU ||
prev1 == LineCharProperty.SY) &&
curr == LineCharProperty.NU) {
setBreak(LineBreakType.prohibited, 25);
continue;
}
// Do not break a Korean syllable.
// LB26: JL × (JL | JV | H2 | H3)
if (prev1 == LineCharProperty.JL &&
(curr == LineCharProperty.JL ||
curr == LineCharProperty.JV ||
curr == LineCharProperty.H2 ||
curr == LineCharProperty.H3)) {
setBreak(LineBreakType.prohibited, 26);
continue;
}
// LB26: (JV | H2) × (JV | JT)
if ((prev1 == LineCharProperty.JV || prev1 == LineCharProperty.H2) &&
(curr == LineCharProperty.JV || curr == LineCharProperty.JT)) {
setBreak(LineBreakType.prohibited, 26);
continue;
}
// LB26: (JT | H3) × JT
if ((prev1 == LineCharProperty.JT || prev1 == LineCharProperty.H3) &&
curr == LineCharProperty.JT) {
setBreak(LineBreakType.prohibited, 26);
continue;
}
// Treat a Korean Syllable Block the same as ID.
// LB27: (JL | JV | JT | H2 | H3) × PO
if (_isKoreanSyllable(prev1) && curr == LineCharProperty.PO) {
setBreak(LineBreakType.prohibited, 27);
continue;
}
// LB27: PR × (JL | JV | JT | H2 | H3)
if (prev1 == LineCharProperty.PR && _isKoreanSyllable(curr)) {
setBreak(LineBreakType.prohibited, 27);
continue;
}
// Do not break between alphabetics.
// LB28: (AL | HL) × (AL | HL)
if (_isALorHL(prev1) && _isALorHL(curr)) {
setBreak(LineBreakType.prohibited, 28);
continue;
}
// Do not break between numeric punctuation and alphabetics (“e.g.”).
// LB29: IS × (AL | HL)
if (prev1 == LineCharProperty.IS && _isALorHL(curr)) {
setBreak(LineBreakType.prohibited, 29);
continue;
}
// Do not break between letters, numbers, or ordinary symbols and opening or
// closing parentheses.
// LB30: (AL | HL | NU) × OP
//
// LB30 requires that we exclude characters that have an Eastern Asian width
// property of value F, W or H classes.
if ((_isALorHL(prev1) || prev1 == LineCharProperty.NU) &&
curr == LineCharProperty.OP &&
!_hasEastAsianWidthFWH(text.codeUnitAt(index))) {
setBreak(LineBreakType.prohibited, 30);
continue;
}
// LB30: CP × (AL | HL | NU)
if (prev1 == LineCharProperty.CP &&
!_hasEastAsianWidthFWH(text.codeUnitAt(index - 1)) &&
(_isALorHL(curr) || curr == LineCharProperty.NU)) {
setBreak(LineBreakType.prohibited, 30);
continue;
}
// Break between two regional indicator symbols if and only if there are an
// even number of regional indicators preceding the position of the break.
// LB30a: sot (RI RI)* RI × RI
// [^RI] (RI RI)* RI × RI
if (curr == LineCharProperty.RI) {
if (regionalIndicatorCount.isOdd) {
setBreak(LineBreakType.prohibited, 30);
} else {
setBreak(LineBreakType.opportunity, 30);
}
continue;
}
// Do not break between an emoji base and an emoji modifier.
// LB30b: EB × EM
if (prev1 == LineCharProperty.EB && curr == LineCharProperty.EM) {
setBreak(LineBreakType.prohibited, 30);
continue;
}
// Break everywhere else.
// LB31: ALL ÷
// ÷ ALL
setBreak(LineBreakType.opportunity, 31);
}
// Always break at the end of text.
// LB3: ! eot
setBreak(LineBreakType.endOfText, 3);
return fragments;
}

View File

@@ -1,123 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../../engine.dart' show registerHotRestartListener;
import '../dom.dart';
import '../platform_dispatcher.dart';
import '../view_embedder/dom_manager.dart';
// TODO(yjbanov): this is a hack we use to compute ideographic baseline; this
// number is the ratio ideographic/alphabetic for font Ahem,
// which matches the Flutter number. It may be completely wrong
// for any other font. We'll need to eventually fix this. That
// said Flutter doesn't seem to use ideographic baseline for
// anything as of this writing.
const double baselineRatioHack = 1.1662499904632568;
/// Hosts ruler DOM elements in a hidden container under [DomManager.renderingHost].
class RulerHost {
RulerHost() {
_rulerHost.style
..position = 'fixed'
..visibility = 'hidden'
..overflow = 'hidden'
..top = '0'
..left = '0'
..width = '0'
..height = '0';
// TODO(mdebbar): There could be multiple views with multiple rendering hosts.
// https://github.com/flutter/flutter/issues/137344
final DomNode renderingHost = EnginePlatformDispatcher.instance.implicitView!.dom.renderingHost;
renderingHost.appendChild(_rulerHost);
registerHotRestartListener(dispose);
}
/// Hosts a cache of rulers that measure text.
///
/// This element exists purely for organizational purposes. Otherwise the
/// rulers would be attached to the `<body>` element polluting the element
/// tree and making it hard to navigate. It does not serve any functional
/// purpose.
final DomElement _rulerHost = createDomElement('flt-ruler-host');
/// Releases the resources used by this [RulerHost].
///
/// After this is called, this object is no longer usable.
void dispose() {
_rulerHost.remove();
}
/// Adds an element used for measuring text as a child of [_rulerHost].
void addElement(DomHTMLElement element) {
_rulerHost.append(element);
}
}
// These global variables are used to memoize calls to [measureSubstring]. They
// are used to remember the last arguments passed to it, and the last return
// value.
// They are being initialized so that the compiler knows they'll never be null.
int _lastStart = -1;
int _lastEnd = -1;
String _lastText = '';
String _lastCssFont = '';
double _lastWidth = -1;
/// Measures the width of the substring of [text] starting from the index
/// [start] (inclusive) to [end] (exclusive).
///
/// This method assumes that the correct font has already been set on
/// [canvasContext].
double measureSubstring(
DomCanvasRenderingContext2D canvasContext,
String text,
int start,
int end, {
double? letterSpacing,
}) {
assert(0 <= start);
assert(start <= end);
assert(end <= text.length);
if (start == end) {
return 0;
}
final String cssFont = canvasContext.font;
double width;
// TODO(mdebbar): Explore caching all widths in a map, not only the last one.
if (start == _lastStart && end == _lastEnd && text == _lastText && cssFont == _lastCssFont) {
// Reuse the previously calculated width if all factors that affect width
// are unchanged. The only exception is letter-spacing. We always add
// letter-spacing to the width later below.
width = _lastWidth;
} else {
final String sub = start == 0 && end == text.length ? text : text.substring(start, end);
width = canvasContext.measureText(sub).width!;
}
_lastStart = start;
_lastEnd = end;
_lastText = text;
_lastCssFont = cssFont;
_lastWidth = width;
// Now add letter spacing to the width.
letterSpacing ??= 0.0;
if (letterSpacing != 0.0) {
width += letterSpacing * (end - start);
}
// What we are doing here is we are rounding to the nearest 2nd decimal
// point. So 39.999423 becomes 40, and 11.243982 becomes 11.24.
// The reason we are doing this is because we noticed that canvas API has a
// ±0.001 error margin.
return _roundWidth(width);
}
double _roundWidth(double width) {
return (width * 100).round() / 100;
}

View File

@@ -1,97 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import '../html/bitmap_canvas.dart';
import '../html/painting.dart';
import 'canvas_paragraph.dart';
import 'layout_fragmenter.dart';
import 'paragraph.dart';
/// Responsible for painting a [CanvasParagraph] on a [BitmapCanvas].
class TextPaintService {
TextPaintService(this.paragraph);
final CanvasParagraph paragraph;
void paint(BitmapCanvas canvas, ui.Offset offset) {
// Loop through all the lines, for each line, loop through all fragments and
// paint them. The fragment objects have enough information to be painted
// individually.
final List<ParagraphLine> lines = paragraph.lines;
for (final ParagraphLine line in lines) {
for (final LayoutFragment fragment in line.fragments) {
_paintBackground(canvas, offset, fragment);
_paintText(canvas, offset, line, fragment);
}
}
}
void _paintBackground(BitmapCanvas canvas, ui.Offset offset, LayoutFragment fragment) {
if (fragment.isPlaceholder) {
return;
}
// Paint the background of the box, if the span has a background.
final SurfacePaint? background = fragment.style.background as SurfacePaint?;
if (background != null) {
final ui.Rect rect = fragment.toPaintingTextBox().toRect();
if (!rect.isEmpty) {
canvas.drawRect(rect.shift(offset), background.paintData);
}
}
}
void _paintText(
BitmapCanvas canvas,
ui.Offset offset,
ParagraphLine line,
LayoutFragment fragment,
) {
// There's no text to paint in placeholder spans.
if (fragment.isPlaceholder) {
return;
}
// Don't paint the text for space-only boxes. This is just an
// optimization, it doesn't have any effect on the output.
if (fragment.isSpaceOnly) {
return;
}
_prepareCanvasForFragment(canvas, fragment);
final double fragmentX =
fragment.textDirection! == ui.TextDirection.ltr ? fragment.left : fragment.right;
final double x = offset.dx + line.left + fragmentX;
final double y = offset.dy + line.baseline;
final EngineTextStyle style = fragment.style;
final String text = fragment.getText(paragraph);
canvas.drawText(text, x, y, style: style.foreground?.style, shadows: style.shadows);
canvas.tearDownPaint();
}
void _prepareCanvasForFragment(BitmapCanvas canvas, LayoutFragment fragment) {
final EngineTextStyle style = fragment.style;
final SurfacePaint? paint;
final ui.Paint? foreground = style.foreground;
if (foreground != null) {
paint = foreground as SurfacePaint;
} else {
paint = ui.Paint() as SurfacePaint;
if (style.color != null) {
paint.color = style.color!;
}
}
canvas.setCssFont(style.cssFontString, fragment.textDirection!);
canvas.setUpPaint(paint.paintData, null);
}
}

View File

@@ -1,202 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../dom.dart';
import '../util.dart';
import '../view_embedder/style_manager.dart';
import 'measurement.dart';
import 'paragraph.dart';
String buildCssFontString({
required ui.FontStyle? fontStyle,
required ui.FontWeight? fontWeight,
required double? fontSize,
required String fontFamily,
}) {
final String cssFontStyle = fontStyle?.toCssString() ?? StyleManager.defaultFontStyle;
final String cssFontWeight = fontWeight?.toCssString() ?? StyleManager.defaultFontWeight;
final int cssFontSize = (fontSize ?? StyleManager.defaultFontSize).floor();
final String cssFontFamily = canonicalizeFontFamily(fontFamily)!;
return '$cssFontStyle $cssFontWeight ${cssFontSize}px $cssFontFamily';
}
/// Contains all styles that have an effect on the height of text.
///
/// This is useful as a cache key for [TextHeightRuler].
class TextHeightStyle {
TextHeightStyle({
required this.fontFamily,
required this.fontSize,
required this.height,
required this.fontFeatures,
required this.fontVariations,
});
final String fontFamily;
final double fontSize;
final double? height;
final List<ui.FontFeature>? fontFeatures;
final List<ui.FontVariation>? fontVariations;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is TextHeightStyle && other.hashCode == hashCode;
}
@override
late final int hashCode = Object.hash(
fontFamily,
fontSize,
height,
fontFeatures == null ? null : Object.hashAll(fontFeatures!),
fontVariations == null ? null : Object.hashAll(fontVariations!),
);
}
/// Provides text dimensions found on [_element]. The idea behind this class is
/// to allow the [ParagraphRuler] to mutate multiple dom elements and allow
/// consumers to lazily read the measurements.
///
/// The [ParagraphRuler] would have multiple instances of [TextDimensions] with
/// different backing elements for different types of measurements. When a
/// measurement is needed, the [ParagraphRuler] would mutate all the backing
/// elements at once. The consumer of the ruler can later read those
/// measurements.
///
/// The rationale behind this is to minimize browser reflows by batching dom
/// writes first, then performing all the reads.
class TextDimensions {
TextDimensions(this._element);
final DomElement _element;
DomRect? _cachedBoundingClientRect;
void _invalidateBoundsCache() {
_cachedBoundingClientRect = null;
}
/// Sets text of contents to a single space character to measure empty text.
void updateTextToSpace() {
_invalidateBoundsCache();
_element.text = ' ';
}
void applyHeightStyle(TextHeightStyle textHeightStyle) {
final String fontFamily = textHeightStyle.fontFamily;
final double fontSize = textHeightStyle.fontSize;
final DomCSSStyleDeclaration style = _element.style;
style
..fontSize = '${fontSize.floor()}px'
..fontFamily = canonicalizeFontFamily(fontFamily)!;
final double? height = textHeightStyle.height;
// Workaround the rounding introduced by https://github.com/flutter/flutter/issues/122066
// in tests.
final double? effectiveLineHeight = height ?? (fontFamily == 'FlutterTest' ? 1.0 : null);
if (effectiveLineHeight != null) {
style.lineHeight = effectiveLineHeight.toString();
}
_invalidateBoundsCache();
}
/// Appends element and probe to hostElement that is set up for a specific
/// TextStyle.
void appendToHost(DomHTMLElement hostElement) {
hostElement.append(_element);
_invalidateBoundsCache();
}
DomRect _readAndCacheMetrics() => _cachedBoundingClientRect ??= _element.getBoundingClientRect();
/// The height of the paragraph being measured.
double get height {
double cachedHeight = _readAndCacheMetrics().height;
if (ui_web.browser.browserEngine == ui_web.BrowserEngine.firefox &&
// In the flutter tester environment, we use a predictable-size for font
// measurement tests.
!ui_web.debugEmulateFlutterTesterEnvironment) {
// See subpixel rounding bug :
// https://bugzilla.mozilla.org/show_bug.cgi?id=442139
// This causes bottom of letters such as 'y' to be cutoff and
// incorrect rendering of double underlines.
cachedHeight += 1.0;
}
return cachedHeight;
}
}
/// Performs height measurement for the given [textHeightStyle].
///
/// The two results of this ruler's measurement are:
///
/// 1. [alphabeticBaseline].
/// 2. [height].
class TextHeightRuler {
TextHeightRuler(this.textHeightStyle, this.rulerHost);
final TextHeightStyle textHeightStyle;
final RulerHost rulerHost;
// Elements used to measure the line-height metric.
late final DomHTMLElement _probe = _createProbe();
late final DomHTMLElement _host = _createHost();
final TextDimensions _dimensions = TextDimensions(domDocument.createElement('flt-paragraph'));
/// The alphabetic baseline for this ruler's [textHeightStyle].
late final double alphabeticBaseline = _probe.getBoundingClientRect().bottom;
/// The height for this ruler's [textHeightStyle].
late final double height = _dimensions.height;
/// Disposes of this ruler and detaches it from the DOM tree.
void dispose() {
_host.remove();
}
DomHTMLElement _createHost() {
final DomHTMLDivElement host = createDomHTMLDivElement();
host.style
..visibility = 'hidden'
..position = 'absolute'
..top = '0'
..left = '0'
..display = 'flex'
..flexDirection = 'row'
..alignItems = 'baseline'
..margin = '0'
..border = '0'
..padding = '0';
assert(() {
host.setAttribute('data-ruler', 'line-height');
return true;
}());
_dimensions.applyHeightStyle(textHeightStyle);
// Force single-line (even if wider than screen) and preserve whitespaces.
_dimensions._element.style.whiteSpace = 'pre';
// To measure line-height, all we need is a whitespace.
_dimensions.updateTextToSpace();
_dimensions.appendToHost(host);
rulerHost.addElement(host);
return host;
}
DomHTMLElement _createProbe() {
final DomHTMLElement probe = createDomHTMLDivElement();
_host.append(probe);
return probe;
}
}

View File

@@ -1,182 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:ui/ui.dart' as ui;
import 'fragmenter.dart';
import 'unicode_range.dart';
enum FragmentFlow {
/// The fragment flows from left to right regardless of its surroundings.
ltr,
/// The fragment flows from right to left regardless of its surroundings.
rtl,
/// The fragment flows the same as the previous fragment.
///
/// If it's the first fragment in a line, then it flows the same as the
/// paragraph direction.
///
/// E.g. digits.
previous,
/// If the previous and next fragments flow in the same direction, then this
/// fragment flows in that same direction. Otherwise, it flows the same as the
/// paragraph direction.
///
/// E.g. spaces, symbols.
sandwich,
}
/// Splits [text] into fragments based on directionality.
class BidiFragmenter extends TextFragmenter {
const BidiFragmenter(super.text);
@override
List<BidiFragment> fragment() {
return _computeBidiFragments(text);
}
}
class BidiFragment extends TextFragment {
const BidiFragment(super.start, super.end, this.textDirection, this.fragmentFlow);
final ui.TextDirection? textDirection;
final FragmentFlow fragmentFlow;
@override
int get hashCode => Object.hash(start, end, textDirection, fragmentFlow);
@override
bool operator ==(Object other) {
return other is BidiFragment &&
other.start == start &&
other.end == end &&
other.textDirection == textDirection &&
other.fragmentFlow == fragmentFlow;
}
@override
String toString() {
return 'BidiFragment($start, $end, $textDirection)';
}
}
// This data was taken from the source code of the Closure library:
//
// - https://github.com/google/closure-library/blob/9d24a6c1809a671c2e54c328897ebeae15a6d172/closure/goog/i18n/bidi.js#L203-L234
final UnicodePropertyLookup<ui.TextDirection?> _textDirectionLookup =
UnicodePropertyLookup<ui.TextDirection?>(<UnicodeRange<ui.TextDirection>>[
// LTR
const UnicodeRange<ui.TextDirection>(kChar_A, kChar_Z, ui.TextDirection.ltr),
const UnicodeRange<ui.TextDirection>(kChar_a, kChar_z, ui.TextDirection.ltr),
const UnicodeRange<ui.TextDirection>(0x00C0, 0x00D6, ui.TextDirection.ltr),
const UnicodeRange<ui.TextDirection>(0x00D8, 0x00F6, ui.TextDirection.ltr),
const UnicodeRange<ui.TextDirection>(0x00F8, 0x02B8, ui.TextDirection.ltr),
const UnicodeRange<ui.TextDirection>(0x0300, 0x0590, ui.TextDirection.ltr),
// RTL
const UnicodeRange<ui.TextDirection>(0x0591, 0x06EF, ui.TextDirection.rtl),
const UnicodeRange<ui.TextDirection>(0x06FA, 0x08FF, ui.TextDirection.rtl),
// LTR
const UnicodeRange<ui.TextDirection>(0x0900, 0x1FFF, ui.TextDirection.ltr),
const UnicodeRange<ui.TextDirection>(0x200E, 0x200E, ui.TextDirection.ltr),
// RTL
const UnicodeRange<ui.TextDirection>(0x200F, 0x200F, ui.TextDirection.rtl),
// LTR
const UnicodeRange<ui.TextDirection>(0x2C00, 0xD801, ui.TextDirection.ltr),
// RTL
const UnicodeRange<ui.TextDirection>(0xD802, 0xD803, ui.TextDirection.rtl),
// LTR
const UnicodeRange<ui.TextDirection>(0xD804, 0xD839, ui.TextDirection.ltr),
// RTL
const UnicodeRange<ui.TextDirection>(0xD83A, 0xD83B, ui.TextDirection.rtl),
// LTR
const UnicodeRange<ui.TextDirection>(0xD83C, 0xDBFF, ui.TextDirection.ltr),
const UnicodeRange<ui.TextDirection>(0xF900, 0xFB1C, ui.TextDirection.ltr),
// RTL
const UnicodeRange<ui.TextDirection>(0xFB1D, 0xFDFF, ui.TextDirection.rtl),
// LTR
const UnicodeRange<ui.TextDirection>(0xFE00, 0xFE6F, ui.TextDirection.ltr),
// RTL
const UnicodeRange<ui.TextDirection>(0xFE70, 0xFEFC, ui.TextDirection.rtl),
// LTR
const UnicodeRange<ui.TextDirection>(0xFEFD, 0xFFFF, ui.TextDirection.ltr),
], null);
List<BidiFragment> _computeBidiFragments(String text) {
final List<BidiFragment> fragments = <BidiFragment>[];
if (text.isEmpty) {
fragments.add(const BidiFragment(0, 0, null, FragmentFlow.previous));
return fragments;
}
int fragmentStart = 0;
ui.TextDirection? textDirection = _getTextDirection(text, 0);
FragmentFlow fragmentFlow = _getFragmentFlow(text, 0);
for (int i = 1; i < text.length; i++) {
final ui.TextDirection? charTextDirection = _getTextDirection(text, i);
if (charTextDirection != textDirection) {
// We've reached the end of a text direction fragment.
fragments.add(BidiFragment(fragmentStart, i, textDirection, fragmentFlow));
fragmentStart = i;
textDirection = charTextDirection;
fragmentFlow = _getFragmentFlow(text, i);
} else {
// This code handles the case of a sequence of digits followed by a sequence
// of LTR characters with no space in between.
if (fragmentFlow == FragmentFlow.previous) {
fragmentFlow = _getFragmentFlow(text, i);
}
}
}
fragments.add(BidiFragment(fragmentStart, text.length, textDirection, fragmentFlow));
return fragments;
}
ui.TextDirection? _getTextDirection(String text, int i) {
final int codePoint = getCodePoint(text, i)!;
if (_isDigit(codePoint) || _isMashriqiDigit(codePoint)) {
// A sequence of regular digits or Mashriqi digits always goes from left to
// regardless of their fragment flow direction.
return ui.TextDirection.ltr;
}
final ui.TextDirection? textDirection = _textDirectionLookup.findForChar(codePoint);
if (textDirection != null) {
return textDirection;
}
return null;
}
FragmentFlow _getFragmentFlow(String text, int i) {
final int codePoint = getCodePoint(text, i)!;
if (_isDigit(codePoint)) {
return FragmentFlow.previous;
}
if (_isMashriqiDigit(codePoint)) {
return FragmentFlow.rtl;
}
final ui.TextDirection? textDirection = _textDirectionLookup.findForChar(codePoint);
return switch (textDirection) {
ui.TextDirection.ltr => FragmentFlow.ltr,
ui.TextDirection.rtl => FragmentFlow.rtl,
null => FragmentFlow.sandwich,
};
}
bool _isDigit(int codePoint) {
return codePoint >= kChar_0 && codePoint <= kChar_9;
}
bool _isMashriqiDigit(int codePoint) {
return codePoint >= kMashriqi_0 && codePoint <= kMashriqi_9;
}

View File

@@ -1,269 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const int kChar_0 = 48;
const int kChar_9 = kChar_0 + 9;
const int kChar_A = 65;
const int kChar_Z = 90;
const int kChar_a = 97;
const int kChar_z = 122;
const int kCharBang = 33;
const int kMashriqi_0 = 0x660;
const int kMashriqi_9 = kMashriqi_0 + 9;
enum _ComparisonResult { inside, higher, lower }
/// Each instance of [UnicodeRange] represents a range of unicode characters
/// that are assigned a [CharProperty]. For example, the following snippet:
///
/// ```dart
/// UnicodeRange(0x0041, 0x005A, CharProperty.ALetter);
/// ```
///
/// is saying that all characters between 0x0041 ("A") and 0x005A ("Z") are
/// assigned the property [CharProperty.ALetter].
///
/// Note that the Unicode spec uses inclusive ranges and we are doing the
/// same here.
class UnicodeRange<P> {
const UnicodeRange(this.start, this.end, this.property);
final int start;
final int end;
final P property;
/// Compare a [value] to this range.
///
/// The return value is either:
/// - lower: The value is lower than the range.
/// - higher: The value is higher than the range
/// - inside: The value is within the range.
_ComparisonResult compare(int value) {
if (value < start) {
return _ComparisonResult.lower;
}
if (value > end) {
return _ComparisonResult.higher;
}
return _ComparisonResult.inside;
}
}
/// Checks whether the given char code is a UTF-16 surrogate.
///
/// See:
/// - http://www.unicode.org/faq//utf_bom.html#utf16-2
bool isUtf16Surrogate(int char) {
return char & 0xF800 == 0xD800;
}
/// Combines a pair of UTF-16 surrogate into a single character code point.
///
/// The surrogate pair is expected to start at [index] in the [text].
///
/// See:
/// - http://www.unicode.org/faq//utf_bom.html#utf16-3
int combineSurrogatePair(String text, int index) {
final int hi = text.codeUnitAt(index);
final int lo = text.codeUnitAt(index + 1);
final int x = (hi & ((1 << 6) - 1)) << 10 | lo & ((1 << 10) - 1);
final int w = (hi >> 6) & ((1 << 5) - 1);
final int u = w + 1;
return u << 16 | x;
}
/// Returns the code point from [text] at [index] and handles surrogate pairs
/// for cases that involve two UTF-16 codes.
int? getCodePoint(String text, int index) {
if (index < 0 || index >= text.length) {
return null;
}
final int char = text.codeUnitAt(index);
if (isUtf16Surrogate(char) && index < text.length - 1) {
return combineSurrogatePair(text, index);
}
return char;
}
/// Given a list of [UnicodeRange]s, this class performs efficient lookup
/// to find which range a value falls into.
///
/// The lookup algorithm expects the ranges to have the following constraints:
/// - Be sorted.
/// - No overlap between the ranges.
/// - Gaps between ranges are ok.
///
/// This is used in the context of unicode to find out what property a letter
/// has. The properties are then used to decide word boundaries, line break
/// opportunities, etc.
class UnicodePropertyLookup<P> {
UnicodePropertyLookup(this.ranges, this.defaultProperty);
/// Creates a [UnicodePropertyLookup] from packed line break data.
factory UnicodePropertyLookup.fromPackedData(
String packedData,
int singleRangesCount,
List<P> propertyEnumValues,
P defaultProperty,
) {
return UnicodePropertyLookup<P>(
_unpackProperties<P>(packedData, singleRangesCount, propertyEnumValues),
defaultProperty,
);
}
/// The list of unicode ranges and their associated properties.
final List<UnicodeRange<P>> ranges;
/// The default property to use when a character doesn't belong in any
/// known range.
final P defaultProperty;
/// Cache for lookup results.
final Map<int, P> _cache = <int, P>{};
/// Take a [text] and an [index], and returns the property of the character
/// located at that [index].
///
/// If the [index] is out of range, null will be returned.
P find(String text, int index) {
final int? codePoint = getCodePoint(text, index);
return codePoint == null ? defaultProperty : findForChar(codePoint);
}
/// Takes one character as an integer code unit and returns its property.
///
/// If a property can't be found for the given character, then the default
/// property will be returned.
P findForChar(int? char) {
if (char == null) {
return defaultProperty;
}
final P? cacheHit = _cache[char];
if (cacheHit != null) {
return cacheHit;
}
final int rangeIndex = _binarySearch(char);
final P result = rangeIndex == -1 ? defaultProperty : ranges[rangeIndex].property;
// Cache the result.
_cache[char] = result;
return result;
}
int _binarySearch(int value) {
int min = 0;
int max = ranges.length;
while (min < max) {
final int mid = min + ((max - min) >> 1);
final UnicodeRange<P> range = ranges[mid];
switch (range.compare(value)) {
case _ComparisonResult.higher:
min = mid + 1;
case _ComparisonResult.lower:
max = mid;
case _ComparisonResult.inside:
return mid;
}
}
return -1;
}
}
List<UnicodeRange<P>> _unpackProperties<P>(
String packedData,
int singleRangesCount,
List<P> propertyEnumValues,
) {
// Packed data is mostly structured in chunks of 9 characters each:
//
// * [0..3]: Range start, encoded as a base36 integer.
// * [4..7]: Range end, encoded as a base36 integer.
// * [8]: Index of the property enum value, encoded as a single letter.
//
// When the range is a single number (i.e. range start == range end), it gets
// packed more efficiently in a chunk of 6 characters:
//
// * [0..3]: Range start (and range end), encoded as a base 36 integer.
// * [4]: "!" to indicate that there's no range end.
// * [5]: Index of the property enum value, encoded as a single letter.
// `packedData.length + singleRangesCount * 3` would have been the size of the
// packed data if the efficient packing of single-range items wasn't applied.
assert((packedData.length + singleRangesCount * 3) % 9 == 0);
final List<UnicodeRange<P>> ranges = <UnicodeRange<P>>[];
final int dataLength = packedData.length;
int i = 0;
while (i < dataLength) {
final int rangeStart = _consumeInt(packedData, i);
i += 4;
int rangeEnd;
if (packedData.codeUnitAt(i) == kCharBang) {
rangeEnd = rangeStart;
i++;
} else {
rangeEnd = _consumeInt(packedData, i);
i += 4;
}
final int charCode = packedData.codeUnitAt(i);
final P property = propertyEnumValues[_getEnumIndexFromPackedValue(charCode)];
i++;
ranges.add(UnicodeRange<P>(rangeStart, rangeEnd, property));
}
return ranges;
}
int _getEnumIndexFromPackedValue(int charCode) {
// This has to stay in sync with [EnumValue.serialized] in
// `tool/unicode_sync_script.dart`.
assert(
(charCode >= kChar_A && charCode <= kChar_Z) || (charCode >= kChar_a && charCode <= kChar_z),
);
// Uppercase letters were assigned to the first 26 enum values.
if (charCode <= kChar_Z) {
return charCode - kChar_A;
}
// Lowercase letters were assigned to enum values above 26.
return 26 + charCode - kChar_a;
}
int _consumeInt(String packedData, int index) {
// The implementation is equivalent to:
//
// ```dart
// return int.tryParse(packedData.substring(index, index + 4), radix: 36);
// ```
//
// But using substring is slow when called too many times. This custom
// implementation makes the unpacking 25%-45% faster than using substring.
final int digit0 = getIntFromCharCode(packedData.codeUnitAt(index + 3));
final int digit1 = getIntFromCharCode(packedData.codeUnitAt(index + 2));
final int digit2 = getIntFromCharCode(packedData.codeUnitAt(index + 1));
final int digit3 = getIntFromCharCode(packedData.codeUnitAt(index));
return digit0 + (digit1 * 36) + (digit2 * 36 * 36) + (digit3 * 36 * 36 * 36);
}
/// Does the same thing as [int.parse(str, 36)] but takes only a single
/// character as a [charCode] integer.
int getIntFromCharCode(int charCode) {
assert(
(charCode >= kChar_0 && charCode <= kChar_9) || (charCode >= kChar_a && charCode <= kChar_z),
);
if (charCode <= kChar_9) {
return charCode - kChar_0;
}
// "a" starts from 10 and remaining letters go up from there.
return charCode - kChar_a + 10;
}

View File

@@ -1,17 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:web_unicode/web_unicode.dart';
import 'unicode_range.dart';
export 'package:web_unicode/web_unicode.dart' show WordCharProperty;
UnicodePropertyLookup<WordCharProperty> wordLookup =
UnicodePropertyLookup<WordCharProperty>.fromPackedData(
packedWordBreakProperties,
singleWordBreakRangesCount,
WordCharProperty.values,
defaultWordCharProperty,
);

View File

@@ -1,319 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../util.dart';
import 'word_break_properties.dart';
enum _FindBreakDirection {
forward(step: 1),
backward(step: -1);
const _FindBreakDirection({required this.step});
final int step;
}
/// [WordBreaker] exposes static methods to identify word boundaries.
abstract final class WordBreaker {
/// It starts from [index] and tries to find the next word boundary in [text].
static int nextBreakIndex(String text, int index) =>
_findBreakIndex(_FindBreakDirection.forward, text, index);
/// It starts from [index] and tries to find the previous word boundary in
/// [text].
static int prevBreakIndex(String text, int index) =>
_findBreakIndex(_FindBreakDirection.backward, text, index);
static int _findBreakIndex(_FindBreakDirection direction, String text, int index) {
int i = index;
while (i >= 0 && i <= text.length) {
i += direction.step;
if (_isBreak(text, i)) {
break;
}
}
return clampInt(i, 0, text.length);
}
/// Find out if there's a word break between [index - 1] and [index].
/// http://unicode.org/reports/tr29/#Word_Boundary_Rules
static bool _isBreak(String? text, int index) {
// Break at the start and end of text.
// WB1: sot ÷ Any
// WB2: Any ÷ eot
if (index <= 0 || index >= text!.length) {
return true;
}
// Do not break inside surrogate pair
if (_isUtf16Surrogate(text.codeUnitAt(index - 1))) {
return false;
}
final WordCharProperty immediateRight = wordLookup.find(text, index);
WordCharProperty immediateLeft = wordLookup.find(text, index - 1);
// Do not break within CRLF.
// WB3: CR × LF
if (immediateLeft == WordCharProperty.CR && immediateRight == WordCharProperty.LF) {
return false;
}
// Otherwise break before and after Newlines (including CR and LF)
// WB3a: (Newline | CR | LF) ÷
if (_oneOf(immediateLeft, WordCharProperty.Newline, WordCharProperty.CR, WordCharProperty.LF)) {
return true;
}
// WB3b: ÷ (Newline | CR | LF)
if (_oneOf(
immediateRight,
WordCharProperty.Newline,
WordCharProperty.CR,
WordCharProperty.LF,
)) {
return true;
}
// WB3c: ZWJ × \p{Extended_Pictographic}
// TODO(mdebbar): What's the right way to implement this?
// Keep horizontal whitespace together.
// WB3d: WSegSpace × WSegSpace
if (immediateLeft == WordCharProperty.WSegSpace &&
immediateRight == WordCharProperty.WSegSpace) {
return false;
}
// Ignore Format and Extend characters, except after sot, CR, LF, and
// Newline.
// WB4: X (Extend | Format | ZWJ)* → X
if (_oneOf(
immediateRight,
WordCharProperty.Extend,
WordCharProperty.Format,
WordCharProperty.ZWJ,
)) {
// The Extend|Format|ZWJ character is to the right, so it is attached
// to a character to the left, don't split here
return false;
}
// We've reached the end of an Extend|Format|ZWJ sequence, collapse it.
int l = 0;
while (_oneOf(
immediateLeft,
WordCharProperty.Extend,
WordCharProperty.Format,
WordCharProperty.ZWJ,
)) {
l++;
if (index - l - 1 < 0) {
// Reached the beginning of text.
return true;
}
immediateLeft = wordLookup.find(text, index - l - 1);
}
// Do not break between most letters.
// WB5: (ALetter | Hebrew_Letter) × (ALetter | Hebrew_Letter)
if (_isAHLetter(immediateLeft) && _isAHLetter(immediateRight)) {
return false;
}
// Some tests beyond this point require more context. We need to get that
// context while also respecting rule WB4. So ignore Format, Extend and ZWJ.
// Skip all Format, Extend and ZWJ to the right.
int r = 0;
WordCharProperty? nextRight;
do {
r++;
nextRight = wordLookup.find(text, index + r);
} while (_oneOf(
nextRight,
WordCharProperty.Extend,
WordCharProperty.Format,
WordCharProperty.ZWJ,
));
// Skip all Format, Extend and ZWJ to the left.
WordCharProperty? nextLeft;
do {
l++;
nextLeft = wordLookup.find(text, index - l - 1);
} while (_oneOf(
nextLeft,
WordCharProperty.Extend,
WordCharProperty.Format,
WordCharProperty.ZWJ,
));
// Do not break letters across certain punctuation.
// WB6: (AHLetter) × (MidLetter | MidNumLet | Single_Quote) (AHLetter)
if (_isAHLetter(immediateLeft) &&
_oneOf(
immediateRight,
WordCharProperty.MidLetter,
WordCharProperty.MidNumLet,
WordCharProperty.SingleQuote,
) &&
_isAHLetter(nextRight)) {
return false;
}
// WB7: (AHLetter) (MidLetter | MidNumLet | Single_Quote) × (AHLetter)
if (_isAHLetter(nextLeft) &&
_oneOf(
immediateLeft,
WordCharProperty.MidLetter,
WordCharProperty.MidNumLet,
WordCharProperty.SingleQuote,
) &&
_isAHLetter(immediateRight)) {
return false;
}
// WB7a: Hebrew_Letter × Single_Quote
if (immediateLeft == WordCharProperty.HebrewLetter &&
immediateRight == WordCharProperty.SingleQuote) {
return false;
}
// WB7b: Hebrew_Letter × Double_Quote Hebrew_Letter
if (immediateLeft == WordCharProperty.HebrewLetter &&
immediateRight == WordCharProperty.DoubleQuote &&
nextRight == WordCharProperty.HebrewLetter) {
return false;
}
// WB7c: Hebrew_Letter Double_Quote × Hebrew_Letter
if (nextLeft == WordCharProperty.HebrewLetter &&
immediateLeft == WordCharProperty.DoubleQuote &&
immediateRight == WordCharProperty.HebrewLetter) {
return false;
}
// Do not break within sequences of digits, or digits adjacent to letters
// (“3a”, or “A3”).
// WB8: Numeric × Numeric
if (immediateLeft == WordCharProperty.Numeric && immediateRight == WordCharProperty.Numeric) {
return false;
}
// WB9: AHLetter × Numeric
if (_isAHLetter(immediateLeft) && immediateRight == WordCharProperty.Numeric) {
return false;
}
// WB10: Numeric × AHLetter
if (immediateLeft == WordCharProperty.Numeric && _isAHLetter(immediateRight)) {
return false;
}
// Do not break within sequences, such as “3.2” or “3,456.789”.
// WB11: Numeric (MidNum | MidNumLet | Single_Quote) × Numeric
if (nextLeft == WordCharProperty.Numeric &&
_oneOf(
immediateLeft,
WordCharProperty.MidNum,
WordCharProperty.MidNumLet,
WordCharProperty.SingleQuote,
) &&
immediateRight == WordCharProperty.Numeric) {
return false;
}
// WB12: Numeric × (MidNum | MidNumLet | Single_Quote) Numeric
if (immediateLeft == WordCharProperty.Numeric &&
_oneOf(
immediateRight,
WordCharProperty.MidNum,
WordCharProperty.MidNumLet,
WordCharProperty.SingleQuote,
) &&
nextRight == WordCharProperty.Numeric) {
return false;
}
// Do not break between Katakana.
// WB13: Katakana × Katakana
if (immediateLeft == WordCharProperty.Katakana && immediateRight == WordCharProperty.Katakana) {
return false;
}
// Do not break from extenders.
// WB13a: (AHLetter | Numeric | Katakana | ExtendNumLet) × ExtendNumLet
if (_oneOf(
immediateLeft,
WordCharProperty.ALetter,
WordCharProperty.HebrewLetter,
WordCharProperty.Numeric,
WordCharProperty.Katakana,
WordCharProperty.ExtendNumLet,
) &&
immediateRight == WordCharProperty.ExtendNumLet) {
return false;
}
// WB13b: ExtendNumLet × (AHLetter | Numeric | Katakana)
if (immediateLeft == WordCharProperty.ExtendNumLet &&
_oneOf(
immediateRight,
WordCharProperty.ALetter,
WordCharProperty.HebrewLetter,
WordCharProperty.Numeric,
WordCharProperty.Katakana,
)) {
return false;
}
// Do not break within emoji flag sequences. That is, do not break between
// regional indicator (RI) symbols if there is an odd number of RI
// characters before the break point.
// WB15: sot (RI RI)* RI × RI
// TODO(mdebbar): implement this.
// WB16: [^RI] (RI RI)* RI × RI
// TODO(mdebbar): implement this.
// Otherwise, break everywhere (including around ideographs).
// WB999: Any ÷ Any
return true;
}
static bool _isUtf16Surrogate(int value) {
return value & 0xF800 == 0xD800;
}
static bool _oneOf(
WordCharProperty? value,
WordCharProperty choice1,
WordCharProperty choice2, [
WordCharProperty? choice3,
WordCharProperty? choice4,
WordCharProperty? choice5,
]) {
if (value == choice1) {
return true;
}
if (value == choice2) {
return true;
}
if (choice3 != null && value == choice3) {
return true;
}
if (choice4 != null && value == choice4) {
return true;
}
if (choice5 != null && value == choice5) {
return true;
}
return false;
}
static bool _isAHLetter(WordCharProperty? property) {
return _oneOf(property, WordCharProperty.ALetter, WordCharProperty.HebrewLetter);
}
}

View File

@@ -22,38 +22,6 @@ import 'package:ui/ui.dart';
/// to disregard.
const double precisionErrorTolerance = 1e-10;
/// Enumerates all persisted surfaces in the tree rooted at [root].
///
/// If [root] is `null` returns all surfaces from the last rendered scene.
///
/// Surfaces are returned in a depth-first order.
Iterable<PersistedSurface> enumerateSurfaces([PersistedSurface? root]) {
root ??= SurfaceSceneBuilder.debugLastFrameScene;
final List<PersistedSurface> surfaces = <PersistedSurface>[root!];
root.visitChildren((PersistedSurface surface) {
surfaces.addAll(enumerateSurfaces(surface));
});
return surfaces;
}
/// Enumerates all pictures nested under [root].
///
/// If [root] is `null` returns all pictures from the last rendered scene.
Iterable<PersistedPicture> enumeratePictures([PersistedSurface? root]) {
root ??= SurfaceSceneBuilder.debugLastFrameScene;
return enumerateSurfaces(root).whereType<PersistedPicture>();
}
/// Enumerates all offset surfaces nested under [root].
///
/// If [root] is `null` returns all pictures from the last rendered scene.
Iterable<PersistedOffset> enumerateOffsets([PersistedSurface? root]) {
root ??= SurfaceSceneBuilder.debugLastFrameScene;
return enumerateSurfaces(root).whereType<PersistedOffset>();
}
/// Computes the distance between two values.
///
/// The distance should be a metric in a metric space (see

View File

@@ -1,207 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
/// Contains method name that was called on [MockEngineCanvas] and arguments
/// that were passed.
class MockCanvasCall {
MockCanvasCall._({required this.methodName, this.arguments});
final String methodName;
final dynamic arguments;
@override
String toString() {
return '$MockCanvasCall($methodName, $arguments)';
}
}
/// A fake implementation of [EngineCanvas] that logs calls to its methods but
/// doesn't actually paint anything.
///
/// Useful for testing interactions between upper layers of the system with
/// canvases.
class MockEngineCanvas implements EngineCanvas {
final List<MockCanvasCall> methodCallLog = <MockCanvasCall>[];
@override
DomElement get rootElement => _rootElement;
final DomElement _rootElement = createDomHTMLDivElement();
void _called(String methodName, {dynamic arguments}) {
methodCallLog.add(MockCanvasCall._(methodName: methodName, arguments: arguments));
}
@override
void dispose() {
_called('dispose');
}
@override
void clear() {
_called('clear');
}
@override
void save() {
_called('save');
}
@override
void restore() {
_called('restore');
}
@override
void translate(double dx, double dy) {
_called('translate', arguments: <String, double>{'dx': dx, 'dy': dy});
}
@override
void scale(double sx, double sy) {
_called('scale', arguments: <String, double>{'sx': sx, 'sy': sy});
}
@override
void rotate(double radians) {
_called('rotate', arguments: radians);
}
@override
void skew(double sx, double sy) {
_called('skew', arguments: <String, double>{'sx': sx, 'sy': sy});
}
@override
void transform(Float32List matrix4) {
_called('transform', arguments: matrix4);
}
@override
void clipRect(Rect rect, ClipOp op) {
_called('clipRect', arguments: rect);
}
@override
void clipRRect(RRect rrect) {
_called('clipRRect', arguments: rrect);
}
@override
void clipRSuperellipse(RSuperellipse rse) {
_called('clipRSuperellipse', arguments: rse);
}
@override
void clipPath(Path path) {
_called('clipPath', arguments: path);
}
@override
void drawColor(Color color, BlendMode blendMode) {
_called('drawColor', arguments: <String, dynamic>{'color': color, 'blendMode': blendMode});
}
@override
void drawLine(Offset p1, Offset p2, SurfacePaintData paint) {
_called('drawLine', arguments: <String, dynamic>{'p1': p1, 'p2': p2, 'paint': paint});
}
@override
void drawPaint(SurfacePaintData paint) {
_called('drawPaint', arguments: paint);
}
@override
void drawRect(Rect rect, SurfacePaintData paint) {
_called('drawRect', arguments: <String, dynamic>{'rect': rect, 'paint': paint});
}
@override
void drawRRect(RRect rrect, SurfacePaintData paint) {
_called('drawRRect', arguments: <String, dynamic>{'rrect': rrect, 'paint': paint});
}
@override
void drawDRRect(RRect outer, RRect inner, SurfacePaintData paint) {
_called(
'drawDRRect',
arguments: <String, dynamic>{'outer': outer, 'inner': inner, 'paint': paint},
);
}
@override
void drawOval(Rect rect, SurfacePaintData paint) {
_called('drawOval', arguments: <String, dynamic>{'rect': rect, 'paint': paint});
}
@override
void drawCircle(Offset c, double radius, SurfacePaintData paint) {
_called('drawCircle', arguments: <String, dynamic>{'c': c, 'radius': radius, 'paint': paint});
}
@override
void drawPath(Path path, SurfacePaintData paint) {
_called('drawPath', arguments: <String, dynamic>{'path': path, 'paint': paint});
}
@override
void drawShadow(Path path, Color color, double elevation, bool transparentOccluder) {
_called(
'drawShadow',
arguments: <String, dynamic>{
'path': path,
'color': color,
'elevation': elevation,
'transparentOccluder': transparentOccluder,
},
);
}
@override
void drawImage(Image image, Offset p, SurfacePaintData paint) {
_called('drawImage', arguments: <String, dynamic>{'image': image, 'p': p, 'paint': paint});
}
@override
void drawImageRect(Image image, Rect src, Rect dst, SurfacePaintData paint) {
_called(
'drawImageRect',
arguments: <String, dynamic>{'image': image, 'src': src, 'dst': dst, 'paint': paint},
);
}
@override
void drawParagraph(Paragraph paragraph, Offset offset) {
_called(
'drawParagraph',
arguments: <String, dynamic>{'paragraph': paragraph, 'offset': offset},
);
}
@override
void drawVertices(Vertices vertices, BlendMode blendMode, SurfacePaintData paint) {
_called(
'drawVertices',
arguments: <String, dynamic>{'vertices': vertices, 'blendMode': blendMode, 'paint': paint},
);
}
@override
void drawPoints(PointMode pointMode, Float32List points, SurfacePaintData paint) {
_called(
'drawPoints',
arguments: <String, dynamic>{'pointMode': pointMode, 'points': points, 'paint': paint},
);
}
@override
void endOfPaint() {
_called('endOfPaint', arguments: <String, dynamic>{});
}
}

View File

@@ -6,7 +6,6 @@ import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
import '../common/test_initialization.dart';
@@ -16,11 +15,11 @@ void main() {
}
Future<void> testMain() async {
setUpImplicitView();
setUpUnitTests();
Future<Image> createTestImageByColor(Color color) async {
final EnginePictureRecorder recorder = EnginePictureRecorder();
final RecordingCanvas canvas = recorder.beginRecording(const Rect.fromLTRB(0, 0, 2, 2));
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder, const Rect.fromLTRB(0, 0, 2, 2));
canvas.drawColor(color, BlendMode.srcOver);
final Picture testPicture = recorder.endRecording();
final Image testImage = await testPicture.toImage(2, 2);

View File

@@ -1,575 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide window;
import '../../common/test_initialization.dart';
import 'helper.dart';
const String _rtlWord1 = 'واحد';
const String _rtlWord2 = 'اثنان';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
void paintBasicBidiStartingWithLtr(
EngineCanvas canvas,
Rect bounds,
double y,
TextDirection textDirection,
TextAlign textAlign,
) {
// The text starts with a left-to-right word.
const String text = 'One 12 $_rtlWord1 $_rtlWord2 34 two 56';
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textDirection: textDirection,
textAlign: textAlign,
);
final CanvasParagraph paragraph = plain(
paragraphStyle,
text,
textStyle: EngineTextStyle.only(color: blue),
);
final double maxWidth = bounds.width - 10;
paragraph.layout(constrain(maxWidth));
canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5));
}
test('basic bidi starting with ltr', () {
const Rect bounds = Rect.fromLTWH(0, 0, 340, 600);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const double height = 40;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBasicBidiStartingWithLtr(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBasicBidiStartingWithLtr(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_ltr');
});
test('basic bidi starting with ltr (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 340, 600);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
const double height = 40;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBasicBidiStartingWithLtr(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBasicBidiStartingWithLtr(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBasicBidiStartingWithLtr(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBasicBidiStartingWithLtr(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_ltr_dom');
});
void paintBasicBidiStartingWithRtl(
EngineCanvas canvas,
Rect bounds,
double y,
TextDirection textDirection,
TextAlign textAlign,
) {
// The text starts with a right-to-left word.
const String text = '$_rtlWord1 12 one 34 $_rtlWord2 56 two';
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textDirection: textDirection,
textAlign: textAlign,
);
final CanvasParagraph paragraph = plain(
paragraphStyle,
text,
textStyle: EngineTextStyle.only(color: blue),
);
final double maxWidth = bounds.width - 10;
paragraph.layout(constrain(maxWidth));
canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5));
}
test('basic bidi starting with rtl', () {
const Rect bounds = Rect.fromLTWH(0, 0, 340, 600);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const double height = 40;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBasicBidiStartingWithRtl(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBasicBidiStartingWithRtl(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_rtl');
});
test('basic bidi starting with rtl (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 340, 600);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
const double height = 40;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 320, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBasicBidiStartingWithRtl(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBasicBidiStartingWithRtl(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(0, ltrBox.height + 10);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBasicBidiStartingWithRtl(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBasicBidiStartingWithRtl(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_start_rtl_dom');
});
void paintMultilineBidi(
EngineCanvas canvas,
Rect bounds,
double y,
TextDirection textDirection,
TextAlign textAlign,
) {
// '''
// Lorem 12 $_rtlWord1
// $_rtlWord2 34 ipsum
// dolor 56
// '''
const String text = 'Lorem 12 $_rtlWord1 $_rtlWord2 34 ipsum dolor 56';
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textDirection: textDirection,
textAlign: textAlign,
);
final CanvasParagraph paragraph = plain(
paragraphStyle,
text,
textStyle: EngineTextStyle.only(color: blue),
);
final double maxWidth = bounds.width - 10;
paragraph.layout(constrain(maxWidth));
canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5));
}
test('multiline bidi', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 500);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const double height = 95;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintMultilineBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintMultilineBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintMultilineBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintMultilineBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintMultilineBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintMultilineBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintMultilineBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintMultilineBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintMultilineBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintMultilineBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multiline');
});
test('multiline bidi (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 500);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
const double height = 95;
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintMultilineBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintMultilineBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintMultilineBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintMultilineBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintMultilineBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintMultilineBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintMultilineBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintMultilineBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintMultilineBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintMultilineBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multiline_dom');
});
void paintMultSpanBidi(
EngineCanvas canvas,
Rect bounds,
double y,
TextDirection textDirection,
TextAlign textAlign,
) {
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textDirection: textDirection,
textAlign: textAlign,
);
// '''
// Lorem 12 $_rtlWord1
// $_rtlWord2 34 ipsum
// dolor 56
// '''
final CanvasParagraph paragraph = rich(paragraphStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('12 ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('$_rtlWord1 ');
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('$_rtlWord2 ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('34 ipsum ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor 56 ');
});
final double maxWidth = bounds.width - 10;
paragraph.layout(constrain(maxWidth));
canvas.drawParagraph(paragraph, Offset(bounds.left + 5, bounds.top + y + 5));
}
test('multi span bidi', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 900);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const double height = 95;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintMultSpanBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintMultSpanBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintMultSpanBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintMultSpanBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintMultSpanBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintMultSpanBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintMultSpanBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintMultSpanBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintMultSpanBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintMultSpanBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multispan');
});
test('multi span bidi (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 900);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
const double height = 95;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintMultSpanBidi(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintMultSpanBidi(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintMultSpanBidi(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintMultSpanBidi(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintMultSpanBidi(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintMultSpanBidi(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintMultSpanBidi(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintMultSpanBidi(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintMultSpanBidi(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintMultSpanBidi(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_multispan_dom');
});
void paintBidiWithSelection(
EngineCanvas canvas,
Rect bounds,
double y,
TextDirection textDirection,
TextAlign textAlign,
) {
// '''
// Lorem 12 $_rtlWord1
// $_rtlWord2 34 ipsum
// dolor 56
// '''
const String text = 'Lorem 12 $_rtlWord1 $_rtlWord2 34 ipsum dolor 56';
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textDirection: textDirection,
textAlign: textAlign,
);
final CanvasParagraph paragraph = plain(
paragraphStyle,
text,
textStyle: EngineTextStyle.only(color: blue),
);
final double maxWidth = bounds.width - 10;
paragraph.layout(constrain(maxWidth));
final Offset offset = Offset(bounds.left + 5, bounds.top + y + 5);
// Range for "em 12 " and the first character of `_rtlWord1`.
fillBoxes(canvas, offset, paragraph.getBoxesForRange(3, 10), lightBlue);
// Range for the second half of `_rtlWord1` and all of `_rtlWord2` and " 3".
fillBoxes(canvas, offset, paragraph.getBoxesForRange(11, 21), lightPurple);
// Range for "psum dolo".
fillBoxes(canvas, offset, paragraph.getBoxesForRange(24, 33), green);
canvas.drawParagraph(paragraph, offset);
}
test('bidi with selection', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 500);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const double height = 95;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBidiWithSelection(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBidiWithSelection(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBidiWithSelection(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBidiWithSelection(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBidiWithSelection(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBidiWithSelection(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBidiWithSelection(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBidiWithSelection(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBidiWithSelection(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBidiWithSelection(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_selection');
});
test('bidi with selection (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 500);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
const double height = 95;
// Border for ltr paragraphs.
final Rect ltrBox = const Rect.fromLTWH(0, 0, 150, 5 * height).inflate(5).translate(10, 10);
canvas.drawRect(
ltrBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// LTR with different text align values:
paintBidiWithSelection(canvas, ltrBox, 0 * height, TextDirection.ltr, TextAlign.left);
paintBidiWithSelection(canvas, ltrBox, 1 * height, TextDirection.ltr, TextAlign.right);
paintBidiWithSelection(canvas, ltrBox, 2 * height, TextDirection.ltr, TextAlign.center);
paintBidiWithSelection(canvas, ltrBox, 3 * height, TextDirection.ltr, TextAlign.start);
paintBidiWithSelection(canvas, ltrBox, 4 * height, TextDirection.ltr, TextAlign.end);
// Border for rtl paragraphs.
final Rect rtlBox = ltrBox.translate(ltrBox.width + 10, 0);
canvas.drawRect(
rtlBox,
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke,
);
// RTL with different text align values:
paintBidiWithSelection(canvas, rtlBox, 0 * height, TextDirection.rtl, TextAlign.left);
paintBidiWithSelection(canvas, rtlBox, 1 * height, TextDirection.rtl, TextAlign.right);
paintBidiWithSelection(canvas, rtlBox, 2 * height, TextDirection.rtl, TextAlign.center);
paintBidiWithSelection(canvas, rtlBox, 3 * height, TextDirection.rtl, TextAlign.start);
paintBidiWithSelection(canvas, rtlBox, 4 * height, TextDirection.rtl, TextAlign.end);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_bidi_selection_dom');
});
}

View File

@@ -1,652 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math' as math;
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide window;
import '../../common/test_initialization.dart';
import 'helper.dart';
const Rect bounds = Rect.fromLTWH(0, 0, 800, 600);
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
test('paints spans and lines correctly', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
Offset offset = Offset.zero;
CanvasParagraph paragraph;
// Single-line multi-span.
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: green, background: Paint()..color = red));
builder.addText('ipsum ');
builder.pop();
builder.addText('.');
})..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
// Multi-line single-span.
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (CanvasParagraphBuilder builder) {
builder.addText('Lorem ipsum dolor sit');
})..layout(constrain(90.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
// Multi-line multi-span.
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ipsum ');
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = red));
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor ');
builder.pop();
builder.addText('sit');
})..layout(constrain(90.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_general');
});
test('respects alignment', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
Offset offset = Offset.zero;
CanvasParagraph paragraph;
void build(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('ipsum ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('sit');
}
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.left), build)
..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.center), build)
..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.right), build)
..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_align');
});
test('respects alignment in DOM mode', () {
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
Offset offset = Offset.zero;
CanvasParagraph paragraph;
void build(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('ipsum ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('sit');
}
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.left), build)
..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.center), build)
..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto', textAlign: TextAlign.right), build)
..layout(constrain(100.0));
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(0, paragraph.height + 10);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_align_dom');
});
void testAlignAndTransform(EngineCanvas canvas) {
CanvasParagraph paragraph;
void build(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: white));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('ipsum\n');
builder.pushStyle(EngineTextStyle.only(color: yellow));
builder.addText('dolor');
}
void drawParagraphAt(Offset offset, TextAlign align) {
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 20.0, textAlign: align),
build,
)..layout(constrain(150.0));
canvas.save();
canvas.translate(offset.dx, offset.dy);
canvas.rotate(math.pi / 4);
final Rect rect = Rect.fromLTRB(0.0, 0.0, 150.0, paragraph.height);
canvas.drawRect(rect, SurfacePaintData()..color = black.value);
canvas.drawParagraph(paragraph, Offset.zero);
canvas.restore();
}
drawParagraphAt(const Offset(50.0, 0.0), TextAlign.left);
drawParagraphAt(const Offset(150.0, 0.0), TextAlign.center);
drawParagraphAt(const Offset(250.0, 0.0), TextAlign.right);
}
test('alignment and transform', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testAlignAndTransform(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_align_transform');
});
test('alignment and transform (DOM)', () {
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testAlignAndTransform(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_align_transform_dom');
});
void testGiantParagraphStyles(EngineCanvas canvas) {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 80.0),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: yellow, fontSize: 24.0));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: red, fontSize: 32.0));
builder.addText('ipsum');
},
)..layout(constrain(double.infinity));
final Rect rect = Rect.fromLTRB(0.0, 0.0, paragraph.maxIntrinsicWidth, paragraph.height);
canvas.drawRect(rect, SurfacePaintData()..color = black.value);
canvas.drawParagraph(paragraph, Offset.zero);
}
test('giant paragraph style', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testGiantParagraphStyles(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_giant_paragraph_style');
});
test('giant paragraph style (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testGiantParagraphStyles(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_giant_paragraph_style_dom');
});
test('giant font size on the body tag (DOM)', () async {
const Rect bounds = Rect.fromLTWH(0, 0, 600, 200);
// Store the old font size value on the body, and set a gaint font size.
final String oldBodyFontSize = domDocument.body!.style.fontSize;
domDocument.body!.style.fontSize = '100px';
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
Offset offset = const Offset(10.0, 10.0);
final CanvasParagraph paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (
CanvasParagraphBuilder builder,
) {
builder.pushStyle(EngineTextStyle.only(color: yellow, fontSize: 24.0));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: red, fontSize: 48.0));
builder.addText('ipsum');
})..layout(constrain(double.infinity));
final Rect rect = Rect.fromLTWH(
offset.dx,
offset.dy,
paragraph.maxIntrinsicWidth,
paragraph.height,
);
canvas.drawRect(rect, SurfacePaintData()..color = black.value);
canvas.drawParagraph(paragraph, offset);
offset = offset.translate(paragraph.maxIntrinsicWidth, 0.0);
// Add some extra padding between the two paragraphs.
offset = offset.translate(20.0, 0.0);
// Use the same height as the previous paragraph so that the 2 paragraphs
// look nice in the screenshot.
final double placeholderHeight = paragraph.height;
final double placeholderWidth = paragraph.height * 2;
final CanvasParagraph paragraph2 = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.addPlaceholder(
placeholderWidth,
placeholderHeight,
PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
);
})..layout(constrain(double.infinity));
final Rect rect2 = Rect.fromLTWH(
offset.dx,
offset.dy,
paragraph2.maxIntrinsicWidth,
paragraph2.height,
);
canvas.drawRect(rect2, SurfacePaintData()..color = black.value);
canvas.drawParagraph(paragraph2, offset);
// Draw a rect in the placeholder.
// Leave some padding around the placeholder to make the black paragraph
// background visible.
const double padding = 5;
final TextBox placeholderBox = paragraph2.getBoxesForPlaceholders().single;
canvas.drawRect(
placeholderBox.toRect().shift(offset).deflate(padding),
SurfacePaintData()..color = red.value,
);
await takeScreenshot(canvas, bounds, 'canvas_paragraph_giant_body_font_size_dom');
// Restore the old font size value.
domDocument.body!.style.fontSize = oldBodyFontSize;
});
test('paints spans with varying heights/baselines', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
final CanvasParagraph paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (
CanvasParagraphBuilder builder,
) {
builder.pushStyle(EngineTextStyle.only(fontSize: 20.0));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(fontSize: 40.0, background: Paint()..color = green));
builder.addText('ipsum ');
builder.pushStyle(
EngineTextStyle.only(fontSize: 10.0, color: white, background: Paint()..color = black),
);
builder.addText('dolor ');
builder.pushStyle(EngineTextStyle.only(fontSize: 30.0));
builder.addText('sit ');
builder.pop();
builder.pop();
builder.pushStyle(EngineTextStyle.only(fontSize: 20.0, background: Paint()..color = blue));
builder.addText('amet');
})..layout(constrain(220.0));
canvas.drawParagraph(paragraph, Offset.zero);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_varying_heights');
});
test('respects letter-spacing', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
final CanvasParagraph paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (
CanvasParagraphBuilder builder,
) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: green, letterSpacing: 1));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: red, letterSpacing: 3));
builder.addText('Lorem');
})..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_letter_spacing');
});
test('letter-spacing Thai', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const String yes = '\u0e43\u0e0a\u0e48';
const String no = '\u0e44\u0e21\u0e48';
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 36),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('$yes $no ');
builder.pushStyle(EngineTextStyle.only(color: green, letterSpacing: 1));
builder.addText('$yes $no ');
builder.pushStyle(EngineTextStyle.only(color: red, letterSpacing: 3));
builder.addText('$yes $no');
},
)..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, const Offset(20, 20));
return takeScreenshot(canvas, bounds, 'canvas_paragraph_letter_spacing_thai');
});
test('draws text decorations', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
final List<TextDecorationStyle> decorationStyles = <TextDecorationStyle>[
TextDecorationStyle.solid,
TextDecorationStyle.double,
TextDecorationStyle.dotted,
TextDecorationStyle.dashed,
TextDecorationStyle.wavy,
];
final CanvasParagraph paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (
CanvasParagraphBuilder builder,
) {
for (final TextDecorationStyle decorationStyle in decorationStyles) {
builder.pushStyle(
EngineTextStyle.only(
color: const Color.fromRGBO(50, 50, 255, 1.0),
decoration: TextDecoration.underline,
decorationStyle: decorationStyle,
decorationColor: red,
fontFamily: 'Roboto',
fontSize: 30,
),
);
builder.addText('Hello World');
builder.pop();
builder.addText(' ');
}
})..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_decoration');
});
void testFontFeatures(EngineCanvas canvas) {
const String text = 'Bb Difficult ';
const FontFeature enableSmallCaps = FontFeature('smcp');
const FontFeature disableSmallCaps = FontFeature('smcp', 0);
const String numeric = '123.4560';
const FontFeature enableOnum = FontFeature('onum');
const FontFeature disableLigatures = FontFeature('liga', 0);
final CanvasParagraph paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (
CanvasParagraphBuilder builder,
) {
// Small Caps
builder.pushStyle(EngineTextStyle.only(height: 1.5, color: black, fontSize: 32.0));
builder.pushStyle(
EngineTextStyle.only(color: blue, fontFeatures: <FontFeature>[enableSmallCaps]),
);
builder.addText(text);
// Make sure disabling a font feature also works.
builder.pushStyle(
EngineTextStyle.only(color: black, fontFeatures: <FontFeature>[disableSmallCaps]),
);
builder.addText(' (smcp)\n');
builder.pop(); // disableSmallCaps
builder.pop(); // enableSmallCaps
// No ligatures
builder.pushStyle(
EngineTextStyle.only(color: blue, fontFeatures: <FontFeature>[disableLigatures]),
);
builder.addText(text);
builder.pop(); // disableLigatures
builder.addText(' (no liga)\n');
// No font features
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText(text);
builder.pop(); // color: blue
builder.addText(' (none)\n');
// Onum
builder.pushStyle(EngineTextStyle.only(color: blue, fontFeatures: <FontFeature>[enableOnum]));
builder.addText(numeric);
builder.pop(); // enableOnum
builder.addText(' (onum)\n');
// No font features
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText(numeric);
builder.pop(); // color: blue
builder.addText(' (none)\n\n');
// Multiple font features
builder.addText('Combined (smcp, onum):\n');
builder.pushStyle(
EngineTextStyle.only(color: blue, fontFeatures: <FontFeature>[enableSmallCaps, enableOnum]),
);
builder.addText('$text $numeric');
builder.pop(); // enableSmallCaps, enableOnum
})..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('font features', () {
const Rect bounds = Rect.fromLTWH(0, 0, 600, 500);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testFontFeatures(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_font_features');
});
test('font features (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 600, 500);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testFontFeatures(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_font_features_dom');
});
void testFontVariations(EngineCanvas canvas) {
const String text = 'ABCDE 12345\n';
FontVariation weight(double w) => FontVariation('wght', w);
final CanvasParagraph paragraph = rich(EngineParagraphStyle(fontFamily: 'RobotoVariable'), (
CanvasParagraphBuilder builder,
) {
builder.pushStyle(EngineTextStyle.only(fontSize: 48.0));
builder.addText(text);
builder.pushStyle(
EngineTextStyle.only(fontSize: 48.0, fontVariations: <FontVariation>[weight(900)]),
);
builder.addText(text);
builder.pushStyle(
EngineTextStyle.only(fontSize: 48.0, fontVariations: <FontVariation>[weight(200)]),
);
builder.addText(text);
builder.pop();
builder.pop();
builder.pop();
})..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('font variations', () {
const Rect bounds = Rect.fromLTWH(0, 0, 600, 500);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testFontVariations(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_font_variations');
});
test('font variations (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 600, 500);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testFontVariations(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_font_variations_dom');
});
void testBackgroundStyle(EngineCanvas canvas) {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 40.0),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = blue));
builder.addText('Lor');
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = black, color: white));
builder.addText('em ');
builder.pop();
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = green));
builder.addText('ipsu');
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = yellow));
builder.addText('m\ndo');
builder.pushStyle(EngineTextStyle.only(background: Paint()..color = red));
builder.addText('lor sit');
},
);
paragraph.layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('background style', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testBackgroundStyle(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_background_style');
});
test('background style (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testBackgroundStyle(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_background_style_dom');
});
void testForegroundStyle(EngineCanvas canvas) {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 40.0),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem');
builder.pop();
builder.pushStyle(
EngineTextStyle.only(
foreground:
Paint()
..color = red
..style = PaintingStyle.stroke,
),
);
builder.addText('ipsum\n');
builder.pop();
builder.pushStyle(
EngineTextStyle.only(
foreground:
Paint()
..color = blue
..style = PaintingStyle.stroke
..strokeWidth = 0.0,
),
);
builder.addText('dolor');
builder.pop();
builder.pushStyle(
EngineTextStyle.only(
foreground:
Paint()
..color = green
..style = PaintingStyle.stroke
..strokeWidth = 2.0,
),
);
builder.addText('sit\n');
builder.pop();
builder.pushStyle(
EngineTextStyle.only(
foreground:
Paint()
..color = yellow
..style = PaintingStyle.stroke
..strokeWidth = 4.0,
),
);
builder.addText('amet');
},
);
paragraph.layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('foreground style', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testForegroundStyle(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_foreground_style');
});
test('foreground style (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 200);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testForegroundStyle(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_foreground_style_dom');
});
test('paragraph bounds hug the text inside the paragraph', () async {
const Rect bounds = Rect.fromLTWH(0, 0, 150, 100);
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(
EngineParagraphStyle(fontFamily: 'Ahem', fontSize: 20, textAlign: TextAlign.center),
);
// Expected layout with center-alignment is something like this:
//
// _________________
// | A |
// | |AAAAA| |
// | | AAA | |
// |----|-----|----|
// | |<--->| |
// | 100 |
// | |
// |<------------->|
// 110
//
// The width of the paragraph is bigger than the actual content because the
// longest line "AAAAA" is 100px, which is smaller than 110px specified in
// the constraint. After the layout and centering the paint bounds would
// "hug" the text inside the paragraph more tightly than the box allocated
// for the paragraph.
builder.addText('A AAAAA AAA');
final CanvasParagraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 110));
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
canvas.translate(20, 20);
canvas.drawParagraph(paragraph, Offset.zero);
canvas.drawRect(
Rect.fromLTRB(0, 0, paragraph.width, paragraph.height),
SurfacePaintData()
..style = PaintingStyle.stroke
..strokeWidth = 1,
);
canvas.drawRect(
paragraph.paintBounds,
SurfacePaintData()
..color = 0xFF00FF00
..style = PaintingStyle.stroke
..strokeWidth = 1,
);
await takeScreenshot(canvas, bounds, 'canvas_paragraph_bounds');
});
}

View File

@@ -1,102 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
import 'package:web_engine_tester/golden_tester.dart';
typedef CanvasTest = FutureOr<void> Function(EngineCanvas canvas);
const LineBreakType prohibited = LineBreakType.prohibited;
const LineBreakType opportunity = LineBreakType.opportunity;
const LineBreakType mandatory = LineBreakType.mandatory;
const LineBreakType endOfText = LineBreakType.endOfText;
const TextDirection ltr = TextDirection.ltr;
const TextDirection rtl = TextDirection.rtl;
const FragmentFlow ffLtr = FragmentFlow.ltr;
const FragmentFlow ffRtl = FragmentFlow.rtl;
const FragmentFlow ffPrevious = FragmentFlow.previous;
const FragmentFlow ffSandwich = FragmentFlow.sandwich;
const String rtlWord1 = 'واحدة';
const String rtlWord2 = 'ثنتان';
const Color white = Color(0xFFFFFFFF);
const Color black = Color(0xFF000000);
const Color red = Color(0xFFFF0000);
const Color lightGreen = Color(0xFFDCEDC8);
const Color green = Color(0xFF00FF00);
const Color lightBlue = Color(0xFFB3E5FC);
const Color blue = Color(0xFF0000FF);
const Color yellow = Color(0xFFFFEB3B);
const Color lightPurple = Color(0xFFE1BEE7);
final EngineParagraphStyle ahemStyle = EngineParagraphStyle(fontFamily: 'Ahem', fontSize: 10);
ParagraphConstraints constrain(double width) {
return ParagraphConstraints(width: width);
}
CanvasParagraph plain(EngineParagraphStyle style, String text, {EngineTextStyle? textStyle}) {
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
if (textStyle != null) {
builder.pushStyle(textStyle);
}
builder.addText(text);
return builder.build();
}
CanvasParagraph rich(EngineParagraphStyle style, void Function(CanvasParagraphBuilder) callback) {
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
callback(builder);
return builder.build();
}
Future<void> takeScreenshot(EngineCanvas canvas, Rect region, String fileName) async {
final DomElement sceneElement = createDomElement('flt-scene');
if (isIosSafari) {
// Shrink to fit on the iPhone screen.
sceneElement.style.position = 'absolute';
sceneElement.style.transformOrigin = '0 0 0';
sceneElement.style.transform = 'scale(0.3)';
}
try {
sceneElement.append(canvas.rootElement);
domDocument.body!.append(sceneElement);
await matchGoldenFile('$fileName.png', region: region);
} finally {
// The page is reused across tests, so remove the element after taking the
// screenshot.
sceneElement.remove();
}
}
/// Fills the single placeholder in the given [paragraph] with a red rectangle.
///
/// The placeholder is filled relative to [offset].
///
/// Throws if the paragraph contains more than one placeholder.
void fillPlaceholder(EngineCanvas canvas, Offset offset, CanvasParagraph paragraph) {
final TextBox placeholderBox = paragraph.getBoxesForPlaceholders().single;
final SurfacePaint paint = SurfacePaint()..color = red;
canvas.drawRect(placeholderBox.toRect().shift(offset), paint.paintData);
}
/// Fill the given [boxes] with rectangles of the given [color].
///
/// All rectangles are filled relative to [offset].
void fillBoxes(EngineCanvas canvas, Offset offset, List<TextBox> boxes, Color color) {
for (final TextBox box in boxes) {
final Rect rect = box.toRect().shift(offset);
canvas.drawRect(rect, SurfacePaintData()..color = color.value);
}
}
String getSpanText(CanvasParagraph paragraph, ParagraphSpan span) {
return paragraph.plainText.substring(span.start, span.end);
}

View File

@@ -1,301 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide window;
import '../../common/test_initialization.dart';
import 'helper.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
void testJustifyWithMultipleSpans(EngineCanvas canvas) {
void build(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('Lorem ipsum dolor sit ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('amet, consectetur ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('adipiscing elit, sed do eiusmod tempor incididunt ut ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('labore et dolore magna aliqua. Ut enim ad minim veniam, ');
builder.pushStyle(EngineTextStyle.only(color: lightPurple));
builder.addText('quis nostrud exercitation ullamco ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('laboris nisi ut aliquip ex ea commodo consequat.');
}
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify),
build,
);
paragraph.layout(constrain(250.0));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('TextAlign.justify with multiple spans', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testJustifyWithMultipleSpans(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify');
});
test('TextAlign.justify with multiple spans (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testJustifyWithMultipleSpans(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_dom');
});
void testJustifyWithEmptyLine(EngineCanvas canvas) {
void build(CanvasParagraphBuilder builder) {
builder.pushStyle(bg(yellow));
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('Loremipsumdolorsit');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('amet, consectetur\n\n');
builder.pushStyle(EngineTextStyle.only(color: lightPurple));
builder.addText('adipiscing elit, sed do eiusmod tempor incididunt ut ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('labore et dolore magna aliqua.');
}
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify),
build,
);
paragraph.layout(constrain(250.0));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('TextAlign.justify with single space and empty line', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testJustifyWithEmptyLine(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_empty_line');
});
test('TextAlign.justify with single space and empty line (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testJustifyWithEmptyLine(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_empty_line_dom');
});
void testJustifyWithEllipsis(EngineCanvas canvas) {
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textAlign: TextAlign.justify,
maxLines: 4,
ellipsis: '...',
);
final CanvasParagraph paragraph = rich(paragraphStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('Lorem ipsum dolor sit ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('amet, consectetur ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('adipiscing elit, sed do eiusmod tempor incididunt ut ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('labore et dolore magna aliqua. Ut enim ad minim veniam, ');
builder.pushStyle(EngineTextStyle.only(color: lightPurple));
builder.addText('quis nostrud exercitation ullamco ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('laboris nisi ut aliquip ex ea commodo consequat.');
});
paragraph.layout(constrain(250));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('TextAlign.justify with ellipsis', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 300);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testJustifyWithEllipsis(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_ellipsis');
});
test('TextAlign.justify with ellipsis (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 300);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testJustifyWithEllipsis(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_ellipsis_dom');
});
void testJustifyWithBackground(EngineCanvas canvas) {
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Roboto',
fontSize: 20.0,
textAlign: TextAlign.justify,
);
final CanvasParagraph paragraph = rich(paragraphStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.pushStyle(bg(blue));
builder.addText('Lorem ipsum dolor sit ');
builder.pushStyle(bg(black));
builder.pushStyle(EngineTextStyle.only(color: white));
builder.addText('amet, consectetur ');
builder.pop();
builder.pushStyle(bg(green));
builder.addText('adipiscing elit, sed do eiusmod tempor incididunt ut ');
builder.pushStyle(bg(yellow));
builder.addText('labore et dolore magna aliqua. Ut enim ad minim veniam, ');
builder.pushStyle(bg(red));
builder.addText('quis nostrud exercitation ullamco ');
builder.pushStyle(bg(green));
builder.addText('laboris nisi ut aliquip ex ea commodo consequat.');
});
paragraph.layout(constrain(250));
canvas.drawParagraph(paragraph, Offset.zero);
}
test('TextAlign.justify with background', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testJustifyWithBackground(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_background');
});
test('TextAlign.justify with background (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testJustifyWithBackground(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_background_dom');
});
void testJustifyWithPlaceholder(EngineCanvas canvas) {
void build(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('Lorem ipsum dolor sit ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('amet, consectetur ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('adipiscing elit, sed do ');
builder.addPlaceholder(40, 40, PlaceholderAlignment.bottom);
builder.addText(' eiusmod tempor incididunt ut ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('labore et dolore magna aliqua.');
}
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify),
build,
);
paragraph.layout(constrain(250.0));
canvas.drawParagraph(paragraph, Offset.zero);
fillPlaceholder(canvas, Offset.zero, paragraph);
}
test('TextAlign.justify with placeholder', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testJustifyWithPlaceholder(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_placeholder');
});
test('TextAlign.justify with placeholder (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testJustifyWithPlaceholder(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_placeholder_dom');
});
void testJustifyWithSelection(EngineCanvas canvas) {
void build(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('Lorem ipsum dolor sit ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('amet, consectetur '); // 40
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('adipiscing elit, sed do eiusmod tempor incididunt ut ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('labore et dolore magna aliqua.');
}
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify),
build,
);
paragraph.layout(constrain(250.0));
// Draw selection for "em ipsum d".
fillBoxes(canvas, Offset.zero, paragraph.getBoxesForRange(3, 13), lightBlue);
// Draw selection for " ut labore et dolore mag".
fillBoxes(canvas, Offset.zero, paragraph.getBoxesForRange(89, 113), lightPurple);
canvas.drawParagraph(paragraph, Offset.zero);
}
test('TextAlign.justify with selection', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testJustifyWithSelection(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_selection');
});
test('TextAlign.justify with selection (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testJustifyWithSelection(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_selection_dom');
});
void testJustifyRtl(EngineCanvas canvas) {
const String rtlWord = 'مرحبا';
void build(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('Lorem $rtlWord dolor sit ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('amet, consectetur '); // 40
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('adipiscing elit, sed do eiusmod $rtlWord incididunt ut ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('labore et dolore magna aliqua.');
}
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 20.0, textAlign: TextAlign.justify),
build,
);
paragraph.layout(constrain(250.0));
// Draw selection for "em $rtlWord d".
fillBoxes(canvas, Offset.zero, paragraph.getBoxesForRange(3, 13), lightBlue);
// Draw selection for " ut labore et dolore mag".
fillBoxes(canvas, Offset.zero, paragraph.getBoxesForRange(89, 113), lightPurple);
canvas.drawParagraph(paragraph, Offset.zero);
}
test('TextAlign.justify rtl', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testJustifyRtl(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_rtl');
});
test('TextAlign.justify rtl (DOM)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 400, 400);
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testJustifyRtl(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_justify_rtl_dom');
});
}
EngineTextStyle bg(Color color) {
return EngineTextStyle.only(background: Paint()..color = color);
}

View File

@@ -1,132 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide window;
import '../../common/test_initialization.dart';
import 'helper.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
void testEllipsis(EngineCanvas canvas) {
Offset offset = Offset.zero;
CanvasParagraph paragraph;
const double fontSize = 22.0;
const double width = 126.0;
const double padding = 20.0;
final SurfacePaintData borderPaint =
SurfacePaintData()
..color = black.value
..style = PaintingStyle.stroke;
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: fontSize, ellipsis: '...'),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('ipsum');
},
)..layout(constrain(width));
canvas.drawParagraph(paragraph, offset);
canvas.drawRect(Rect.fromLTWH(offset.dx, offset.dy, width, paragraph.height), borderPaint);
offset = offset.translate(0, paragraph.height + padding);
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: fontSize, ellipsis: '...'),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem\n');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('ipsum ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('dolor sit');
},
)..layout(constrain(width));
canvas.drawParagraph(paragraph, offset);
canvas.drawRect(Rect.fromLTWH(offset.dx, offset.dy, width, paragraph.height), borderPaint);
offset = offset.translate(0, paragraph.height + padding);
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: fontSize, ellipsis: '...'),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem\n');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('ipsum ');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('d');
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('o');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('l');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('o');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('r');
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText(' ');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('s');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('i');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('t');
},
)..layout(constrain(width));
canvas.drawParagraph(paragraph, offset);
canvas.drawRect(Rect.fromLTWH(offset.dx, offset.dy, width, paragraph.height), borderPaint);
offset = offset.translate(0, paragraph.height + padding);
paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: fontSize, maxLines: 2, ellipsis: '...'),
(CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('ipsu');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('mdolor');
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('sit');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('amet');
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('consectetur');
},
)..layout(constrain(width));
canvas.drawParagraph(paragraph, offset);
canvas.drawRect(Rect.fromLTWH(offset.dx, offset.dy, width, paragraph.height), borderPaint);
offset = offset.translate(0, paragraph.height + padding);
}
test('ellipsis', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 300);
final EngineCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
testEllipsis(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_ellipsis');
});
test('ellipsis (dom)', () {
const Rect bounds = Rect.fromLTWH(0, 0, 300, 300);
final EngineCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
testEllipsis(canvas);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_ellipsis_dom');
});
}

View File

@@ -1,203 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide window;
import '../../common/test_initialization.dart';
import 'helper.dart';
const Rect bounds = Rect.fromLTWH(0, 0, 800, 600);
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
test('draws paragraphs with placeholders', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
Offset offset = Offset.zero;
for (final PlaceholderAlignment placeholderAlignment in PlaceholderAlignment.values) {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 14.0),
(CanvasParagraphBuilder builder) {
builder.pushStyle(TextStyle(color: black));
builder.addText('Lorem ipsum');
builder.addPlaceholder(
80.0,
50.0,
placeholderAlignment,
baselineOffset: 40.0,
baseline: TextBaseline.alphabetic,
);
builder.pushStyle(TextStyle(color: blue));
builder.addText('dolor sit amet, consecteur.');
},
)..layout(constrain(200.0));
// Draw the paragraph.
canvas.drawParagraph(paragraph, offset);
// Then fill the placeholders.
fillPlaceholder(canvas, offset, paragraph);
offset = offset.translate(0.0, paragraph.height + 30.0);
}
return takeScreenshot(canvas, bounds, 'canvas_paragraph_placeholders');
});
test('draws paragraphs with placeholders and text align', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
const List<TextAlign> aligns = <TextAlign>[TextAlign.left, TextAlign.center, TextAlign.right];
Offset offset = Offset.zero;
for (final TextAlign align in aligns) {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 14.0, textAlign: align),
(CanvasParagraphBuilder builder) {
builder.pushStyle(TextStyle(color: black));
builder.addText('Lorem');
builder.addPlaceholder(80.0, 50.0, PlaceholderAlignment.bottom);
builder.pushStyle(TextStyle(color: blue));
builder.addText('ipsum.');
},
)..layout(constrain(200.0));
// Draw the paragraph.
canvas.drawParagraph(paragraph, offset);
// Then fill the placeholders.
fillPlaceholder(canvas, offset, paragraph);
offset = offset.translate(0.0, paragraph.height + 30.0);
}
return takeScreenshot(canvas, bounds, 'canvas_paragraph_placeholders_align');
});
test('draws paragraphs with placeholders and text align in DOM mode', () {
final DomCanvas canvas = DomCanvas(domDocument.createElement('flt-picture'));
const List<TextAlign> aligns = <TextAlign>[TextAlign.left, TextAlign.center, TextAlign.right];
Offset offset = Offset.zero;
for (final TextAlign align in aligns) {
final CanvasParagraph paragraph = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 14.0, textAlign: align),
(CanvasParagraphBuilder builder) {
builder.pushStyle(TextStyle(color: black));
builder.addText('Lorem');
builder.addPlaceholder(80.0, 50.0, PlaceholderAlignment.bottom);
builder.pushStyle(TextStyle(color: blue));
builder.addText('ipsum.');
},
)..layout(constrain(200.0));
// Draw the paragraph.
canvas.drawParagraph(paragraph, offset);
// Then fill the placeholders.
fillPlaceholder(canvas, offset, paragraph);
offset = offset.translate(0.0, paragraph.height + 30.0);
}
return takeScreenshot(canvas, bounds, 'canvas_paragraph_placeholders_align_dom');
});
test('draws paragraphs starting or ending with a placeholder', () {
const Rect bounds = Rect.fromLTWH(0, 0, 420, 300);
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
Offset offset = const Offset(10, 10);
// First paragraph with a placeholder at the beginning.
final CanvasParagraph paragraph1 = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 24.0, textAlign: TextAlign.center),
(CanvasParagraphBuilder builder) {
builder.addPlaceholder(
80.0,
50.0,
PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
);
builder.pushStyle(TextStyle(color: black));
builder.addText(' Lorem ipsum.');
},
)..layout(constrain(400.0));
// Draw the paragraph.
canvas.drawParagraph(paragraph1, offset);
fillPlaceholder(canvas, offset, paragraph1);
surroundParagraph(canvas, offset, paragraph1);
offset = offset.translate(0.0, paragraph1.height + 30.0);
// Second paragraph with a placeholder at the end.
final CanvasParagraph paragraph2 = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 24.0, textAlign: TextAlign.center),
(CanvasParagraphBuilder builder) {
builder.pushStyle(TextStyle(color: black));
builder.addText('Lorem ipsum ');
builder.addPlaceholder(
80.0,
50.0,
PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
);
},
)..layout(constrain(400.0));
// Draw the paragraph.
canvas.drawParagraph(paragraph2, offset);
fillPlaceholder(canvas, offset, paragraph2);
surroundParagraph(canvas, offset, paragraph2);
offset = offset.translate(0.0, paragraph2.height + 30.0);
// Third paragraph with a placeholder alone in the second line.
final CanvasParagraph paragraph3 = rich(
EngineParagraphStyle(fontFamily: 'Roboto', fontSize: 24.0, textAlign: TextAlign.center),
(CanvasParagraphBuilder builder) {
builder.pushStyle(TextStyle(color: black));
builder.addText('Lorem ipsum ');
builder.addPlaceholder(
80.0,
50.0,
PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
);
},
)..layout(constrain(200.0));
// Draw the paragraph.
canvas.drawParagraph(paragraph3, offset);
fillPlaceholder(canvas, offset, paragraph3);
surroundParagraph(canvas, offset, paragraph3);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_placeholders_start_and_end');
});
}
void surroundParagraph(EngineCanvas canvas, Offset offset, CanvasParagraph paragraph) {
final Rect rect = offset & Size(paragraph.width, paragraph.height);
final SurfacePaint paint =
SurfacePaint()
..color = blue
..style = PaintingStyle.stroke;
canvas.drawRect(rect, paint.paintData);
}

View File

@@ -1,58 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide window;
import '../../common/test_initialization.dart';
import 'helper.dart';
const Rect bounds = Rect.fromLTWH(0, 0, 800, 600);
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
test('paints multiple shadows', () {
final BitmapCanvas canvas = BitmapCanvas(bounds, RenderStrategy());
final CanvasParagraph paragraph = rich(EngineParagraphStyle(fontFamily: 'Roboto'), (
CanvasParagraphBuilder builder,
) {
builder.pushStyle(
EngineTextStyle.only(
fontSize: 32.0,
color: blue,
shadows: <Shadow>[
const Shadow(color: red, blurRadius: 2.0, offset: Offset(4.0, 2.0)),
const Shadow(color: green, blurRadius: 3.0),
],
),
);
builder.addText('Lorem ');
builder.pushStyle(
EngineTextStyle.only(
color: green,
background: Paint()..color = yellow,
shadows: <Shadow>[const Shadow(blurRadius: 10.0)],
),
);
builder.addText('ipsum');
builder.pop();
builder.addText('dolor.');
})..layout(constrain(double.infinity));
canvas.drawParagraph(paragraph, Offset.zero);
return takeScreenshot(canvas, bounds, 'canvas_paragraph_shadows');
});
}

View File

@@ -1,101 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:web_engine_tester/golden_tester.dart';
import 'helper.dart';
/// Class that controls some details of how screenshotting is made.
class EngineGoldenTester {
EngineGoldenTester(this.viewportSize);
/// The size of the browser window used in this golden test.
final ui.Size viewportSize;
static Future<EngineGoldenTester> initialize({
ui.Size viewportSize = const ui.Size(2400, 1800),
}) async {
assert(() {
if (viewportSize.width.ceil() != viewportSize.width ||
viewportSize.height.ceil() != viewportSize.height) {
throw Exception('Gold only supports integer screen sizes, but found: $viewportSize');
}
return true;
}());
return EngineGoldenTester(viewportSize);
}
ui.Rect get viewportRegion => ui.Rect.fromLTWH(0, 0, viewportSize.width, viewportSize.height);
Future<void> diffScreenshot(String fileName, {ui.Rect? region}) async {
await matchGoldenFile('$fileName.png', region: region ?? viewportRegion);
}
/// Prepares the DOM and inserts all the necessary nodes, then invokes Gold's
/// screenshot diffing.
///
/// It also cleans up the DOM after itself.
Future<void> diffCanvasScreenshot(EngineCanvas canvas, String fileName, {ui.Rect? region}) async {
// Wrap in <flt-scene> so that our CSS selectors kick in.
final DomElement sceneElement = createDomElement('flt-scene');
if (isIosSafari) {
// Shrink to fit on the iPhone screen.
sceneElement.style.position = 'absolute';
sceneElement.style.transformOrigin = '0 0 0';
sceneElement.style.transform = 'scale(0.3)';
}
try {
sceneElement.append(canvas.rootElement);
domDocument.body!.append(sceneElement);
String screenshotName = '${fileName}_${canvas.runtimeType}';
if (canvas is BitmapCanvas) {
screenshotName += '+canvas_measurement';
}
await diffScreenshot(screenshotName, region: region);
} finally {
// The page is reused across tests, so remove the element after taking the
// screenshot.
sceneElement.remove();
}
}
}
/// Runs the given test [body] with each type of canvas.
void testEachCanvas(String description, CanvasTest body) {
const ui.Rect bounds = ui.Rect.fromLTWH(0, 0, 600, 800);
test('$description (bitmap + canvas measurement)', () async {
return body(BitmapCanvas(bounds, RenderStrategy()));
});
test('$description (dom)', () {
return body(DomCanvas(domDocument.createElement('flt-picture')));
});
}
final ui.TextStyle _defaultTextStyle = ui.TextStyle(
color: const ui.Color(0xFF000000),
fontFamily: 'Roboto',
fontSize: 14,
);
CanvasParagraph paragraph(
String text, {
ui.ParagraphStyle? paragraphStyle,
ui.TextStyle? textStyle,
double maxWidth = double.infinity,
}) {
final ui.ParagraphBuilder builder = ui.ParagraphBuilder(paragraphStyle ?? ui.ParagraphStyle());
builder.pushStyle(textStyle ?? _defaultTextStyle);
builder.addText(text);
builder.pop();
final CanvasParagraph paragraph = builder.build() as CanvasParagraph;
paragraph.layout(ui.ParagraphConstraints(width: maxWidth));
return paragraph;
}

View File

@@ -1,190 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:test/bootstrap/browser.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
import '../../common/test_initialization.dart';
import 'text_goldens.dart';
typedef PaintTest = void Function(RecordingCanvas recordingCanvas);
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
final EngineGoldenTester goldenTester = await EngineGoldenTester.initialize(
viewportSize: const Size(600, 600),
);
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
void paintTest(EngineCanvas canvas, PaintTest painter) {
const Rect screenRect = Rect.fromLTWH(0, 0, 600, 600);
final RecordingCanvas recordingCanvas = RecordingCanvas(screenRect);
painter(recordingCanvas);
recordingCanvas.endRecording();
recordingCanvas.apply(canvas, screenRect);
}
testEachCanvas('clips multiline text against rectangle', (EngineCanvas canvas) {
// [DomCanvas] doesn't support clip commands.
if (canvas is! DomCanvas) {
paintTest(canvas, paintTextWithClipRect);
return goldenTester.diffCanvasScreenshot(canvas, 'multiline_text_clipping_rect');
}
return null;
});
testEachCanvas('clips multiline text against rectangle with transform', (EngineCanvas canvas) {
// [DomCanvas] doesn't support clip commands.
if (canvas is! DomCanvas) {
paintTest(canvas, paintTextWithClipRectTranslated);
return goldenTester.diffCanvasScreenshot(canvas, 'multiline_text_clipping_rect_translate');
}
return null;
});
testEachCanvas('clips multiline text against round rectangle', (EngineCanvas canvas) {
// [DomCanvas] doesn't support clip commands.
if (canvas is! DomCanvas) {
paintTest(canvas, paintTextWithClipRoundRect);
return goldenTester.diffCanvasScreenshot(canvas, 'multiline_text_clipping_roundrect');
}
return null;
});
testEachCanvas('clips multiline text against path', (EngineCanvas canvas) {
// [DomCanvas] doesn't support clip commands.
if (canvas is! DomCanvas) {
paintTest(canvas, paintTextWithClipPath);
return goldenTester.diffCanvasScreenshot(canvas, 'multiline_text_clipping_path');
}
return null;
});
testEachCanvas('clips multiline text against stack of rects', (EngineCanvas canvas) {
// [DomCanvas] doesn't support clip commands.
if (canvas is! DomCanvas) {
paintTest(canvas, paintTextWithClipStack);
return goldenTester.diffCanvasScreenshot(canvas, 'multiline_text_clipping_stack1');
}
return null;
});
}
const Rect testBounds = Rect.fromLTRB(50, 50, 230, 220);
void drawBackground(RecordingCanvas canvas) {
canvas.drawRect(
testBounds,
SurfacePaint()
..style = PaintingStyle.fill
..color = const Color(0xFF9E9E9E),
);
canvas.drawRect(
testBounds.inflate(-40),
SurfacePaint()
..strokeWidth = 1
..style = PaintingStyle.stroke
..color = const Color(0xFF009688),
);
}
void drawQuickBrownFox(RecordingCanvas canvas) {
canvas.drawParagraph(
paragraph(
'The quick brown fox jumps over the lazy dog',
textStyle: TextStyle(
color: const Color(0xFF000000),
decoration: TextDecoration.none,
fontFamily: 'Roboto',
fontSize: 30,
background: Paint()..color = const Color.fromRGBO(50, 255, 50, 1.0),
),
maxWidth: 180,
),
Offset(testBounds.left, testBounds.top),
);
}
void paintTextWithClipRect(RecordingCanvas canvas) {
drawBackground(canvas);
canvas.clipRect(testBounds.inflate(-40), ClipOp.intersect);
drawQuickBrownFox(canvas);
}
void paintTextWithClipRectTranslated(RecordingCanvas canvas) {
drawBackground(canvas);
canvas.clipRect(testBounds.inflate(-40), ClipOp.intersect);
canvas.translate(30, 10);
drawQuickBrownFox(canvas);
}
const Color deepOrange = Color(0xFFFF5722);
void paintTextWithClipRoundRect(RecordingCanvas canvas) {
final RRect roundRect = RRect.fromRectAndCorners(
testBounds.inflate(-40),
topRight: const Radius.elliptical(45, 40),
bottomLeft: const Radius.elliptical(50, 40),
bottomRight: const Radius.circular(30),
);
drawBackground(canvas);
canvas.drawRRect(
roundRect,
SurfacePaint()
..color = deepOrange
..style = PaintingStyle.fill,
);
canvas.clipRRect(roundRect);
drawQuickBrownFox(canvas);
}
void paintTextWithClipPath(RecordingCanvas canvas) {
drawBackground(canvas);
final Path path = Path();
const double delta = 40.0;
final Rect clipBounds = testBounds.inflate(-delta);
final double midX = (clipBounds.left + clipBounds.right) / 2.0;
final double midY = (clipBounds.top + clipBounds.bottom) / 2.0;
path.moveTo(clipBounds.left - delta, midY);
path.quadraticBezierTo(midX, midY, midX, clipBounds.top - delta);
path.quadraticBezierTo(midX, midY, clipBounds.right + delta, midY);
path.quadraticBezierTo(midX, midY, midX, clipBounds.bottom + delta);
path.quadraticBezierTo(midX, midY, clipBounds.left - delta, midY);
path.close();
canvas.drawPath(
path,
SurfacePaint()
..color = deepOrange
..style = PaintingStyle.fill,
);
canvas.clipPath(path);
drawQuickBrownFox(canvas);
}
void paintTextWithClipStack(RecordingCanvas canvas) {
drawBackground(canvas);
final Rect inflatedRect = testBounds.inflate(-40);
canvas.clipRect(inflatedRect, ClipOp.intersect);
canvas.rotate(math.pi / 8.0);
canvas.translate(40, -40);
canvas.clipRect(inflatedRect, ClipOp.intersect);
canvas.drawRect(
inflatedRect,
SurfacePaint()
..color = deepOrange
..style = PaintingStyle.fill,
);
drawQuickBrownFox(canvas);
}

View File

@@ -1,59 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:test/bootstrap/browser.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' hide window;
import '../../common/test_initialization.dart';
import 'text_goldens.dart';
const String threeLines = 'First\nSecond\nThird';
const String veryLong =
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
final EngineGoldenTester goldenTester = await EngineGoldenTester.initialize(
viewportSize: const Size(800, 800),
);
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
testEachCanvas('maxLines clipping', (EngineCanvas canvas) {
Offset offset = Offset.zero;
CanvasParagraph p;
// All three lines are rendered.
p = paragraph(threeLines);
canvas.drawParagraph(p, offset);
offset = offset.translate(0, p.height + 10);
// Only the first two lines are rendered.
p = paragraph(threeLines, paragraphStyle: ParagraphStyle(maxLines: 2));
canvas.drawParagraph(p, offset);
offset = offset.translate(0, p.height + 10);
// The whole text is rendered.
p = paragraph(veryLong, maxWidth: 200);
canvas.drawParagraph(p, offset);
offset = offset.translate(0, p.height + 10);
// Only the first two lines are rendered.
p = paragraph(veryLong, paragraphStyle: ParagraphStyle(maxLines: 2), maxWidth: 200);
canvas.drawParagraph(p, offset);
offset = offset.translate(0, p.height + 10);
return goldenTester.diffCanvasScreenshot(canvas, 'text_max_lines');
});
}

View File

@@ -1,125 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
import '../../common/test_initialization.dart';
import 'helper.dart';
import 'text_goldens.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
final EngineGoldenTester goldenTester = await EngineGoldenTester.initialize(
viewportSize: const Size(600, 600),
);
setUpUnitTests(
withImplicitView: true,
emulateTesterEnvironment: false,
setUpTestViewDimensions: false,
);
testEachCanvas('draws paragraphs with placeholders', (EngineCanvas canvas) {
const Rect screenRect = Rect.fromLTWH(0, 0, 600, 600);
final RecordingCanvas recordingCanvas = RecordingCanvas(screenRect);
Offset offset = Offset.zero;
for (final PlaceholderAlignment placeholderAlignment in PlaceholderAlignment.values) {
_paintTextWithPlaceholder(
recordingCanvas,
offset,
before: 'Lorem ipsum',
after: 'dolor sit amet, consectetur.',
placeholderAlignment: placeholderAlignment,
);
offset = offset.translate(0.0, 80.0);
}
recordingCanvas.endRecording();
recordingCanvas.apply(canvas, screenRect);
return goldenTester.diffCanvasScreenshot(canvas, 'text_with_placeholders');
});
testEachCanvas('text alignment and placeholders', (EngineCanvas canvas) {
const Rect screenRect = Rect.fromLTWH(0, 0, 600, 600);
final RecordingCanvas recordingCanvas = RecordingCanvas(screenRect);
Offset offset = Offset.zero;
_paintTextWithPlaceholder(
recordingCanvas,
offset,
before: 'Lorem',
after: 'ipsum.',
textAlignment: TextAlign.start,
);
offset = offset.translate(0.0, 80.0);
_paintTextWithPlaceholder(
recordingCanvas,
offset,
before: 'Lorem',
after: 'ipsum.',
textAlignment: TextAlign.center,
);
offset = offset.translate(0.0, 80.0);
_paintTextWithPlaceholder(
recordingCanvas,
offset,
before: 'Lorem',
after: 'ipsum.',
textAlignment: TextAlign.end,
);
recordingCanvas.endRecording();
recordingCanvas.apply(canvas, screenRect);
return goldenTester.diffCanvasScreenshot(canvas, 'text_align_with_placeholders');
});
}
const Size placeholderSize = Size(80.0, 50.0);
void _paintTextWithPlaceholder(
RecordingCanvas canvas,
Offset offset, {
required String before,
required String after,
PlaceholderAlignment placeholderAlignment = PlaceholderAlignment.baseline,
TextAlign textAlignment = TextAlign.left,
}) {
// First let's draw the paragraph.
final Paragraph paragraph = _createParagraphWithPlaceholder(
before,
after,
placeholderAlignment,
textAlignment,
);
canvas.drawParagraph(paragraph, offset);
// Then fill the placeholders.
final TextBox placeholderBox = paragraph.getBoxesForPlaceholders().single;
canvas.drawRect(placeholderBox.toRect().shift(offset), SurfacePaint()..color = red);
}
Paragraph _createParagraphWithPlaceholder(
String before,
String after,
PlaceholderAlignment placeholderAlignment,
TextAlign textAlignment,
) {
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(textAlign: textAlignment));
builder.pushStyle(TextStyle(color: black, fontFamily: 'Roboto', fontSize: 14));
builder.addText(before);
builder.addPlaceholder(
placeholderSize.width,
placeholderSize.height,
placeholderAlignment,
baselineOffset: 40.0,
baseline: TextBaseline.alphabetic,
);
builder.pushStyle(TextStyle(color: blue, fontFamily: 'Roboto', fontSize: 14));
builder.addText(after);
return builder.build()..layout(const ParagraphConstraints(width: 200.0));
}

View File

@@ -1,542 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../../common/test_initialization.dart';
import '../paragraph/helper.dart';
/// Some text measurements are sensitive to browser implementations. Position
/// info in the following tests only pass in Chrome, they are slightly different
/// on each browser. So we need to ignore position info on non-Chrome browsers
/// when comparing expectations with actual output.
bool get isBlink => ui_web.browser.browserEngine == ui_web.BrowserEngine.blink;
String fontFamilyToAttribute(String fontFamily) {
fontFamily = canonicalizeFontFamily(fontFamily)!;
if (ui_web.browser.browserEngine == ui_web.BrowserEngine.firefox) {
return fontFamily.replaceAll('"', '&quot;');
} else if (ui_web.browser.browserEngine == ui_web.BrowserEngine.blink ||
ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit) {
return fontFamily.replaceAll('"', '');
}
return fontFamily;
}
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(withImplicitView: true);
test('empty paragraph', () {
final CanvasParagraph paragraph1 = rich(
EngineParagraphStyle(),
(CanvasParagraphBuilder builder) {},
);
expect(paragraph1.plainText, '');
expect(paragraph1.spans, hasLength(1));
expect(paragraph1.spans.single.start, 0);
expect(paragraph1.spans.single.end, 0);
final CanvasParagraph paragraph2 = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.addText('');
});
expect(paragraph2.plainText, '');
expect(paragraph2.spans, hasLength(1));
expect(paragraph2.spans.single.start, 0);
expect(paragraph2.spans.single.end, 0);
});
test('Builds a text-only canvas paragraph', () {
final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 13.0);
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
builder.addText('Hello');
final CanvasParagraph paragraph = builder.build();
expect(paragraph.paragraphStyle, style);
expect(paragraph.plainText, 'Hello');
expect(paragraph.spans, hasLength(1));
paragraph.layout(const ParagraphConstraints(width: double.infinity));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: 0, left: 0, width: 13 * 5, fontSize: 13)}">'
'Hello'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: !isBlink,
);
// Should break "Hello" into "Hel" and "lo".
paragraph.layout(const ParagraphConstraints(width: 39.0));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: 0, left: 0, width: 13 * 3, fontSize: 13)}">'
'Hel'
'</flt-span>'
'<flt-span style="${spanStyle(top: 13, left: 0, width: 13 * 2, fontSize: 13)}">'
'lo'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: !isBlink,
);
final ParagraphSpan span = paragraph.spans.single;
expect(getSpanText(paragraph, span), 'Hello');
expect(span.style, styleWithDefaults(fontSize: 13.0));
});
test('Correct defaults', () {
final EngineParagraphStyle style = EngineParagraphStyle();
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
builder.addText('Hello');
final CanvasParagraph paragraph = builder.build();
expect(paragraph.paragraphStyle, style);
expect(paragraph.plainText, 'Hello');
expect(paragraph.spans, hasLength(1));
paragraph.layout(const ParagraphConstraints(width: double.infinity));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: 0, left: 0, width: 14 * 5)}">'
'Hello'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: !isBlink,
);
final ParagraphSpan span = paragraph.spans.single;
expect(span.style, styleWithDefaults());
});
test('Sets correct styles for max-lines', () {
final EngineParagraphStyle style = EngineParagraphStyle(maxLines: 2);
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
builder.addText('Hello');
final CanvasParagraph paragraph = builder.build();
expect(paragraph.paragraphStyle, style);
expect(paragraph.plainText, 'Hello');
paragraph.layout(const ParagraphConstraints(width: double.infinity));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: 0, left: 0, width: 14 * 5)}">'
'Hello'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: !isBlink,
);
});
test('Sets correct styles for ellipsis', () {
final EngineParagraphStyle style = EngineParagraphStyle(ellipsis: '...');
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
builder.addText('HelloWorld');
final CanvasParagraph paragraph = builder.build();
expect(paragraph.paragraphStyle, style);
expect(paragraph.plainText, 'HelloWorld');
paragraph.layout(const ParagraphConstraints(width: 100.0));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: 0, left: 0, width: 14 * 4)}">'
'Hell'
'</flt-span>'
'<flt-span style="${spanStyle(top: 0, left: 14 * 4, width: 14 * 3)}">'
'...'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: !isBlink,
);
});
test('Builds a single-span paragraph with complex styles', () {
final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 13.0, height: 1.5);
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
builder.pushStyle(TextStyle(fontSize: 9.0));
builder.pushStyle(TextStyle(fontWeight: FontWeight.bold));
builder.pushStyle(TextStyle(fontSize: 40.0));
builder.pop();
builder.pushStyle(TextStyle(fontStyle: FontStyle.italic, letterSpacing: 2.0));
builder.addText('Hello');
final CanvasParagraph paragraph = builder.build();
expect(paragraph.plainText, 'Hello');
expect(paragraph.spans, hasLength(1));
paragraph.layout(const ParagraphConstraints(width: double.infinity));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: 0, left: 0, width: (9 + 2) * 5, lineHeight: 1.5 * 9, fontSize: 9, fontWeight: 'bold', fontStyle: 'italic', letterSpacing: 2)}">'
'Hello'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: !isBlink,
);
final ParagraphSpan span = paragraph.spans.single;
expect(getSpanText(paragraph, span), 'Hello');
expect(
span.style,
styleWithDefaults(
height: 1.5,
fontSize: 9.0,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic,
letterSpacing: 2.0,
),
);
});
test('Builds a multi-span paragraph', () {
final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 13.0);
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
builder.pushStyle(TextStyle(fontWeight: FontWeight.bold));
builder.addText('Hello');
builder.pop();
builder.pushStyle(TextStyle(fontStyle: FontStyle.italic));
builder.addText(' world');
final CanvasParagraph paragraph = builder.build();
expect(paragraph.plainText, 'Hello world');
expect(paragraph.spans, hasLength(2));
paragraph.layout(const ParagraphConstraints(width: double.infinity));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: 0, left: 0, width: 13 * 5, fontSize: 13, fontWeight: 'bold')}">'
'Hello'
'</flt-span>'
'<flt-span style="${spanStyle(top: 0, left: 65, width: 13 * 1, fontSize: 13, fontStyle: 'italic')}">'
' '
'</flt-span>'
'<flt-span style="${spanStyle(top: 0, left: 78, width: 13 * 5, fontSize: 13, fontStyle: 'italic')}">'
'world'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: !isBlink,
);
// Should break "Hello world" into 2 lines: "Hello " and "world".
paragraph.layout(const ParagraphConstraints(width: 75.0));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: 0, left: 0, width: 13 * 5, fontSize: 13, fontWeight: 'bold')}">'
'Hello'
'</flt-span>'
'<flt-span style="${spanStyle(top: 0, left: 65, width: 0, fontSize: 13, fontStyle: 'italic')}">'
' '
'</flt-span>'
'<flt-span style="${spanStyle(top: 13, left: 0, width: 13 * 5, fontSize: 13, fontStyle: 'italic')}">'
'world'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: !isBlink,
);
final ParagraphSpan hello = paragraph.spans.first;
expect(getSpanText(paragraph, hello), 'Hello');
expect(hello.style, styleWithDefaults(fontSize: 13.0, fontWeight: FontWeight.bold));
final ParagraphSpan world = paragraph.spans.last;
expect(getSpanText(paragraph, world), ' world');
expect(world.style, styleWithDefaults(fontSize: 13.0, fontStyle: FontStyle.italic));
});
test('Builds a multi-span paragraph with complex styles', () {
final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 13.0);
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
builder.pushStyle(TextStyle(fontWeight: FontWeight.bold));
builder.pushStyle(TextStyle(height: 2.0));
builder.addText('Hello');
builder.pop(); // pop TextStyle(height: 2.0).
builder.pushStyle(TextStyle(fontStyle: FontStyle.italic));
builder.addText(' world');
builder.pushStyle(TextStyle(fontWeight: FontWeight.normal));
builder.addText('!');
final CanvasParagraph paragraph = builder.build();
expect(paragraph.plainText, 'Hello world!');
expect(paragraph.spans, hasLength(3));
paragraph.layout(const ParagraphConstraints(width: double.infinity));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: 0, left: 0, width: 13 * 5, lineHeight: 2 * 13, fontSize: 13, fontWeight: 'bold')}">'
'Hello'
'</flt-span>'
'<flt-span style="${spanStyle(top: 6, left: 65, width: 13 * 1, fontSize: 13, fontWeight: 'bold', fontStyle: 'italic')}">'
' '
'</flt-span>'
'<flt-span style="${spanStyle(top: 6, left: 78, width: 13 * 5, fontSize: 13, fontWeight: 'bold', fontStyle: 'italic')}">'
'world'
'</flt-span>'
'<flt-span style="${spanStyle(top: 6, left: 143, width: 13 * 1, fontSize: 13, fontWeight: 'normal', fontStyle: 'italic')}">'
'!'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: !isBlink,
);
final ParagraphSpan hello = paragraph.spans[0];
expect(getSpanText(paragraph, hello), 'Hello');
expect(
hello.style,
styleWithDefaults(fontSize: 13.0, fontWeight: FontWeight.bold, height: 2.0),
);
final ParagraphSpan world = paragraph.spans[1];
expect(getSpanText(paragraph, world), ' world');
expect(
world.style,
styleWithDefaults(fontSize: 13.0, fontWeight: FontWeight.bold, fontStyle: FontStyle.italic),
);
final ParagraphSpan bang = paragraph.spans[2];
expect(getSpanText(paragraph, bang), '!');
expect(
bang.style,
styleWithDefaults(fontSize: 13.0, fontWeight: FontWeight.normal, fontStyle: FontStyle.italic),
);
});
test('Paragraph with new lines generates correct DOM', () {
final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 13.0);
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
builder.addText('First\nSecond ');
builder.pushStyle(TextStyle(fontStyle: FontStyle.italic));
builder.addText('ThirdLongLine');
final CanvasParagraph paragraph = builder.build();
expect(paragraph.plainText, 'First\nSecond ThirdLongLine');
expect(paragraph.spans, hasLength(2));
// There's a new line between "First" and "Second", but "Second" and
// "ThirdLongLine" remain together since constraints are infinite.
paragraph.layout(const ParagraphConstraints(width: double.infinity));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: 0, left: 0, width: 13 * 5, fontSize: 13)}">'
'First'
'</flt-span>'
'<flt-span style="${spanStyle(top: 13, left: 0, width: 13 * 6, fontSize: 13)}">'
'Second'
'</flt-span>'
'<flt-span style="${spanStyle(top: 13, left: 13 * 6, width: 13 * 1, fontSize: 13)}">'
' '
'</flt-span>'
'<flt-span style="${spanStyle(top: 13, left: 13 * 7, width: 13 * 13, fontSize: 13, fontStyle: 'italic')}">'
'ThirdLongLine'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: !isBlink,
);
// Should break the paragraph into "First", "Second " and "ThirdLongLine".
paragraph.layout(const ParagraphConstraints(width: 180.0));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: 0, left: 0, width: 13 * 5, fontSize: 13)}">'
'First'
'</flt-span>'
'<flt-span style="${spanStyle(top: 13, left: 0, width: 13 * 6, fontSize: 13)}">'
'Second'
'</flt-span>'
'<flt-span style="${spanStyle(top: 13, left: 13 * 6, width: 0, fontSize: 13)}">'
' '
'</flt-span>'
'<flt-span style="${spanStyle(top: 26, left: 0, width: 13 * 13, fontSize: 13, fontStyle: 'italic')}">'
'ThirdLongLine'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: !isBlink,
);
});
test('various font sizes', () {
// Paragraphs and spans force the FlutterTest font in test mode. We need to
// trick them into thinking they are not in test mode, so they use the
// provided font family.
ui_web.debugEmulateFlutterTesterEnvironment = false;
final EngineParagraphStyle style = EngineParagraphStyle(fontSize: 12.0, fontFamily: 'first');
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
builder.addText('First ');
builder.pushStyle(TextStyle(fontSize: 18.0, fontFamily: 'second'));
builder.addText('Second ');
builder.pushStyle(TextStyle(fontSize: 10.0, fontFamily: 'third'));
builder.addText('Third');
final CanvasParagraph paragraph = builder.build();
expect(paragraph.plainText, 'First Second Third');
expect(paragraph.spans, hasLength(3));
// The paragraph should take the font size and family from the span with the
// greatest font size.
paragraph.layout(const ParagraphConstraints(width: double.infinity));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 12, fontFamily: 'first')}">'
'First'
'</flt-span>'
'<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 12, fontFamily: 'first')}">'
' '
'</flt-span>'
'<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 18, fontFamily: 'second')}">'
'Second'
'</flt-span>'
'<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 18, fontFamily: 'second')}">'
' '
'</flt-span>'
'<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 10, fontFamily: 'third')}">'
'Third'
'</flt-span>'
'</flt-paragraph>',
// Since we are using unknown font families, we can't predict the text
// measurements.
ignorePositions: true,
);
ui_web.debugEmulateFlutterTesterEnvironment = true;
});
// Regression test for https://github.com/flutter/flutter/issues/108431.
// Set dir attribute for RTL fragments in order to let the browser
// handle mirrored characters.
test('Sets "dir" attribute for RTL fragment', () {
final EngineParagraphStyle style = EngineParagraphStyle(
fontSize: 20.0,
textDirection: TextDirection.rtl,
);
final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style);
builder.addText('(1)');
final CanvasParagraph paragraph = builder.build();
expect(paragraph.paragraphStyle, style);
expect(paragraph.plainText, '(1)');
paragraph.layout(const ParagraphConstraints(width: double.infinity));
expectOuterHtml(
paragraph,
'<flt-paragraph style="${paragraphStyle()}">'
'<flt-span dir="rtl" style="${spanStyle(top: null, left: null, width: null, fontSize: 20)}">'
'('
'</flt-span>'
'<flt-span style="${spanStyle(top: null, left: null, width: null, fontSize: 20)}">'
'1'
'</flt-span>'
'<flt-span dir="rtl" style="${spanStyle(top: null, left: null, width: null, fontSize: 20)}">'
')'
'</flt-span>'
'</flt-paragraph>',
ignorePositions: true,
);
});
}
const String defaultFontFamily = 'FlutterTest';
const num defaultFontSize = 14;
String paragraphStyle() {
return <String>['position: absolute;', 'white-space: pre;'].join(' ');
}
String spanStyle({
required num? top,
required num? left,
required num? width,
String fontFamily = defaultFontFamily,
num fontSize = defaultFontSize,
String? fontWeight,
String? fontStyle,
num? lineHeight,
num? letterSpacing,
}) {
return <String>[
'font-size: ${fontSize}px;',
if (fontWeight != null) 'font-weight: $fontWeight;',
if (fontStyle != null) 'font-style: $fontStyle;',
'font-family: ${fontFamilyToAttribute(fontFamily)};',
if (letterSpacing != null) 'letter-spacing: ${letterSpacing}px;',
'position: absolute;',
if (top != null) 'top: ${top}px;',
if (left != null) 'left: ${left}px;',
if (width != null) 'width: ${width}px;',
'line-height: ${lineHeight ?? fontSize}px;',
].join(' ');
}
TextStyle styleWithDefaults({
String fontFamily = StyleManager.defaultFontFamily,
double fontSize = StyleManager.defaultFontSize,
FontWeight? fontWeight,
FontStyle? fontStyle,
double? height,
double? letterSpacing,
}) {
return TextStyle(
fontFamily: fontFamily,
fontSize: fontSize,
fontWeight: fontWeight,
fontStyle: fontStyle,
height: height,
letterSpacing: letterSpacing,
);
}
void expectOuterHtml(CanvasParagraph paragraph, String expected, {required bool ignorePositions}) {
String outerHtml = paragraph.toDomElement().outerHTML!;
if (ignorePositions) {
outerHtml = removeMeasurementInfo(outerHtml);
expected = removeMeasurementInfo(expected);
}
expect(outerHtml, expected);
}
/// Removes CSS styles that are based on text measurement from the given html
/// string.
///
/// Examples: top, left, line-height, width.
///
/// This is needed when the measurement is unknown or could be different
/// depending on browser and environment.
String removeMeasurementInfo(String outerHtml) {
return outerHtml
.replaceAll(RegExp(r'\s*line-height:\s*[\d\.]+px\s*;\s*'), '')
.replaceAll(RegExp(r'\s*width:\s*[\d\.]+px\s*;\s*'), '')
.replaceAll(RegExp(r'\s*top:\s*[\d\.]+px\s*;\s*'), '')
.replaceAll(RegExp(r'\s*left:\s*[\d\.]+px\s*;\s*'), '');
}

View File

@@ -1,795 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import '../../common/rendering.dart';
import '../../common/test_initialization.dart';
import '../paragraph/helper.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(withImplicitView: true);
group('$CanvasParagraph.getBoxesForRange', () {
test('return empty list for invalid ranges', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('Lorem ipsum');
})..layout(constrain(double.infinity));
expect(paragraph.getBoxesForRange(-1, 0), <ui.TextBox>[]);
expect(paragraph.getBoxesForRange(0, 0), <ui.TextBox>[]);
expect(paragraph.getBoxesForRange(11, 11), <ui.TextBox>[]);
expect(paragraph.getBoxesForRange(11, 12), <ui.TextBox>[]);
expect(paragraph.getBoxesForRange(4, 3), <ui.TextBox>[]);
});
test('handles single-line multi-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('ipsum ');
builder.pop();
builder.addText('.');
})..layout(constrain(double.infinity));
// Within the first span "Lorem ".
expect(
// "or"
paragraph.getBoxesForRange(1, 3),
<ui.TextBox>[box(10, 0, 30, 10)],
);
expect(
// "Lorem"
paragraph.getBoxesForRange(0, 5),
<ui.TextBox>[box(0, 0, 50, 10)],
);
// Make sure the trailing space is also included in the box.
expect(
// "Lorem "
paragraph.getBoxesForRange(0, 6),
<ui.TextBox>[
// "Lorem"
box(0, 0, 50, 10),
// " "
box(50, 0, 60, 10),
],
);
// Within the second span "ipsum ".
expect(
// "psum"
paragraph.getBoxesForRange(7, 11),
<ui.TextBox>[box(70, 0, 110, 10)],
);
expect(
// "um "
paragraph.getBoxesForRange(9, 12),
<ui.TextBox>[
// "um"
box(90, 0, 110, 10),
// " "
box(110, 0, 120, 10),
],
);
// Across the two spans "Lorem " and "ipsum ".
expect(
// "rem ipsum"
paragraph.getBoxesForRange(2, 11),
<ui.TextBox>[
// "rem"
box(20, 0, 50, 10),
// " "
box(50, 0, 60, 10),
// "ipsum"
box(60, 0, 110, 10),
],
);
// Across all spans "Lorem ", "ipsum ", ".".
expect(
// "Lorem ipsum ."
paragraph.getBoxesForRange(0, 13),
<ui.TextBox>[
// "Lorem"
box(0, 0, 50, 10),
// " "
box(50, 0, 60, 10),
// "ipsum"
box(60, 0, 110, 10),
// " "
box(110, 0, 120, 10),
// "."
box(120, 0, 130, 10),
],
);
});
test('handles multi-line single-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('Lorem ipsum dolor sit');
})..layout(constrain(90.0));
// Lines:
// "Lorem "
// "ipsum "
// "dolor sit"
// Within the first line "Lorem ".
expect(
// "or"
paragraph.getBoxesForRange(1, 3),
<ui.TextBox>[box(10, 0, 30, 10)],
);
// Make sure the trailing space at the end of line is also included in the
// box.
expect(
// "Lorem "
paragraph.getBoxesForRange(0, 6),
<ui.TextBox>[
// "Lorem"
box(0, 0, 50, 10),
// " "
box(50, 0, 60, 10),
],
);
// Within the second line "ipsum ".
expect(
// "psum "
paragraph.getBoxesForRange(7, 12),
<ui.TextBox>[
// "psum"
box(10, 10, 50, 20),
// " "
box(50, 10, 60, 20),
],
);
// Across all lines.
expect(
// "em "
// "ipsum "
// "dolor s"
paragraph.getBoxesForRange(3, 19),
<ui.TextBox>[
// "em"
box(30, 0, 50, 10),
// " "
box(50, 0, 60, 10),
// "ipsum"
box(0, 10, 50, 20),
// " "
box(50, 10, 60, 20),
// "dolor"
box(0, 20, 50, 30),
// " "
box(50, 20, 60, 30),
// "s"
box(60, 20, 70, 30),
],
);
});
test('handles multi-line multi-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ipsum ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor ');
builder.pop();
builder.addText('sit');
})..layout(constrain(90.0));
// Lines:
// "Lorem "
// "ipsum "
// "dolor sit"
// Within the first line "Lorem ".
expect(
// "ore"
paragraph.getBoxesForRange(1, 4),
<ui.TextBox>[box(10, 0, 40, 10)],
);
expect(
// "Lorem "
paragraph.getBoxesForRange(0, 6),
<ui.TextBox>[
// "Lorem"
box(0, 0, 50, 10),
// " "
box(50, 0, 60, 10),
],
);
// Within the second line "ipsum ".
expect(
// "psum "
paragraph.getBoxesForRange(7, 12),
<ui.TextBox>[
// "psum"
box(10, 10, 50, 20),
// " "
box(50, 10, 60, 20),
],
);
// Within the third line "dolor sit" which is made of 2 spans.
expect(
// "lor sit"
paragraph.getBoxesForRange(14, 21),
<ui.TextBox>[
// "lor"
box(20, 20, 50, 30),
// " "
box(50, 20, 60, 30),
// "sit"
box(60, 20, 90, 30),
],
);
// Across all lines.
expect(
// "em "
// "ipsum "
// "dolor s"
paragraph.getBoxesForRange(3, 19),
<ui.TextBox>[
// "em"
box(30, 0, 50, 10),
// " "
box(50, 0, 60, 10),
// "ipsum"
box(0, 10, 50, 20),
// " "
box(50, 10, 60, 20),
// "dolor"
box(0, 20, 50, 30),
// " "
box(50, 20, 60, 30),
// "s"
box(60, 20, 70, 30),
],
);
});
test('handles spans with varying heights/baselines', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(fontSize: 20.0));
// width = 20.0 * 6 = 120.0
// baseline = 20.0 * 80% = 16.0
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(fontSize: 40.0));
// width = 40.0 * 6 = 240.0
// baseline = 40.0 * 80% = 32.0
builder.addText('ipsum ');
builder.pushStyle(EngineTextStyle.only(fontSize: 10.0));
// width = 10.0 * 6 = 60.0
// baseline = 10.0 * 80% = 8.0
builder.addText('dolor ');
builder.pushStyle(EngineTextStyle.only(fontSize: 30.0));
// width = 30.0 * 4 = 120.0
// baseline = 30.0 * 80% = 24.0
builder.addText('sit ');
builder.pushStyle(EngineTextStyle.only(fontSize: 20.0));
// width = 20.0 * 4 = 80.0
// baseline = 20.0 * 80% = 16.0
builder.addText('amet');
})..layout(constrain(420.0));
// Lines:
// "Lorem ipsum dolor " (width: 420, height: 40, baseline: 32)
// "sit amet" (width: 200, height: 30, baseline: 24)
expect(
// "em ipsum dol"
paragraph.getBoxesForRange(3, 15),
<ui.TextBox>[
// "em"
box(60, 16, 100, 36),
// " "
box(100, 16, 120, 36),
// "ipsum"
box(120, 0, 320, 40),
// " "
box(320, 0, 360, 40),
// "dol"
box(360, 24, 390, 34),
],
);
expect(
// "sum dolor "
// "sit amet"
paragraph.getBoxesForRange(8, 26),
<ui.TextBox>[
// "sum"
box(200, 0, 320, 40),
// " "
box(320, 0, 360, 40),
// "dolor"
box(360, 24, 410, 34),
// " "
box(410, 24, 420, 34),
// "sit"
box(0, 40, 90, 70),
// " "
box(90, 40, 120, 70),
// "amet"
box(120, 48, 200, 68),
],
);
});
test('reverts to last line break opportunity', () {
final CanvasParagraph paragraph = rich(ahemStyle, (ui.ParagraphBuilder builder) {
// Lines:
// "AAA "
// "B_C DD"
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('AAA B');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('_C ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('DD');
});
String getTextForFragment(LayoutFragment fragment) {
return paragraph.plainText.substring(fragment.start, fragment.end);
}
// The layout algorithm will keep appending segments to the line builder
// until it reaches: "AAA B_". At that point, it'll try to add the "C" but
// realizes there isn't enough width in the line. Since the line already
// had a line break opportunity, the algorithm tries to revert the line to
// that opportunity (i.e. "AAA ") and pops the segments "_" and "B".
//
// Because the segments "B" and "_" have different directionality
// preferences (LTR and no-preferenece, respectively), the algorithm
// should've already created a box for "B". When the "B" segment is popped
// we want to make sure that the "B" box is also popped.
paragraph.layout(constrain(60));
final ParagraphLine firstLine = paragraph.lines[0];
final ParagraphLine secondLine = paragraph.lines[1];
// There should be no "B" in the first line's fragments.
expect(firstLine.fragments, hasLength(2));
expect(getTextForFragment(firstLine.fragments[0]), 'AAA');
expect(firstLine.fragments[0].left, 0.0);
expect(getTextForFragment(firstLine.fragments[1]), ' ');
expect(firstLine.fragments[1].left, 30.0);
// Make sure the second line isn't missing any fragments.
expect(secondLine.fragments, hasLength(5));
expect(getTextForFragment(secondLine.fragments[0]), 'B');
expect(secondLine.fragments[0].left, 0.0);
expect(getTextForFragment(secondLine.fragments[1]), '_');
expect(secondLine.fragments[1].left, 10.0);
expect(getTextForFragment(secondLine.fragments[2]), 'C');
expect(secondLine.fragments[2].left, 20.0);
expect(getTextForFragment(secondLine.fragments[3]), ' ');
expect(secondLine.fragments[3].left, 30.0);
expect(getTextForFragment(secondLine.fragments[4]), 'DD');
expect(secondLine.fragments[4].left, 40.0);
});
});
group('$CanvasParagraph.getPositionForOffset', () {
test('handles single-line multi-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('ipsum ');
builder.pop();
builder.addText('.');
})..layout(constrain(double.infinity));
// Above the line, at the beginning.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, -5)),
pos(0, ui.TextAffinity.downstream),
);
// At the top left corner of the line.
expect(paragraph.getPositionForOffset(ui.Offset.zero), pos(0, ui.TextAffinity.downstream));
// At the beginning of the line.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, 5)),
pos(0, ui.TextAffinity.downstream),
);
// Below the line, at the end.
expect(
paragraph.getPositionForOffset(const ui.Offset(130, 12)),
pos(13, ui.TextAffinity.upstream),
);
// At the end of the line.
expect(
paragraph.getPositionForOffset(const ui.Offset(130, 5)),
pos(13, ui.TextAffinity.upstream),
);
// On the left half of "p" in "ipsum".
expect(
paragraph.getPositionForOffset(const ui.Offset(74, 5)),
pos(7, ui.TextAffinity.downstream),
);
// On the left half of "p" in "ipsum" (above the line).
expect(
paragraph.getPositionForOffset(const ui.Offset(74, -5)),
pos(7, ui.TextAffinity.downstream),
);
// On the left half of "p" in "ipsum" (below the line).
expect(
paragraph.getPositionForOffset(const ui.Offset(74, 15)),
pos(7, ui.TextAffinity.downstream),
);
// On the right half of "p" in "ipsum".
expect(
paragraph.getPositionForOffset(const ui.Offset(76, 5)),
pos(8, ui.TextAffinity.upstream),
);
// At the top of the line, on the left half of "p" in "ipsum".
expect(
paragraph.getPositionForOffset(const ui.Offset(74, 0)),
pos(7, ui.TextAffinity.downstream),
);
// At the top of the line, on the right half of "p" in "ipsum".
expect(
paragraph.getPositionForOffset(const ui.Offset(76, 0)),
pos(8, ui.TextAffinity.upstream),
);
});
test('handles multi-line single-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('Lorem ipsum dolor sit');
})..layout(constrain(90.0));
// Lines:
// "Lorem "
// "ipsum "
// "dolor sit"
// Above the first line, at the beginning.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, -5)),
pos(0, ui.TextAffinity.downstream),
);
// At the top left corner of the line.
expect(paragraph.getPositionForOffset(ui.Offset.zero), pos(0, ui.TextAffinity.downstream));
// At the beginning of the first line.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, 5)),
pos(0, ui.TextAffinity.downstream),
);
// At the end of the first line.
expect(
paragraph.getPositionForOffset(const ui.Offset(60, 5)),
pos(6, ui.TextAffinity.upstream),
);
// At the end of the first line (above the line).
expect(
paragraph.getPositionForOffset(const ui.Offset(60, -5)),
pos(6, ui.TextAffinity.upstream),
);
// After the end of the first line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(70, 5)),
pos(6, ui.TextAffinity.upstream),
);
// On the left half of " " in "Lorem ".
expect(
paragraph.getPositionForOffset(const ui.Offset(54, 5)),
pos(5, ui.TextAffinity.downstream),
);
// On the right half of " " in "Lorem ".
expect(
paragraph.getPositionForOffset(const ui.Offset(56, 5)),
pos(6, ui.TextAffinity.upstream),
);
// At the beginning of the second line "ipsum ".
expect(
paragraph.getPositionForOffset(const ui.Offset(0, 15)),
pos(6, ui.TextAffinity.downstream),
);
// At the end of the second line.
expect(
paragraph.getPositionForOffset(const ui.Offset(60, 15)),
pos(12, ui.TextAffinity.upstream),
);
// After the end of the second line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(70, 15)),
pos(12, ui.TextAffinity.upstream),
);
// Below the third line "dolor sit", at the end.
expect(
paragraph.getPositionForOffset(const ui.Offset(90, 40)),
pos(21, ui.TextAffinity.upstream),
);
// At the end of the third line.
expect(
paragraph.getPositionForOffset(const ui.Offset(90, 25)),
pos(21, ui.TextAffinity.upstream),
);
// After the end of the third line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(100, 25)),
pos(21, ui.TextAffinity.upstream),
);
// On the left half of " " in "dolor sit".
expect(
paragraph.getPositionForOffset(const ui.Offset(54, 25)),
pos(17, ui.TextAffinity.downstream),
);
// On the right half of " " in "dolor sit".
expect(
paragraph.getPositionForOffset(const ui.Offset(56, 25)),
pos(18, ui.TextAffinity.upstream),
);
});
test('handles multi-line multi-span paragraphs', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('Lorem ipsum ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('dolor ');
builder.pop();
builder.addText('sit');
})..layout(constrain(90.0));
// Lines:
// "Lorem "
// "ipsum "
// "dolor sit"
// Above the first line, at the beginning.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, -5)),
pos(0, ui.TextAffinity.downstream),
);
// At the beginning of the first line.
expect(
paragraph.getPositionForOffset(const ui.Offset(0, 5)),
pos(0, ui.TextAffinity.downstream),
);
// At the end of the first line.
expect(
paragraph.getPositionForOffset(const ui.Offset(60, 5)),
pos(6, ui.TextAffinity.upstream),
);
// After the end of the first line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(70, 5)),
pos(6, ui.TextAffinity.upstream),
);
// On the left half of " " in "Lorem ".
expect(
paragraph.getPositionForOffset(const ui.Offset(54, 5)),
pos(5, ui.TextAffinity.downstream),
);
// On the right half of " " in "Lorem ".
expect(
paragraph.getPositionForOffset(const ui.Offset(56, 5)),
pos(6, ui.TextAffinity.upstream),
);
// At the beginning of the second line "ipsum ".
expect(
paragraph.getPositionForOffset(const ui.Offset(0, 15)),
pos(6, ui.TextAffinity.downstream),
);
// At the end of the second line.
expect(
paragraph.getPositionForOffset(const ui.Offset(60, 15)),
pos(12, ui.TextAffinity.upstream),
);
// After the end of the second line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(70, 15)),
pos(12, ui.TextAffinity.upstream),
);
// Below the third line "dolor sit", at the end.
expect(
paragraph.getPositionForOffset(const ui.Offset(90, 40)),
pos(21, ui.TextAffinity.upstream),
);
// At the end of the third line.
expect(
paragraph.getPositionForOffset(const ui.Offset(90, 25)),
pos(21, ui.TextAffinity.upstream),
);
// After the end of the third line to the right.
expect(
paragraph.getPositionForOffset(const ui.Offset(100, 25)),
pos(21, ui.TextAffinity.upstream),
);
// On the left half of " " in "dolor sit".
expect(
paragraph.getPositionForOffset(const ui.Offset(54, 25)),
pos(17, ui.TextAffinity.downstream),
);
// On the right half of " " in "dolor sit".
expect(
paragraph.getPositionForOffset(const ui.Offset(56, 25)),
pos(18, ui.TextAffinity.upstream),
);
});
});
group('$CanvasParagraph.getLineBoundary', () {
test('single-line', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('One single line');
})..layout(constrain(400.0));
// "One single line".length == 15
for (int i = 0; i < 15; i++) {
expect(
paragraph.getLineBoundary(ui.TextPosition(offset: i)),
const ui.TextRange(start: 0, end: 15),
reason: 'failed at offset $i',
);
}
});
test('multi-line', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('First line\n');
builder.addText('Second line\n');
builder.addText('Third line');
})..layout(constrain(400.0));
// "First line\n".length == 11
for (int i = 0; i < 11; i++) {
expect(
paragraph.getLineBoundary(ui.TextPosition(offset: i)),
// The "\n" is not included in the line boundary.
const ui.TextRange(start: 0, end: 10),
reason: 'failed at offset $i',
);
}
// "Second line\n".length == 12
for (int i = 11; i < 23; i++) {
expect(
paragraph.getLineBoundary(ui.TextPosition(offset: i)),
// The "\n" is not included in the line boundary.
const ui.TextRange(start: 11, end: 22),
reason: 'failed at offset $i',
);
}
// "Third line".length == 10
for (int i = 23; i < 33; i++) {
expect(
paragraph.getLineBoundary(ui.TextPosition(offset: i)),
const ui.TextRange(start: 23, end: 33),
reason: 'failed at offset $i',
);
}
});
});
test('$CanvasParagraph.getWordBoundary', () {
final ui.Paragraph paragraph = plain(ahemStyle, 'Lorem ipsum dolor');
const ui.TextRange loremRange = ui.TextRange(start: 0, end: 5);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 0)), loremRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 1)), loremRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 2)), loremRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 3)), loremRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 4)), loremRange);
const ui.TextRange firstSpace = ui.TextRange(start: 5, end: 6);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 5)), firstSpace);
const ui.TextRange ipsumRange = ui.TextRange(start: 6, end: 11);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 6)), ipsumRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 7)), ipsumRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 8)), ipsumRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 9)), ipsumRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 10)), ipsumRange);
const ui.TextRange secondSpace = ui.TextRange(start: 11, end: 12);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 11)), secondSpace);
const ui.TextRange dolorRange = ui.TextRange(start: 12, end: 17);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 12)), dolorRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 13)), dolorRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 14)), dolorRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 15)), dolorRange);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 16)), dolorRange);
const ui.TextRange endRange = ui.TextRange(start: 17, end: 17);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 17)), endRange);
});
test('$CanvasParagraph.getWordBoundary can handle text affinity', () {
final ui.Paragraph paragraph = plain(ahemStyle, 'Lorem ipsum dolor');
const ui.TextRange loremRange = ui.TextRange(start: 0, end: 5);
expect(paragraph.getWordBoundary(const ui.TextPosition(offset: 4)), loremRange);
expect(
paragraph.getWordBoundary(
const ui.TextPosition(offset: 5, affinity: ui.TextAffinity.upstream),
),
loremRange,
);
});
test('$CanvasParagraph.longestLine', () {
final ui.Paragraph paragraph = plain(ahemStyle, 'abcd\nabcde abc');
paragraph.layout(const ui.ParagraphConstraints(width: 80.0));
expect(paragraph.longestLine, 50.0);
});
test('Render after dispose', () async {
final ui.Paragraph paragraph = plain(ahemStyle, 'abc');
paragraph.layout(const ui.ParagraphConstraints(width: 30.8));
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
canvas.drawParagraph(paragraph, ui.Offset.zero);
final ui.Picture picture = recorder.endRecording();
paragraph.dispose();
final ui.SceneBuilder builder = ui.SceneBuilder();
builder.addPicture(ui.Offset.zero, picture);
final ui.Scene scene = builder.build();
await renderScene(scene);
picture.dispose();
scene.dispose();
});
}
/// Shortcut to create a [ui.TextBox] with an optional [ui.TextDirection].
ui.TextBox box(
double left,
double top,
double right,
double bottom, [
ui.TextDirection direction = ui.TextDirection.ltr,
]) {
return ui.TextBox.fromLTRBD(left, top, right, bottom, direction);
}
/// Shortcut to create a [ui.TextPosition].
ui.TextPosition pos(int offset, ui.TextAffinity affinity) {
return ui.TextPosition(offset: offset, affinity: affinity);
}

View File

@@ -1,238 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../../common/fake_asset_manager.dart';
import '../../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('$HtmlFontCollection', () {
setUpUnitTests();
const String testFontUrl = '/assets/fonts/ahem.ttf';
late FakeAssetScope testScope;
setUp(() {
testScope = fakeAssetManager.pushAssetScope();
testScope.setAssetPassthrough(testFontUrl);
// Clear the fonts before the test begins to wipe out the fonts from the
// test initialization.
domDocument.fonts!.clear();
});
tearDown(() {
fakeAssetManager.popAssetScope(testScope);
});
group('regular special characters', () {
test('Register Asset with no special characters', () async {
const String testFontFamily = 'Ahem';
final List<String> fontFamilyList = <String>[];
final HtmlFontCollection collection = HtmlFontCollection();
await collection.loadAssetFonts(
FontManifest(<FontFamily>[
FontFamily(testFontFamily, <FontAsset>[FontAsset(testFontUrl, <String, String>{})]),
]),
);
domDocument.fonts!.forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) {
fontFamilyList.add(f.family!);
});
expect(fontFamilyList.length, equals(1));
expect(fontFamilyList.first, 'Ahem');
});
test(
'Register Asset with white space in the family name',
() async {
const String testFontFamily = 'Ahem ahem ahem';
final List<String> fontFamilyList = <String>[];
final HtmlFontCollection collection = HtmlFontCollection();
await collection.loadAssetFonts(
FontManifest(<FontFamily>[
FontFamily(testFontFamily, <FontAsset>[FontAsset(testFontUrl, <String, String>{})]),
]),
);
domDocument.fonts!.forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) {
fontFamilyList.add(f.family!);
});
expect(fontFamilyList.length, equals(1));
expect(fontFamilyList.first, 'Ahem ahem ahem');
},
// TODO(mdebbar): https://github.com/flutter/flutter/issues/51142
skip: ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit,
);
test('Register Asset with capital case letters', () async {
const String testFontFamily = 'AhEm';
final List<String> fontFamilyList = <String>[];
final HtmlFontCollection collection = HtmlFontCollection();
await collection.loadAssetFonts(
FontManifest(<FontFamily>[
FontFamily(testFontFamily, <FontAsset>[FontAsset(testFontUrl, <String, String>{})]),
]),
);
domDocument.fonts!.forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) {
fontFamilyList.add(f.family!);
});
expect(fontFamilyList.length, equals(1));
expect(fontFamilyList.first, 'AhEm');
});
test('Register Asset with descriptor', () async {
const String testFontFamily = 'Ahem';
final List<String> fontFamilyList = <String>[];
final HtmlFontCollection collection = HtmlFontCollection();
await collection.loadAssetFonts(
FontManifest(<FontFamily>[
FontFamily(testFontFamily, <FontAsset>[
FontAsset(testFontUrl, <String, String>{'weight': 'bold'}),
]),
]),
);
domDocument.fonts!.forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) {
expect(f.weight, 'bold');
expect(f2.weight, 'bold');
fontFamilyList.add(f.family!);
});
expect(fontFamilyList.length, equals(1));
expect(fontFamilyList.first, 'Ahem');
});
});
group('fonts with special characters', () {
test(
'Register Asset twice with special character slash',
() async {
const String testFontFamily = '/Ahem';
final List<String> fontFamilyList = <String>[];
final HtmlFontCollection collection = HtmlFontCollection();
await collection.loadAssetFonts(
FontManifest(<FontFamily>[
FontFamily(testFontFamily, <FontAsset>[FontAsset(testFontUrl, <String, String>{})]),
]),
);
domDocument.fonts!.forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) {
fontFamilyList.add(f.family!);
});
if (ui_web.browser.browserEngine != ui_web.BrowserEngine.firefox) {
expect(fontFamilyList.length, equals(2));
expect(fontFamilyList, contains("'/Ahem'"));
expect(fontFamilyList, contains('/Ahem'));
} else {
expect(fontFamilyList.length, equals(1));
expect(fontFamilyList.first, '"/Ahem"');
}
},
// TODO(mdebbar): https://github.com/flutter/flutter/issues/51142
skip: ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit,
);
test(
'Register Asset twice with exclamation mark',
() async {
const String testFontFamily = 'Ahem!!ahem';
final List<String> fontFamilyList = <String>[];
final HtmlFontCollection collection = HtmlFontCollection();
await collection.loadAssetFonts(
FontManifest(<FontFamily>[
FontFamily(testFontFamily, <FontAsset>[FontAsset(testFontUrl, <String, String>{})]),
]),
);
domDocument.fonts!.forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) {
fontFamilyList.add(f.family!);
});
if (ui_web.browser.browserEngine != ui_web.BrowserEngine.firefox) {
expect(fontFamilyList.length, equals(2));
expect(fontFamilyList, contains("'Ahem!!ahem'"));
expect(fontFamilyList, contains('Ahem!!ahem'));
} else {
expect(fontFamilyList.length, equals(1));
expect(fontFamilyList.first, '"Ahem!!ahem"');
}
},
// TODO(mdebbar): https://github.com/flutter/flutter/issues/51142
skip: ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit,
);
test(
'Register Asset twice with comma',
() async {
const String testFontFamily = 'Ahem ,ahem';
final List<String> fontFamilyList = <String>[];
final HtmlFontCollection collection = HtmlFontCollection();
await collection.loadAssetFonts(
FontManifest(<FontFamily>[
FontFamily(testFontFamily, <FontAsset>[FontAsset(testFontUrl, <String, String>{})]),
]),
);
domDocument.fonts!.forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) {
fontFamilyList.add(f.family!);
});
if (ui_web.browser.browserEngine != ui_web.BrowserEngine.firefox) {
expect(fontFamilyList.length, equals(2));
expect(fontFamilyList, contains("'Ahem ,ahem'"));
expect(fontFamilyList, contains('Ahem ,ahem'));
} else {
expect(fontFamilyList.length, equals(1));
expect(fontFamilyList.first, '"Ahem ,ahem"');
}
},
// TODO(mdebbar): https://github.com/flutter/flutter/issues/51142
skip: ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit,
);
test(
'Register Asset twice with a digit at the start of a token',
() async {
const String testFontFamily = 'Ahem 1998';
final List<String> fontFamilyList = <String>[];
final HtmlFontCollection collection = HtmlFontCollection();
await collection.loadAssetFonts(
FontManifest(<FontFamily>[
FontFamily(testFontFamily, <FontAsset>[FontAsset(testFontUrl, <String, String>{})]),
]),
);
domDocument.fonts!.forEach((DomFontFace f, DomFontFace f2, DomFontFaceSet s) {
fontFamilyList.add(f.family!);
});
if (ui_web.browser.browserEngine != ui_web.BrowserEngine.firefox) {
expect(fontFamilyList.length, equals(2));
expect(fontFamilyList, contains('Ahem 1998'));
expect(fontFamilyList, contains("'Ahem 1998'"));
} else {
expect(fontFamilyList.length, equals(1));
expect(fontFamilyList.first, '"Ahem 1998"');
}
},
// TODO(mdebbar): https://github.com/flutter/flutter/issues/51142
skip: ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit,
);
});
});
}

View File

@@ -1,127 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../../common/test_initialization.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(withImplicitView: true);
group('loadFontFromList', () {
const String testFontUrl = '/assets/fonts/ahem.ttf';
tearDown(() {
domDocument.fonts!.clear();
});
test(
'returns normally from invalid font buffer',
() async {
await expectLater(
() async => ui.loadFontFromList(Uint8List(0), fontFamily: 'test-font'),
returnsNormally,
);
},
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/56702
skip: ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit,
);
test(
'loads Blehm font from buffer',
() async {
expect(_containsFontFamily('Blehm'), isFalse);
final ByteBuffer response = await httpFetchByteBuffer(testFontUrl);
await ui.loadFontFromList(response.asUint8List(), fontFamily: 'Blehm');
expect(_containsFontFamily('Blehm'), isTrue);
},
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/56702
skip: ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit,
);
test(
'loading font should clear measurement caches',
() async {
final EngineParagraphStyle style = EngineParagraphStyle();
const ui.ParagraphConstraints constraints = ui.ParagraphConstraints(width: 30.0);
final CanvasParagraphBuilder canvasBuilder = CanvasParagraphBuilder(style);
canvasBuilder.addText('test');
// Triggers the measuring and verifies the ruler cache has been populated.
canvasBuilder.build().layout(constraints);
expect(Spanometer.rulers.length, 1);
// Now, loads a new font using loadFontFromList. This should clear the
// cache
final ByteBuffer response = await httpFetchByteBuffer(testFontUrl);
await ui.loadFontFromList(response.asUint8List(), fontFamily: 'Blehm');
// Verifies the font is loaded, and the cache is cleaned.
expect(_containsFontFamily('Blehm'), isTrue);
expect(Spanometer.rulers.length, 0);
},
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/56702
skip: ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit,
);
test(
'loading font should send font change message',
() async {
final ui.PlatformMessageCallback? oldHandler =
ui.PlatformDispatcher.instance.onPlatformMessage;
String? actualName;
String? message;
ui.PlatformDispatcher.instance.onPlatformMessage = (
String name,
ByteData? data,
ui.PlatformMessageResponseCallback? callback,
) {
actualName = name;
final ByteBuffer buffer = data!.buffer;
final Uint8List list = buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
message = utf8.decode(list);
};
final ByteBuffer response = await httpFetchByteBuffer(testFontUrl);
await ui.loadFontFromList(response.asUint8List(), fontFamily: 'Blehm');
final Completer<void> completer = Completer<void>();
domWindow.requestAnimationFrame((_) {
completer.complete();
});
await completer.future;
ui.PlatformDispatcher.instance.onPlatformMessage = oldHandler;
expect(actualName, 'flutter/system');
expect(message, '{"type":"fontsChange"}');
},
// TODO(hterkelsen): https://github.com/flutter/flutter/issues/56702
skip: ui_web.browser.browserEngine == ui_web.BrowserEngine.webkit,
);
});
}
bool _containsFontFamily(String family) {
bool found = false;
domDocument.fonts!.forEach((
DomFontFace fontFace,
DomFontFace fontFaceAgain,
DomFontFaceSet fontFaceSet,
) {
if (fontFace.family == family) {
found = true;
}
});
return found;
}

View File

@@ -1,336 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
import '../paragraph/helper.dart';
final EngineTextStyle defaultStyle = EngineTextStyle.only(
fontFamily: StyleManager.defaultFontFamily,
fontSize: StyleManager.defaultFontSize,
);
final EngineTextStyle style1 = defaultStyle.copyWith(fontSize: 20);
final EngineTextStyle style2 = defaultStyle.copyWith(color: blue);
final EngineTextStyle style3 = defaultStyle.copyWith(fontFamily: 'Roboto');
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
group('$LayoutFragmenter', () {
test('empty paragraph', () {
final CanvasParagraph paragraph1 = rich(
EngineParagraphStyle(),
(CanvasParagraphBuilder builder) {},
);
expect(split(paragraph1), <_Fragment>[
_Fragment('', endOfText, null, ffPrevious, defaultStyle),
]);
final CanvasParagraph paragraph2 = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.addText('');
});
expect(split(paragraph2), <_Fragment>[
_Fragment('', endOfText, null, ffPrevious, defaultStyle),
]);
final CanvasParagraph paragraph3 = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.pushStyle(style1);
builder.addText('');
});
expect(split(paragraph3), <_Fragment>[_Fragment('', endOfText, null, ffPrevious, style1)]);
});
test('single span', () {
final CanvasParagraph paragraph = plain(
EngineParagraphStyle(),
'Lorem 12 $rtlWord1 ipsum34',
);
expect(split(paragraph), <_Fragment>[
_Fragment('Lorem', prohibited, ltr, ffLtr, defaultStyle),
_Fragment(' ', opportunity, null, ffSandwich, defaultStyle, sp: 1),
_Fragment('12', prohibited, ltr, ffPrevious, defaultStyle),
_Fragment(' ', opportunity, null, ffSandwich, defaultStyle, sp: 1),
_Fragment(rtlWord1, prohibited, rtl, ffRtl, defaultStyle),
_Fragment(' ', opportunity, null, ffSandwich, defaultStyle, sp: 3),
_Fragment('ipsum34', endOfText, ltr, ffLtr, defaultStyle),
]);
});
test('multi span', () {
final CanvasParagraph paragraph = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.pushStyle(style1);
builder.addText('Lorem');
builder.pop();
builder.pushStyle(style2);
builder.addText(' ipsum 12 ');
builder.pop();
builder.pushStyle(style3);
builder.addText(' $rtlWord1 foo.');
builder.pop();
});
expect(split(paragraph), <_Fragment>[
_Fragment('Lorem', prohibited, ltr, ffLtr, style1),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 1),
_Fragment('ipsum', prohibited, ltr, ffLtr, style2),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 1),
_Fragment('12', prohibited, ltr, ffPrevious, style2),
_Fragment(' ', prohibited, null, ffSandwich, style2, sp: 1),
_Fragment(' ', opportunity, null, ffSandwich, style3, sp: 1),
_Fragment(rtlWord1, prohibited, rtl, ffRtl, style3),
_Fragment(' ', opportunity, null, ffSandwich, style3, sp: 1),
_Fragment('foo', prohibited, ltr, ffLtr, style3),
_Fragment('.', endOfText, null, ffSandwich, style3),
]);
});
test('new lines', () {
final CanvasParagraph paragraph = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.pushStyle(style1);
builder.addText('Lor\nem \n');
builder.pop();
builder.pushStyle(style2);
builder.addText(' \n ipsum 12 ');
builder.pop();
builder.pushStyle(style3);
builder.addText(' $rtlWord1 fo');
builder.pop();
builder.pushStyle(style1);
builder.addText('o.');
builder.pop();
});
expect(split(paragraph), <_Fragment>[
_Fragment('Lor', prohibited, ltr, ffLtr, style1),
_Fragment('\n', mandatory, null, ffSandwich, style1, nl: 1, sp: 1),
_Fragment('em', prohibited, ltr, ffLtr, style1),
_Fragment(' \n', mandatory, null, ffSandwich, style1, nl: 1, sp: 2),
_Fragment(' \n', mandatory, null, ffSandwich, style2, nl: 1, sp: 2),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 2),
_Fragment('ipsum', prohibited, ltr, ffLtr, style2),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 1),
_Fragment('12', prohibited, ltr, ffPrevious, style2),
_Fragment(' ', prohibited, null, ffSandwich, style2, sp: 1),
_Fragment(' ', opportunity, null, ffSandwich, style3, sp: 1),
_Fragment(rtlWord1, prohibited, rtl, ffRtl, style3),
_Fragment(' ', opportunity, null, ffSandwich, style3, sp: 1),
_Fragment('fo', prohibited, ltr, ffLtr, style3),
_Fragment('o', prohibited, ltr, ffLtr, style1),
_Fragment('.', endOfText, null, ffSandwich, style1),
]);
});
test('last line is empty', () {
final CanvasParagraph paragraph = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.pushStyle(style1);
builder.addText('Lorem \n');
builder.pop();
builder.pushStyle(style2);
builder.addText(' \n ipsum \n');
builder.pop();
});
expect(split(paragraph), <_Fragment>[
_Fragment('Lorem', prohibited, ltr, ffLtr, style1),
_Fragment(' \n', mandatory, null, ffSandwich, style1, nl: 1, sp: 2),
_Fragment(' \n', mandatory, null, ffSandwich, style2, nl: 1, sp: 2),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 2),
_Fragment('ipsum', prohibited, ltr, ffLtr, style2),
_Fragment(' \n', mandatory, null, ffSandwich, style2, nl: 1, sp: 2),
_Fragment('', endOfText, null, ffSandwich, style2),
]);
});
test('space-only spans', () {
final CanvasParagraph paragraph = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.addText('Lorem ');
builder.pushStyle(style1);
builder.addText(' ');
builder.pop();
builder.pushStyle(style2);
builder.addText(' ');
builder.pop();
builder.addText('ipsum');
});
expect(split(paragraph), <_Fragment>[
_Fragment('Lorem', prohibited, ltr, ffLtr, defaultStyle),
_Fragment(' ', prohibited, null, ffSandwich, defaultStyle, sp: 1),
_Fragment(' ', prohibited, null, ffSandwich, style1, sp: 3),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 2),
_Fragment('ipsum', endOfText, ltr, ffLtr, defaultStyle),
]);
});
test('placeholders', () {
final CanvasParagraph paragraph = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.pushStyle(style1);
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText('Lorem');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText('ipsum\n');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.pop();
builder.pushStyle(style2);
builder.addText('$rtlWord1 ');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText('\nsit');
builder.pop();
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
});
expect(split(paragraph), <_Fragment>[
_Fragment(placeholderChar, opportunity, ltr, ffLtr, style1),
_Fragment('Lorem', opportunity, ltr, ffLtr, style1),
_Fragment(placeholderChar, opportunity, ltr, ffLtr, style1),
_Fragment('ipsum', prohibited, ltr, ffLtr, style1),
_Fragment('\n', mandatory, null, ffSandwich, style1, nl: 1, sp: 1),
_Fragment(placeholderChar, opportunity, ltr, ffLtr, style1),
_Fragment(rtlWord1, prohibited, rtl, ffRtl, style2),
_Fragment(' ', opportunity, null, ffSandwich, style2, sp: 1),
_Fragment(placeholderChar, prohibited, ltr, ffLtr, style2),
_Fragment('\n', mandatory, null, ffSandwich, style2, nl: 1, sp: 1),
_Fragment('sit', opportunity, ltr, ffLtr, style2),
_Fragment(placeholderChar, endOfText, ltr, ffLtr, defaultStyle),
]);
});
});
}
/// Holds information about how a fragment.
class _Fragment {
_Fragment(
this.text,
this.type,
this.textDirection,
this.fragmentFlow,
this.style, {
this.nl = 0,
this.sp = 0,
});
factory _Fragment._fromLayoutFragment(String text, LayoutFragment layoutFragment) {
return _Fragment(
text.substring(layoutFragment.start, layoutFragment.end),
layoutFragment.type,
layoutFragment.textDirection,
layoutFragment.fragmentFlow,
layoutFragment.style,
nl: layoutFragment.trailingNewlines,
sp: layoutFragment.trailingSpaces,
);
}
final String text;
final LineBreakType type;
final TextDirection? textDirection;
final FragmentFlow fragmentFlow;
final EngineTextStyle style;
/// The number of trailing new line characters.
final int nl;
/// The number of trailing spaces.
final int sp;
@override
int get hashCode => Object.hash(text, type, textDirection, fragmentFlow, style, nl, sp);
@override
bool operator ==(Object other) {
return other is _Fragment &&
other.text == text &&
other.type == type &&
other.textDirection == textDirection &&
other.fragmentFlow == fragmentFlow &&
other.style == style &&
other.nl == nl &&
other.sp == sp;
}
@override
String toString() {
return '"$text" ($type, $textDirection, $fragmentFlow, nl: $nl, sp: $sp)';
}
}
List<_Fragment> split(CanvasParagraph paragraph) {
return <_Fragment>[
for (final LayoutFragment layoutFragment in computeLayoutFragments(paragraph))
_Fragment._fromLayoutFragment(paragraph.plainText, layoutFragment),
];
}
List<LayoutFragment> computeLayoutFragments(CanvasParagraph paragraph) {
return LayoutFragmenter(paragraph.plainText, paragraph.spans).fragment();
}
extension _EngineTextStyle on EngineTextStyle {
EngineTextStyle copyWith({
Color? color,
TextDecoration? decoration,
Color? decorationColor,
TextDecorationStyle? decorationStyle,
double? decorationThickness,
FontWeight? fontWeight,
FontStyle? fontStyle,
TextBaseline? textBaseline,
String? fontFamily,
List<String>? fontFamilyFallback,
double? fontSize,
double? letterSpacing,
double? wordSpacing,
double? height,
TextLeadingDistribution? leadingDistribution,
Locale? locale,
Paint? background,
Paint? foreground,
List<Shadow>? shadows,
List<FontFeature>? fontFeatures,
List<FontVariation>? fontVariations,
}) {
return EngineTextStyle(
color: color ?? this.color,
decoration: decoration ?? this.decoration,
decorationColor: decorationColor ?? this.decorationColor,
decorationStyle: decorationStyle ?? this.decorationStyle,
decorationThickness: decorationThickness ?? this.decorationThickness,
fontWeight: fontWeight ?? this.fontWeight,
fontStyle: fontStyle ?? this.fontStyle,
textBaseline: textBaseline ?? this.textBaseline,
fontFamily: fontFamily ?? this.fontFamily,
fontFamilyFallback: fontFamilyFallback ?? this.fontFamilyFallback,
fontSize: fontSize ?? this.fontSize,
letterSpacing: letterSpacing ?? this.letterSpacing,
wordSpacing: wordSpacing ?? this.wordSpacing,
height: height ?? this.height,
leadingDistribution: leadingDistribution,
locale: locale ?? this.locale,
background: background ?? this.background,
foreground: foreground ?? this.foreground,
shadows: shadows ?? this.shadows,
fontFeatures: fontFeatures ?? this.fontFeatures,
fontVariations: fontVariations ?? this.fontVariations,
);
}
}

View File

@@ -1,141 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
TestLine l(
String? displayText,
int? startIndex,
int? endIndex, {
bool? hardBreak,
double? height,
double? width,
double? widthWithTrailingSpaces,
double? left,
double? baseline,
}) {
return TestLine(
displayText: displayText,
startIndex: startIndex,
endIndex: endIndex,
hardBreak: hardBreak,
height: height,
width: width,
widthWithTrailingSpaces: widthWithTrailingSpaces,
left: left,
baseline: baseline,
);
}
void expectLines(CanvasParagraph paragraph, List<TestLine> expectedLines) {
final List<ParagraphLine> lines = paragraph.lines;
expect(lines, hasLength(expectedLines.length));
for (int i = 0; i < lines.length; i++) {
final ParagraphLine line = lines[i];
final TestLine expectedLine = expectedLines[i];
expect(
line.lineNumber,
i,
reason: 'line #$i had the wrong `lineNumber`. Expected: $i. Actual: ${line.lineNumber}',
);
if (expectedLine.displayText != null) {
final String displayText = line.getText(paragraph);
expect(
displayText,
expectedLine.displayText,
reason:
'line #$i had a different `displayText` value: "$displayText" vs. "${expectedLine.displayText}"',
);
}
if (expectedLine.startIndex != null) {
expect(
line.startIndex,
expectedLine.startIndex,
reason:
'line #$i had a different `startIndex` value: "${line.startIndex}" vs. "${expectedLine.startIndex}"',
);
}
if (expectedLine.endIndex != null) {
expect(
line.endIndex,
expectedLine.endIndex,
reason:
'line #$i had a different `endIndex` value: "${line.endIndex}" vs. "${expectedLine.endIndex}"',
);
}
if (expectedLine.hardBreak != null) {
expect(
line.hardBreak,
expectedLine.hardBreak,
reason:
'line #$i had a different `hardBreak` value: "${line.hardBreak}" vs. "${expectedLine.hardBreak}"',
);
}
if (expectedLine.height != null) {
expect(
line.height,
expectedLine.height,
reason:
'line #$i had a different `height` value: "${line.height}" vs. "${expectedLine.height}"',
);
}
if (expectedLine.width != null) {
expect(
line.width,
expectedLine.width,
reason:
'line #$i had a different `width` value: "${line.width}" vs. "${expectedLine.width}"',
);
}
if (expectedLine.widthWithTrailingSpaces != null) {
expect(
line.widthWithTrailingSpaces,
expectedLine.widthWithTrailingSpaces,
reason:
'line #$i had a different `widthWithTrailingSpaces` value: "${line.widthWithTrailingSpaces}" vs. "${expectedLine.widthWithTrailingSpaces}"',
);
}
if (expectedLine.left != null) {
expect(
line.left,
expectedLine.left,
reason: 'line #$i had a different `left` value: "${line.left}" vs. "${expectedLine.left}"',
);
}
if (expectedLine.baseline != null) {
expect(
line.baseline,
expectedLine.baseline,
reason:
'line #$i had a different `baseline` value: "${line.baseline}" vs. "${expectedLine.baseline}"',
);
}
}
}
class TestLine {
TestLine({
this.displayText,
this.startIndex,
this.endIndex,
this.hardBreak,
this.height,
this.width,
this.widthWithTrailingSpaces,
this.left,
this.baseline,
});
final String? displayText;
final int? startIndex;
final int? endIndex;
final bool? hardBreak;
final double? height;
final double? width;
final double? widthWithTrailingSpaces;
final double? left;
final double? baseline;
}

View File

@@ -1,701 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../../common/test_initialization.dart';
import '../paragraph/helper.dart';
import 'layout_service_helper.dart';
const bool skipWordSpacing = true;
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(withImplicitView: true);
test('no text', () {
final CanvasParagraph paragraph = CanvasParagraphBuilder(ahemStyle).build();
paragraph.layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 0);
expect(paragraph.minIntrinsicWidth, 0);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[l('', 0, 0, width: 0.0, height: 10.0, baseline: 8.0)]);
});
test('preserves whitespace when measuring', () {
CanvasParagraph paragraph;
// leading whitespaces
paragraph = plain(ahemStyle, ' abc')..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 60);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[l(' abc', 0, 6, hardBreak: true, width: 60.0)]);
// trailing whitespaces
paragraph = plain(ahemStyle, 'abc ')..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 60);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[l('abc ', 0, 6, hardBreak: true, width: 30.0)]);
// mixed whitespaces
paragraph = plain(ahemStyle, ' ab c ')..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 100);
expect(paragraph.minIntrinsicWidth, 20);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l(' ab c ', 0, 10, hardBreak: true, width: 80.0, left: 0.0),
]);
// single whitespace
paragraph = plain(ahemStyle, ' ')..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 10);
expect(paragraph.minIntrinsicWidth, 0);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[l(' ', 0, 1, hardBreak: true, width: 0.0, left: 0.0)]);
// whitespace only
paragraph = plain(ahemStyle, ' ')..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 50);
expect(paragraph.minIntrinsicWidth, 0);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[l(' ', 0, 5, hardBreak: true, width: 0.0, left: 0.0)]);
});
test('uses single-line when text can fit without wrapping', () {
final CanvasParagraph paragraph = plain(ahemStyle, '12345')..layout(constrain(50.0));
// Should fit on a single line.
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 50);
expect(paragraph.minIntrinsicWidth, 50);
expect(paragraph.width, 50);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[
l('12345', 0, 5, hardBreak: true, width: 50.0, left: 0.0, height: 10.0, baseline: 8.0),
]);
});
test('simple multi-line text', () {
final CanvasParagraph paragraph = plain(ahemStyle, 'foo bar baz')..layout(constrain(70.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 110);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.width, 70);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('foo bar ', 0, 8, hardBreak: false, width: 70.0, left: 0.0, height: 10.0, baseline: 8.0),
l('baz', 8, 11, hardBreak: true, width: 30.0, left: 0.0, height: 10.0, baseline: 18.0),
]);
});
test('uses multi-line for long text', () {
CanvasParagraph paragraph;
// The long text doesn't fit in 50px of width, so it needs to wrap.
paragraph = plain(ahemStyle, '1234567890')..layout(constrain(50.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 100);
expect(paragraph.minIntrinsicWidth, 100);
expect(paragraph.width, 50);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('12345', 0, 5, hardBreak: false, width: 50.0, left: 0.0, height: 10.0, baseline: 8.0),
l('67890', 5, 10, hardBreak: true, width: 50.0, left: 0.0, height: 10.0, baseline: 18.0),
]);
// The first word is force-broken twice.
paragraph = plain(ahemStyle, 'abcdefghijk lm')..layout(constrain(50.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 140);
expect(paragraph.minIntrinsicWidth, 110);
expect(paragraph.width, 50);
expect(paragraph.height, 30);
expectLines(paragraph, <TestLine>[
l('abcde', 0, 5, hardBreak: false, width: 50.0, left: 0.0, height: 10.0, baseline: 8.0),
l('fghij', 5, 10, hardBreak: false, width: 50.0, left: 0.0, height: 10.0, baseline: 18.0),
l('k lm', 10, 14, hardBreak: true, width: 40.0, left: 0.0, height: 10.0, baseline: 28.0),
]);
// Constraints enough only for "abcdef" but not for the trailing space.
paragraph = plain(ahemStyle, 'abcdef gh')..layout(constrain(60.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 90);
expect(paragraph.minIntrinsicWidth, 60);
expect(paragraph.width, 60);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcdef ', 0, 7, hardBreak: false, width: 60.0, left: 0.0, height: 10.0, baseline: 8.0),
l('gh', 7, 9, hardBreak: true, width: 20.0, left: 0.0, height: 10.0, baseline: 18.0),
]);
// Constraints aren't enough even for a single character. In this case,
// we show a minimum of one character per line.
paragraph = plain(ahemStyle, 'AA')..layout(constrain(8.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 20);
expect(paragraph.minIntrinsicWidth, 20);
expect(paragraph.width, 8);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('A', 0, 1, hardBreak: false, width: 10.0, left: 0.0, height: 10.0, baseline: 8.0),
l('A', 1, 2, hardBreak: true, width: 10.0, left: 0.0, height: 10.0, baseline: 18.0),
]);
// Extremely narrow constraints with new line in the middle.
paragraph = plain(ahemStyle, 'AA\nA')..layout(constrain(8.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 20);
expect(paragraph.minIntrinsicWidth, 20);
expect(paragraph.width, 8);
expect(paragraph.height, 30);
expectLines(paragraph, <TestLine>[
l('A', 0, 1, hardBreak: false, width: 10.0, left: 0.0, height: 10.0, baseline: 8.0),
l('A', 1, 3, hardBreak: true, width: 10.0, left: 0.0, height: 10.0, baseline: 18.0),
l('A', 3, 4, hardBreak: true, width: 10.0, left: 0.0, height: 10.0, baseline: 28.0),
]);
// Extremely narrow constraints with new line in the end.
paragraph = plain(ahemStyle, 'AAA\n')..layout(constrain(8.0));
expect(paragraph.alphabeticBaseline, 8);
expect(paragraph.maxIntrinsicWidth, 30);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.width, 8);
expect(paragraph.height, 40);
expectLines(paragraph, <TestLine>[
l('A', 0, 1, hardBreak: false, width: 10.0, left: 0.0, height: 10.0, baseline: 8.0),
l('A', 1, 2, hardBreak: false, width: 10.0, left: 0.0, height: 10.0, baseline: 18.0),
l('A', 2, 4, hardBreak: true, width: 10.0, left: 0.0, height: 10.0, baseline: 28.0),
l('', 4, 4, hardBreak: true, width: 0.0, left: 0.0, height: 10.0, baseline: 38.0),
]);
});
test('uses multi-line for text that contains new-line', () {
final CanvasParagraph paragraph = plain(ahemStyle, '12\n34')..layout(constrain(50.0));
// Text containing newlines should always be drawn in multi-line mode.
expect(paragraph.maxIntrinsicWidth, 20);
expect(paragraph.minIntrinsicWidth, 20);
expect(paragraph.width, 50);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('12', 0, 3, hardBreak: true, width: 20.0, left: 0.0),
l('34', 3, 5, hardBreak: true, width: 20.0, left: 0.0),
]);
});
test('empty lines', () {
CanvasParagraph paragraph;
// Empty lines in the beginning.
paragraph = plain(ahemStyle, '\n\n1234')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 40);
expect(paragraph.minIntrinsicWidth, 40);
expect(paragraph.height, 30);
expectLines(paragraph, <TestLine>[
l('', 0, 1, hardBreak: true, width: 0.0, left: 0.0),
l('', 1, 2, hardBreak: true, width: 0.0, left: 0.0),
l('1234', 2, 6, hardBreak: true, width: 40.0, left: 0.0),
]);
// Empty lines in the middle.
paragraph = plain(ahemStyle, '12\n\n345')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 30);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.height, 30);
expectLines(paragraph, <TestLine>[
l('12', 0, 3, hardBreak: true, width: 20.0, left: 0.0),
l('', 3, 4, hardBreak: true, width: 0.0, left: 0.0),
l('345', 4, 7, hardBreak: true, width: 30.0, left: 0.0),
]);
// Empty lines in the end.
paragraph = plain(ahemStyle, '1234\n\n')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 40);
expect(paragraph.minIntrinsicWidth, 40);
expect(paragraph.height, 30);
expectLines(paragraph, <TestLine>[
l('1234', 0, 5, hardBreak: true, width: 40.0, left: 0.0),
l('', 5, 6, hardBreak: true, width: 0.0, left: 0.0),
l('', 6, 6, hardBreak: true, width: 0.0, left: 0.0),
]);
});
test('wraps multi-line text correctly when constraint width is infinite', () {
final CanvasParagraph paragraph = plain(ahemStyle, '123\n456 789')
..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 70);
expect(paragraph.minIntrinsicWidth, 30);
expect(paragraph.width, double.infinity);
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('123', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('456 789', 4, 11, hardBreak: true, width: 70.0, left: 0.0),
]);
});
test('takes letter spacing into account', () {
final EngineTextStyle spacedTextStyle = EngineTextStyle.only(letterSpacing: 3);
final CanvasParagraph spacedText = plain(ahemStyle, 'abc', textStyle: spacedTextStyle)
..layout(constrain(100.0));
expect(spacedText.minIntrinsicWidth, 39);
expect(spacedText.maxIntrinsicWidth, 39);
});
test('takes word spacing into account', () {
final CanvasParagraph normalText = plain(ahemStyle, 'a b c')..layout(constrain(100.0));
final CanvasParagraph spacedText = plain(
ahemStyle,
'a b c',
textStyle: EngineTextStyle.only(wordSpacing: 1.5),
)..layout(constrain(100.0));
expect(normalText.maxIntrinsicWidth < spacedText.maxIntrinsicWidth, isTrue);
}, skip: skipWordSpacing);
test('minIntrinsicWidth', () {
CanvasParagraph paragraph;
// Simple case.
paragraph = plain(ahemStyle, 'abc de fghi')..layout(constrain(50.0));
expect(paragraph.minIntrinsicWidth, 40);
expectLines(paragraph, <TestLine>[
l('abc ', 0, 4, hardBreak: false, width: 30.0, left: 0.0),
l('de ', 4, 7, hardBreak: false, width: 20.0, left: 0.0),
l('fghi', 7, 11, hardBreak: true, width: 40.0, left: 0.0),
]);
// With new lines.
paragraph = plain(ahemStyle, 'abcd\nef\nghi')..layout(constrain(50.0));
expect(paragraph.minIntrinsicWidth, 40);
expectLines(paragraph, <TestLine>[
l('abcd', 0, 5, hardBreak: true, width: 40.0, left: 0.0),
l('ef', 5, 8, hardBreak: true, width: 20.0, left: 0.0),
l('ghi', 8, 11, hardBreak: true, width: 30.0, left: 0.0),
]);
// With trailing whitespace.
paragraph = plain(ahemStyle, 'abcd efg')..layout(constrain(50.0));
expect(paragraph.minIntrinsicWidth, 40);
expectLines(paragraph, <TestLine>[
l('abcd ', 0, 10, hardBreak: false, width: 40.0, left: 0.0),
l('efg', 10, 13, hardBreak: true, width: 30.0, left: 0.0),
]);
// With trailing whitespace and new lines.
paragraph = plain(ahemStyle, 'abc \ndefg')..layout(constrain(50.0));
expect(paragraph.minIntrinsicWidth, 40);
expectLines(paragraph, <TestLine>[
l('abc ', 0, 8, hardBreak: true, width: 30.0, left: 0.0),
l('defg', 8, 12, hardBreak: true, width: 40.0, left: 0.0),
]);
// Very long text.
paragraph = plain(ahemStyle, 'AAAAAAAAAAAA')..layout(constrain(50.0));
expect(paragraph.minIntrinsicWidth, 120);
expectLines(paragraph, <TestLine>[
l('AAAAA', 0, 5, hardBreak: false, width: 50.0, left: 0.0),
l('AAAAA', 5, 10, hardBreak: false, width: 50.0, left: 0.0),
l('AA', 10, 12, hardBreak: true, width: 20.0, left: 0.0),
]);
});
test('maxIntrinsicWidth', () {
CanvasParagraph paragraph;
// Simple case.
paragraph = plain(ahemStyle, 'abc de fghi')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 110);
expectLines(paragraph, <TestLine>[
l('abc ', 0, 4, hardBreak: false, width: 30.0, left: 0.0),
l('de ', 4, 7, hardBreak: false, width: 20.0, left: 0.0),
l('fghi', 7, 11, hardBreak: true, width: 40.0, left: 0.0),
]);
// With new lines.
paragraph = plain(ahemStyle, 'abcd\nef\nghi')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 40);
expectLines(paragraph, <TestLine>[
l('abcd', 0, 5, hardBreak: true, width: 40.0, left: 0.0),
l('ef', 5, 8, hardBreak: true, width: 20.0, left: 0.0),
l('ghi', 8, 11, hardBreak: true, width: 30.0, left: 0.0),
]);
// With long whitespace.
paragraph = plain(ahemStyle, 'abcd efg')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 100);
expectLines(paragraph, <TestLine>[
l('abcd ', 0, 7, hardBreak: false, width: 40.0, left: 0.0),
l('efg', 7, 10, hardBreak: true, width: 30.0, left: 0.0),
]);
// With trailing whitespace.
paragraph = plain(ahemStyle, 'abc def ')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 100);
expectLines(paragraph, <TestLine>[
l('abc ', 0, 4, hardBreak: false, width: 30.0, left: 0.0),
l('def ', 4, 10, hardBreak: true, width: 30.0, left: 0.0),
]);
// With trailing whitespace and new lines.
paragraph = plain(ahemStyle, 'abc \ndef ')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 60);
expectLines(paragraph, <TestLine>[
l('abc ', 0, 5, hardBreak: true, width: 30.0, left: 0.0),
l('def ', 5, 11, hardBreak: true, width: 30.0, left: 0.0),
]);
// Very long text.
paragraph = plain(ahemStyle, 'AAAAAAAAAAAA')..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 120);
expectLines(paragraph, <TestLine>[
l('AAAAA', 0, 5, hardBreak: false, width: 50.0, left: 0.0),
l('AAAAA', 5, 10, hardBreak: false, width: 50.0, left: 0.0),
l('AA', 10, 12, hardBreak: true, width: 20.0, left: 0.0),
]);
});
test('respects text overflow', () {
final EngineParagraphStyle overflowStyle = EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
ellipsis: '...',
);
// The text shouldn't be broken into multiple lines, so the height should
// be equal to a height of a single line.
final CanvasParagraph longText = plain(
overflowStyle,
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
)..layout(constrain(50.0));
expect(longText.minIntrinsicWidth, 480);
expect(longText.maxIntrinsicWidth, 480);
expect(longText.height, 10);
expectLines(longText, <TestLine>[l('AA...', 0, 2, hardBreak: true, width: 50.0, left: 0.0)]);
// The short prefix should make the text break into two lines, but the
// second line should remain unbroken.
final CanvasParagraph longTextShortPrefix = plain(
overflowStyle,
'AAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
)..layout(constrain(50.0));
expect(longTextShortPrefix.minIntrinsicWidth, 450);
expect(longTextShortPrefix.maxIntrinsicWidth, 450);
expect(longTextShortPrefix.height, 20);
expectLines(longTextShortPrefix, <TestLine>[
l('AAA', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('AA...', 4, 6, hardBreak: true, width: 50.0, left: 0.0),
]);
// Constraints only enough to fit "AA" with the ellipsis, but not the
// trailing white space.
final CanvasParagraph trailingSpace = plain(overflowStyle, 'AA AAA')..layout(constrain(50.0));
expect(trailingSpace.minIntrinsicWidth, 30);
expect(trailingSpace.maxIntrinsicWidth, 60);
expect(trailingSpace.height, 10);
expectLines(trailingSpace, <TestLine>[
l('AA...', 0, 2, hardBreak: true, width: 50.0, left: 0.0),
]);
// Tiny constraints.
final CanvasParagraph paragraph = plain(overflowStyle, 'AAAA')..layout(constrain(30.0));
expect(paragraph.minIntrinsicWidth, 40);
expect(paragraph.maxIntrinsicWidth, 40);
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[l('...', 0, 0, hardBreak: true, width: 30.0, left: 0.0)]);
// Tinier constraints (not enough for the ellipsis).
paragraph.layout(constrain(10.0));
expect(paragraph.minIntrinsicWidth, 40);
expect(paragraph.maxIntrinsicWidth, 40);
expect(paragraph.height, 10);
// TODO(mdebbar): https://github.com/flutter/flutter/issues/34346
// expectLines(paragraph, <TestLine>[
// l('.', 0, 0, hardBreak: false, width: 10.0, left: 0.0),
// ]);
expectLines(paragraph, <TestLine>[l('...', 0, 0, hardBreak: true, width: 30.0, left: 0.0)]);
});
test('respects max lines', () {
final EngineParagraphStyle maxlinesStyle = EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
maxLines: 2,
);
// The height should be that of a single line.
final CanvasParagraph oneline = plain(maxlinesStyle, 'One line')
..layout(constrain(double.infinity));
expect(oneline.height, 10);
expectLines(oneline, <TestLine>[l('One line', 0, 8, hardBreak: true, width: 80.0, left: 0.0)]);
// The height should respect max lines and be limited to two lines here.
final CanvasParagraph threelines = plain(maxlinesStyle, 'First\nSecond\nThird')
..layout(constrain(double.infinity));
expect(threelines.height, 20);
expectLines(threelines, <TestLine>[
l('First', 0, 6, hardBreak: true, width: 50.0, left: 0.0),
l('Second', 6, 13, hardBreak: true, width: 60.0, left: 0.0),
]);
// The height should respect max lines and be limited to two lines here.
final CanvasParagraph veryLong = plain(
maxlinesStyle,
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
)..layout(constrain(50.0));
expect(veryLong.height, 20);
expectLines(veryLong, <TestLine>[
l('Lorem ', 0, 6, hardBreak: false, width: 50.0, left: 0.0),
l('ipsum ', 6, 12, hardBreak: false, width: 50.0, left: 0.0),
]);
// Case when last line is a long unbreakable word.
final CanvasParagraph veryLongLastLine = plain(maxlinesStyle, 'AAA AAAAAAAAAAAAAAAAAAA')
..layout(constrain(50.0));
expect(veryLongLastLine.height, 20);
expectLines(veryLongLastLine, <TestLine>[
l('AAA ', 0, 4, hardBreak: false, width: 30.0, left: 0.0),
l('AAAAA', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
]);
});
test('respects text overflow and max lines combined', () {
final EngineParagraphStyle onelineStyle = EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
maxLines: 1,
ellipsis: '...',
);
final EngineParagraphStyle multilineStyle = EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
maxLines: 2,
ellipsis: '...',
);
CanvasParagraph paragraph;
// Simple no overflow case.
paragraph = plain(onelineStyle, 'abcdef')..layout(constrain(60.0));
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[l('abcdef', 0, 6, hardBreak: true, width: 60.0, left: 0.0)]);
// Simple overflow case.
paragraph = plain(onelineStyle, 'abcd efg')..layout(constrain(60.0));
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[l('abc...', 0, 3, hardBreak: true, width: 60.0, left: 0.0)]);
// Another simple overflow case.
paragraph = plain(onelineStyle, 'a bcde fgh')..layout(constrain(60.0));
expect(paragraph.height, 10);
expectLines(paragraph, <TestLine>[l('a b...', 0, 3, hardBreak: true, width: 60.0, left: 0.0)]);
// The ellipsis is supposed to go on the second line, but because the
// 2nd line doesn't overflow, no ellipsis is shown.
paragraph = plain(multilineStyle, 'abcdef ghijkl')..layout(constrain(60.0));
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcdef ', 0, 7, hardBreak: false, width: 60.0, left: 0.0),
l('ghijkl', 7, 13, hardBreak: true, width: 60.0, left: 0.0),
]);
// But when the 2nd line is long enough, the ellipsis is shown.
paragraph = plain(multilineStyle, 'abcd efghijkl')..layout(constrain(60.0));
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcd ', 0, 5, hardBreak: false, width: 40.0, left: 0.0),
l('efg...', 5, 8, hardBreak: true, width: 60.0, left: 0.0),
]);
// Even if the second line can be broken, we don't break it, we just
// insert the ellipsis.
paragraph = plain(multilineStyle, 'abcde f gh ijk')..layout(constrain(60.0));
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcde ', 0, 6, hardBreak: false, width: 50.0, left: 0.0),
l('f g...', 6, 9, hardBreak: true, width: 60.0, left: 0.0),
]);
// First line overflows but second line doesn't.
paragraph = plain(multilineStyle, 'abcdefg hijk')..layout(constrain(60.0));
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcdef', 0, 6, hardBreak: false, width: 60.0, left: 0.0),
l('g hijk', 6, 12, hardBreak: true, width: 60.0, left: 0.0),
]);
// Both first and second lines overflow.
paragraph = plain(multilineStyle, 'abcdefg hijklmnop')..layout(constrain(60.0));
expect(paragraph.height, 20);
expectLines(paragraph, <TestLine>[
l('abcdef', 0, 6, hardBreak: false, width: 60.0, left: 0.0),
l('g h...', 6, 9, hardBreak: true, width: 60.0, left: 0.0),
]);
});
test('handles textAlign', () {
CanvasParagraph paragraph;
EngineParagraphStyle createStyle(ui.TextAlign textAlign) {
return EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
textAlign: textAlign,
textDirection: ui.TextDirection.ltr,
);
}
paragraph = plain(createStyle(ui.TextAlign.start), 'abc\ndefghi')..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 0.0),
]);
paragraph = plain(createStyle(ui.TextAlign.end), 'abc\ndefghi')..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 20.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 40.0),
]);
paragraph = plain(createStyle(ui.TextAlign.center), 'abc\ndefghi')..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 10.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 20.0),
]);
paragraph = plain(createStyle(ui.TextAlign.left), 'abc\ndefghi')..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 0.0),
]);
paragraph = plain(createStyle(ui.TextAlign.right), 'abc\ndefghi')..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 20.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 40.0),
]);
});
test('handles rtl with textAlign', () {
CanvasParagraph paragraph;
EngineParagraphStyle createStyle(ui.TextAlign textAlign) {
return EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
textAlign: textAlign,
textDirection: ui.TextDirection.rtl,
);
}
paragraph = plain(createStyle(ui.TextAlign.start), 'abc\ndefghi')..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 20.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 40.0),
]);
paragraph = plain(createStyle(ui.TextAlign.end), 'abc\ndefghi')..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 0.0),
]);
paragraph = plain(createStyle(ui.TextAlign.center), 'abc\ndefghi')..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 10.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 20.0),
]);
paragraph = plain(createStyle(ui.TextAlign.left), 'abc\ndefghi')..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 0.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 0.0),
]);
paragraph = plain(createStyle(ui.TextAlign.right), 'abc\ndefghi')..layout(constrain(50.0));
expectLines(paragraph, <TestLine>[
l('abc', 0, 4, hardBreak: true, width: 30.0, left: 20.0),
l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0),
l('i', 9, 10, hardBreak: true, width: 10.0, left: 40.0),
]);
});
test('uses a single minimal canvas', () {
debugResetCanvasCount();
plain(ahemStyle, 'Lorem').layout(constrain(double.infinity));
plain(ahemStyle, 'ipsum dolor').layout(constrain(150.0));
// Try different styles too.
plain(
EngineParagraphStyle(fontWeight: ui.FontWeight.bold),
'sit amet',
).layout(constrain(300.0));
expect(textContext.canvas!.width, isZero);
expect(textContext.canvas!.height, isZero);
// This number is 0 instead of 1 because the canvas is created at the top
// level as a global variable. So by the time this test runs, the canvas
// would have been created already.
//
// So we just make sure that no new canvas is created after the above layout
// calls.
expect(debugCanvasCount, 0);
});
test('does not leak styles across spanometers', () {
// This prevents the Ahem font from being forced in all paragraphs.
ui_web.debugEmulateFlutterTesterEnvironment = false;
final CanvasParagraph p1 = plain(
EngineParagraphStyle(fontSize: 20.0, fontFamily: 'FontFamily1'),
'Lorem',
)..layout(constrain(double.infinity));
// After the layout, the canvas should have the above style applied.
expect(textContext.font, contains('20px'));
expect(textContext.font, contains('FontFamily1'));
final CanvasParagraph p2 = plain(
EngineParagraphStyle(fontSize: 40.0, fontFamily: 'FontFamily2'),
'ipsum dolor',
)..layout(constrain(double.infinity));
// After the layout, the canvas should have the above style applied.
expect(textContext.font, contains('40px'));
expect(textContext.font, contains('FontFamily2'));
p1.getBoxesForRange(0, 2);
// getBoxesForRange performs some text measurements. Let's make sure that it
// applied the correct style.
expect(textContext.font, contains('20px'));
expect(textContext.font, contains('FontFamily1'));
p2.getBoxesForRange(0, 4);
// getBoxesForRange performs some text measurements. Let's make sure that it
// applied the correct style.
expect(textContext.font, contains('40px'));
expect(textContext.font, contains('FontFamily2'));
ui_web.debugEmulateFlutterTesterEnvironment = true;
});
}

View File

@@ -1,255 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart' as ui;
import '../../common/test_initialization.dart';
import '../paragraph/helper.dart';
import 'layout_service_helper.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
setUpUnitTests(withImplicitView: true);
test('does not crash on empty spans', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('');
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('Lorem ipsum');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('');
});
expect(() => paragraph.layout(constrain(double.infinity)), returnsNormally);
});
test('measures spans in the same line correctly', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(fontSize: 12.0));
// 12.0 * 6 = 72.0 (with spaces)
// 12.0 * 5 = 60.0 (without spaces)
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(fontSize: 13.0));
// 13.0 * 6 = 78.0 (with spaces)
// 13.0 * 5 = 65.0 (without spaces)
builder.addText('ipsum ');
builder.pushStyle(EngineTextStyle.only(fontSize: 11.0));
// 11.0 * 5 = 55.0
builder.addText('dolor');
})..layout(constrain(double.infinity));
expect(paragraph.maxIntrinsicWidth, 205.0);
expect(paragraph.minIntrinsicWidth, 65.0); // "ipsum"
expect(paragraph.width, double.infinity);
expectLines(paragraph, <TestLine>[
l('Lorem ipsum dolor', 0, 17, hardBreak: true, width: 205.0, left: 0.0),
]);
});
test('breaks lines correctly at the end of spans', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('Lorem ');
builder.pushStyle(EngineTextStyle.only(fontSize: 15.0));
builder.addText('sit ');
builder.pop();
builder.addText('.');
})..layout(constrain(60.0));
expect(paragraph.maxIntrinsicWidth, 130.0);
expect(paragraph.minIntrinsicWidth, 50.0); // "Lorem"
expect(paragraph.width, 60.0);
expectLines(paragraph, <TestLine>[
l('Lorem ', 0, 6, hardBreak: false, width: 50.0, left: 0.0),
l('sit ', 6, 10, hardBreak: false, width: 45.0, left: 0.0),
l('.', 10, 11, hardBreak: true, width: 10.0, left: 0.0),
]);
});
test('breaks lines correctly in the middle of spans', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.addText('Lorem ipsum ');
builder.pushStyle(EngineTextStyle.only(fontSize: 11.0));
builder.addText('sit dolor');
})..layout(constrain(100.0));
expect(paragraph.maxIntrinsicWidth, 219.0);
expect(paragraph.minIntrinsicWidth, 55.0); // "dolor"
expect(paragraph.width, 100.0);
expectLines(paragraph, <TestLine>[
l('Lorem ', 0, 6, hardBreak: false, width: 50.0, left: 0.0),
l('ipsum sit ', 6, 16, hardBreak: false, width: 93.0, left: 0.0),
l('dolor', 16, 21, hardBreak: true, width: 55.0, left: 0.0),
]);
});
test('handles space-only spans', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('Lorem ');
builder.pop();
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText(' ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText(' ');
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('ipsum');
});
paragraph.layout(constrain(80.0));
expect(paragraph.maxIntrinsicWidth, 160.0);
expect(paragraph.minIntrinsicWidth, 50.0); // "Lorem" or "ipsum"
expect(paragraph.width, 80.0);
expectLines(paragraph, <TestLine>[
l(
'Lorem ',
0,
11,
hardBreak: false,
width: 50.0,
widthWithTrailingSpaces: 110.0,
left: 0.0,
),
l('ipsum', 11, 16, hardBreak: true, width: 50.0, left: 0.0),
]);
});
test('should not break at span end if it is not a line break', () {
final CanvasParagraph paragraph = rich(ahemStyle, (CanvasParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: red));
builder.addText('Lorem');
builder.pop();
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText(' ');
builder.pushStyle(EngineTextStyle.only(color: black));
builder.addText('ip');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('su');
builder.pushStyle(EngineTextStyle.only(color: white));
builder.addText('m');
})..layout(constrain(50.0));
expect(paragraph.maxIntrinsicWidth, 110.0);
expect(paragraph.minIntrinsicWidth, 50.0); // "Lorem" or "ipsum"
expect(paragraph.width, 50.0);
expectLines(paragraph, <TestLine>[
l('Lorem ', 0, 6, hardBreak: false, width: 50.0, left: 0.0),
l('ipsum', 6, 11, hardBreak: true, width: 50.0, left: 0.0),
]);
});
test('should handle placeholder-only paragraphs', () {
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
textAlign: ui.TextAlign.center,
);
final CanvasParagraph paragraph = rich(paragraphStyle, (CanvasParagraphBuilder builder) {
builder.addPlaceholder(
300.0,
50.0,
ui.PlaceholderAlignment.baseline,
baseline: ui.TextBaseline.alphabetic,
);
})..layout(constrain(500.0));
expect(paragraph.maxIntrinsicWidth, 300.0);
expect(paragraph.minIntrinsicWidth, 300.0);
expect(paragraph.height, 50.0);
expectLines(paragraph, <TestLine>[
l(placeholderChar, 0, 1, hardBreak: true, width: 300.0, left: 100.0),
]);
});
test('correct maxIntrinsicWidth when paragraph ends with placeholder', () {
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
textAlign: ui.TextAlign.center,
);
final CanvasParagraph paragraph = rich(paragraphStyle, (CanvasParagraphBuilder builder) {
builder.addText('abcd');
builder.addPlaceholder(300.0, 50.0, ui.PlaceholderAlignment.bottom);
})..layout(constrain(400.0));
expect(paragraph.maxIntrinsicWidth, 340.0);
expect(paragraph.minIntrinsicWidth, 300.0);
expect(paragraph.height, 50.0);
expectLines(paragraph, <TestLine>[
l('abcd$placeholderChar', 0, 5, hardBreak: true, width: 340.0, left: 30.0),
]);
});
test('handles new line followed by a placeholder', () {
final EngineParagraphStyle paragraphStyle = EngineParagraphStyle(
fontFamily: 'Ahem',
fontSize: 10,
textAlign: ui.TextAlign.center,
);
final CanvasParagraph paragraph = rich(paragraphStyle, (CanvasParagraphBuilder builder) {
builder.addText('Lorem\n');
builder.addPlaceholder(300.0, 40.0, ui.PlaceholderAlignment.bottom);
builder.addText('ipsum');
})..layout(constrain(300.0));
// The placeholder's width + "ipsum"
expect(paragraph.maxIntrinsicWidth, 300.0 + 50.0);
expect(paragraph.minIntrinsicWidth, 300.0);
expect(paragraph.height, 10.0 + 40.0 + 10.0);
expectLines(paragraph, <TestLine>[
l('Lorem', 0, 6, hardBreak: true, width: 50.0, height: 10.0, left: 125.0),
l(placeholderChar, 6, 7, hardBreak: false, width: 300.0, height: 40.0, left: 0.0),
l('ipsum', 7, 12, hardBreak: true, width: 50.0, height: 10.0, left: 125.0),
]);
});
test('correctly force-breaks consecutive non-breakable spans', () {
final CanvasParagraph paragraph = rich(ahemStyle, (ui.ParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(fontSize: 1));
builder.addText('A');
builder.pop(); // Back to fontSize: 10
builder.addText('A' * 20);
builder.pushStyle(EngineTextStyle.only(fontSize: 1));
builder.addText('A');
});
paragraph.layout(constrain(200));
expect(paragraph.maxIntrinsicWidth, 200.0 + 2.0);
expect(paragraph.height, 20.0);
expectLines(paragraph, <TestLine>[
// 1x small "A" + 19x big "A"
l('A' * 20, 0, 20, hardBreak: false, width: 1.0 + 190.0, height: 10.0),
// 1x big "A" + 1x small "A"
l('AA', 20, 22, hardBreak: true, width: 10.0 + 1.0, height: 10.0),
]);
});
test('does not make prohibited line breaks', () {
final CanvasParagraph paragraph = rich(ahemStyle, (ui.ParagraphBuilder builder) {
builder.pushStyle(EngineTextStyle.only(color: blue));
builder.addText('AAA B');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('BB ');
builder.pushStyle(EngineTextStyle.only(color: green));
builder.addText('CC');
});
paragraph.layout(constrain(60));
expect(paragraph.maxIntrinsicWidth, 100.0);
expectLines(paragraph, <TestLine>[
l('AAA ', 0, 4, hardBreak: false, width: 30.0),
l('BBB CC', 4, 10, hardBreak: true, width: 60.0),
]);
});
}

View File

@@ -1,461 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
import '../paragraph/helper.dart';
import 'line_breaker_test_helper.dart';
import 'line_breaker_test_raw_data.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
groupForEachFragmenter(({required bool isV8}) {
List<Line> split(String text) {
final LineBreakFragmenter fragmenter =
isV8 ? V8LineBreakFragmenter(text) : FWLineBreakFragmenter(text);
return <Line>[
for (final LineBreakFragment fragment in fragmenter.fragment())
Line.fromLineBreakFragment(text, fragment),
];
}
test('empty string', () {
expect(split(''), <Line>[Line('', endOfText)]);
});
test('whitespace', () {
expect(split('foo bar'), <Line>[Line('foo ', opportunity, sp: 1), Line('bar', endOfText)]);
expect(split(' foo bar '), <Line>[
Line(' ', opportunity, sp: 2),
Line('foo ', opportunity, sp: 4),
Line('bar ', endOfText, sp: 2),
]);
});
test('single-letter lines', () {
expect(split('foo a bar'), <Line>[
Line('foo ', opportunity, sp: 1),
Line('a ', opportunity, sp: 1),
Line('bar', endOfText),
]);
expect(split('a b c'), <Line>[
Line('a ', opportunity, sp: 1),
Line('b ', opportunity, sp: 1),
Line('c', endOfText),
]);
expect(split(' a b '), <Line>[
Line(' ', opportunity, sp: 1),
Line('a ', opportunity, sp: 1),
Line('b ', endOfText, sp: 1),
]);
});
test('new line characters', () {
final String bk = String.fromCharCode(0x000B);
// Can't have a line break between CR×LF.
expect(split('foo\r\nbar'), <Line>[
Line('foo\r\n', mandatory, nl: 2, sp: 2),
Line('bar', endOfText),
]);
// Any other new line is considered a line break on its own.
expect(split('foo\n\nbar'), <Line>[
Line('foo\n', mandatory, nl: 1, sp: 1),
Line('\n', mandatory, nl: 1, sp: 1),
Line('bar', endOfText),
]);
expect(split('foo\r\rbar'), <Line>[
Line('foo\r', mandatory, nl: 1, sp: 1),
Line('\r', mandatory, nl: 1, sp: 1),
Line('bar', endOfText),
]);
expect(split('foo$bk${bk}bar'), <Line>[
Line('foo$bk', mandatory, nl: 1, sp: 1),
Line(bk, mandatory, nl: 1, sp: 1),
Line('bar', endOfText),
]);
expect(split('foo\n\rbar'), <Line>[
Line('foo\n', mandatory, nl: 1, sp: 1),
Line('\r', mandatory, nl: 1, sp: 1),
Line('bar', endOfText),
]);
expect(split('foo$bk\rbar'), <Line>[
Line('foo$bk', mandatory, nl: 1, sp: 1),
Line('\r', mandatory, nl: 1, sp: 1),
Line('bar', endOfText),
]);
expect(split('foo\r${bk}bar'), <Line>[
Line('foo\r', mandatory, nl: 1, sp: 1),
Line(bk, mandatory, nl: 1, sp: 1),
Line('bar', endOfText),
]);
expect(split('foo$bk\nbar'), <Line>[
Line('foo$bk', mandatory, nl: 1, sp: 1),
Line('\n', mandatory, nl: 1, sp: 1),
Line('bar', endOfText),
]);
expect(split('foo\n${bk}bar'), <Line>[
Line('foo\n', mandatory, nl: 1, sp: 1),
Line(bk, mandatory, nl: 1, sp: 1),
Line('bar', endOfText),
]);
// New lines at the beginning and end.
expect(split('foo\n'), <Line>[Line('foo\n', mandatory, nl: 1, sp: 1), Line('', endOfText)]);
expect(split('foo\r'), <Line>[Line('foo\r', mandatory, nl: 1, sp: 1), Line('', endOfText)]);
expect(split('foo$bk'), <Line>[Line('foo$bk', mandatory, nl: 1, sp: 1), Line('', endOfText)]);
expect(split('\nfoo'), <Line>[Line('\n', mandatory, nl: 1, sp: 1), Line('foo', endOfText)]);
expect(split('\rfoo'), <Line>[Line('\r', mandatory, nl: 1, sp: 1), Line('foo', endOfText)]);
expect(split('${bk}foo'), <Line>[Line(bk, mandatory, nl: 1, sp: 1), Line('foo', endOfText)]);
// Whitespace with new lines.
expect(split('foo \n'), <Line>[
Line('foo \n', mandatory, nl: 1, sp: 3),
Line('', endOfText),
]);
expect(split('foo \n '), <Line>[
Line('foo \n', mandatory, nl: 1, sp: 3),
Line(' ', endOfText, sp: 3),
]);
expect(split('foo \n bar'), <Line>[
Line('foo \n', mandatory, nl: 1, sp: 3),
Line(' ', opportunity, sp: 3),
Line('bar', endOfText),
]);
expect(split('\n foo'), <Line>[
Line('\n', mandatory, nl: 1, sp: 1),
Line(' ', opportunity, sp: 2),
Line('foo', endOfText),
]);
expect(split(' \n foo'), <Line>[
Line(' \n', mandatory, nl: 1, sp: 4),
Line(' ', opportunity, sp: 2),
Line('foo', endOfText),
]);
});
test('trailing spaces and new lines', () {
expect(split('foo bar '), <Line>[
Line('foo ', opportunity, sp: 1),
Line('bar ', endOfText, sp: 2),
]);
expect(split('foo \nbar\nbaz \n'), <Line>[
Line('foo \n', mandatory, nl: 1, sp: 3),
Line('bar\n', mandatory, nl: 1, sp: 1),
Line('baz \n', mandatory, nl: 1, sp: 4),
Line('', endOfText),
]);
});
test('leading spaces', () {
expect(split(' foo'), <Line>[Line(' ', opportunity, sp: 1), Line('foo', endOfText)]);
expect(split(' foo'), <Line>[Line(' ', opportunity, sp: 3), Line('foo', endOfText)]);
expect(split(' foo bar'), <Line>[
Line(' ', opportunity, sp: 2),
Line('foo ', opportunity, sp: 3),
Line('bar', endOfText),
]);
expect(split(' \n foo'), <Line>[
Line(' \n', mandatory, nl: 1, sp: 3),
Line(' ', opportunity, sp: 3),
Line('foo', endOfText),
]);
});
test('whitespace before the last character', () {
expect(split('Lorem sit .'), <Line>[
Line('Lorem ', opportunity, sp: 1),
Line('sit ', opportunity, sp: 1),
Line('.', endOfText),
]);
});
test('placeholders', () {
final CanvasParagraph paragraph = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText('Lorem');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText('ipsum\n');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText('dolor');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText('\nsit');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
});
final String placeholderChar = String.fromCharCode(0xFFFC);
expect(split(paragraph.plainText), <Line>[
Line(placeholderChar, opportunity),
Line('Lorem', opportunity),
Line(placeholderChar, opportunity),
Line('ipsum\n', mandatory, nl: 1, sp: 1),
Line(placeholderChar, opportunity),
Line('dolor', opportunity),
Line('$placeholderChar\n', mandatory, nl: 1, sp: 1),
Line('sit', opportunity),
Line(placeholderChar, endOfText),
]);
});
test('single placeholder', () {
final CanvasParagraph paragraph = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
});
final String placeholderChar = String.fromCharCode(0xFFFC);
expect(split(paragraph.plainText), <Line>[Line(placeholderChar, endOfText)]);
});
test('placeholders surrounded by spaces and new lines', () {
final CanvasParagraph paragraph = rich(EngineParagraphStyle(), (
CanvasParagraphBuilder builder,
) {
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText(' Lorem ');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText(' \nipsum \n');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
builder.addText('\n');
builder.addPlaceholder(100, 100, PlaceholderAlignment.top);
});
expect(split(paragraph.plainText), <Line>[
Line('$placeholderChar ', opportunity, sp: 2),
Line('Lorem ', opportunity, sp: 2),
Line('$placeholderChar \n', mandatory, nl: 1, sp: 3),
Line('ipsum \n', mandatory, nl: 1, sp: 2),
Line('$placeholderChar\n', mandatory, nl: 1, sp: 1),
Line(placeholderChar, endOfText),
]);
});
test('surrogates', () {
expect(split('A\u{1F600}'), <Line>[Line('A', opportunity), Line('\u{1F600}', endOfText)]);
expect(split('\u{1F600}A'), <Line>[Line('\u{1F600}', opportunity), Line('A', endOfText)]);
expect(split('\u{1F600}\u{1F600}'), <Line>[
Line('\u{1F600}', opportunity),
Line('\u{1F600}', endOfText),
]);
expect(split('A \u{1F600} \u{1F600}'), <Line>[
Line('A ', opportunity, sp: 1),
Line('\u{1F600} ', opportunity, sp: 1),
Line('\u{1F600}', endOfText),
]);
});
test('comprehensive test', () {
final List<TestCase> testCollection = parseRawTestData(rawLineBreakTestData, isV8: isV8);
for (int t = 0; t < testCollection.length; t++) {
final TestCase testCase = testCollection[t];
final String text = testCase.toText();
final LineBreakFragmenter fragmenter =
isV8 ? V8LineBreakFragmenter(text) : FWLineBreakFragmenter(text);
final List<LineBreakFragment> fragments = fragmenter.fragment();
// `f` is the index in the `fragments` list.
int f = 0;
LineBreakFragment currentFragment = fragments[f];
int surrogateCount = 0;
// `s` is the index in the `testCase.signs` list.
for (int s = 0; s < testCase.signs.length - 1; s++) {
// `i` is the index in the `text`.
final int i = s + surrogateCount;
final Sign sign = testCase.signs[s];
if (sign.isBreakOpportunity) {
expect(
currentFragment.end,
i,
reason:
'Failed at test case number $t:\n'
'$testCase\n'
'"$text"\n'
'\nExpected fragment to end at {$i} but ended at {${currentFragment.end}}.',
);
currentFragment = fragments[++f];
} else {
expect(
currentFragment.end,
greaterThan(i),
reason:
'Failed at test case number $t:\n'
'$testCase\n'
'"$text"\n'
'\nFragment ended in early at {${currentFragment.end}}.',
);
}
if (s < testCase.chars.length && testCase.chars[s].isSurrogatePair) {
surrogateCount++;
}
}
// Now let's look at the last sign, which requires different handling.
// The last line break is an endOfText (or a hard break followed by
// endOfText if the last character is a hard line break).
if (currentFragment.type == mandatory) {
// When last character is a hard line break, there should be an
// extra fragment to represent the empty line at the end.
expect(
fragments,
hasLength(f + 2),
reason:
'Failed at test case number $t:\n'
'$testCase\n'
'"$text"\n'
"\nExpected an extra fragment for endOfText but there wasn't one.",
);
currentFragment = fragments[++f];
}
expect(
currentFragment.type,
endOfText,
reason:
'Failed at test case number $t:\n'
'$testCase\n'
'"$text"\n\n'
'Expected an endOfText fragment but found: $currentFragment',
);
expect(
currentFragment.end,
text.length,
reason:
'Failed at test case number $t:\n'
'$testCase\n'
'"$text"\n\n'
'Expected an endOfText fragment ending at {${text.length}} but found: $currentFragment',
);
}
});
});
group('v8BreakIterator hard line breaks', () {
List<Line> split(String text) {
return V8LineBreakFragmenter(text)
.fragment()
.map((LineBreakFragment fragment) => Line.fromLineBreakFragment(text, fragment))
.toList();
}
test('thai text with hard line breaks', () {
const String thaiText = '\u0E1A\u0E38\u0E1C\u0E25\u0E01\u0E32\u0E23';
expect(split(thaiText), <Line>[
Line('\u0E1A\u0E38', opportunity),
Line('\u0E1C\u0E25', opportunity),
Line('\u0E01\u0E32\u0E23', endOfText),
]);
expect(split('$thaiText\n'), <Line>[
Line('\u0E1A\u0E38', opportunity),
Line('\u0E1C\u0E25', opportunity),
Line('\u0E01\u0E32\u0E23\n', mandatory, nl: 1, sp: 1),
Line('', endOfText),
]);
});
test('khmer text with hard line breaks', () {
const String khmerText = '\u179B\u1792\u17D2\u179C\u17BE\u17B2\u17D2\u1799';
expect(split(khmerText), <Line>[
Line('\u179B', opportunity),
Line('\u1792\u17D2\u179C\u17BE', opportunity),
Line('\u17B2\u17D2\u1799', endOfText),
]);
expect(split('$khmerText\n'), <Line>[
Line('\u179B', opportunity),
Line('\u1792\u17D2\u179C\u17BE', opportunity),
Line('\u17B2\u17D2\u1799\n', mandatory, nl: 1, sp: 1),
Line('', endOfText),
]);
});
}, skip: domIntl.v8BreakIterator == null);
}
typedef GroupBody = void Function({required bool isV8});
void groupForEachFragmenter(GroupBody callback) {
group('$FWLineBreakFragmenter', () => callback(isV8: false));
if (domIntl.v8BreakIterator != null) {
group('$V8LineBreakFragmenter', () => callback(isV8: true));
}
}
/// Holds information about how a line was split from a string.
class Line {
Line(this.text, this.breakType, {this.nl = 0, this.sp = 0});
factory Line.fromLineBreakFragment(String text, LineBreakFragment fragment) {
return Line(
text.substring(fragment.start, fragment.end),
fragment.type,
nl: fragment.trailingNewlines,
sp: fragment.trailingSpaces,
);
}
final String text;
final LineBreakType breakType;
final int nl;
final int sp;
@override
int get hashCode => Object.hash(text, breakType, nl, sp);
@override
bool operator ==(Object other) {
return other is Line &&
other.text == text &&
other.breakType == breakType &&
other.nl == nl &&
other.sp == sp;
}
String get escapedText {
final String bk = String.fromCharCode(0x000B);
final String nl = String.fromCharCode(0x0085);
return text
.replaceAll('"', r'\"')
.replaceAll('\n', r'\n')
.replaceAll('\r', r'\r')
.replaceAll(bk, '{BK}')
.replaceAll(nl, '{NL}');
}
@override
String toString() {
return '"$escapedText" ($breakType, nl: $nl, sp: $sp)';
}
}

View File

@@ -1,208 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Parses raw test data into a list of [TestCase] objects.
List<TestCase> parseRawTestData(String rawTestData, {required bool isV8}) {
return rawTestData
.split('\n')
.where(isValidTestCase)
.map((String line) => _checkReplacement(line, isV8: isV8))
.map(_parse)
.toList();
}
bool isValidTestCase(String line) {
return line.startsWith('×');
}
String _checkReplacement(String line, {required bool isV8}) {
String replacement = line;
// Special cases for rules LB8, LB11, LB13, LB14, LB15, LB16, LB17 to allow
// line breaks after spaces.
final RegExp spacesRegex = RegExp(r'SPACE \(SP\) × \[(8|11|13|14|15|16|17)\.');
if (replacement.contains(spacesRegex)) {
replacement = replacement
.replaceAll('0020 ×', '0020 ÷') // SPACE (SP)
.replaceAllMapped(spacesRegex, (Match m) => 'SPACE (SP) ÷ [${m.group(1)}.');
}
if (!isV8) {
// Some test cases contradict rule LB25, so we are fixing them with the few
// regexes below.
final RegExp lb25Regex1 = RegExp(r'\((CP_CP30|CL)\)(.*?) ÷ \[999\.0\] (PERCENT|DOLLAR)');
if (replacement.contains(lb25Regex1)) {
replacement = replacement
.replaceAll(' ÷ 0024', ' × 0024') // DOLLAR SIGN (PR)
.replaceAll(' ÷ 0025', ' × 0025') // PERCENT SIGN (PO)
.replaceAllMapped(
lb25Regex1,
(Match m) => '(${m.group(1)})${m.group(2)} × [999.0] ${m.group(3)}',
);
}
final RegExp lb25Regex2 = RegExp(r'\((IS|SY)\)(.*?) ÷ \[999\.0\] (DIGIT)');
if (replacement.contains(lb25Regex2)) {
replacement = replacement
.replaceAll(' ÷ 0030', ' × 0030') // DIGIT ZERO (NU)
.replaceAllMapped(
lb25Regex2,
(Match m) => '(${m.group(1)})${m.group(2)} × [999.0] ${m.group(3)}',
);
}
final RegExp lb25Regex3 = RegExp(r'\((PR|PO)\)(.*?) ÷ \[999\.0\] (LEFT)');
if (replacement.contains(lb25Regex3)) {
replacement = replacement
.replaceAll(' ÷ 0028', ' × 0028') // LEFT PARENTHESIS (OP_OP30)
.replaceAll(' ÷ 007B', ' × 007B') // LEFT CURLY BRACKET (OP_OP30)
.replaceAll(' ÷ 2329', ' × 2329') // LEFT-POINTING ANGLE BRACKET (OP)
.replaceAllMapped(
lb25Regex3,
(Match m) => '(${m.group(1)})${m.group(2)} × [999.0] ${m.group(3)}',
);
}
}
if (isV8) {
// v8BreakIterator deviates from the spec around Hiragana and Katakana
// letters.
final RegExp hiragana21Regex = RegExp(
r' × \[21\.03\] (HIRAGANA LETTER|KATAKANA LETTER|KATAKANA-HIRAGANA)',
);
if (replacement.contains(hiragana21Regex) &&
!replacement.contains('(BB)') &&
!replacement.contains('(PR)')) {
replacement = replacement
.replaceAll(' × 3041', ' ÷ 3041') // HIRAGANA LETTER (CJ)
.replaceAll(' × 30E5', ' ÷ 30E5') // KATAKANA LETTER (CJ)
.replaceAll(' × 30FC', ' ÷ 30FC') // KATAKANA-HIRAGANA PROLONGED SOUND MARK (CJ)
.replaceAllMapped(hiragana21Regex, (Match m) => ' ÷ [21.03] ${m.group(1)}');
}
if (replacement.contains(' × [16.0] HIRAGANA LETTER')) {
replacement = replacement
.replaceAll(' × 3041', ' ÷ 3041') // HIRAGANA LETTER (CJ)
.replaceAll(' × [16.0] HIRAGANA LETTER', ' ÷ [16.0] HIRAGANA LETTER');
}
final RegExp hiraganaPercentRegex = RegExp(r'HIRAGANA .*? ÷ \[999\.0\] PERCENT');
if (replacement.contains(hiraganaPercentRegex)) {
replacement = replacement
.replaceAll(' ÷ 0025', ' × 0025') // PERCENT SIGN (PO)
.replaceAll(' ÷ [999.0] PERCENT', ' × [999.0] PERCENT');
}
// v8BreakIterator also deviates from the spec around hyphens, commas and
// full stops.
final RegExp hyphenRegex = RegExp(
r'\((HY|IS)\)(.*?) ÷ \[999\.0\] (DIGIT|NUMBER|SECTION|THAI|<reserved-50005>)',
);
if (replacement.contains(hyphenRegex)) {
replacement = replacement
.replaceAll(' ÷ 0030', ' × 0030') // DIGIT ZERO (NU)
.replaceAll(' ÷ 0023', ' × 0023') // NUMBER SIGN (AL)
.replaceAll(' ÷ 00A7', ' × 00A7') // SECTION SIGN (AI_AL)
.replaceAll(' ÷ 0E01', ' × 0E01') // THAI CHARACTER KO KAI (SA_AL)
.replaceAll(' ÷ 50005', ' × 50005') // <reserved-50005> (XX_AL)
.replaceAllMapped(
hyphenRegex,
(Match m) => '(${m.group(1)})${m.group(2)} × [999.0] ${m.group(3)}',
);
}
}
return replacement;
}
final RegExp spaceRegex = RegExp(r'\s+');
final RegExp signRegex = RegExp(r'([×÷])\s+\[(\d+\.\d+)\]\s*');
final RegExp charRegex = RegExp(
r'([A-Z0-9-]+(?:\s+[A-Z0-9-]+)*)\s+\(([A-Z0-9_]+)\)\s*',
caseSensitive: false,
);
final RegExp charWithBracketsRegex = RegExp(
r'(\<[A-Z0-9()-]+(?:\s+[A-Z0-9()-]+)*\>)\s+\(([A-Z0-9_]+)\)\s*',
caseSensitive: false,
);
TestCase _parse(String line) {
final int hashIndex = line.indexOf('#');
final List<String> sequence = line.substring(0, hashIndex).trim().split(spaceRegex);
final String explanation = line.substring(hashIndex + 1).trim();
final List<Sign> signs = <Sign>[];
final Match signMatch = signRegex.matchAsPrefix(explanation)!;
signs.add(Sign._(code: signMatch.group(1)!, rule: signMatch.group(2)!));
final List<Char> chars = <Char>[];
int i = signMatch.group(0)!.length;
while (i < explanation.length) {
final Match charMatch =
explanation[i] == '<'
? charWithBracketsRegex.matchAsPrefix(explanation, i)!
: charRegex.matchAsPrefix(explanation, i)!;
final int charCode = int.parse(sequence[2 * chars.length + 1], radix: 16);
chars.add(Char._(code: charCode, name: charMatch.group(1)!, property: charMatch.group(2)!));
i += charMatch.group(0)!.length;
final Match signMatch = signRegex.matchAsPrefix(explanation, i)!;
signs.add(Sign._(code: signMatch.group(1)!, rule: signMatch.group(2)!));
i += signMatch.group(0)!.length;
}
return TestCase._(signs: signs, chars: chars, raw: line);
}
/// Represents a character in a test case.
///
/// The character has a code, name and a property that determines how it behaves
/// with regards to line breaks.
class Char {
Char._({required this.code, required this.name, required this.property});
final int code;
final String name;
final String property;
/// Whether this character is a code point that gets encoded as a UTF-16
/// surrogate pair.
bool get isSurrogatePair => code > 0xFFFF;
}
/// Represents a sign between two characters in a test case.
///
/// The sign could either be "×" to indicate no line break, or "÷" to indicate
/// the existence of a line break opportunity.
class Sign {
Sign._({required this.code, required this.rule});
final String code;
final String rule;
bool get isBreakOpportunity => code == '÷';
}
/// Represents an entire test case.
///
/// A test case is a sequence of characters combined with signs between them.
/// The signs indicate where line break opportunities exist.
class TestCase {
TestCase._({required this.signs, required this.chars, required this.raw});
final List<Sign> signs;
final List<Char> chars;
final String raw;
Iterable<int> get charCodes => chars.map((Char char) => char.code);
/// Returns the text that this test case is covering.
String toText() {
return String.fromCharCodes(charCodes);
}
@override
String toString() {
return raw;
}
}

View File

@@ -1,194 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
import '../paragraph/helper.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
group('$BidiFragmenter', () {
test('empty string', () {
expect(split(''), <_Bidi>[_Bidi('', null, ffPrevious)]);
});
test('basic cases', () {
expect(split('Lorem 11 $rtlWord1 22 ipsum'), <_Bidi>[
_Bidi('Lorem', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi('11', ltr, ffPrevious),
_Bidi(' ', null, ffSandwich),
_Bidi(rtlWord1, rtl, ffRtl),
_Bidi(' ', null, ffSandwich),
_Bidi('22', ltr, ffPrevious),
_Bidi(' ', null, ffSandwich),
_Bidi('ipsum', ltr, ffLtr),
]);
});
test('text and digits', () {
expect(split('Lorem11 ${rtlWord1}22 33ipsum44dolor ${rtlWord2}55$rtlWord1'), <_Bidi>[
_Bidi('Lorem11', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi(rtlWord1, rtl, ffRtl),
_Bidi('22', ltr, ffPrevious),
_Bidi(' ', null, ffSandwich),
_Bidi('33ipsum44dolor', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi(rtlWord2, rtl, ffRtl),
_Bidi('55', ltr, ffPrevious),
_Bidi(rtlWord1, rtl, ffRtl),
]);
});
test('Mashriqi digits', () {
expect(split('foo ١١ ٢٢ bar'), <_Bidi>[
_Bidi('foo', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi('١١', ltr, ffRtl),
_Bidi(' ', null, ffSandwich),
_Bidi('٢٢', ltr, ffRtl),
_Bidi(' ', null, ffSandwich),
_Bidi('bar', ltr, ffLtr),
]);
expect(split('$rtlWord1 ١١ ٢٢ $rtlWord2'), <_Bidi>[
_Bidi(rtlWord1, rtl, ffRtl),
_Bidi(' ', null, ffSandwich),
_Bidi('١١', ltr, ffRtl),
_Bidi(' ', null, ffSandwich),
_Bidi('٢٢', ltr, ffRtl),
_Bidi(' ', null, ffSandwich),
_Bidi(rtlWord2, rtl, ffRtl),
]);
});
test('spaces', () {
expect(split(' '), <_Bidi>[_Bidi(' ', null, ffSandwich)]);
});
test('symbols', () {
expect(split('Calculate 2.2 + 4.5 and write the result'), <_Bidi>[
_Bidi('Calculate', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi('2', ltr, ffPrevious),
_Bidi('.', null, ffSandwich),
_Bidi('2', ltr, ffPrevious),
_Bidi(' + ', null, ffSandwich),
_Bidi('4', ltr, ffPrevious),
_Bidi('.', null, ffSandwich),
_Bidi('5', ltr, ffPrevious),
_Bidi(' ', null, ffSandwich),
_Bidi('and', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi('write', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi('the', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi('result', ltr, ffLtr),
]);
expect(split('Calculate $rtlWord1 2.2 + 4.5 and write the result'), <_Bidi>[
_Bidi('Calculate', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi(rtlWord1, rtl, ffRtl),
_Bidi(' ', null, ffSandwich),
_Bidi('2', ltr, ffPrevious),
_Bidi('.', null, ffSandwich),
_Bidi('2', ltr, ffPrevious),
_Bidi(' + ', null, ffSandwich),
_Bidi('4', ltr, ffPrevious),
_Bidi('.', null, ffSandwich),
_Bidi('5', ltr, ffPrevious),
_Bidi(' ', null, ffSandwich),
_Bidi('and', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi('write', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi('the', ltr, ffLtr),
_Bidi(' ', null, ffSandwich),
_Bidi('result', ltr, ffLtr),
]);
expect(split('12 + 24 = 36'), <_Bidi>[
_Bidi('12', ltr, ffPrevious),
_Bidi(' + ', null, ffSandwich),
_Bidi('24', ltr, ffPrevious),
_Bidi(' = ', null, ffSandwich),
_Bidi('36', ltr, ffPrevious),
]);
});
test('handles new lines', () {
expect(split('Lorem\n12\nipsum \n'), <_Bidi>[
_Bidi('Lorem', ltr, ffLtr),
_Bidi('\n', null, ffSandwich),
_Bidi('12', ltr, ffPrevious),
_Bidi('\n', null, ffSandwich),
_Bidi('ipsum', ltr, ffLtr),
_Bidi(' \n', null, ffSandwich),
]);
expect(split('$rtlWord1\n $rtlWord2 \n'), <_Bidi>[
_Bidi(rtlWord1, rtl, ffRtl),
_Bidi('\n ', null, ffSandwich),
_Bidi(rtlWord2, rtl, ffRtl),
_Bidi(' \n', null, ffSandwich),
]);
});
test('surrogates', () {
expect(split('A\u{1F600}'), <_Bidi>[
_Bidi('A', ltr, ffLtr),
_Bidi('\u{1F600}', null, ffSandwich),
]);
});
});
}
/// Holds information about how a bidi region was split from a string.
class _Bidi {
_Bidi(this.text, this.textDirection, this.fragmentFlow);
factory _Bidi.fromBidiFragment(String text, BidiFragment bidiFragment) {
return _Bidi(
text.substring(bidiFragment.start, bidiFragment.end),
bidiFragment.textDirection,
bidiFragment.fragmentFlow,
);
}
final String text;
final TextDirection? textDirection;
final FragmentFlow fragmentFlow;
@override
int get hashCode => Object.hash(text, textDirection);
@override
bool operator ==(Object other) {
return other is _Bidi &&
other.text == text &&
other.textDirection == textDirection &&
other.fragmentFlow == fragmentFlow;
}
@override
String toString() {
return '"$text" ($textDirection | $fragmentFlow)';
}
}
List<_Bidi> split(String text) {
return <_Bidi>[
for (final BidiFragment bidiFragment in BidiFragmenter(text).fragment())
_Bidi.fromBidiFragment(text, bidiFragment),
];
}

View File

@@ -1,171 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
void testMain() {
group('$WordBreaker', () {
test('Does not go beyond the ends of a string', () {
expect(WordBreaker.prevBreakIndex('foo', -1), 0);
expect(WordBreaker.prevBreakIndex('foo', 0), 0);
expect(WordBreaker.prevBreakIndex('foo', 'foo'.length + 1), 'foo'.length);
expect(WordBreaker.nextBreakIndex('foo', -1), 0);
expect(WordBreaker.nextBreakIndex('foo', 'foo'.length), 'foo'.length);
expect(WordBreaker.nextBreakIndex('foo', 'foo'.length + 1), 'foo'.length);
});
test('Words and spaces', () {
expectWords('foo bar', <String>['foo', ' ', 'bar']);
expectWords('foo bar', <String>['foo', ' ', 'bar']);
});
test('Single-letter words', () {
expectWords('foo a bar', <String>['foo', ' ', 'a', ' ', 'bar']);
expectWords('a b c', <String>['a', ' ', 'b', ' ', 'c']);
expectWords(' a b ', <String>[' ', 'a', ' ', 'b', ' ']);
});
test('Multiple consecutive spaces', () {
// Different types of whitespace:
final String oghamSpace = String.fromCharCode(0x1680);
final String punctuationSpace = String.fromCharCode(0x2008);
final String mathSpace = String.fromCharCode(0x205F);
final String ideographicSpace = String.fromCharCode(0x3000);
expectWords('foo$oghamSpace ${punctuationSpace}bar', <String>[
'foo',
'$oghamSpace $punctuationSpace',
'bar',
]);
expectWords('$mathSpace$ideographicSpace${oghamSpace}foo', <String>[
'$mathSpace$ideographicSpace$oghamSpace',
'foo',
]);
expectWords('foo$punctuationSpace$mathSpace ', <String>[
'foo',
'$punctuationSpace$mathSpace ',
]);
expectWords('$oghamSpace $punctuationSpace$mathSpace$ideographicSpace', <String>[
'$oghamSpace $punctuationSpace$mathSpace$ideographicSpace',
]);
});
test('Punctuation', () {
expectWords('foo,bar.baz', <String>['foo', ',', 'bar.baz']);
expectWords('foo_bar', <String>['foo_bar']);
expectWords('foo-bar', <String>['foo', '-', 'bar']);
});
test('Numeric', () {
expectWords('12ab ab12', <String>['12ab', ' ', 'ab12']);
expectWords('ab12,34cd', <String>['ab12,34cd']);
expectWords('123,456_789.0', <String>['123,456_789.0']);
});
test('Quotes', () {
expectWords("Mike's bike", <String>["Mike's", ' ', 'bike']);
expectWords("Students' grades", <String>['Students', "'", ' ', 'grades']);
expectWords('Joe said: "I\'m here"', <String>[
'Joe',
' ',
'said',
':',
' ',
'"',
"I'm",
' ',
'here',
'"',
]);
});
// Hebrew letters have the same rules as other letters, except
// when they are around quotes. So we need to test those rules separately.
test('Hebrew with quotes', () {
// A few hebrew letters:
const String h1 = 'א';
const String h2 = 'ל';
const String h3 = 'ט';
// Test the single quote behavior that should be the same as other letters.
expectWords("$h1$h2'$h3", <String>["$h1$h2'$h3"]);
// Single quote following a hebrew shouldn't break.
expectWords("$h1$h2'", <String>["$h1$h2'"]);
expectWords("$h1$h2' $h3", <String>["$h1$h2'", ' ', h3]);
// Double quotes around hebrew words should break.
expectWords('"$h1$h3"', <String>['"', '$h1$h3', '"']);
// Double quotes within hebrew words shouldn't break.
expectWords('$h3"$h2', <String>['$h3"$h2']);
});
test('Newline, CR and LF', () {
final String newline = String.fromCharCode(0x000B);
// The only sequence of new lines that isn't a word boundary is CR×LF.
expectWords('foo\r\nbar', <String>['foo', '\r\n', 'bar']);
// All other sequences are considered word boundaries.
expectWords('foo\n\nbar', <String>['foo', '\n', '\n', 'bar']);
expectWords('foo\r\rbar', <String>['foo', '\r', '\r', 'bar']);
expectWords('foo$newline${newline}bar', <String>['foo', newline, newline, 'bar']);
expectWords('foo\n\rbar', <String>['foo', '\n', '\r', 'bar']);
expectWords('foo$newline\rbar', <String>['foo', newline, '\r', 'bar']);
expectWords('foo\r${newline}bar', <String>['foo', '\r', newline, 'bar']);
expectWords('foo$newline\nbar', <String>['foo', newline, '\n', 'bar']);
expectWords('foo\n${newline}bar', <String>['foo', '\n', newline, 'bar']);
});
test('katakana', () {
// Katakana letters should stick together but not with other letters.
expectWords('ナヌ', <String>['ナヌ']);
expectWords('ナabcヌ', <String>['ナ', 'abc', 'ヌ']);
// Katakana sometimes behaves the same as other letters.
expectWords('ナ,ヌ_イ', <String>['ナ', ',', 'ヌ_イ']);
// Katakana sometimes behaves differently from other letters.
expectWords('ナ.ヌ', <String>['ナ', '.', 'ヌ']);
expectWords("ナ'ヌ", <String>['ナ', "'", 'ヌ']);
expectWords('ナ12ヌ', <String>['ナ', '12', 'ヌ']);
});
});
}
void expectWords(String text, List<String> expectedWords) {
int strIndex = 0;
// Forward word break lookup.
for (final String word in expectedWords) {
final int nextBreak = WordBreaker.nextBreakIndex(text, strIndex);
expect(
nextBreak,
strIndex + word.length,
reason: 'Forward word break lookup: expecting to move to the end of "$word" in "$text".',
);
strIndex += word.length;
}
// Backward word break lookup.
strIndex = text.length;
for (final String word in expectedWords.reversed) {
final int prevBreak = WordBreaker.prevBreakIndex(text, strIndex);
expect(
prevBreak,
strIndex - word.length,
reason: 'Backward word break lookup: expecting to move to the start of "$word" in "$text".',
);
strIndex -= word.length;
}
}

View File

@@ -1,568 +0,0 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is testing some of the named constants.
// ignore_for_file: use_named_constants
import 'package:test/bootstrap/browser.dart';
import 'package:test/test.dart';
import 'package:ui/src/engine.dart';
import 'package:ui/ui.dart';
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../common/matchers.dart';
import '../common/test_initialization.dart';
import 'paragraph/helper.dart';
void main() {
internalBootstrapBrowserTest(() => testMain);
}
Future<void> testMain() async {
const double baselineRatio = 1.1662499904632568;
setUpUnitTests(withImplicitView: true);
late String fallback;
setUp(() {
if (ui_web.browser.operatingSystem == ui_web.OperatingSystem.macOs ||
ui_web.browser.operatingSystem == ui_web.OperatingSystem.iOs) {
if (isIOS15) {
fallback = 'BlinkMacSystemFont';
} else {
fallback = '-apple-system, BlinkMacSystemFont';
}
} else {
fallback = 'Arial';
}
});
test('predictably lays out a single-line paragraph', () {
for (final double fontSize in <double>[10.0, 20.0, 30.0, 40.0]) {
final ParagraphBuilder builder = ParagraphBuilder(
ParagraphStyle(
fontFamily: 'Ahem',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
),
);
builder.addText('Test');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 400.0));
expect(paragraph.height, fontSize);
expect(paragraph.width, 400.0);
expect(paragraph.minIntrinsicWidth, fontSize * 4.0);
expect(paragraph.maxIntrinsicWidth, fontSize * 4.0);
expect(paragraph.alphabeticBaseline, fontSize * .8);
expect(
paragraph.ideographicBaseline,
within(distance: 0.001, from: paragraph.alphabeticBaseline * baselineRatio),
);
}
});
test('predictably lays out a multi-line paragraph', () {
for (final double fontSize in <double>[10.0, 20.0, 30.0, 40.0]) {
final ParagraphBuilder builder = ParagraphBuilder(
ParagraphStyle(
fontFamily: 'Ahem',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
),
);
builder.addText('Test Ahem');
final Paragraph paragraph = builder.build();
paragraph.layout(ParagraphConstraints(width: fontSize * 5.0));
expect(paragraph.height, fontSize * 2.0); // because it wraps
expect(paragraph.width, fontSize * 5.0);
expect(paragraph.minIntrinsicWidth, fontSize * 4.0);
expect(paragraph.maxIntrinsicWidth, fontSize * 9.0);
expect(paragraph.alphabeticBaseline, fontSize * .8);
expect(
paragraph.ideographicBaseline,
within(distance: 0.001, from: paragraph.alphabeticBaseline * baselineRatio),
);
}
});
test('Basic line related metrics', () {
const double fontSize = 10;
final ParagraphBuilder builder = ParagraphBuilder(
ParagraphStyle(
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
maxLines: 1,
ellipsis: 'BBB',
),
)..addText('A' * 100);
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 100.0));
expect(paragraph.numberOfLines, 1);
expect(paragraph.getLineMetricsAt(-1), isNull);
expect(paragraph.getLineMetricsAt(0)?.lineNumber, 0);
expect(paragraph.getLineMetricsAt(1), isNull);
expect(paragraph.getLineNumberAt(-1), isNull);
expect(paragraph.getLineNumberAt(0), 0);
expect(paragraph.getLineNumberAt(6), 0);
// The last 3 characters on the first line are ellipsized with BBB.
expect(paragraph.getLineNumberAt(7), isNull);
});
test('Basic glyph metrics', () {
const double fontSize = 10;
final ParagraphBuilder builder = ParagraphBuilder(
ParagraphStyle(
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
maxLines: 1,
ellipsis: 'BBB',
),
)..addText('A' * 100);
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 100.0));
expect(paragraph.getGlyphInfoAt(-1), isNull);
// The last 3 characters on the first line are ellipsized with BBB.
expect(
paragraph.getGlyphInfoAt(0)?.graphemeClusterCodeUnitRange,
const TextRange(start: 0, end: 1),
);
expect(
paragraph.getGlyphInfoAt(6)?.graphemeClusterCodeUnitRange,
const TextRange(start: 6, end: 7),
);
expect(paragraph.getGlyphInfoAt(7), isNull);
expect(paragraph.getGlyphInfoAt(200), isNull);
});
test('Basic glyph metrics - hit test', () {
const double fontSize = 10.0;
final ParagraphBuilder builder = ParagraphBuilder(
ParagraphStyle(fontSize: fontSize, fontFamily: 'FlutterTest'),
)..addText('Test\nTest');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: double.infinity));
final GlyphInfo? bottomRight = paragraph.getClosestGlyphInfoForOffset(const Offset(99.0, 99.0));
final GlyphInfo? last = paragraph.getGlyphInfoAt(8);
expect(bottomRight, equals(last));
expect(bottomRight, isNot(paragraph.getGlyphInfoAt(0)));
expect(bottomRight?.graphemeClusterLayoutBounds, const Rect.fromLTWH(30, 10, 10, 10));
expect(bottomRight?.graphemeClusterCodeUnitRange, const TextRange(start: 8, end: 9));
expect(bottomRight?.writingDirection, TextDirection.ltr);
});
test('Basic glyph metrics - hit test - center aligned text in separate fragments', () {
const double fontSize = 10.0;
final ParagraphBuilder builder =
ParagraphBuilder(
ParagraphStyle(
fontSize: fontSize,
textAlign: TextAlign.center,
fontFamily: 'FlutterTest',
),
)
..addText('12345\n')
..addText('1')
..addText('2')
..addText('3');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 50));
final GlyphInfo? bottomCenter = paragraph.getClosestGlyphInfoForOffset(
const Offset(25.0, 99.0),
);
final GlyphInfo? expected = paragraph.getGlyphInfoAt(7);
expect(bottomCenter, equals(expected));
expect(bottomCenter, isNot(paragraph.getGlyphInfoAt(8)));
expect(bottomCenter?.graphemeClusterLayoutBounds, const Rect.fromLTWH(20, 10, 10, 10));
expect(bottomCenter?.graphemeClusterCodeUnitRange, const TextRange(start: 7, end: 8));
expect(bottomCenter?.writingDirection, TextDirection.ltr);
});
test(
'Glyph metrics with grapheme split into different runs',
() {
const double fontSize = 10;
final ParagraphBuilder builder =
ParagraphBuilder(
ParagraphStyle(
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
maxLines: 1,
),
)
..addText('A') // The base charater A.
..addText(
'̀',
); // The diacritical grave accent, which should combine with the base character to form a single grapheme.
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: double.infinity));
expect(
paragraph.getGlyphInfoAt(0)?.graphemeClusterCodeUnitRange,
const TextRange(start: 0, end: 2),
);
expect(
paragraph.getGlyphInfoAt(0)?.graphemeClusterLayoutBounds,
const Rect.fromLTWH(0.0, 0.0, 10.0, 10.0),
);
expect(
paragraph.getGlyphInfoAt(1)?.graphemeClusterCodeUnitRange,
const TextRange(start: 0, end: 2),
);
expect(
paragraph.getGlyphInfoAt(1)?.graphemeClusterLayoutBounds,
const Rect.fromLTWH(0.0, 0.0, 10.0, 10.0),
);
final GlyphInfo? bottomRight = paragraph.getClosestGlyphInfoForOffset(
const Offset(99.0, 99.0),
);
expect(bottomRight?.graphemeClusterCodeUnitRange, const TextRange(start: 0, end: 2));
expect(bottomRight?.graphemeClusterLayoutBounds, const Rect.fromLTWH(0.0, 0.0, 10.0, 10.0));
},
skip: domIntl.v8BreakIterator == null,
); // Intended: Intl.v8breakiterator is needed for correctly breaking grapheme clusters.
test('disable rounding hack', () {
const double fontSize = 1;
const String text = '12345';
const double letterSpacing = 0.25;
const double expectedIntrinsicWidth = text.length * (fontSize + letterSpacing);
assert(expectedIntrinsicWidth.truncate() != expectedIntrinsicWidth);
final ParagraphBuilder builder = ParagraphBuilder(
ParagraphStyle(fontSize: fontSize, fontFamily: 'FlutterTest'),
);
builder.pushStyle(TextStyle(letterSpacing: letterSpacing));
builder.addText(text);
final Paragraph paragraph =
builder.build()..layout(const ParagraphConstraints(width: expectedIntrinsicWidth));
expect(paragraph.maxIntrinsicWidth, expectedIntrinsicWidth);
switch (paragraph.computeLineMetrics()) {
case [LineMetrics(width: final double width)]:
expect(width, expectedIntrinsicWidth);
case final List<LineMetrics> metrics:
expect(metrics, hasLength(1));
}
});
test('lay out unattached paragraph', () {
final CanvasParagraph paragraph = plain(
EngineParagraphStyle(
fontFamily: 'sans-serif',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: 14.0,
),
'How do you do this fine morning?',
);
expect(paragraph.height, 0.0);
expect(paragraph.width, -1.0);
expect(paragraph.minIntrinsicWidth, 0.0);
expect(paragraph.maxIntrinsicWidth, 0.0);
expect(paragraph.alphabeticBaseline, -1.0);
expect(paragraph.ideographicBaseline, -1.0);
paragraph.layout(const ParagraphConstraints(width: 60.0));
expect(paragraph.height, greaterThan(0.0));
expect(paragraph.width, greaterThan(0.0));
expect(paragraph.minIntrinsicWidth, greaterThan(0.0));
expect(paragraph.maxIntrinsicWidth, greaterThan(0.0));
expect(paragraph.minIntrinsicWidth, lessThan(paragraph.maxIntrinsicWidth));
expect(paragraph.alphabeticBaseline, greaterThan(0.0));
expect(paragraph.ideographicBaseline, greaterThan(0.0));
});
Paragraph measure({String text = 'Hello', double fontSize = 14.0, double width = 50.0}) {
final ParagraphBuilder builder = ParagraphBuilder(
ParagraphStyle(
fontFamily: 'sans-serif',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
),
);
builder.addText(text);
final Paragraph paragraph = builder.build();
paragraph.layout(ParagraphConstraints(width: width));
return paragraph;
}
test('baseline increases with font size', () {
Paragraph previousParagraph = measure(fontSize: 10.0);
for (int i = 0; i < 6; i++) {
final double fontSize = 20.0 + 10.0 * i;
final Paragraph paragraph = measure(fontSize: fontSize);
expect(paragraph.alphabeticBaseline, greaterThan(previousParagraph.alphabeticBaseline));
expect(paragraph.ideographicBaseline, greaterThan(previousParagraph.ideographicBaseline));
previousParagraph = paragraph;
}
});
test('baseline does not depend on text', () {
final Paragraph golden = measure(fontSize: 30.0);
for (int i = 1; i < 30; i++) {
final Paragraph paragraph = measure(text: 'hello ' * i, fontSize: 30.0);
expect(paragraph.alphabeticBaseline, golden.alphabeticBaseline);
expect(paragraph.ideographicBaseline, golden.ideographicBaseline);
}
});
test('$ParagraphBuilder detects plain text', () {
ParagraphBuilder builder = ParagraphBuilder(
EngineParagraphStyle(
fontFamily: 'sans-serif',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: 15.0,
),
);
builder.addText('hi');
CanvasParagraph paragraph = builder.build() as CanvasParagraph;
expect(paragraph.plainText, isNotNull);
expect(paragraph.paragraphStyle.fontWeight, FontWeight.normal);
builder = ParagraphBuilder(
EngineParagraphStyle(
fontFamily: 'sans-serif',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: 15.0,
),
);
builder.pushStyle(TextStyle(fontWeight: FontWeight.bold));
builder.addText('hi');
paragraph = builder.build() as CanvasParagraph;
expect(paragraph.plainText, isNotNull);
});
test('$ParagraphBuilder detects rich text', () {
final ParagraphBuilder builder = ParagraphBuilder(
EngineParagraphStyle(
fontFamily: 'sans-serif',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: 15.0,
),
);
builder.addText('h');
builder.pushStyle(TextStyle(fontWeight: FontWeight.bold));
builder.addText('i');
final CanvasParagraph paragraph = builder.build() as CanvasParagraph;
expect(paragraph.plainText, 'hi');
});
test('$ParagraphBuilder treats empty text as plain', () {
final ParagraphBuilder builder = ParagraphBuilder(
EngineParagraphStyle(
fontFamily: 'sans-serif',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: 15.0,
),
);
builder.pushStyle(TextStyle(fontWeight: FontWeight.bold));
final CanvasParagraph paragraph = builder.build() as CanvasParagraph;
expect(paragraph.plainText, '');
});
// Regression test for https://github.com/flutter/flutter/issues/38972
test(
'should not set fontFamily to effectiveFontFamily for spans in rich text',
() {
final ParagraphBuilder builder = ParagraphBuilder(
EngineParagraphStyle(
fontFamily: 'Roboto',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: 15.0,
),
);
builder.pushStyle(TextStyle(fontFamily: 'Menlo', fontWeight: FontWeight.bold));
const String firstSpanText = 'abc';
builder.addText(firstSpanText);
builder.pushStyle(TextStyle(fontSize: 30.0, fontWeight: FontWeight.normal));
const String secondSpanText = 'def';
builder.addText(secondSpanText);
final CanvasParagraph paragraph = builder.build() as CanvasParagraph;
paragraph.layout(const ParagraphConstraints(width: 800.0));
expect(paragraph.plainText, 'abcdef');
final List<DomElement> spans = paragraph.toDomElement().querySelectorAll('flt-span').toList();
expect(spans[0].style.fontFamily, 'FlutterTest, $fallback, sans-serif');
// The nested span here should not set it's family to default sans-serif.
expect(spans[1].style.fontFamily, 'FlutterTest, $fallback, sans-serif');
},
// TODO(mdebbar): https://github.com/flutter/flutter/issues/46638
skip: ui_web.browser.browserEngine == ui_web.BrowserEngine.firefox,
);
test(
'adds Arial and sans-serif as fallback fonts',
() {
// Set this to false so it doesn't default to the test font.
ui_web.debugEmulateFlutterTesterEnvironment = false;
final CanvasParagraph paragraph = plain(
EngineParagraphStyle(fontFamily: 'SomeFont', fontSize: 12.0),
'Hello',
);
paragraph.layout(constrain(double.infinity));
expect(
paragraph.toDomElement().children.single.style.fontFamily,
'SomeFont, $fallback, sans-serif',
);
ui_web.debugEmulateFlutterTesterEnvironment = true;
},
// TODO(mdebbar): https://github.com/flutter/flutter/issues/46638
skip: ui_web.browser.browserEngine == ui_web.BrowserEngine.firefox,
);
test('does not add fallback fonts to generic families', () {
// Set this to false so it doesn't default to the default test font.
ui_web.debugEmulateFlutterTesterEnvironment = false;
final CanvasParagraph paragraph = plain(
EngineParagraphStyle(fontFamily: 'serif', fontSize: 12.0),
'Hello',
);
paragraph.layout(constrain(double.infinity));
expect(paragraph.toDomElement().children.single.style.fontFamily, 'serif');
ui_web.debugEmulateFlutterTesterEnvironment = true;
});
test('can set font families that need to be quoted', () {
// Set this to false so it doesn't default to the default test font.
ui_web.debugEmulateFlutterTesterEnvironment = false;
final CanvasParagraph paragraph = plain(
EngineParagraphStyle(fontFamily: 'MyFont 2000', fontSize: 12.0),
'Hello',
);
paragraph.layout(constrain(double.infinity));
expect(
paragraph.toDomElement().children.single.style.fontFamily,
'"MyFont 2000", $fallback, sans-serif',
);
ui_web.debugEmulateFlutterTesterEnvironment = true;
});
group('TextRange', () {
test('empty ranges are correct', () {
const TextRange range = TextRange(start: -1, end: -1);
expect(range, equals(TextRange.collapsed(-1))); // ignore: prefer_const_constructors
expect(range, equals(TextRange.empty));
});
test('isValid works', () {
expect(TextRange.empty.isValid, isFalse);
expect(const TextRange(start: 0, end: 0).isValid, isTrue);
expect(const TextRange(start: 0, end: 10).isValid, isTrue);
expect(const TextRange(start: 10, end: 10).isValid, isTrue);
expect(const TextRange(start: -1, end: 10).isValid, isFalse);
expect(const TextRange(start: 10, end: 0).isValid, isTrue);
expect(const TextRange(start: 10, end: -1).isValid, isFalse);
});
test('isCollapsed works', () {
expect(TextRange.empty.isCollapsed, isTrue);
expect(const TextRange(start: 0, end: 0).isCollapsed, isTrue);
expect(const TextRange(start: 0, end: 10).isCollapsed, isFalse);
expect(const TextRange(start: 10, end: 10).isCollapsed, isTrue);
expect(const TextRange(start: -1, end: 10).isCollapsed, isFalse);
expect(const TextRange(start: 10, end: 0).isCollapsed, isFalse);
expect(const TextRange(start: 10, end: -1).isCollapsed, isFalse);
});
test('isNormalized works', () {
expect(TextRange.empty.isNormalized, isTrue);
expect(const TextRange(start: 0, end: 0).isNormalized, isTrue);
expect(const TextRange(start: 0, end: 10).isNormalized, isTrue);
expect(const TextRange(start: 10, end: 10).isNormalized, isTrue);
expect(const TextRange(start: -1, end: 10).isNormalized, isTrue);
expect(const TextRange(start: 10, end: 0).isNormalized, isFalse);
expect(const TextRange(start: 10, end: -1).isNormalized, isFalse);
});
test('textBefore works', () {
expect(const TextRange(start: 0, end: 0).textBefore('hello'), isEmpty);
expect(const TextRange(start: 1, end: 1).textBefore('hello'), equals('h'));
expect(const TextRange(start: 1, end: 2).textBefore('hello'), equals('h'));
expect(const TextRange(start: 5, end: 5).textBefore('hello'), equals('hello'));
expect(const TextRange(start: 0, end: 5).textBefore('hello'), isEmpty);
});
test('textAfter works', () {
expect(const TextRange(start: 0, end: 0).textAfter('hello'), equals('hello'));
expect(const TextRange(start: 1, end: 1).textAfter('hello'), equals('ello'));
expect(const TextRange(start: 1, end: 2).textAfter('hello'), equals('llo'));
expect(const TextRange(start: 5, end: 5).textAfter('hello'), isEmpty);
expect(const TextRange(start: 0, end: 5).textAfter('hello'), isEmpty);
});
test('textInside works', () {
expect(const TextRange(start: 0, end: 0).textInside('hello'), isEmpty);
expect(const TextRange(start: 1, end: 1).textInside('hello'), isEmpty);
expect(const TextRange(start: 1, end: 2).textInside('hello'), equals('e'));
expect(const TextRange(start: 5, end: 5).textInside('hello'), isEmpty);
expect(const TextRange(start: 0, end: 5).textInside('hello'), equals('hello'));
});
});
test('FontWeights have the correct value', () {
expect(FontWeight.w100.value, 100);
expect(FontWeight.w200.value, 200);
expect(FontWeight.w300.value, 300);
expect(FontWeight.w400.value, 400);
expect(FontWeight.w500.value, 500);
expect(FontWeight.w600.value, 600);
expect(FontWeight.w700.value, 700);
expect(FontWeight.w800.value, 800);
expect(FontWeight.w900.value, 900);
});
group('test fonts in flutterTester environment', () {
final bool resetValue = ui_web.debugEmulateFlutterTesterEnvironment;
ui_web.debugEmulateFlutterTesterEnvironment = true;
tearDownAll(() {
ui_web.debugEmulateFlutterTesterEnvironment = resetValue;
});
const List<String> testFonts = <String>['FlutterTest', 'Ahem'];
test(
'The default test font is used when a non-test fontFamily is specified, or fontFamily is not specified',
() {
final String defaultTestFontFamily = testFonts.first;
expect(EngineTextStyle.only().effectiveFontFamily, defaultTestFontFamily);
expect(
EngineTextStyle.only(fontFamily: 'BogusFontFamily').effectiveFontFamily,
defaultTestFontFamily,
);
},
);
test('Can specify test fontFamily to use', () {
for (final String testFont in testFonts) {
expect(EngineTextStyle.only(fontFamily: testFont).effectiveFontFamily, testFont);
}
});
});
}