From 3c08ceeae6c4b45aa54794204c4fbb09e88de7ed Mon Sep 17 00:00:00 2001 From: Yegor Date: Thu, 22 Aug 2019 16:38:03 -0700 Subject: [PATCH] sync web engine; run web engine tests (flutter/engine#11031) sync web engine; run web engine tests --- engine/src/flutter/.cirrus.yml | 4 + .../ci/licenses_golden/licenses_flutter | 7 +- .../flutter/ci/licenses_golden/tool_signature | 2 +- engine/src/flutter/lib/web_ui/dart_test.yaml | 18 + engine/src/flutter/lib/web_ui/dev/test.dart | 189 +++ .../flutter/lib/web_ui/lib/assets/.gitignore | 1 + .../lib/web_ui/lib/assets/houdini_painter.js | 1069 ++++++++++++++ .../flutter/lib/web_ui/lib/src/engine.dart | 5 +- .../lib/web_ui/lib/src/engine/assets.dart | 27 +- .../web_ui/lib/src/engine/bitmap_canvas.dart | 30 +- .../lib/src/engine/compositor/canvas.dart | 41 +- .../lib/src/engine/compositor/fonts.dart | 92 ++ .../lib/src/engine/compositor/image.dart | 61 + .../src/engine/compositor/initialization.dart | 14 +- .../lib/src/engine/compositor/layer.dart | 45 +- .../compositor/layer_scene_builder.dart | 9 +- .../lib/src/engine/compositor/matrix.dart | 27 - .../lib/src/engine/compositor/path.dart | 140 +- .../engine/compositor/picture_recorder.dart | 3 +- .../engine/compositor/recording_canvas.dart | 162 ++- .../lib/src/engine/compositor/util.dart | 275 ++++ .../lib/src/engine/html_image_codec.dart | 2 +- .../lib/src/engine/pointer_binding.dart | 132 +- .../lib/src/engine/recording_canvas.dart | 10 +- .../lib/src/engine/semantics/semantics.dart | 5 - .../lib/web_ui/lib/src/engine/shader.dart | 210 +++ .../lib/src/engine/surface/picture.dart | 2 +- .../lib/src/engine/text/font_collection.dart | 2 +- .../lib/src/engine/text/measurement.dart | 27 + .../web_ui/lib/src/engine/text/paragraph.dart | 13 +- .../lib/web_ui/lib/src/engine/text/ruler.dart | 47 + .../web_ui/lib/src/engine/text_editing.dart | 6 +- .../flutter/lib/web_ui/lib/src/ui/canvas.dart | 2 +- .../lib/web_ui/lib/src/ui/compositing.dart | 5 + .../lib/web_ui/lib/src/ui/initialization.dart | 20 +- .../lib/web_ui/lib/src/ui/painting.dart | 173 +-- .../lib/web_ui/lib/src/ui/semantics.dart | 17 +- .../flutter/lib/web_ui/lib/src/ui/window.dart | 2 - engine/src/flutter/lib/web_ui/pubspec.yaml | 15 +- .../lib/web_ui/test/alarm_clock_test.dart | 28 +- .../flutter/lib/web_ui/test/canvas_test.dart | 8 +- .../flutter/lib/web_ui/test/color_test.dart | 6 +- .../flutter/lib/web_ui/test/colors_test.dart | 140 -- .../lib/web_ui/test/compositing_test.dart | 104 +- .../lib/web_ui/test/dom_renderer_test.dart | 73 +- .../engine/semantics/accessibility_test.dart | 52 + .../test/engine/semantics/semantics_test.dart | 1258 +++++++++++++++++ .../engine/services/serialization_test.dart | 82 ++ .../test/engine/surface/surface_test.dart | 314 ++++ .../lib/web_ui/test/geometry_test.dart | 184 +-- .../lib/web_ui/test/gradient_test.dart | 8 +- .../lib/web_ui/test/keyboard_test.dart | 8 +- .../src/flutter/lib/web_ui/test/matchers.dart | 69 +- .../lib/web_ui/test/mock_engine_canvas.dart | 28 +- .../lib/web_ui/test/paragraph_test.dart | 65 + .../flutter/lib/web_ui/test/path_test.dart | 218 +-- .../flutter/lib/web_ui/test/rect_test.dart | 82 ++ .../flutter/lib/web_ui/test/rrect_test.dart | 45 + .../web_ui/test/text/measurement_test.dart | 420 ++++-- .../web_ui/test/text/word_breaker_test.dart | 94 +- .../lib/web_ui/test/text_editing_test.dart | 589 ++++++++ .../flutter/lib/web_ui/test/text_test.dart | 219 +++ .../flutter/lib/web_ui/test/title_test.dart | 47 + .../src/flutter/tools/licenses/lib/main.dart | 39 +- 64 files changed, 6011 insertions(+), 1080 deletions(-) create mode 100644 engine/src/flutter/lib/web_ui/dart_test.yaml create mode 100644 engine/src/flutter/lib/web_ui/dev/test.dart create mode 100644 engine/src/flutter/lib/web_ui/lib/assets/.gitignore create mode 100644 engine/src/flutter/lib/web_ui/lib/assets/houdini_painter.js create mode 100644 engine/src/flutter/lib/web_ui/lib/src/engine/compositor/fonts.dart create mode 100644 engine/src/flutter/lib/web_ui/lib/src/engine/compositor/image.dart delete mode 100644 engine/src/flutter/lib/web_ui/lib/src/engine/compositor/matrix.dart create mode 100644 engine/src/flutter/lib/web_ui/lib/src/engine/compositor/util.dart create mode 100644 engine/src/flutter/lib/web_ui/lib/src/engine/shader.dart delete mode 100644 engine/src/flutter/lib/web_ui/test/colors_test.dart create mode 100644 engine/src/flutter/lib/web_ui/test/engine/semantics/accessibility_test.dart create mode 100644 engine/src/flutter/lib/web_ui/test/engine/semantics/semantics_test.dart create mode 100644 engine/src/flutter/lib/web_ui/test/engine/services/serialization_test.dart create mode 100644 engine/src/flutter/lib/web_ui/test/engine/surface/surface_test.dart create mode 100644 engine/src/flutter/lib/web_ui/test/paragraph_test.dart create mode 100644 engine/src/flutter/lib/web_ui/test/rect_test.dart create mode 100644 engine/src/flutter/lib/web_ui/test/rrect_test.dart create mode 100644 engine/src/flutter/lib/web_ui/test/text_editing_test.dart create mode 100644 engine/src/flutter/lib/web_ui/test/text_test.dart create mode 100644 engine/src/flutter/lib/web_ui/test/title_test.dart diff --git a/engine/src/flutter/.cirrus.yml b/engine/src/flutter/.cirrus.yml index 55c7da293e..427712d9da 100644 --- a/engine/src/flutter/.cirrus.yml +++ b/engine/src/flutter/.cirrus.yml @@ -35,6 +35,10 @@ task: test_host_script: | cd $ENGINE_PATH/src ./flutter/testing/run_tests.sh host_debug_unopt + test_web_engine_script: | + cd $ENGINE_PATH/src/flutter/lib/web_ui + $ENGINE_PATH/src/out/host_debug_unopt/dart-sdk/bin/pub get + $ENGINE_PATH/src/out/host_debug_unopt/dart-sdk/bin/dart dev/test.dart fetch_framework_script: | mkdir -p $FRAMEWORK_PATH cd $FRAMEWORK_PATH diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index f52e181a1c..83ec4ba1c7 100644 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -345,6 +345,8 @@ FILE: ../../../flutter/lib/ui/window/viewport_metrics.cc FILE: ../../../flutter/lib/ui/window/viewport_metrics.h FILE: ../../../flutter/lib/ui/window/window.cc FILE: ../../../flutter/lib/ui/window/window.h +FILE: ../../../flutter/lib/web_ui/dev/test.dart +FILE: ../../../flutter/lib/web_ui/lib/assets/houdini_painter.js 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/assets.dart @@ -353,11 +355,12 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/browser_detection.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/browser_location.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/canvas.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/engine_delegate.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/fonts.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/image.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/initialization.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/layer.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/layer_scene_builder.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/layer_tree.dart -FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/matrix.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/path.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/picture.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/picture_recorder.dart @@ -367,6 +370,7 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/rasterizer.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/recording_canvas.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/runtime_delegate.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/surface.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/util.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/viewport_metrics.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/conic.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/dom_canvas.dart @@ -395,6 +399,7 @@ FILE: ../../../flutter/lib/web_ui/lib/src/engine/services/buffers.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/services/message_codec.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/services/message_codecs.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/services/serialization.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/shader.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/shadow.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/surface/backdrop_filter.dart FILE: ../../../flutter/lib/web_ui/lib/src/engine/surface/clip.dart diff --git a/engine/src/flutter/ci/licenses_golden/tool_signature b/engine/src/flutter/ci/licenses_golden/tool_signature index 43d9a858d1..ec6b163fb1 100644 --- a/engine/src/flutter/ci/licenses_golden/tool_signature +++ b/engine/src/flutter/ci/licenses_golden/tool_signature @@ -1,2 +1,2 @@ -Signature: 2009f69daad0d2b8a8037b2903f145ee +Signature: 24e0fa6ad08ae80380158c2b4ba44c65 diff --git a/engine/src/flutter/lib/web_ui/dart_test.yaml b/engine/src/flutter/lib/web_ui/dart_test.yaml new file mode 100644 index 0000000000..5715dbe897 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/dart_test.yaml @@ -0,0 +1,18 @@ +# Sources of inspiration for this file: +# +# * https://github.com/dart-lang/angular/blob/master/dev/tool/test/dart_test_repo.yaml +# * https://github.com/dart-lang/angular/blob/master/_tests/dart_test.yaml + +platforms: + - chrome + - vm +presets: + cirrus: + override_platforms: + chrome: + settings: + # Required because Cirrus runs us as root. + # https://chromium.googlesource.com/chromium/src/+/master/docs/design/sandbox.md + # https://docs.travis-ci.com/user/chrome#Sandboxing + arguments: --no-sandbox + reporter: expanded diff --git a/engine/src/flutter/lib/web_ui/dev/test.dart b/engine/src/flutter/lib/web_ui/dev/test.dart new file mode 100644 index 0000000000..3522407dd0 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/dev/test.dart @@ -0,0 +1,189 @@ +// 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:io' as io; + +import 'package:path/path.dart' as pathlib; + +final Environment environment = Environment(); + +void main() async { + if (io.Directory.current.absolute.path != environment.webUiRootDir.absolute.path) { + io.stderr.writeln('Current directory is not the root of the web_ui package directory.'); + io.stderr.writeln('web_ui directory is: ${environment.webUiRootDir.absolute.path}'); + io.stderr.writeln('current directory is: ${io.Directory.current.absolute.path}'); + io.exit(1); + } + + await _checkLicenseHeaders(); + await _runTests(); +} + +void _checkLicenseHeaders() { + final List allSourceFiles = _flatListSourceFiles(environment.webUiRootDir); + _expect(allSourceFiles.isNotEmpty, 'Dart source listing of ${environment.webUiRootDir.path} must not be empty.'); + + final List allDartPaths = allSourceFiles.map((f) => f.path).toList(); + print(allDartPaths.join('\n')); + + for (String expectedDirectory in const ['lib', 'test', 'dev', 'tool']) { + final String expectedAbsoluteDirectory = pathlib.join(environment.webUiRootDir.path, expectedDirectory); + _expect( + allDartPaths.where((p) => p.startsWith(expectedAbsoluteDirectory)).isNotEmpty, + 'Must include the $expectedDirectory/ directory', + ); + } + + allSourceFiles.forEach(_expectLicenseHeader); +} + +final _copyRegex = RegExp(r'// Copyright 2013 The Flutter Authors\. All rights reserved\.'); + +void _expectLicenseHeader(io.File file) { + List head = file.readAsStringSync().split('\n').take(3).toList(); + + _expect(head.length >= 3, 'File too short: ${file.path}'); + _expect( + _copyRegex.firstMatch(head[0]) != null, + 'Invalid first line of license header in file ${file.path}', + ); + _expect( + head[1] == '// Use of this source code is governed by a BSD-style license that can be', + 'Invalid second line of license header in file ${file.path}', + ); + _expect( + head[2] == '// found in the LICENSE file.', + 'Invalid second line of license header in file ${file.path}', + ); +} + +void _expect(bool value, String requirement) { + if (!value) { + throw Exception('Test failed: ${requirement}'); + } +} + +List _flatListSourceFiles(io.Directory directory) { + return directory + .listSync(recursive: true) + .whereType() + .where((f) => f.path.endsWith('.dart') || f.path.endsWith('.js')) + .toList(); +} + +Future _runTests() async { + // TODO(yjbanov): make the following tests pass. + const List testBlacklist = [ + 'test/text/measurement_test.dart', + 'test/paragraph_test.dart', + 'test/text_test.dart', + ]; + + final List testFiles = io.Directory('test') + .listSync(recursive: true) + .whereType() + .map((io.File file) => file.path) + .where((String path) => path.endsWith('_test.dart') && !testBlacklist.contains(path)) + .toList(); + + final io.Process pubRunTest = await io.Process.start( + environment.pubExecutable, + [ + 'run', + 'test', + '--preset=cirrus', + '--platform=chrome', + ...testFiles, + ], + ); + + final StreamSubscription stdoutSub = pubRunTest.stdout.listen(io.stdout.add); + final StreamSubscription stderrSub = pubRunTest.stderr.listen(io.stderr.add); + final int exitCode = await pubRunTest.exitCode; + stdoutSub.cancel(); + stderrSub.cancel(); + + if (exitCode != 0) { + io.stderr.writeln('Test process exited with exit code $exitCode'); + io.exit(1); + } +} + +class Environment { + factory Environment() { + final io.File self = io.File.fromUri(io.Platform.script); + final io.Directory webUiRootDir = self.parent.parent; + final io.Directory engineSrcDir = webUiRootDir.parent.parent.parent; + final io.Directory outDir = io.Directory(pathlib.join(engineSrcDir.path, 'out')); + final io.Directory hostDebugUnoptDir = io.Directory(pathlib.join(outDir.path, 'host_debug_unopt')); + final String dartExecutable = pathlib.canonicalize(io.File(_which(io.Platform.executable)).absolute.path); + final io.Directory dartSdkDir = io.File(dartExecutable).parent.parent; + + // Googlers frequently have their Dart SDK misconfigured for open-source projects. Let's help them out. + if (dartExecutable.startsWith('/usr/lib/google-dartlang')) { + io.stderr.writeln('ERROR: Using unsupported version of the Dart SDK: $dartExecutable'); + io.exit(1); + } + + return Environment._( + self: self, + webUiRootDir: webUiRootDir, + engineSrcDir: engineSrcDir, + outDir: outDir, + hostDebugUnoptDir: hostDebugUnoptDir, + dartExecutable: dartExecutable, + dartSdkDir: dartSdkDir, + ); + } + + Environment._({ + this.self, + this.webUiRootDir, + this.engineSrcDir, + this.outDir, + this.hostDebugUnoptDir, + this.dartSdkDir, + this.dartExecutable, + }); + + final io.File self; + final io.Directory webUiRootDir; + final io.Directory engineSrcDir; + final io.Directory outDir; + final io.Directory hostDebugUnoptDir; + final io.Directory dartSdkDir; + final String dartExecutable; + + String get pubExecutable => pathlib.join(dartSdkDir.path, 'bin', 'pub'); + + @override + String toString() { + return ''' +runTest.dart script: + ${self.path} +web_ui directory: + ${webUiRootDir.path} +engine/src directory: + ${engineSrcDir.path} +out directory: + ${outDir.path} +out/host_debug_unopt directory: + ${hostDebugUnoptDir.path} +Dart SDK directory: + ${dartSdkDir.path} +dart executable: + ${dartExecutable} +'''; + } +} + +String _which(String executable) { + final io.ProcessResult result = io.Process.runSync('which', [executable]); + if (result.exitCode != 0) { + io.stderr.writeln(result.stderr); + io.exit(result.exitCode); + } + return result.stdout; +} diff --git a/engine/src/flutter/lib/web_ui/lib/assets/.gitignore b/engine/src/flutter/lib/web_ui/lib/assets/.gitignore new file mode 100644 index 0000000000..252e3401e5 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/assets/.gitignore @@ -0,0 +1 @@ +ahem.ttf \ No newline at end of file diff --git a/engine/src/flutter/lib/web_ui/lib/assets/houdini_painter.js b/engine/src/flutter/lib/web_ui/lib/assets/houdini_painter.js new file mode 100644 index 0000000000..74ec4a29e2 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/assets/houdini_painter.js @@ -0,0 +1,1069 @@ +// 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): Consider the following optimizations: +// - Switch from JSON to typed arrays. See: +// https://github.com/w3c/css-houdini-drafts/issues/136 +// - When there is no DOM-rendered content, then clipping in the canvas is more +// efficient than DOM-rendered clipping. +// - When DOM-rendered clip is the only option, then clipping _again_ in the +// canvas is superfluous. +// - When transform is a 2D transform and there is no DOM-rendered content, then +// canvas transform is more efficient than DOM-rendered transform. +// - If a transform must be DOM-rendered, then clipping in the canvas _again_ is +// superfluous. + +/** + * Applies paint commands to CSS Paint API (a.k.a. Houdini). + * + * This painter is driven by houdini_canvas.dart. This painter and the + * HoudiniCanvas class must be kept in sync with each other. + */ +class FlutterPainter { + /** + * Properties used by this painter. + * + * @return {string[]} list of CSS properties this painter depends on. + */ + static get inputProperties() { + return ['--flt']; + } + + /** + * Implements the painter interface. + */ + paint(ctx, geom, properties) { + let fltProp = properties.get('--flt').toString(); + if (!fltProp) { + // Nothing to paint. + return; + } + const commands = JSON.parse(fltProp); + for (let i = 0; i < commands.length; i++) { + let command = commands[i]; + // TODO(yjbanov): we should probably move command identifiers into an enum + switch (command[0]) { + case 1: + this._save(ctx, geom, command); + break; + case 2: + this._restore(ctx, geom, command); + break; + case 3: + this._translate(ctx, geom, command); + break; + case 4: + this._scale(ctx, geom, command); + break; + case 5: + this._rotate(ctx, geom, command); + break; + // Skip case 6: implemented in the DOM for now. + case 7: + this._skew(ctx, geom, command); + break; + case 8: + this._clipRect(ctx, geom, command); + break; + case 9: + this._clipRRect(ctx, geom, command); + break; + case 10: + this._clipPath(ctx, geom, command); + break; + case 11: + this._drawColor(ctx, geom, command); + break; + case 12: + this._drawLine(ctx, geom, command); + break; + case 13: + this._drawPaint(ctx, geom, command); + break; + case 14: + this._drawRect(ctx, geom, command); + break; + case 15: + this._drawRRect(ctx, geom, command); + break; + case 16: + this._drawDRRect(ctx, geom, command); + break; + case 17: + this._drawOval(ctx, geom, command); + break; + case 18: + this._drawCircle(ctx, geom, command); + break; + case 19: + this._drawPath(ctx, geom, command); + break; + case 20: + this._drawShadow(ctx, geom, command); + break; + default: + throw new Error(`Unsupported command ID: ${command[0]}`); + } + } + } + + _applyPaint(ctx, paint) { + let blendMode = _stringForBlendMode(paint.blendMode); + ctx.globalCompositeOperation = blendMode ? blendMode : 'source-over'; + ctx.lineWidth = paint.strokeWidth ? paint.strokeWidth : 1.0; + + let strokeCap = _stringForStrokeCap(paint.strokeCap); + ctx.lineCap = strokeCap ? strokeCap : 'butt'; + + if (paint.shader != null) { + let paintStyle = paint.shader.createPaintStyle(ctx); + ctx.fillStyle = paintStyle; + ctx.strokeStyle = paintStyle; + } else if (paint.color != null) { + let colorString = paint.color; + ctx.fillStyle = colorString; + ctx.strokeStyle = colorString; + } + if (paint.maskFilter != null) { + ctx.filter = `blur(${paint.maskFilter[1]}px)`; + } + } + + _strokeOrFill(ctx, paint, resetPaint) { + switch (paint.style) { + case PaintingStyle.stroke: + ctx.stroke(); + break; + case PaintingStyle.fill: + default: + ctx.fill(); + break; + } + if (resetPaint) { + this._resetPaint(ctx); + } + } + + _resetPaint(ctx) { + ctx.globalCompositeOperation = 'source-over'; + ctx.lineWidth = 1.0; + ctx.lineCap = 'butt'; + ctx.filter = 'none'; + ctx.fillStyle = null; + ctx.strokeStyle = null; + } + + _save(ctx, geom, command) { + ctx.save(); + } + + _restore(ctx, geom, command) { + ctx.restore(); + } + + _translate(ctx, geom, command) { + ctx.translate(command[1], command[2]); + } + + _scale(ctx, geom, command) { + ctx.translate(command[1], command[2]); + } + + _rotate(ctx, geom, command) { + ctx.rotate(command[1]); + } + + _skew(ctx, geom, command) { + ctx.translate(command[1], command[2]); + } + + _drawRect(ctx, geom, command) { + let scanner = _scanCommand(command); + let rect = scanner.scanRect(); + let paint = scanner.scanPaint(); + this._applyPaint(ctx, paint); + ctx.beginPath(); + ctx.rect(rect.left, rect.top, rect.width(), rect.height()); + this._strokeOrFill(ctx, paint, true); + } + + _drawRRect(ctx, geom, command) { + let scanner = _scanCommand(command); + let rrect = scanner.scanRRect(); + let paint = scanner.scanPaint(); + + this._applyPaint(ctx, paint); + this._drawRRectPath(ctx, rrect, true); + this._strokeOrFill(ctx, paint, true); + } + + _drawDRRect(ctx, geom, command) { + let scanner = _scanCommand(command); + let outer = scanner.scanRRect(); + let inner = scanner.scanRRect(); + let paint = scanner.scanPaint(); + this._applyPaint(ctx, paint); + this._drawRRectPath(ctx, outer, true); + this._drawRRectPathReverse(ctx, inner, false); + this._strokeOrFill(ctx, paint, true); + } + + _drawRRectPath(ctx, rrect, startNewPath) { + // TODO(mdebbar): there's a bug in this code, it doesn't correctly handle + // the case when the radius is greater than the width of the + // rect. When we fix that in BitmapCanvas, we need to fix it + // here too. + // To draw the rounded rectangle, perform the following 8 steps: + // 1. draw the line for the top + // 2. draw the arc for the top-right corner + // 3. draw the line for the right side + // 4. draw the arc for the bottom-right corner + // 5. draw the line for the bottom of the rectangle + // 6. draw the arc for the bottom-left corner + // 7. draw the line for the left side + // 8. draw the arc for the top-left corner + // + // After drawing, the current point will be the left side of the top of the + // rounded rectangle (after the corner). + // TODO(het): Confirm that this is the end point in Flutter for RRect + + if (startNewPath) { + ctx.beginPath(); + } + + ctx.moveTo(rrect.left + rrect.trRadiusX, rrect.top); + + // Top side and top-right corner + ctx.lineTo(rrect.right - rrect.trRadiusX, rrect.top); + ctx.ellipse( + rrect.right - rrect.trRadiusX, + rrect.top + rrect.trRadiusY, + rrect.trRadiusX, + rrect.trRadiusY, + 0, + 1.5 * Math.PI, + 2.0 * Math.PI, + false, + ); + + // Right side and bottom-right corner + ctx.lineTo(rrect.right, rrect.bottom - rrect.brRadiusY); + ctx.ellipse( + rrect.right - rrect.brRadiusX, + rrect.bottom - rrect.brRadiusY, + rrect.brRadiusX, + rrect.brRadiusY, + 0, + 0, + 0.5 * Math.PI, + false, + ); + + // Bottom side and bottom-left corner + ctx.lineTo(rrect.left + rrect.blRadiusX, rrect.bottom); + ctx.ellipse( + rrect.left + rrect.blRadiusX, + rrect.bottom - rrect.blRadiusY, + rrect.blRadiusX, + rrect.blRadiusY, + 0, + 0.5 * Math.PI, + Math.PI, + false, + ); + + // Left side and top-left corner + ctx.lineTo(rrect.left, rrect.top + rrect.tlRadiusY); + ctx.ellipse( + rrect.left + rrect.tlRadiusX, + rrect.top + rrect.tlRadiusY, + rrect.tlRadiusX, + rrect.tlRadiusY, + 0, + Math.PI, + 1.5 * Math.PI, + false, + ); + } + + _drawRRectPathReverse(ctx, rrect, startNewPath) { + // Draw the rounded rectangle, counterclockwise. + ctx.moveTo(rrect.right - rrect.trRadiusX, rrect.top); + + if (startNewPath) { + ctx.beginPath(); + } + + // Top side and top-left corner + ctx.lineTo(rrect.left + rrect.tlRadiusX, rrect.top); + ctx.ellipse( + rrect.left + rrect.tlRadiusX, + rrect.top + rrect.tlRadiusY, + rrect.tlRadiusX, + rrect.tlRadiusY, + 0, + 1.5 * Math.PI, + Math.PI, + true, + ); + + // Left side and bottom-left corner + ctx.lineTo(rrect.left, rrect.bottom - rrect.blRadiusY); + ctx.ellipse( + rrect.left + rrect.blRadiusX, + rrect.bottom - rrect.blRadiusY, + rrect.blRadiusX, + rrect.blRadiusY, + 0, + Math.PI, + 0.5 * Math.PI, + true, + ); + + // Bottom side and bottom-right corner + ctx.lineTo(rrect.right - rrect.brRadiusX, rrect.bottom); + ctx.ellipse( + rrect.right - rrect.brRadiusX, + rrect.bottom - rrect.brRadiusY, + rrect.brRadiusX, + rrect.brRadiusY, + 0, + 0.5 * Math.PI, + 0, + true, + ); + + // Right side and top-right corner + ctx.lineTo(rrect.right, rrect.top + rrect.trRadiusY); + ctx.ellipse( + rrect.right - rrect.trRadiusX, + rrect.top + rrect.trRadiusY, + rrect.trRadiusX, + rrect.trRadiusY, + 0, + 0, + 1.5 * Math.PI, + true, + ); + } + + _clipRect(ctx, geom, command) { + let scanner = _scanCommand(command); + let rect = scanner.scanRect(); + ctx.beginPath(); + ctx.rect(rect.left, rect.top, rect.width(), rect.height()); + ctx.clip(); + } + + _clipRRect(ctx, geom, command) { + let path = new Path([]); + let commands = [new RRectCommand(command[1])]; + path.subpaths.push(new Subpath(commands)); + this._runPath(ctx, path); + ctx.clip(); + } + + _clipPath(ctx, geom, command) { + let scanner = _scanCommand(command); + let path = scanner.scanPath(); + this._runPath(ctx, path); + ctx.clip(); + } + + _drawCircle(ctx, geom, command) { + let scanner = _scanCommand(command); + let dx = scanner.scanNumber(); + let dy = scanner.scanNumber(); + let radius = scanner.scanNumber(); + let paint = scanner.scanPaint(); + + this._applyPaint(ctx, paint); + ctx.beginPath(); + ctx.ellipse(dx, dy, radius, radius, 0, 0, 2.0 * Math.PI, false); + this._strokeOrFill(ctx, paint, true); + } + + _drawOval(ctx, geom, command) { + let scanner = _scanCommand(command); + let rect = scanner.scanRect(); + let paint = scanner.scanPaint(); + + this._applyPaint(ctx, paint); + ctx.beginPath(); + ctx.ellipse( + (rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2, + rect.width / 2, rect.height / 2, 0, 0, 2.0 * Math.PI, false); + this._strokeOrFill(ctx, paint, true); + } + + _drawPath(ctx, geom, command) { + let scanner = _scanCommand(command); + let path = scanner.scanPath(); + let paint = scanner.scanPaint(); + this._applyPaint(ctx, paint); + this._runPath(ctx, path); + this._strokeOrFill(ctx, paint, true); + } + + _drawShadow(ctx, geom, command) { + // TODO: this is mostly a stub; implement properly. + let scanner = _scanCommand(command); + let path = scanner.scanPath(); + let color = scanner.scanArray(); + let elevation = scanner.scanNumber(); + let transparentOccluder = scanner.scanBool(); + + let shadows = _computeShadowsForElevation(elevation, color); + for (let i = 0; i < shadows.length; i++) { + let shadow = shadows[i]; + + let paint = new Paint( + null, // blendMode + PaintingStyle.fill, // style + 1.0, // strokeWidth + null, // strokeCap + true, // isAntialias + shadow.color, // color + null, // shader + [BlurStyle.normal, shadow.blur], // maskFilter + null, // filterQuality + null // colorFilter + ); + + ctx.save(); + ctx.translate(shadow.offsetX, shadow.offsetY); + this._applyPaint(ctx, paint); + this._runPath(ctx, path, true); + this._strokeOrFill(ctx, paint, false); + ctx.restore(); + } + this._resetPaint(ctx); + } + + _runPath(ctx, path) { + ctx.beginPath(); + for (let i = 0; i < path.subpaths.length; i++) { + let subpath = path.subpaths[i]; + for (let j = 0; j < subpath.commands.length; j++) { + let command = subpath.commands[j]; + switch (command.type()) { + case PathCommandType.bezierCurveTo: + ctx.bezierCurveTo( + command.x1, command.y1, command.x2, command.y2, command.x3, + command.y3); + break; + case PathCommandType.close: + ctx.closePath(); + break; + case PathCommandType.ellipse: + ctx.ellipse( + command.x, command.y, command.radiusX, command.radiusY, + command.rotation, command.startAngle, command.endAngle, + command.anticlockwise); + break; + case PathCommandType.lineTo: + ctx.lineTo(command.x, command.y); + break; + case PathCommandType.moveTo: + ctx.moveTo(command.x, command.y); + break; + case PathCommandType.rrect: + this._drawRRectPath(ctx, command.rrect, false); + break; + case PathCommandType.rect: + ctx.rect(command.x, command.y, command.width, command.height); + break; + case PathCommandType.quadraticCurveTo: + ctx.quadraticCurveTo( + command.x1, command.y1, command.x2, command.y2); + break; + default: + throw new Error(`Unknown path command ${command.type()}`); + } + } + } + } + + _drawColor(ctx, geom, command) { + ctx.globalCompositeOperation = _stringForBlendMode(command[2]); + ctx.fillStyle = command[1]; + + // Fill a virtually infinite rect with the color. + // + // We can't use (0, 0, width, height) because the current transform can + // cause it to not fill the entire clip. + ctx.fillRect(-10000, -10000, 20000, 20000); + this._resetPaint(ctx); + } + + _drawLine(ctx, geom, command) { + let scanner = _scanCommand(command); + let p1dx = scanner.scanNumber(); + let p1dy = scanner.scanNumber(); + let p2dx = scanner.scanNumber(); + let p2dy = scanner.scanNumber(); + let paint = scanner.scanPaint(); + this._applyPaint(ctx, paint); + ctx.beginPath(); + ctx.moveTo(p1dx, p1dy); + ctx.lineTo(p2dx, p2dy); + ctx.stroke(); + this._resetPaint(ctx); + } + + _drawPaint(ctx, geom, command) { + let scanner = _scanCommand(command); + let paint = scanner.scanPaint(); + this._applyPaint(ctx, paint); + ctx.beginPath(); + + // Fill a virtually infinite rect with the color. + // + // We can't use (0, 0, width, height) because the current transform can + // cause it to not fill the entire clip. + ctx.fillRect(-10000, -10000, 20000, 20000); + this._resetPaint(ctx); + } +} + +function _scanCommand(command) { + return new CommandScanner(command); +} + +const PaintingStyle = { + fill: 0, + stroke: 1, +}; + +/// A singleton used to parse serialized commands. +class CommandScanner { + constructor(command) { + // Skip the first element, which is always the command ID. + this.index = 1; + this.command = command; + } + + scanRect() { + let rect = this.command[this.index++]; + return new Rect(rect[0], rect[1], rect[2], rect[3]); + } + + scanRRect() { + let rrect = this.command[this.index++]; + return new RRect( + rrect[0], rrect[1], rrect[2], rrect[3], rrect[4], rrect[5], rrect[6], + rrect[7], rrect[8], rrect[9], rrect[10], rrect[11]); + } + + scanPaint() { + let paint = this.command[this.index++]; + return new Paint( + paint[0], paint[1], paint[2], paint[3], paint[4], paint[5], paint[6], + paint[7], paint[8], paint[9]); + } + + scanNumber() { + return this.command[this.index++]; + } + + scanString() { + return this.command[this.index++]; + } + + scanBool() { + return this.command[this.index++]; + } + + scanPath() { + let subpaths = this.command[this.index++]; + return new Path(subpaths); + } + + scanArray() { + return this.command[this.index++]; + } +} + +class Rect { + constructor(left, top, right, bottom) { + this.left = left; + this.top = top; + this.right = right; + this.bottom = bottom; + } + + width() { + return this.right - this.left; + } + + height() { + return this.bottom - this.top; + } +} + +class RRect { + constructor( + left, top, right, bottom, tlRadiusX, tlRadiusY, trRadiusX, trRadiusY, + brRadiusX, brRadiusY, blRadiusX, blRadiusY) { + this.left = left; + this.top = top; + this.right = right; + this.bottom = bottom; + this.tlRadiusX = tlRadiusX; + this.tlRadiusY = tlRadiusY; + this.trRadiusX = trRadiusX; + this.trRadiusY = trRadiusY; + this.brRadiusX = brRadiusX; + this.brRadiusY = brRadiusY; + this.blRadiusX = blRadiusX; + this.blRadiusY = blRadiusY; + } + + tallMiddleRect() { + let leftRadius = Math.max(this.blRadiusX, this.tlRadiusX); + let rightRadius = Math.max(this.trRadiusX, this.brRadiusX); + return new Rect( + this.left + leftRadius, this.top, this.right - rightRadius, + this.bottom); + } + + middleRect() { + let leftRadius = Math.max(this.blRadiusX, this.tlRadiusX); + let topRadius = Math.max(this.tlRadiusY, this.trRadiusY); + let rightRadius = Math.max(this.trRadiusX, this.brRadiusX); + let bottomRadius = Math.max(this.brRadiusY, this.blRadiusY); + return new Rect( + this.left + leftRadius, this.top + topRadius, this.right - rightRadius, + this.bottom - bottomRadius); + } + + wideMiddleRect() { + let topRadius = Math.max(this.tlRadiusY, this.trRadiusY); + let bottomRadius = Math.max(this.brRadiusY, this.blRadiusY); + return new Rect( + this.left, this.top + topRadius, this.right, + this.bottom - bottomRadius); + } +} + +class Paint { + constructor( + blendMode, style, strokeWidth, strokeCap, isAntialias, color, shader, + maskFilter, filterQuality, colorFilter) { + this.blendMode = blendMode; + this.style = style; + this.strokeWidth = strokeWidth; + this.strokeCap = strokeCap; + this.isAntialias = isAntialias; + this.color = color; + this.shader = _deserializeShader(shader); // TODO: deserialize + this.maskFilter = maskFilter; + this.filterQuality = filterQuality; + this.colorFilter = colorFilter; // TODO: deserialize + } +} + +function _deserializeShader(data) { + if (!data) { + return null; + } + + switch (data[0]) { + case 1: + return new GradientLinear(data); + default: + throw new Error(`Shader type not supported: ${data}`); + } +} + +class GradientLinear { + constructor(data) { + this.fromX = data[1]; + this.fromY = data[2]; + this.toX = data[3]; + this.toY = data[4]; + this.colors = data[5]; + this.colorStops = data[6]; + this.tileMode = data[7]; + } + + createPaintStyle(ctx) { + let gradient = + ctx.createLinearGradient(this.fromX, this.fromY, this.toX, this.toY); + if (this.colorStops == null) { + gradient.addColorStop(0, this.colors[0]); + gradient.addColorStop(1, this.colors[1]); + return gradient; + } + for (let i = 0; i < this.colors.length; i++) { + gradient.addColorStop(this.colorStops[i], this.colors[i]); + } + return gradient; + } +} + +const BlendMode = { + clear: 0, + src: 1, + dst: 2, + srcOver: 3, + dstOver: 4, + srcIn: 5, + dstIn: 6, + srcOut: 7, + dstOut: 8, + srcATop: 9, + dstATop: 10, + xor: 11, + plus: 12, + modulate: 13, + screen: 14, + overlay: 15, + darken: 16, + lighten: 17, + colorDodge: 18, + colorBurn: 19, + hardLight: 20, + softLight: 21, + difference: 22, + exclusion: 23, + multiply: 24, + hue: 25, + saturation: 26, + color: 27, + luminosity: 28, +}; + +function _stringForBlendMode(blendMode) { + if (blendMode == null) return null; + switch (blendMode) { + case BlendMode.srcOver: + return 'source-over'; + case BlendMode.srcIn: + return 'source-in'; + case BlendMode.srcOut: + return 'source-out'; + case BlendMode.srcATop: + return 'source-atop'; + case BlendMode.dstOver: + return 'destination-over'; + case BlendMode.dstIn: + return 'destination-in'; + case BlendMode.dstOut: + return 'destination-out'; + case BlendMode.dstATop: + return 'destination-atop'; + case BlendMode.plus: + return 'lighten'; + case BlendMode.src: + return 'copy'; + case BlendMode.xor: + return 'xor'; + case BlendMode.multiply: + // Falling back to multiply, ignoring alpha channel. + // TODO(flutter_web): only used for debug, find better fallback for web. + case BlendMode.modulate: + return 'multiply'; + case BlendMode.screen: + return 'screen'; + case BlendMode.overlay: + return 'overlay'; + case BlendMode.darken: + return 'darken'; + case BlendMode.lighten: + return 'lighten'; + case BlendMode.colorDodge: + return 'color-dodge'; + case BlendMode.colorBurn: + return 'color-burn'; + case BlendMode.hardLight: + return 'hard-light'; + case BlendMode.softLight: + return 'soft-light'; + case BlendMode.difference: + return 'difference'; + case BlendMode.exclusion: + return 'exclusion'; + case BlendMode.hue: + return 'hue'; + case BlendMode.saturation: + return 'saturation'; + case BlendMode.color: + return 'color'; + case BlendMode.luminosity: + return 'luminosity'; + default: + throw new Error( + 'Flutter web does not support the blend mode: $blendMode'); + } +} + +const StrokeCap = { + butt: 0, + round: 1, + square: 2, +}; + +function _stringForStrokeCap(strokeCap) { + if (strokeCap == null) return null; + switch (strokeCap) { + case StrokeCap.butt: + return 'butt'; + case StrokeCap.round: + return 'round'; + case StrokeCap.square: + default: + return 'square'; + } +} + +class Path { + constructor(serializedSubpaths) { + this.subpaths = []; + for (let i = 0; i < serializedSubpaths.length; i++) { + let subpath = serializedSubpaths[i]; + let pathCommands = []; + for (let j = 0; j < subpath.length; j++) { + let pathCommand = subpath[j]; + switch (pathCommand[0]) { + case 1: + pathCommands.push(new MoveTo(pathCommand)); + break; + case 2: + pathCommands.push(new LineTo(pathCommand)); + break; + case 3: + pathCommands.push(new Ellipse(pathCommand)); + break; + case 4: + pathCommands.push(new QuadraticCurveTo(pathCommand)); + break; + case 5: + pathCommands.push(new BezierCurveTo(pathCommand)); + break; + case 6: + pathCommands.push(new RectCommand(pathCommand)); + break; + case 7: + pathCommands.push(new RRectCommand(pathCommand)); + break; + case 8: + pathCommands.push(new CloseCommand()); + break; + default: + throw new Error(`Unsupported path command: ${pathCommand}`); + } + } + + this.subpaths.push(new Subpath(pathCommands)); + } + } +} + +class Subpath { + constructor(commands) { + this.commands = commands; + } +} + +class MoveTo { + constructor(data) { + this.x = data[1]; + this.y = data[2]; + } + + type() { + return PathCommandType.moveTo; + } +} + +class LineTo { + constructor(data) { + this.x = data[1]; + this.y = data[2]; + } + + type() { + return PathCommandType.lineTo; + } +} + +class Ellipse { + constructor(data) { + this.x = data[1]; + this.y = data[2]; + this.radiusX = data[3]; + this.radiusY = data[4]; + this.rotation = data[5]; + this.startAngle = data[6]; + this.endAngle = data[7]; + this.anticlockwise = data[8]; + } + + type() { + return PathCommandType.ellipse; + } +} + +class QuadraticCurveTo { + constructor(data) { + this.x1 = data[1]; + this.y1 = data[2]; + this.x2 = data[3]; + this.y2 = data[4]; + } + + type() { + return PathCommandType.quadraticCurveTo; + } +} + +class BezierCurveTo { + constructor(data) { + this.x1 = data[1]; + this.y1 = data[2]; + this.x2 = data[3]; + this.y2 = data[4]; + this.x3 = data[5]; + this.y3 = data[6]; + } + + type() { + return PathCommandType.bezierCurveTo; + } +} + +class RectCommand { + constructor(data) { + this.x = data[1]; + this.y = data[2]; + this.width = data[3]; + this.height = data[4]; + } + + type() { + return PathCommandType.rect; + } +} + +class RRectCommand { + constructor(data) { + let scanner = _scanCommand(data); + this.rrect = scanner.scanRRect(); + } + + type() { + return PathCommandType.rrect; + } +} + +class CloseCommand { + type() { + return PathCommandType.close; + } +} + +class CanvasShadow { + constructor(offsetX, offsetY, blur, spread, color) { + this.offsetX = offsetX; + this.offsetY = offsetY; + this.blur = blur; + this.spread = spread; + this.color = color; + } +} + +const _noShadows = []; + +function _computeShadowsForElevation(elevation, color) { + if (elevation <= 0.0) { + return _noShadows; + } else if (elevation <= 1.0) { + return _computeShadowElevation(2, color); + } else if (elevation <= 2.0) { + return _computeShadowElevation(4, color); + } else if (elevation <= 3.0) { + return _computeShadowElevation(6, color); + } else if (elevation <= 4.0) { + return _computeShadowElevation(8, color); + } else if (elevation <= 5.0) { + return _computeShadowElevation(16, color); + } else { + return _computeShadowElevation(24, color); + } +} + +function _computeShadowElevation(dp, color) { + // TODO(yjbanov): multiple shadows are very expensive. Find a more efficient + // method to render them. + let red = color[1]; + let green = color[2]; + let blue = color[3]; + + // let penumbraColor = `rgba(${red}, ${green}, ${blue}, 0.14)`; + // let ambientShadowColor = `rgba(${red}, ${green}, ${blue}, 0.12)`; + let umbraColor = `rgba(${red}, ${green}, ${blue}, 0.2)`; + + let result = []; + if (dp === 2) { + // result.push(new CanvasShadow(0.0, 2.0, 1.0, 0.0, penumbraColor)); + // result.push(new CanvasShadow(0.0, 3.0, 0.5, -2.0, ambientShadowColor)); + result.push(new CanvasShadow(0.0, 1.0, 2.5, 0.0, umbraColor)); + } else if (dp === 3) { + // result.push(new CanvasShadow(0.0, 1.5, 4.0, 0.0, penumbraColor)); + // result.push(new CanvasShadow(0.0, 3.0, 1.5, -2.0, ambientShadowColor)); + result.push(new CanvasShadow(0.0, 1.0, 4.0, 0.0, umbraColor)); + } else if (dp === 4) { + // result.push(new CanvasShadow(0.0, 4.0, 2.5, 0.0, penumbraColor)); + // result.push(new CanvasShadow(0.0, 1.0, 5.0, 0.0, ambientShadowColor)); + result.push(new CanvasShadow(0.0, 2.0, 2.0, -1.0, umbraColor)); + } else if (dp === 6) { + // result.push(new CanvasShadow(0.0, 6.0, 5.0, 0.0, penumbraColor)); + // result.push(new CanvasShadow(0.0, 1.0, 9.0, 0.0, ambientShadowColor)); + result.push(new CanvasShadow(0.0, 3.0, 2.5, -1.0, umbraColor)); + } else if (dp === 8) { + // result.push(new CanvasShadow(0.0, 4.0, 10.0, 1.0, penumbraColor)); + // result.push(new CanvasShadow(0.0, 3.0, 7.0, 2.0, ambientShadowColor)); + result.push(new CanvasShadow(0.0, 5.0, 2.5, -3.0, umbraColor)); + } else if (dp === 12) { + // result.push(new CanvasShadow(0.0, 12.0, 8.5, 2.0, penumbraColor)); + // result.push(new CanvasShadow(0.0, 5.0, 11.0, 4.0, ambientShadowColor)); + result.push(new CanvasShadow(0.0, 7.0, 4.0, -4.0, umbraColor)); + } else if (dp === 16) { + // result.push(new CanvasShadow(0.0, 16.0, 12.0, 2.0, penumbraColor)); + // result.push(new CanvasShadow(0.0, 6.0, 15.0, 5.0, ambientShadowColor)); + result.push(new CanvasShadow(0.0, 0.0, 5.0, -5.0, umbraColor)); + } else { + // result.push(new CanvasShadow(0.0, 24.0, 18.0, 3.0, penumbraColor)); + // result.push(new CanvasShadow(0.0, 9.0, 23.0, 8.0, ambientShadowColor)); + result.push(new CanvasShadow(0.0, 11.0, 7.5, -7.0, umbraColor)); + } + return result; +} + +const PathCommandType = { + moveTo: 0, + lineTo: 1, + ellipse: 2, + close: 3, + quadraticCurveTo: 4, + bezierCurveTo: 5, + rect: 6, + rrect: 7, +}; + +const TileMode = { + clamp: 0, + repeated: 1, +}; + +const BlurStyle = { + normal: 0, + solid: 1, + outer: 2, + inner: 3, +}; + +/// This makes the painter available as "background-image: paint(flt)". +registerPaint('flt', FlutterPainter); diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine.dart b/engine/src/flutter/lib/web_ui/lib/src/engine.dart index 132a7c16f3..aaf3587d13 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine.dart @@ -25,11 +25,12 @@ part 'engine/browser_detection.dart'; part 'engine/browser_location.dart'; part 'engine/compositor/canvas.dart'; part 'engine/compositor/engine_delegate.dart'; +part 'engine/compositor/fonts.dart'; +part 'engine/compositor/image.dart'; part 'engine/compositor/initialization.dart'; part 'engine/compositor/layer.dart'; part 'engine/compositor/layer_scene_builder.dart'; part 'engine/compositor/layer_tree.dart'; -part 'engine/compositor/matrix.dart'; part 'engine/compositor/path.dart'; part 'engine/compositor/picture.dart'; part 'engine/compositor/picture_recorder.dart'; @@ -39,6 +40,7 @@ part 'engine/compositor/rasterizer.dart'; part 'engine/compositor/recording_canvas.dart'; part 'engine/compositor/runtime_delegate.dart'; part 'engine/compositor/surface.dart'; +part 'engine/compositor/util.dart'; part 'engine/compositor/viewport_metrics.dart'; part 'engine/conic.dart'; part 'engine/dom_canvas.dart'; @@ -67,6 +69,7 @@ part 'engine/services/buffers.dart'; part 'engine/services/message_codec.dart'; part 'engine/services/message_codecs.dart'; part 'engine/services/serialization.dart'; +part 'engine/shader.dart'; part 'engine/shadow.dart'; part 'engine/surface/backdrop_filter.dart'; part 'engine/surface/clip.dart'; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/assets.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/assets.dart index 3c4bf801d0..83d4c28a65 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/assets.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/assets.dart @@ -6,7 +6,8 @@ part of engine; /// This class downloads assets over the network. /// -/// The assets are resolved relative to [assetsDir]. +/// The assets are resolved relative to [assetsDir] inside the directory +/// containing the currently executing JS script. class AssetManager { static const String _defaultAssetsDir = 'assets'; @@ -15,18 +16,19 @@ class AssetManager { const AssetManager({this.assetsDir = _defaultAssetsDir}); + String get _baseUrl { + return html.window.document + .querySelectorAll('meta') + .whereType() + .firstWhere((dynamic e) => e.name == 'assetBase', orElse: () => null) + ?.content; + } + String getAssetUrl(String asset) { - final Uri assetUri = Uri.parse(asset); - - String url; - - if (assetUri.hasScheme) { - url = asset; - } else { - url = '$assetsDir/$asset'; + if (Uri.parse(asset).hasScheme) { + return asset; } - - return url; + return (_baseUrl ?? '') + '$assetsDir/$asset'; } Future load(String asset) async { @@ -72,6 +74,9 @@ class WebOnlyMockAssetManager implements AssetManager { @override String get assetsDir => defaultAssetsDir; + @override + String get _baseUrl => ''; + @override String getAssetUrl(String asset) => '$asset'; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/bitmap_canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/bitmap_canvas.dart index 94d18c199b..3b2a5c8fce 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/bitmap_canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/bitmap_canvas.dart @@ -226,7 +226,8 @@ class BitmapCanvas extends EngineCanvas with SaveStackTracking { ctx.lineJoin = 'miter'; } if (paint.shader != null) { - final Object paintStyle = paint.shader.createPaintStyle(ctx); + final EngineGradient engineShader = paint.shader; + final Object paintStyle = engineShader.createPaintStyle(ctx); _setFillAndStrokeStyle(paintStyle, paintStyle); } else if (paint.color != null) { final String colorString = paint.color.toCssString(); @@ -367,20 +368,6 @@ class BitmapCanvas extends EngineCanvas with SaveStackTracking { // // This matrix is sufficient to represent 2D rotates, translates, scales, // and skews. - assert(() { - if (matrix4[2] != 0.0 || - matrix4[3] != 0.0 || - matrix4[7] != 0.0 || - matrix4[8] != 0.0 || - matrix4[9] != 0.0 || - matrix4[10] != 1.0 || - matrix4[11] != 0.0 || - matrix4[14] != 0.0 || - matrix4[15] != 1.0) { - print('WARNING: 3D transformation matrix was passed to BitmapCanvas.'); - } - return true; - }()); _ctx.transform( matrix4[0], matrix4[1], @@ -505,12 +492,12 @@ class BitmapCanvas extends EngineCanvas with SaveStackTracking { final double blRadiusY = rrect.blRadiusY.abs(); final double brRadiusY = rrect.brRadiusY.abs(); - ctx.moveTo(left + trRadiusX, top); - if (startNewPath) { ctx.beginPath(); } + ctx.moveTo(left + trRadiusX, top); + // Top side and top-right corner ctx.lineTo(right - trRadiusX, top); ctx.ellipse( @@ -838,7 +825,9 @@ class BitmapCanvas extends EngineCanvas with SaveStackTracking { } else { final String cssTransform = matrix4ToCssTransform(transformWithOffset(currentTransform, offset)); - paragraphElement.style.transform = cssTransform; + paragraphElement.style + ..transformOrigin = '0 0 0' + ..transform = cssTransform; rootElement.append(paragraphElement); } _children.add(paragraphElement); @@ -1075,8 +1064,9 @@ List _clipContent(List<_SaveClipEntry> clipStack, root.style.position = 'absolute'; domRenderer.append(curElement, content); - content.style.transform = - _cssTransformAtOffset(currentTransform, offset.dx, offset.dy); + content.style + ..transformOrigin = '0 0 0' + ..transform = _cssTransformAtOffset(currentTransform, offset.dx, offset.dy); return [root]..addAll(clipDefs); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/canvas.dart index 85dd77417d..4b69abf36a 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/canvas.dart @@ -30,7 +30,7 @@ class SkCanvas { int saveLayer(ui.Rect bounds, ui.Paint paint) { return skCanvas.callMethod( - 'saveLayer', [_makeSkRect(bounds), _makeSkPaint(paint)]); + 'saveLayer', [makeSkRect(bounds), makeSkPaint(paint)]); } void restore() { @@ -50,16 +50,26 @@ class SkCanvas { } void transform(Float64List matrix) { - skCanvas.callMethod('concat', >[toSkMatrix(matrix)]); + skCanvas.callMethod('concat', >[makeSkMatrix(matrix)]); } - void clipPath(ui.Path path) { + void clipPath(ui.Path path, {bool doAntiAlias = true}) { final SkPath skPath = path; - skCanvas.callMethod('clipPath', [skPath._skPath]); + final js.JsObject intersectClipOp = canvasKit['ClipOp']['Intersect']; + skCanvas.callMethod('clipPath', [ + skPath._skPath, + intersectClipOp, + doAntiAlias, + ]); } - void clipRect(ui.Rect rect) { - skCanvas.callMethod('clipRect', [_makeSkRect(rect)]); + void clipRect(ui.Rect rect, {bool doAntiAlias = true}) { + final js.JsObject intersectClipOp = canvasKit['ClipOp']['Intersect']; + skCanvas.callMethod('clipRect', [ + makeSkRect(rect), + intersectClipOp, + doAntiAlias, + ]); } void clipRRect(ui.RRect rrect) { @@ -76,30 +86,17 @@ class SkCanvas { void drawPath(ui.Path path, ui.Paint paint) { final SkPath skPath = path; skCanvas.callMethod( - 'drawPath', [skPath._skPath, _makeSkPaint(paint)]); + 'drawPath', [skPath._skPath, makeSkPaint(paint)]); } void drawPaint(ui.Paint paint) { - skCanvas.callMethod('drawPaint', [_makeSkPaint(paint)]); + skCanvas.callMethod('drawPaint', [makeSkPaint(paint)]); } void drawShadow(ui.Path path, ui.Color color, double elevation, bool transparentOccluder) { - throw 'drawShadow'; + drawSkShadow(skCanvas, path, color, elevation, transparentOccluder); } Matrix4 get currentTransform => throw 'currentTransform'; - - js.JsObject _makeSkRect(ui.Rect rect) { - return js.JsObject(canvasKit['LTRBRect'], - [rect.left, rect.top, rect.right, rect.bottom]); - } - - js.JsObject _makeSkPaint(ui.Paint paint) { - final js.JsObject skPaint = js.JsObject(canvasKit['SkPaint']); - if (paint.color != null) { - skPaint.callMethod('setColor', [paint.color.value]); - } - return skPaint; - } } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/fonts.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/fonts.dart new file mode 100644 index 0000000000..b37425ba92 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/fonts.dart @@ -0,0 +1,92 @@ +// 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. +part of engine; + +class SkiaFontCollection { + final Map, js.JsObject>> + _registeredTypefaces = , js.JsObject>>{}; + + final List> _fontLoadingFutures = >[]; + + Future ensureFontsLoaded() async { + await Future.wait(_fontLoadingFutures); + } + + Future registerFonts(AssetManager assetManager) async { + ByteData byteData; + + try { + byteData = await assetManager.load('FontManifest.json'); + } on AssetManagerException catch (e) { + if (e.httpStatus == 404) { + html.window.console + .warn('Font manifest does not exist at `${e.url}` – ignoring.'); + return; + } else { + rethrow; + } + } + + if (byteData == null) { + throw AssertionError( + 'There was a problem trying to load FontManifest.json'); + } + + final List fontManifest = + json.decode(utf8.decode(byteData.buffer.asUint8List())); + if (fontManifest == null) { + throw AssertionError( + 'There was a problem trying to load FontManifest.json'); + } + + // Add Roboto to the bundled fonts since it is provided by default by + // Flutter. + _fontLoadingFutures + .add(_registerFont('Roboto', _robotoFontUrl, {})); + + for (Map fontFamily in fontManifest) { + final String family = fontFamily['family']; + final List fontAssets = fontFamily['fonts']; + + for (dynamic fontAssetItem in fontAssets) { + final Map fontAsset = fontAssetItem; + final String asset = fontAsset['asset']; + final Map descriptors = {}; + for (String descriptor in fontAsset.keys) { + if (descriptor != 'asset') { + descriptors[descriptor] = '${fontAsset[descriptor]}'; + } + } + _fontLoadingFutures.add(_registerFont( + family, assetManager.getAssetUrl(asset), descriptors)); + } + } + } + + Future _registerFont( + String family, String url, Map descriptors) async { + final dynamic fetchResult = await html.window.fetch(url); + final ByteBuffer resultBuffer = await fetchResult.arrayBuffer(); + final js.JsObject skTypeFace = skFontMgr.callMethod( + 'MakeTypefaceFromData', [resultBuffer.asUint8List()]); + _registeredTypefaces.putIfAbsent( + family, () => , js.JsObject>{}); + _registeredTypefaces[family][descriptors] = skTypeFace; + } + + js.JsObject getFont(String family, double size) { + if (_registeredTypefaces[family] == null) { + if (family == 'sans-serif') { + // If it's the default font, return a default SkFont + return js.JsObject(canvasKit['SkFont'], [null, size]); + } + throw Exception('Unregistered font: $family'); + } + final js.JsObject skTypeface = _registeredTypefaces[family].values.first; + return js.JsObject(canvasKit['SkFont'], [skTypeface, size]); + } + + final js.JsObject skFontMgr = + js.JsObject(canvasKit['SkFontMgr']['RefDefault']); +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/image.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/image.dart new file mode 100644 index 0000000000..fb5f493ccd --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/image.dart @@ -0,0 +1,61 @@ +// 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. +part of engine; + +/// Instantiates a [ui.Codec] backed by an `SkImage` from Skia. +void skiaInstantiateImageCodec(Uint8List list, Callback callback, + [int width, int height, int format, int rowBytes]) { + final js.JsObject skImage = + canvasKit.callMethod('MakeImageFromEncoded', [list]); + final SkImage image = SkImage(skImage); + final SkImageCodec codec = SkImageCodec(image); + callback(codec); +} + +/// A [ui.Image] backed by an `SkImage` from Skia. +class SkImage implements ui.Image { + js.JsObject skImage; + + SkImage(this.skImage); + + @override + void dispose() { + skImage = null; + } + + @override + int get width => skImage.callMethod('width'); + + @override + int get height => skImage.callMethod('height'); + + @override + Future toByteData( + {ui.ImageByteFormat format = ui.ImageByteFormat.rawRgba}) { + throw 'unimplemented'; + } +} + +/// A [ui.Codec] backed by an `SkImage` from Skia. +class SkImageCodec implements ui.Codec { + final SkImage skImage; + + SkImageCodec(this.skImage); + + @override + void dispose() { + // TODO: implement dispose + } + + @override + int get frameCount => 1; + + @override + Future getNextFrame() { + return Future.value(SingleFrameInfo(skImage)); + } + + @override + int get repetitionCount => 0; +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/initialization.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/initialization.dart index dcf38d6fc1..792db2ebcf 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/initialization.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/initialization.dart @@ -5,7 +5,8 @@ part of engine; /// EXPERIMENTAL: Enable the Skia-based rendering backend. -const bool experimentalUseSkia = false; +const bool experimentalUseSkia = + bool.fromEnvironment('FLUTTER_WEB_USE_SKIA', defaultValue: false); /// The URL to use when downloading the CanvasKit script and associated wasm. const String canvasKitBaseUrl = 'https://unpkg.com/canvaskit-wasm@0.6.0/bin/'; @@ -18,17 +19,17 @@ Future initializeSkia() { StreamSubscription loadSubscription; loadSubscription = domRenderer.canvasKitScript.onLoad.listen((_) { loadSubscription.cancel(); - final js.JsObject canvasKitInitArgs = js.JsObject.jsify({ - 'locateFile': js.allowInterop((String file) => canvasKitBaseUrl + file) + final js.JsObject canvasKitInitArgs = js.JsObject.jsify({ + 'locateFile': (String file, String unusedBase) => canvasKitBaseUrl + file, }); final js.JsObject canvasKitInit = js.JsObject(js.context['CanvasKitInit'], [canvasKitInitArgs]); final js.JsObject canvasKitInitPromise = canvasKitInit.callMethod('ready'); canvasKitInitPromise.callMethod('then', [ - js.allowInterop((js.JsObject ck) { + (js.JsObject ck) { canvasKit = ck; canvasKitCompleter.complete(); - }) + }, ]); }); return canvasKitCompleter.future; @@ -38,3 +39,6 @@ Future initializeSkia() { /// /// This is created by [initializeSkia]. js.JsObject canvasKit; + +/// The Skia font collection. +SkiaFontCollection skiaFontCollection; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer.dart index 65dd3499e3..9bd04f42ea 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer.dart @@ -172,6 +172,42 @@ class ClipRRectLayer extends ContainerLayer { } } +/// A layer that paints its children with the given opacity. +class OpacityLayer extends ContainerLayer implements ui.OpacityEngineLayer { + final int _alpha; + final ui.Offset _offset; + + OpacityLayer(this._alpha, this._offset); + + @override + void preroll(PrerollContext prerollContext, Matrix4 matrix) { + Matrix4 childMatrix = Matrix4.copy(matrix); + childMatrix.translate(_offset.dx, _offset.dy); + final ui.Rect childPaintBounds = + prerollChildren(prerollContext, childMatrix); + paintBounds = childPaintBounds.translate(_offset.dx, _offset.dy); + } + + @override + void paint(PaintContext context) { + assert(needsPainting); + + final ui.Paint paint = ui.Paint(); + paint.color = ui.Color.fromARGB(_alpha, 0, 0, 0); + + context.canvas.save(); + context.canvas.translate(_offset.dx, _offset.dy); + + final ui.Rect saveLayerBounds = paintBounds.shift(-_offset); + + context.canvas.saveLayer(saveLayerBounds, paint); + paintChildren(context); + // Restore twice: once for the translate and once for the saveLayer. + context.canvas.restore(); + context.canvas.restore(); + } +} + /// A layer that transforms its child layers by the given transform matrix. class TransformLayer extends ContainerLayer implements ui.OffsetEngineLayer, ui.TransformEngineLayer { @@ -330,16 +366,13 @@ class PhysicalShapeLayer extends ContainerLayer final int saveCount = paintContext.canvas.save(); switch (_clipBehavior) { case ui.Clip.hardEdge: - paintContext.canvas.clipPath(_path); + paintContext.canvas.clipPath(_path, doAntiAlias: false); break; case ui.Clip.antiAlias: - // TODO(het): This is supposed to be different from Clip.hardEdge in - // that it anti-aliases the clip. The canvas clipPath() method - // should support this. - paintContext.canvas.clipPath(_path); + paintContext.canvas.clipPath(_path, doAntiAlias: true); break; case ui.Clip.antiAliasWithSaveLayer: - paintContext.canvas.clipPath(_path); + paintContext.canvas.clipPath(_path, doAntiAlias: true); paintContext.canvas.saveLayer(paintBounds, null); break; case ui.Clip.none: diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer_scene_builder.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer_scene_builder.dart index ee7a7991c1..0bb05f096d 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer_scene_builder.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer_scene_builder.dart @@ -118,7 +118,8 @@ class LayerSceneBuilder implements ui.SceneBuilder { @override ui.ColorFilterEngineLayer pushColorFilter(ui.ColorFilter filter, - {ui.EngineLayer oldLayer}) { + {ui.ColorFilterEngineLayer oldLayer}) { + assert(filter != null); throw UnimplementedError(); } @@ -134,9 +135,9 @@ class LayerSceneBuilder implements ui.SceneBuilder { @override ui.OpacityEngineLayer pushOpacity(int alpha, {ui.EngineLayer oldLayer, ui.Offset offset = ui.Offset.zero}) { - // TODO(het): Implement opacity - pushOffset(0.0, 0.0); - return null; + final OpacityLayer layer = OpacityLayer(alpha, offset); + pushLayer(layer); + return layer; } @override diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/matrix.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/matrix.dart deleted file mode 100644 index 23962cef1d..0000000000 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/matrix.dart +++ /dev/null @@ -1,27 +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. - -part of engine; - -// Mappings from SkMatrix-index to input-index. -const List _skMatrixIndexToMatrix4Index = [ - 0, 4, 12, // Row 1 - 1, 5, 13, // Row 2 - 3, 7, 15, // Row 3 -]; - -/// Converts a 4x4 Flutter matrix (represented as a [Float64List]) to an -/// SkMatrix, which is a 3x3 transform matrix. -js.JsArray toSkMatrix(Float64List matrix4) { - js.JsArray skMatrix = new js.JsArray(); - skMatrix.length = 9; - for (int i = 0; i < 9; ++i) { - int matrix4Index = _skMatrixIndexToMatrix4Index[i]; - if (matrix4Index < matrix4.length) - skMatrix[i] = matrix4[matrix4Index]; - else - skMatrix[i] = 0.0; - } - return skMatrix; -} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/path.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/path.dart index 4b7dbe6de2..5e21d8e4fb 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/path.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/path.dart @@ -12,15 +12,32 @@ class SkPath implements ui.Path { SkPath() { _skPath = js.JsObject(canvasKit['SkPath']); + fillType = ui.PathFillType.nonZero; } - js.JsObject _makeSkRect(ui.Rect rect) { - return js.JsObject(canvasKit['LTRBRect'], - [rect.left, rect.top, rect.right, rect.bottom]); - } + SkPath._fromSkPath(js.JsObject skPath) : _skPath = skPath; + + ui.PathFillType _fillType; @override - ui.PathFillType fillType; + ui.PathFillType get fillType => _fillType; + + @override + set fillType(ui.PathFillType newFillType) { + _fillType = newFillType; + + js.JsObject skFillType; + switch (newFillType) { + case ui.PathFillType.nonZero: + skFillType = canvasKit['FillType']['Winding']; + break; + case ui.PathFillType.evenOdd: + skFillType = canvasKit['FillType']['EvenOdd']; + break; + } + + _skPath.callMethod('setFillType', [skFillType]); + } @override void addArc(ui.Rect oval, double startAngle, double sweepAngle) { @@ -29,7 +46,9 @@ class SkPath implements ui.Path { @override void addOval(ui.Rect oval) { - throw 'addOval'; + // TODO(het): Use `addOval` instead when CanvasKit exposes it. + // Since CanvasKit doesn't expose `addOval`, use `addArc` instead. + _skPath.callMethod('addArc', [makeSkRect(oval), 0.0, 360.0]); } @override @@ -39,13 +58,26 @@ class SkPath implements ui.Path { @override void addPolygon(List points, bool close) { - throw 'addPolygon'; + // TODO(het): Use `addPoly` once CanvasKit makes it available. + assert(points != null); + if (points.isEmpty) { + return; + } + + moveTo(points.first.dx, points.first.dy); + for (int i = 1; i < points.length; i++) { + final ui.Offset point = points[i]; + lineTo(point.dx, point.dy); + } + if (close) { + this.close(); + } } @override void addRRect(ui.RRect rrect) { - final js.JsObject skRect = _makeSkRect(rrect.outerRect); - final List radii = [ + final js.JsObject skRect = makeSkRect(rrect.outerRect); + final List radii = [ rrect.tlRadiusX, rrect.tlRadiusY, rrect.trRadiusX, @@ -55,18 +87,25 @@ class SkPath implements ui.Path { rrect.blRadiusX, rrect.blRadiusY, ]; - _skPath.callMethod('addRoundRect', [skRect, radii]); + _skPath.callMethod('addRoundRect', + [skRect, js.JsArray.from(radii), false]); } @override void addRect(ui.Rect rect) { - throw 'addRect'; + _skPath.callMethod('addRect', [makeSkRect(rect)]); } @override void arcTo( ui.Rect rect, double startAngle, double sweepAngle, bool forceMoveTo) { - throw 'arcTo'; + const double radsToDegrees = 180.0 / math.pi; + _skPath.callMethod('arcTo', [ + makeSkRect(rect), + startAngle * radsToDegrees, + sweepAngle * radsToDegrees, + forceMoveTo, + ]); } @override @@ -75,12 +114,31 @@ class SkPath implements ui.Path { double rotation = 0.0, bool largeArc = false, bool clockwise = true}) { - throw 'arcToPoint'; + assert(rotation == 0.0, + 'Skia backend does not support `arcToPoint` rotation.'); + assert(!largeArc, 'Skia backend does not support `arcToPoint` largeArc.'); + assert(radius.x == radius.y, + 'Skia backend does not support `arcToPoint` with elliptical radius.'); + + // TODO(het): Remove asserts above and use the correct override of `arcTo` + // when it is available in CanvasKit. + // The only `arcTo` method exposed in CanvasKit is: + // arcTo(x1, y1, x2, y2, radius) + final ui.Offset lastPoint = _getCurrentPoint(); + _skPath.callMethod('arcTo', + [lastPoint.dx, lastPoint.dy, arcEnd.dx, arcEnd.dy, radius.x]); + } + + ui.Offset _getCurrentPoint() { + final int pointCount = _skPath.callMethod('countPoints'); + final js.JsObject lastPoint = + _skPath.callMethod('getPoint', [pointCount - 1]); + return ui.Offset(lastPoint[0], lastPoint[1]); } @override void close() { - throw 'close'; + _skPath.callMethod('close'); } @override @@ -95,38 +153,62 @@ class SkPath implements ui.Path { @override bool contains(ui.Offset point) { - throw 'contains'; + return _skPath.callMethod('contains', [point.dx, point.dy]); } @override void cubicTo( double x1, double y1, double x2, double y2, double x3, double y3) { - throw 'cubicTo'; + _skPath.callMethod('cubicTo', [x1, y1, x2, y2, x3, y3]); } @override void extendWithPath(ui.Path path, ui.Offset offset, {Float64List matrix4}) { - throw 'extendWithPath'; + List skMatrix; + if (matrix4 == null) { + skMatrix = makeSkMatrix( + Matrix4.translationValues(offset.dx, offset.dy, 0.0).storage); + } else { + skMatrix = makeSkMatrix(matrix4); + skMatrix[2] += offset.dx; + skMatrix[5] += offset.dy; + } + final SkPath otherPath = path; + _skPath.callMethod('addPath', [ + otherPath._skPath, + skMatrix[0], + skMatrix[1], + skMatrix[2], + skMatrix[3], + skMatrix[4], + skMatrix[5], + skMatrix[6], + skMatrix[7], + skMatrix[8], + true, + ]); } @override ui.Rect getBounds() { - throw 'getBounds'; + final js.JsObject bounds = _skPath.callMethod('getBounds'); + return ui.Rect.fromLTRB( + bounds['fLeft'], bounds['fTop'], bounds['fRight'], bounds['fBottom']); } @override void lineTo(double x, double y) { - throw 'lineTo'; + _skPath.callMethod('lineTo', [x, y]); } @override void moveTo(double x, double y) { - throw 'moveTo'; + _skPath.callMethod('moveTo', [x, y]); } @override void quadraticBezierTo(double x1, double y1, double x2, double y2) { - throw 'quadraticBezierTo'; + _skPath.callMethod('quadTo', [x1, y1, x2, y2]); } @override @@ -166,12 +248,17 @@ class SkPath implements ui.Path { @override void reset() { - throw 'reset'; + _skPath.callMethod('reset'); } @override ui.Path shift(ui.Offset offset) { - throw 'shift'; + // Since CanvasKit does not expose `SkPath.offset`, create a copy of this + // path and call `transform` on it. + final js.JsObject newPath = _skPath.callMethod('copy'); + newPath.callMethod('transform', + [1.0, 0.0, offset.dx, 0.0, 1.0, offset.dy, 0.0, 0.0, 0.0]); + return SkPath._fromSkPath(newPath); } @override @@ -182,21 +269,18 @@ class SkPath implements ui.Path { throw 'transform'; } + // TODO(het): Remove these. @override - // TODO: implement webOnlyPathAsCircle Ellipse get webOnlyPathAsCircle => null; @override - // TODO: implement webOnlyPathAsRect ui.Rect get webOnlyPathAsRect => null; @override - // TODO: implement webOnlyPathAsRoundedRect ui.RRect get webOnlyPathAsRoundedRect => null; @override - List webOnlySerializeToCssPaint() { - // TODO: implement webOnlySerializeToCssPaint + List webOnlySerializeToCssPaint() { return null; } } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/picture_recorder.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/picture_recorder.dart index 0dd491fa6a..9211bbddb7 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/picture_recorder.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/picture_recorder.dart @@ -23,7 +23,8 @@ class SkPictureRecorder implements ui.PictureRecorder { @override ui.Picture endRecording() { - js.JsObject skPicture = _recorder.callMethod('finishRecordingAsPicture'); + final js.JsObject skPicture = + _recorder.callMethod('finishRecordingAsPicture'); _recorder.callMethod('delete'); return SkPicture(skPicture, cullRect); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/recording_canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/recording_canvas.dart index 71ec4cb2c8..a084c75ec3 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/recording_canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/recording_canvas.dart @@ -8,31 +8,6 @@ class SkRecordingCanvas implements RecordingCanvas { final js.JsObject skCanvas; SkRecordingCanvas(this.skCanvas); - js.JsObject _makeSkRect(ui.Rect rect) { - return js.JsObject(canvasKit['LTRBRect'], - [rect.left, rect.top, rect.right, rect.bottom]); - } - - js.JsObject _makeSkPaint(ui.Paint paint) { - final skPaint = js.JsObject(canvasKit['SkPaint']); - - skPaint.callMethod('setColor', [paint.color.value]); - - js.JsObject skPaintStyle; - switch (paint.style) { - case ui.PaintingStyle.stroke: - skPaintStyle = canvasKit['PaintStyle']['Stroke']; - break; - case ui.PaintingStyle.fill: - skPaintStyle = canvasKit['PaintStyle']['Fill']; - break; - } - skPaint.callMethod('setStyle', [skPaintStyle]); - - skPaint.callMethod('setAntiAlias', [paint.isAntiAlias]); - return skPaint; - } - @override bool _didDraw = true; @@ -40,7 +15,7 @@ class SkRecordingCanvas implements RecordingCanvas { bool _hasArbitraryPaint = true; @override - int saveCount; + int saveCount = 0; @override // TODO: implement _commands @@ -56,18 +31,47 @@ class SkRecordingCanvas implements RecordingCanvas { } @override - void clipPath(ui.Path path) { - throw 'clipPath'; + void clipPath(ui.Path path, {bool doAntiAlias = true}) { + final SkPath skPath = path; + final js.JsObject intersectClipOp = canvasKit['ClipOp']['Intersect']; + skCanvas.callMethod('clipPath', [ + skPath._skPath, + intersectClipOp, + doAntiAlias, + ]); } @override - void clipRRect(ui.RRect rrect) { - throw 'clipRRect'; + void clipRRect( + ui.RRect rrect, { + bool doAntiAlias = true, + }) { + // TODO(het): Use `clipRRect` when CanvasKit makes it available. + // CanvasKit doesn't expose `Canvas.clipRRect`, so we create a path, add the + // RRect to it, and call clipPath with it. + final SkPath rrectPath = SkPath(); + rrectPath.addRRect(rrect); + clipPath(rrectPath, doAntiAlias: doAntiAlias); } @override - void clipRect(ui.Rect rect) { - throw 'clipRect'; + void clipRect( + ui.Rect rect, { + ui.ClipOp clipOp = ui.ClipOp.intersect, + bool doAntiAlias = true, + }) { + js.JsObject skClipOp; + switch (clipOp) { + case ui.ClipOp.difference: + skClipOp = canvasKit['ClipOp']['Difference']; + break; + case ui.ClipOp.intersect: + skClipOp = canvasKit['ClipOp']['Intersect']; + break; + } + + skCanvas.callMethod( + 'clipRect', [makeSkRect(rect), skClipOp, doAntiAlias]); } @override @@ -95,7 +99,12 @@ class SkRecordingCanvas implements RecordingCanvas { @override void drawCircle(ui.Offset c, double radius, ui.Paint paint) { - throw 'drawCircle'; + final js.JsObject skPaint = makeSkPaint(paint); + // TODO(het): Use `drawCircle` when CanvasKit makes it available. + // Since CanvasKit does not expose `drawCircle`, use `drawOval` instead. + final js.JsObject skRect = makeSkRect(ui.Rect.fromLTWH( + c.dx - radius, c.dy - radius, 2.0 * radius, 2.0 * radius)); + skCanvas.callMethod('drawOval', [skRect, skPaint]); } @override @@ -115,12 +124,25 @@ class SkRecordingCanvas implements RecordingCanvas { @override void drawImageRect(ui.Image image, ui.Rect src, ui.Rect dst, ui.Paint paint) { - throw 'drawImageRect'; + final SkImage skImage = image; + skCanvas.callMethod('drawImageRect', [ + skImage.skImage, + makeSkRect(src), + makeSkRect(dst), + makeSkPaint(paint), + false, + ]); } @override void drawLine(ui.Offset p1, ui.Offset p2, ui.Paint paint) { - throw 'drawLine'; + skCanvas.callMethod('drawLine', [ + p1.dx, + p1.dy, + p2.dx, + p2.dy, + makeSkPaint(paint), + ]); } @override @@ -135,30 +157,67 @@ class SkRecordingCanvas implements RecordingCanvas { @override void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) { - throw 'drawParagraph'; + // TODO(het): This doesn't support most paragraph features. We are just + // creating a font from the family and size, and drawing it with + // ShapedText. + final EngineParagraph engineParagraph = paragraph; + final ParagraphGeometricStyle style = engineParagraph.geometricStyle; + final js.JsObject skFont = + skiaFontCollection.getFont(style.effectiveFontFamily, style.fontSize); + final js.JsObject skShapedTextOpts = js.JsObject.jsify({ + 'font': skFont, + 'leftToRight': true, + 'text': engineParagraph.plainText, + 'width': engineParagraph.width + 1, + }); + final js.JsObject skShapedText = + js.JsObject(canvasKit['ShapedText'], [skShapedTextOpts]); + skCanvas.callMethod('drawText', [ + skShapedText, + offset.dx + engineParagraph._alignOffset, + offset.dy, + makeSkPaint(engineParagraph._paint) + ]); } @override void drawPath(ui.Path path, ui.Paint paint) { - throw 'drawPath'; + final js.JsObject skPaint = makeSkPaint(paint); + final SkPath enginePath = path; + final js.JsObject skPath = enginePath._skPath; + skCanvas.callMethod('drawPath', [skPath, skPaint]); } @override void drawRRect(ui.RRect rrect, ui.Paint paint) { - throw 'drawRRect'; + // Since CanvasKit does not expose `drawRRect` we have to make do with + // `drawRoundRect`. The downside of `drawRoundRect` is that all of the + // corner radii must be the same. + assert( + rrect.tlRadius == rrect.trRadius && + rrect.tlRadius == rrect.brRadius && + rrect.tlRadius == rrect.blRadius, + 'CanvasKit only supports drawing RRects where the radii are all the same.', + ); + skCanvas.callMethod('drawRoundRect', [ + makeSkRect(rrect.outerRect), + rrect.tlRadiusX, + rrect.tlRadiusY, + makeSkPaint(paint), + ]); } @override void drawRect(ui.Rect rect, ui.Paint paint) { - final js.JsObject skRect = _makeSkRect(rect); - final js.JsObject skPaint = _makeSkPaint(paint); + final js.JsObject skRect = makeSkRect(rect); + final js.JsObject skPaint = makeSkPaint(paint); skCanvas.callMethod('drawRect', [skRect, skPaint]); } @override void drawShadow(ui.Path path, ui.Color color, double elevation, bool transparentOccluder) { - throw 'drawShadow'; + drawSkShadow(skCanvas, path, color, elevation, transparentOccluder); } @override @@ -166,22 +225,29 @@ class SkRecordingCanvas implements RecordingCanvas { @override void restore() { - throw 'restore'; + skCanvas.callMethod('restore'); + saveCount--; } @override void rotate(double radians) { - throw 'rotate'; + skCanvas + .callMethod('rotate', [radians * 180.0 / math.pi, 0.0, 0.0]); } @override void save() { - throw 'save'; + skCanvas.callMethod('save'); + saveCount++; } @override void saveLayer(ui.Rect bounds, ui.Paint paint) { - throw 'saveLayer'; + skCanvas.callMethod('saveLayer', [ + makeSkRect(bounds), + makeSkPaint(paint), + ]); + saveCount++; } @override @@ -191,7 +257,7 @@ class SkRecordingCanvas implements RecordingCanvas { @override void scale(double sx, double sy) { - throw 'scale'; + skCanvas.callMethod('scale', [sx, sy]); } @override @@ -201,11 +267,11 @@ class SkRecordingCanvas implements RecordingCanvas { @override void transform(Float64List matrix4) { - throw 'transform'; + skCanvas.callMethod('concat', >[makeSkMatrix(matrix4)]); } @override void translate(double dx, double dy) { - throw 'translate'; + skCanvas.callMethod('translate', [dx, dy]); } } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/util.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/util.dart new file mode 100644 index 0000000000..0d98969351 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/util.dart @@ -0,0 +1,275 @@ +// 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. +part of engine; + +js.JsObject makeSkRect(ui.Rect rect) { + return js.JsObject(canvasKit['LTRBRect'], + [rect.left, rect.top, rect.right, rect.bottom]); +} + +js.JsArray makeSkPoint(ui.Offset point) { + js.JsArray skPoint = new js.JsArray(); + skPoint.length = 2; + skPoint[0] = point.dx; + skPoint[1] = point.dy; + return skPoint; +} + +js.JsObject makeSkPaint(ui.Paint paint) { + final dynamic skPaint = js.JsObject(canvasKit['SkPaint']); + + if (paint.shader != null) { + final EngineGradient engineShader = paint.shader; + skPaint.callMethod( + 'setShader', [engineShader.createSkiaShader()]); + } + + if (paint.color != null) { + skPaint.callMethod('setColor', [paint.color.value]); + } + + js.JsObject skPaintStyle; + switch (paint.style) { + case ui.PaintingStyle.stroke: + skPaintStyle = canvasKit['PaintStyle']['Stroke']; + break; + case ui.PaintingStyle.fill: + skPaintStyle = canvasKit['PaintStyle']['Fill']; + break; + } + skPaint.callMethod('setStyle', [skPaintStyle]); + + js.JsObject skBlendMode; + switch (paint.blendMode) { + case ui.BlendMode.clear: + skBlendMode = canvasKit['BlendMode']['Clear']; + break; + + case ui.BlendMode.src: + skBlendMode = canvasKit['BlendMode']['Src']; + break; + + case ui.BlendMode.dst: + skBlendMode = canvasKit['BlendMode']['Dst']; + break; + + case ui.BlendMode.srcOver: + skBlendMode = canvasKit['BlendMode']['SrcOver']; + break; + + case ui.BlendMode.dstOver: + skBlendMode = canvasKit['BlendMode']['DstOver']; + break; + + case ui.BlendMode.srcIn: + skBlendMode = canvasKit['BlendMode']['SrcIn']; + break; + + case ui.BlendMode.dstIn: + skBlendMode = canvasKit['BlendMode']['DstIn']; + break; + + case ui.BlendMode.srcOut: + skBlendMode = canvasKit['BlendMode']['SrcOut']; + break; + + case ui.BlendMode.dstOut: + skBlendMode = canvasKit['BlendMode']['DstOut']; + break; + + case ui.BlendMode.srcATop: + skBlendMode = canvasKit['BlendMode']['SrcATop']; + break; + + case ui.BlendMode.dstATop: + skBlendMode = canvasKit['BlendMode']['DstATop']; + break; + + case ui.BlendMode.xor: + skBlendMode = canvasKit['BlendMode']['Xor']; + break; + + case ui.BlendMode.plus: + skBlendMode = canvasKit['BlendMode']['Plus']; + break; + + case ui.BlendMode.modulate: + skBlendMode = canvasKit['BlendMode']['Modulate']; + break; + + case ui.BlendMode.screen: + skBlendMode = canvasKit['BlendMode']['Screen']; + break; + + case ui.BlendMode.overlay: + skBlendMode = canvasKit['BlendMode']['Overlay']; + break; + + case ui.BlendMode.darken: + skBlendMode = canvasKit['BlendMode']['Darken']; + break; + + case ui.BlendMode.lighten: + skBlendMode = canvasKit['BlendMode']['Lighten']; + break; + + case ui.BlendMode.colorDodge: + skBlendMode = canvasKit['BlendMode']['ColorDodge']; + break; + + case ui.BlendMode.colorBurn: + skBlendMode = canvasKit['BlendMode']['ColorBurn']; + break; + + case ui.BlendMode.hardLight: + skBlendMode = canvasKit['BlendMode']['HardLight']; + break; + + case ui.BlendMode.softLight: + skBlendMode = canvasKit['BlendMode']['SoftLight']; + break; + + case ui.BlendMode.difference: + skBlendMode = canvasKit['BlendMode']['Difference']; + break; + + case ui.BlendMode.exclusion: + skBlendMode = canvasKit['BlendMode']['Exclusion']; + break; + + case ui.BlendMode.multiply: + skBlendMode = canvasKit['BlendMode']['Multiply']; + break; + + case ui.BlendMode.hue: + skBlendMode = canvasKit['BlendMode']['Hue']; + break; + + case ui.BlendMode.saturation: + skBlendMode = canvasKit['BlendMode']['Saturation']; + break; + + case ui.BlendMode.color: + skBlendMode = canvasKit['BlendMode']['Color']; + break; + + case ui.BlendMode.luminosity: + skBlendMode = canvasKit['BlendMode']['Luminosity']; + break; + } + if (skBlendMode != null) { + skPaint.callMethod('setBlendMode', [skBlendMode]); + } + + skPaint.callMethod('setAntiAlias', [paint.isAntiAlias]); + + if (paint.strokeWidth != 0.0) { + skPaint.callMethod('setStrokeWidth', [paint.strokeWidth]); + } + + if (paint.maskFilter != null) { + final ui.BlurStyle blurStyle = paint.maskFilter.webOnlyBlurStyle; + final double sigma = paint.maskFilter.webOnlySigma; + + js.JsObject skBlurStyle; + switch (blurStyle) { + case ui.BlurStyle.normal: + skBlurStyle = canvasKit['BlurStyle']['Normal']; + break; + case ui.BlurStyle.solid: + skBlurStyle = canvasKit['BlurStyle']['Solid']; + break; + case ui.BlurStyle.outer: + skBlurStyle = canvasKit['BlurStyle']['Outer']; + break; + case ui.BlurStyle.inner: + skBlurStyle = canvasKit['BlurStyle']['Inner']; + break; + } + + final js.JsObject skMaskFilter = canvasKit + .callMethod('MakeBlurMaskFilter', [skBlurStyle, sigma, true]); + skPaint.callMethod('setMaskFilter', [skMaskFilter]); + } + + return skPaint; +} + +// Mappings from SkMatrix-index to input-index. +const List _skMatrixIndexToMatrix4Index = [ + 0, 4, 12, // Row 1 + 1, 5, 13, // Row 2 + 3, 7, 15, // Row 3 +]; + +/// Converts a 4x4 Flutter matrix (represented as a [Float64List]) to an +/// SkMatrix, which is a 3x3 transform matrix. +js.JsArray makeSkMatrix(Float64List matrix4) { + final js.JsArray skMatrix = js.JsArray(); + skMatrix.length = 9; + for (int i = 0; i < 9; ++i) { + final int matrix4Index = _skMatrixIndexToMatrix4Index[i]; + if (matrix4Index < matrix4.length) + skMatrix[i] = matrix4[matrix4Index]; + else + skMatrix[i] = 0.0; + } + return skMatrix; +} + +void drawSkShadow( + js.JsObject skCanvas, + SkPath path, + ui.Color color, + double elevation, + bool transparentOccluder, +) { + const double ambientAlpha = 0.039; + const double spotAlpha = 0.25; + + final int flags = transparentOccluder ? 0x01 : 0x00; + + final ui.Rect bounds = path.getBounds(); + final double shadowX = (bounds.left + bounds.right) / 2.0; + final double shadowY = bounds.top - 600.0; + + final ui.Color ambientColor = + ui.Color.fromARGB((color.alpha * ambientAlpha).round(), 0, 0, 0); + + // This is a port of SkShadowUtils::ComputeTonalColors + final int minSpot = math.min(color.red, math.min(color.green, color.blue)); + final int maxSpot = math.max(color.red, math.max(color.green, color.blue)); + final double luminance = 0.5 * (maxSpot + minSpot) / 255.0; + final double originalAlpha = (color.alpha * spotAlpha) / 255.0; + final double alphaAdjust = + (2.6 + (-2.66667 + 1.06667 * originalAlpha) * originalAlpha) * + originalAlpha; + double colorAlpha = + (3.544762 + (-4.891428 + 2.3466 * luminance) * luminance) * luminance; + colorAlpha = (colorAlpha * alphaAdjust).clamp(0.0, 1.0); + + final double greyscaleAlpha = + (originalAlpha * (1.0 - 0.4 * luminance)).clamp(0.0, 1.0); + + final double colorScale = colorAlpha * (1.0 - greyscaleAlpha); + final double tonalAlpha = colorScale + greyscaleAlpha; + final double unPremulScale = colorScale / tonalAlpha; + + final ui.Color spotColor = ui.Color.fromARGB( + (tonalAlpha * 255.999).round(), + (unPremulScale * color.red).round(), + (unPremulScale * color.green).round(), + (unPremulScale * color.blue).round(), + ); + + skCanvas.callMethod('drawShadow', [ + path._skPath, + js.JsArray.from([0, 0, elevation]), + js.JsArray.from([shadowX, shadowY, 600]), + 800, + ambientColor.value, + spotColor.value, + flags, + ]); +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/html_image_codec.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/html_image_codec.dart index 290267b605..b90701d2f6 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/html_image_codec.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html_image_codec.dart @@ -4,7 +4,7 @@ part of engine; -final _supportsDecode = +final bool _supportsDecode = js_util.hasProperty(js.JsObject(js.context['Image']), 'decode'); class HtmlCodec implements ui.Codec { diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding.dart index bd1ad440b0..59b86632ce 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding.dart @@ -14,6 +14,12 @@ class PointerBinding { /// The singleton instance of this object. static PointerBinding get instance => _instance; static PointerBinding _instance; + // Set of pointerIds that are added before routing hover and mouse wheel + // events. + // + // The device needs to send a one time PointerChange.add before hover and + // wheel events. + Set _activePointerIds = {}; PointerBinding(this.domRenderer) { if (_instance == null) { @@ -24,6 +30,7 @@ class PointerBinding { assert(() { registerHotRestartListener(() { _adapter?.clearListeners(); + _activePointerIds.clear(); }); return true; }()); @@ -75,7 +82,7 @@ class PointerBinding { void _onPointerData(List data) { final ui.PointerDataPacket packet = ui.PointerDataPacket(data: data); - ui.window.onPointerDataPacket(packet); + ui.window?.onPointerDataPacket(packet); } } @@ -183,10 +190,21 @@ class PointerAdapter extends BaseAdapter { // button to -1 as opposed to mouse move which sets it to 2. // This check is currently defaulting to primary button for now. // Change this when context gesture is implemented in flutter framework. - if (!_isButtonDown(_pointerButtonFromHtmlEvent(event))) { - return; - } - _callback(_convertEventToPointerData(ui.PointerChange.move, event)); + final html.PointerEvent pointerEvent = event; + final int pointerButton = _pointerButtonFromHtmlEvent(pointerEvent); + final List data = _convertEventToPointerData( + _isButtonDown(pointerButton) + ? ui.PointerChange.move + : ui.PointerChange.hover, + pointerEvent); + _ensureMouseDeviceAdded( + data, + pointerEvent.client.x, + pointerEvent.client.y, + pointerEvent.buttons, + pointerEvent.timeStamp, + pointerEvent.pointerId); + _callback(data); }); _addEventListener('pointerup', (html.Event event) { @@ -203,6 +221,8 @@ class PointerAdapter extends BaseAdapter { // A browser fires cancel event if it concludes the pointer will no longer // be able to generate events (example: device is deactivated) _addEventListener('pointercancel', (html.Event event) { + final int pointerButton = _pointerButtonFromHtmlEvent(event); + _updateButtonDownState(pointerButton, false); _callback(_convertEventToPointerData(ui.PointerChange.cancel, event)); }); @@ -222,10 +242,10 @@ class PointerAdapter extends BaseAdapter { html.PointerEvent evt, ) { final List allEvents = _expandEvents(evt); - final List data = List(allEvents.length); + final List data = []; for (int i = 0; i < allEvents.length; i++) { final html.PointerEvent event = allEvents[i]; - data[i] = ui.PointerData( + data.add(ui.PointerData( change: change, timeStamp: _eventTimeStampToDuration(event.timeStamp), kind: _pointerTypeToDeviceKind(event.pointerType), @@ -237,7 +257,7 @@ class PointerAdapter extends BaseAdapter { pressureMin: 0.0, pressureMax: 1.0, tilt: _computeHighestTilt(event), - ); + )); } return data; } @@ -356,10 +376,13 @@ class MouseAdapter extends BaseAdapter { }); _addEventListener('mousemove', (html.Event event) { - if (!_isButtonDown(_pointerButtonFromHtmlEvent(event))) { - return; - } - _callback(_convertEventToPointerData(ui.PointerChange.move, event)); + final int pointerButton = _pointerButtonFromHtmlEvent(event); + final List data = _convertEventToPointerData( + _isButtonDown(pointerButton) + ? ui.PointerChange.move + : ui.PointerChange.hover, + event); + _callback(data); }); _addEventListener('mouseup', (html.Event event) { @@ -380,21 +403,25 @@ class MouseAdapter extends BaseAdapter { ui.PointerChange change, html.MouseEvent event, ) { - return [ - ui.PointerData( - change: change, - timeStamp: _eventTimeStampToDuration(event.timeStamp), - kind: ui.PointerDeviceKind.mouse, - signalKind: ui.PointerSignalKind.none, - device: _mouseDeviceId, - physicalX: event.client.x, - physicalY: event.client.y, - buttons: event.buttons, - pressure: 1.0, - pressureMin: 0.0, - pressureMax: 1.0, - ) - ]; + final List data = []; + if (event.type == 'mousemove') { + _ensureMouseDeviceAdded(data, event.client.x, event.client.y, + event.buttons, event.timeStamp, _mouseDeviceId); + } + data.add(ui.PointerData( + change: change, + timeStamp: _eventTimeStampToDuration(event.timeStamp), + kind: ui.PointerDeviceKind.mouse, + signalKind: ui.PointerSignalKind.none, + device: _mouseDeviceId, + physicalX: event.client.x, + physicalY: event.client.y, + buttons: event.buttons, + pressure: 1.0, + pressureMin: 0.0, + pressureMax: 1.0, + )); + return data; } } @@ -407,7 +434,33 @@ Duration _eventTimeStampToDuration(num milliseconds) { return Duration(milliseconds: ms, microseconds: micro); } -bool _isWheelDeviceAdded = false; +void _ensureMouseDeviceAdded(List data, double clientX, + double clientY, int buttons, double timeStamp, int deviceId) { + if (PointerBinding.instance._activePointerIds.contains(deviceId)) { + return; + } + PointerBinding.instance._activePointerIds.add(deviceId); + // Only send [PointerChange.add] the first time. + data.insert( + 0, + ui.PointerData( + change: ui.PointerChange.add, + timeStamp: _eventTimeStampToDuration(timeStamp), + kind: ui.PointerDeviceKind.mouse, + // In order for Flutter to actually add this pointer, we need to set the + // signal to none. + signalKind: ui.PointerSignalKind.none, + device: deviceId, + physicalX: clientX, + physicalY: clientY, + buttons: buttons, + pressure: 1.0, + pressureMin: 0.0, + pressureMax: 1.0, + scrollDeltaX: 0, + scrollDeltaY: 0, + )); +} List _convertWheelEventToPointerData( html.WheelEvent event, @@ -435,27 +488,8 @@ List _convertWheelEventToPointerData( } final List data = []; - // Only send [PointerChange.add] the first time. - if (!_isWheelDeviceAdded) { - _isWheelDeviceAdded = true; - data.add(ui.PointerData( - change: ui.PointerChange.add, - timeStamp: _eventTimeStampToDuration(event.timeStamp), - kind: ui.PointerDeviceKind.mouse, - // In order for Flutter to actually add this pointer, we need to set the - // signal to none. - signalKind: ui.PointerSignalKind.none, - device: _mouseDeviceId, - physicalX: event.client.x, - physicalY: event.client.y, - buttons: event.buttons, - pressure: 1.0, - pressureMin: 0.0, - pressureMax: 1.0, - scrollDeltaX: deltaX, - scrollDeltaY: deltaY, - )); - } + _ensureMouseDeviceAdded(data, event.client.x, event.client.y, event.buttons, + event.timeStamp, _mouseDeviceId); data.add(ui.PointerData( change: ui.PointerChange.hover, timeStamp: _eventTimeStampToDuration(event.timeStamp), diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/recording_canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/recording_canvas.dart index 07b6f9dd82..f845868a3b 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/recording_canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/recording_canvas.dart @@ -154,7 +154,7 @@ class RecordingCanvas { _commands.add(PaintClipRRect(rrect)); } - void clipPath(ui.Path path) { + void clipPath(ui.Path path, {bool doAntiAlias = true}) { _paintBounds.clipRect(path.getBounds()); _hasArbitraryPaint = true; _commands.add(PaintClipPath(path)); @@ -267,7 +267,10 @@ class RecordingCanvas { pathBounds = pathBounds.inflate(paint.strokeWidth); } _paintBounds.grow(pathBounds); - _commands.add(PaintDrawPath(path, paint.webOnlyPaintData)); + // Clone path so it can be reused for subsequent draw calls. + final ui.Path clone = ui.Path.from(path); + clone.fillType = path.fillType; + _commands.add(PaintDrawPath(clone, paint.webOnlyPaintData)); } void drawImage(ui.Image image, ui.Offset offset, ui.Paint paint) { @@ -982,6 +985,7 @@ class PaintDrawParagraph extends PaintCommand { } List _serializePaintToCssPaint(ui.PaintData paint) { + final EngineGradient engineShader = paint.shader; return [ paint.blendMode?.index, paint.style?.index, @@ -989,7 +993,7 @@ List _serializePaintToCssPaint(ui.PaintData paint) { paint.strokeCap?.index, paint.isAntiAlias, paint.color.toCssString(), - paint.shader?.webOnlySerializeToCssPaint(), + engineShader?.webOnlySerializeToCssPaint(), paint.maskFilter?.webOnlySerializeToCssPaint(), paint.filterQuality?.index, paint.colorFilter?.webOnlySerializeToCssPaint(), diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart index b7fba09978..36f9b2f188 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart @@ -585,11 +585,6 @@ class SemanticsObject { /// Whether this object represents an editable text field. bool get isTextField => hasFlag(ui.SemanticsFlag.isTextField); - /// Whether this object is read only. - /// - /// Only applicable when [isTextField] is true. - bool get isReadOnly => hasFlag(ui.SemanticsFlag.isReadOnly); - /// Whether this object needs screen readers attention right away. bool get isLiveRegion => hasFlag(ui.SemanticsFlag.isLiveRegion) && diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/shader.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/shader.dart new file mode 100644 index 0000000000..5050d8c5ed --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/shader.dart @@ -0,0 +1,210 @@ +// 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. +part of engine; + +bool _offsetIsValid(ui.Offset offset) { + assert(offset != null, 'Offset argument was null.'); + assert(!offset.dx.isNaN && !offset.dy.isNaN, + 'Offset argument contained a NaN value.'); + return true; +} + +bool _matrix4IsValid(Float64List matrix4) { + assert(matrix4 != null, 'Matrix4 argument was null.'); + assert(matrix4.length == 16, 'Matrix4 must have 16 entries.'); + return true; +} + +abstract class EngineGradient implements ui.Gradient { + /// Hidden constructor to prevent subclassing. + EngineGradient._(); + + /// Creates a fill style to be used in painting. + Object createPaintStyle(html.CanvasRenderingContext2D ctx); + + List webOnlySerializeToCssPaint() { + throw UnsupportedError('CSS paint not implemented for this shader type'); + } + + /// Create a shader for use in the Skia backend. + js.JsObject createSkiaShader(); +} + +class GradientSweep extends EngineGradient { + GradientSweep(this.center, this.colors, this.colorStops, this.tileMode, + this.startAngle, this.endAngle, this.matrix4) + : assert(_offsetIsValid(center)), + assert(colors != null), + assert(tileMode != null), + assert(startAngle != null), + assert(endAngle != null), + assert(startAngle < endAngle), + assert(matrix4 == null || _matrix4IsValid(matrix4)), + super._() { + _validateColorStops(colors, colorStops); + } + + @override + Object createPaintStyle(_) { + throw UnimplementedError(); + } + + final ui.Offset center; + final List colors; + final List colorStops; + final ui.TileMode tileMode; + final double startAngle; + final double endAngle; + final Float64List matrix4; + + @override + js.JsObject createSkiaShader() { + throw UnimplementedError(); + } +} + +void _validateColorStops(List colors, List colorStops) { + if (colorStops == null) { + if (colors.length != 2) + throw ArgumentError( + '"colors" must have length 2 if "colorStops" is omitted.'); + } else { + if (colors.length != colorStops.length) + throw ArgumentError( + '"colors" and "colorStops" arguments must have equal length.'); + } +} + +class GradientLinear extends EngineGradient { + GradientLinear( + this.from, + this.to, + this.colors, + this.colorStops, + this.tileMode, + ) : assert(_offsetIsValid(from)), + assert(_offsetIsValid(to)), + assert(colors != null), + assert(tileMode != null), + super._() { + _validateColorStops(colors, colorStops); + } + + final ui.Offset from; + final ui.Offset to; + final List colors; + final List colorStops; + final ui.TileMode tileMode; + + @override + html.CanvasGradient createPaintStyle(html.CanvasRenderingContext2D ctx) { + final html.CanvasGradient gradient = + ctx.createLinearGradient(from.dx, from.dy, to.dx, to.dy); + if (colorStops == null) { + assert(colors.length == 2); + gradient.addColorStop(0, colors[0].toCssString()); + gradient.addColorStop(1, colors[1].toCssString()); + return gradient; + } + for (int i = 0; i < colors.length; i++) { + gradient.addColorStop(colorStops[i], colors[i].toCssString()); + } + return gradient; + } + + @override + List webOnlySerializeToCssPaint() { + final List serializedColors = []; + for (int i = 0; i < colors.length; i++) { + serializedColors.add(colors[i].toCssString()); + } + return [ + 1, + from.dx, + from.dy, + to.dx, + to.dy, + serializedColors, + colorStops, + tileMode.index + ]; + } + + @override + js.JsObject createSkiaShader() { + assert(experimentalUseSkia); + + js.JsArray jsColors = js.JsArray(); + jsColors.length = colors.length; + for (int i = 0; i < colors.length; i++) { + jsColors[i] = colors[i].value; + } + + js.JsArray jsColorStops; + if (colorStops == null) { + jsColorStops = js.JsArray(); + jsColorStops.length = 2; + jsColorStops[0] = 0; + jsColorStops[1] = 1; + } else { + jsColorStops = js.JsArray.from(colorStops); + jsColorStops.length = colorStops.length; + } + return canvasKit.callMethod('MakeLinearGradientShader', [ + makeSkPoint(from), + makeSkPoint(to), + jsColors, + jsColorStops, + tileMode.index, + ]); + } +} + +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 colors; + final List colorStops; + final ui.TileMode tileMode; + final Float64List matrix4; + + @override + Object createPaintStyle(_) { + throw UnimplementedError(); + } + + @override + js.JsObject createSkiaShader() { + throw UnimplementedError(); + } +} + +class GradientConical extends EngineGradient { + GradientConical(this.focal, this.focalRadius, this.center, this.radius, + this.colors, this.colorStops, this.tileMode, this.matrix4) + : super._(); + + final ui.Offset focal; + final double focalRadius; + final ui.Offset center; + final double radius; + final List colors; + final List colorStops; + final ui.TileMode tileMode; + final Float64List matrix4; + + @override + Object createPaintStyle(_) { + throw UnimplementedError(); + } + + @override + js.JsObject createSkiaShader() { + throw UnimplementedError(); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/picture.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/picture.dart index e9d55a1378..534f9b7bf7 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/picture.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/picture.dart @@ -114,7 +114,7 @@ class PersistedHoudiniPicture extends PersistedPicture { paintWorklet, 'addModule', [ - '/packages/flutter_web/assets/houdini_painter.js', + '/packages/flutter_web_ui/assets/houdini_painter.js', ], ); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/text/font_collection.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/text/font_collection.dart index d3c1b284e7..b64a1e6273 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/text/font_collection.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/font_collection.dart @@ -5,7 +5,7 @@ part of engine; const String _testFontFamily = 'Ahem'; -const String _testFontUrl = 'packages/flutter_web/assets/Ahem.ttf'; +const String _testFontUrl = 'packages/ui/assets/ahem.ttf'; const String _robotoFontUrl = 'packages/flutter_web_ui/assets/Roboto-Regular.ttf'; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/text/measurement.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/text/measurement.dart index 20ec23dbc5..c947860c2b 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/text/measurement.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/measurement.dart @@ -231,6 +231,10 @@ abstract class TextMeasurementService { /// constraints. double measureSubstringWidth(EngineParagraph paragraph, int start, int end); + /// Returns text position given a paragraph, constraints and offset. + ui.TextPosition getTextPositionForOffset(EngineParagraph paragraph, + ui.ParagraphConstraints constraints, ui.Offset offset); + /// Delegates to a [ParagraphRuler] to measure a list of text boxes that /// enclose the given range of text. List measureBoxesForRange( @@ -318,6 +322,7 @@ class DomTextMeasurementService extends TextMeasurementService { @override double measureSubstringWidth(EngineParagraph paragraph, int start, int end) { + assert(paragraph._plainText != null); final ParagraphGeometricStyle style = paragraph._geometricStyle; final ParagraphRuler ruler = TextMeasurementService.rulerManager.findOrCreateRuler(style); @@ -332,6 +337,20 @@ class DomTextMeasurementService extends TextMeasurementService { return dimensions.width; } + @override + ui.TextPosition getTextPositionForOffset(EngineParagraph paragraph, + ui.ParagraphConstraints constraints, ui.Offset offset) { + assert(paragraph._plainText == null, 'should only be called for multispan'); + + final ParagraphGeometricStyle style = paragraph._geometricStyle; + final ParagraphRuler ruler = + TextMeasurementService.rulerManager.findOrCreateRuler(style); + ruler.willMeasure(paragraph); + final int position = ruler.hitTest(constraints, offset); + ruler.didMeasure(); + return ui.TextPosition(offset: position); + } + /// Called when we have determined that the paragraph fits the [constraints] /// without wrapping. /// @@ -528,6 +547,7 @@ class CanvasTextMeasurementService extends TextMeasurementService { @override double measureSubstringWidth(EngineParagraph paragraph, int start, int end) { + assert(paragraph._plainText != null); final String text = paragraph._plainText; final ParagraphGeometricStyle style = paragraph._geometricStyle; _canvasContext.font = style.cssFontString; @@ -539,6 +559,13 @@ class CanvasTextMeasurementService extends TextMeasurementService { end, ); } + + @override + ui.TextPosition getTextPositionForOffset(EngineParagraph paragraph, + ui.ParagraphConstraints constraints, ui.Offset offset) { + // TODO(flutter_web): implement. + return new ui.TextPosition(offset: 0); + } } // These global variables are used to memoize calls to [_measureSubstring]. They diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/text/paragraph.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/text/paragraph.dart index 448faf8f46..dba71fe15e 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/text/paragraph.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/paragraph.dart @@ -236,9 +236,8 @@ class EngineParagraph implements ui.Paragraph { @override ui.TextPosition getPositionForOffset(ui.Offset offset) { if (_plainText == null) { - return const ui.TextPosition(offset: 0); + return getPositionForMultiSpanOffset(offset); } - final double dx = offset.dx - _alignOffset; final TextMeasurementService instance = _measurementService; @@ -273,6 +272,14 @@ class EngineParagraph implements ui.Paragraph { } } + ui.TextPosition getPositionForMultiSpanOffset(ui.Offset offset) { + assert(_lastUsedConstraints != null, + 'missing call to paragraph layout before reading text position'); + final TextMeasurementService instance = _measurementService; + return instance.getTextPositionForOffset( + this, _lastUsedConstraints, offset); + } + @override List getWordBoundary(int offset) { if (_plainText == null) { @@ -707,7 +714,7 @@ class EngineParagraphBuilder implements ui.ParagraphBuilder { double baselineOffset, ui.TextBaseline baseline, }) { - // TODO(garyq): Implement web_ui version of this. + // TODO(garyq): Implement stub_ui version of this. throw UnimplementedError(); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/text/ruler.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/text/ruler.dart index 97d12477ff..7bd1819752 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/text/ruler.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/ruler.dart @@ -571,6 +571,53 @@ class ParagraphRuler { constrainedDimensions.updateWidth('${constraints.width + 0.5}px'); } + /// Returns text position in a paragraph that contains multiple + /// nested spans given an offset. + int hitTest(ui.ParagraphConstraints constraints, ui.Offset offset) { + measureWithConstraints(constraints); + // Get paragraph element root used to measure constrainedDimensions. + final html.HtmlElement el = constrainedDimensions._element; + final List textNodes = []; + // Collect all text nodes (breadth first traversal). + // Since there is no api to get bounds of text nodes directly we work + // upwards and measure span elements and finally the paragraph. + _collectTextNodes(el.childNodes, textNodes); + // Hit test spans starting from leaf nodes up (backwards). + for (int i = textNodes.length - 1; i >= 0; i--) { + final html.Node node = textNodes[i]; + // Check if offset is within client rect bounds of text node's + // parent element. + final html.Element parent = node.parentNode; + final html.Rectangle bounds = parent.getBoundingClientRect(); + final double dx = offset.dx; + final double dy = offset.dy; + if (dx >= bounds.left && + dy < bounds.right && + dy >= bounds.top && + dy < bounds.bottom) { + // We found the element bounds that contains offset. + // Calculate text position for this node. + int textPosition = 0; + for (int nodeIndex = 0; nodeIndex < i; nodeIndex++) { + textPosition += textNodes[nodeIndex].text.length; + } + return textPosition; + } + } + return 0; + } + + void _collectTextNodes(Iterable nodes, List textNodes) { + for (html.Node node in nodes) { + if (node.nodeType == html.Node.TEXT_NODE) { + textNodes.add(node); + } + if (node.hasChildNodes()) { + _collectTextNodes(node.childNodes, textNodes); + } + } + } + /// Performs clean-up after a measurement is done, preparing this ruler for /// a future reuse. /// diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/text_editing.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/text_editing.dart index cc22d6f26c..228e68066e 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/text_editing.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text_editing.dart @@ -467,9 +467,9 @@ class PersistentTextEditingElement extends TextEditingElement { PersistentTextEditingElement( html.HtmlElement domElement, { @required html.VoidCallback onDomElementSwap, - }) : _onDomElementSwap = onDomElementSwap, - // Make sure the dom element is of a type that we support for text editing. - assert(_getTypeFromElement(domElement) != null) { + }) : _onDomElementSwap = onDomElementSwap { + // Make sure the dom element is of a type that we support for text editing. + assert(_getTypeFromElement(domElement) != null); this.domElement = domElement; } diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/canvas.dart index f066e25c76..d14bbc0bb5 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/canvas.dart @@ -436,7 +436,7 @@ class Canvas { } void _clipPath(Path path, bool doAntiAlias) { - _canvas.clipPath(path); + _canvas.clipPath(path, doAntiAlias: doAntiAlias); } /// Paints the given [Color] onto the canvas, applying the given diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/compositing.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/compositing.dart index 8ef7e68f51..def31dbc7b 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/compositing.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/compositing.dart @@ -266,9 +266,14 @@ class SceneBuilder { /// 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. ColorFilterEngineLayer pushColorFilter(ColorFilter filter, {ColorFilterEngineLayer oldLayer}) { + assert(filter != null); throw UnimplementedError(); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/initialization.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/initialization.dart index 163f61cb6f..50bda44673 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/initialization.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/initialization.dart @@ -12,9 +12,6 @@ Future webOnlyInitializePlatform({ engine.window.webOnlyLocationStrategy = const engine.HashLocationStrategy(); } - assetManager ??= const engine.AssetManager(); - await webOnlySetAssetManager(assetManager); - await _fontCollection.ensureFontsLoaded(); engine.webOnlyInitializeEngine(); // This needs to be after `webOnlyInitializeEngine` because that is where the @@ -22,6 +19,14 @@ Future webOnlyInitializePlatform({ if (engine.experimentalUseSkia) { await engine.initializeSkia(); } + + assetManager ??= const engine.AssetManager(); + await webOnlySetAssetManager(assetManager); + await _fontCollection.ensureFontsLoaded(); + if (engine.experimentalUseSkia) { + await engine.skiaFontCollection.ensureFontsLoaded(); + } + _webOnlyIsInitialized = true; } @@ -43,10 +48,19 @@ Future webOnlySetAssetManager(engine.AssetManager assetManager) async { _assetManager = assetManager; + if (engine.experimentalUseSkia) { + engine.skiaFontCollection ??= engine.SkiaFontCollection(); + } + _fontCollection ??= engine.FontCollection(); + _fontCollection.clear(); if (_assetManager != null) { await _fontCollection.registerFonts(_assetManager); + + if (engine.experimentalUseSkia) { + await engine.skiaFontCollection.registerFonts(_assetManager); + } } if (debugEmulateFlutterTesterEnvironment) { diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart index 32cd53b6e4..0f9c1c6029 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart @@ -17,6 +17,18 @@ bool _matrix4IsValid(Float64List matrix4) { return true; } +void _validateColorStops(List colors, List colorStops) { + if (colorStops == null) { + if (colors.length != 2) + throw ArgumentError( + '"colors" must have length 2 if "colorStops" is omitted.'); + } else { + if (colors.length != colorStops.length) + throw ArgumentError( + '"colors" and "colorStops" arguments must have equal length.'); + } +} + Color _scaleAlpha(Color a, double factor) { return a.withAlpha((a.alpha * factor).round().clamp(0, 255)); } @@ -1217,13 +1229,6 @@ abstract class Shader { /// This class is created by the engine, and should not be instantiated /// or extended directly. Shader._(); - - /// Creates a fill style to be used in painting. - Object createPaintStyle(html.CanvasRenderingContext2D ctx); - - List webOnlySerializeToCssPaint() { - throw UnsupportedError('CSS paint not implemented for this shader type'); - } } /// A shader (as used by [Paint.shader]) that renders a color gradient. @@ -1259,7 +1264,7 @@ abstract class Gradient extends Shader { Float64List matrix4, // TODO(flutter_web): see https://github.com/flutter/flutter/issues/32819 ]) => - _GradientLinear(from, to, colors, colorStops, tileMode); + engine.GradientLinear(from, to, colors, colorStops, tileMode); /// Creates a radial gradient centered at `center` that ends at `radius` /// distance from the center. @@ -1301,12 +1306,12 @@ abstract class Gradient extends Shader { // If focal is null or focal radius is null, this should be treated as a regular radial gradient // If focal == center and the focal radius is 0.0, it's still a regular radial gradient if (focal == null || (focal == center && focalRadius == 0.0)) { - return _GradientRadial( + return engine.GradientRadial( center, radius, colors, colorStops, tileMode, matrix4); } else { assert(center != Offset.zero || focal != Offset.zero); // will result in exception(s) in Skia side - return _GradientConical(focal, focalRadius, center, radius, colors, + return engine.GradientConical(focal, focalRadius, center, radius, colors, colorStops, tileMode, matrix4); } } @@ -1346,144 +1351,10 @@ abstract class Gradient extends Shader { double endAngle = math.pi * 2, Float64List matrix4, ]) => - _GradientSweep( + engine.GradientSweep( center, colors, colorStops, tileMode, startAngle, endAngle, matrix4); } -class _GradientSweep extends Gradient { - _GradientSweep(this.center, this.colors, this.colorStops, this.tileMode, - this.startAngle, this.endAngle, this.matrix4) - : assert(_offsetIsValid(center)), - assert(colors != null), - assert(tileMode != null), - assert(startAngle != null), - assert(endAngle != null), - assert(startAngle < endAngle), - assert(matrix4 == null || _matrix4IsValid(matrix4)), - super._() { - _validateColorStops(colors, colorStops); - } - - @override - Object createPaintStyle(_) { - throw UnimplementedError(); - } - - final Offset center; - final List colors; - final List colorStops; - final TileMode tileMode; - final double startAngle; - final double endAngle; - final Float64List matrix4; -} - -void _validateColorStops(List colors, List colorStops) { - if (colorStops == null) { - if (colors.length != 2) - throw ArgumentError( - '"colors" must have length 2 if "colorStops" is omitted.'); - } else { - if (colors.length != colorStops.length) - throw ArgumentError( - '"colors" and "colorStops" arguments must have equal length.'); - } -} - -class _GradientLinear extends Gradient { - _GradientLinear( - this.from, - this.to, - this.colors, - this.colorStops, - this.tileMode, - ) : assert(_offsetIsValid(from)), - assert(_offsetIsValid(to)), - assert(colors != null), - assert(tileMode != null), - super._() { - _validateColorStops(colors, colorStops); - } - - final Offset from; - final Offset to; - final List colors; - final List colorStops; - final TileMode tileMode; - - @override - html.CanvasGradient createPaintStyle(html.CanvasRenderingContext2D ctx) { - final html.CanvasGradient gradient = - ctx.createLinearGradient(from.dx, from.dy, to.dx, to.dy); - if (colorStops == null) { - assert(colors.length == 2); - gradient.addColorStop(0, colors[0].toCssString()); - gradient.addColorStop(1, colors[1].toCssString()); - return gradient; - } - for (int i = 0; i < colors.length; i++) { - gradient.addColorStop(colorStops[i], colors[i].toCssString()); - } - return gradient; - } - - @override - List webOnlySerializeToCssPaint() { - final List serializedColors = []; - for (int i = 0; i < colors.length; i++) { - serializedColors.add(colors[i].toCssString()); - } - return [ - 1, - from.dx, - from.dy, - to.dx, - to.dy, - serializedColors, - colorStops, - tileMode.index - ]; - } -} - -class _GradientRadial extends Gradient { - _GradientRadial(this.center, this.radius, this.colors, this.colorStops, - this.tileMode, this.matrix4) - : super._(); - - final Offset center; - final double radius; - final List colors; - final List colorStops; - final TileMode tileMode; - final Float64List matrix4; - - @override - Object createPaintStyle(_) { - throw UnimplementedError(); - } -} - -class _GradientConical extends Gradient { - _GradientConical(this.focal, this.focalRadius, this.center, this.radius, - this.colors, this.colorStops, this.tileMode, this.matrix4) - : super._(); - - final Offset focal; - final double focalRadius; - final Offset center; - final double radius; - final List colors; - final List colorStops; - final TileMode tileMode; - final Float64List matrix4; - - @override - Object createPaintStyle(_) { - throw UnimplementedError(); - } -} - /// Opaque handle to raw decoded image data (pixels). /// /// To obtain an [Image] object, use [instantiateImageCodec]. @@ -1637,6 +1508,9 @@ class MaskFilter { /// On the web returns the value of sigma passed to [MaskFilter.blur]. double get webOnlySigma => _sigma; + /// On the web returns the value of `style` passed to [MaskFilter.blur]. + BlurStyle get webOnlyBlurStyle => _style; + @override bool operator ==(dynamic other) { if (other is! MaskFilter) { @@ -1848,6 +1722,15 @@ Future instantiateImageCodec(Uint8List list, /// Returns an error message if the instantiation has failed, null otherwise. String _instantiateImageCodec( Uint8List list, engine.Callback callback, _ImageInfo imageInfo) { + if (engine.experimentalUseSkia) { + if (imageInfo == null) { + engine.skiaInstantiateImageCodec(list, callback); + } else { + engine.skiaInstantiateImageCodec(list, callback, imageInfo.width, + imageInfo.height, imageInfo.format, imageInfo.rowBytes); + } + return null; + } final html.Blob blob = html.Blob([list.buffer]); callback(engine.HtmlBlobCodec(blob)); return null; diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart index bf5896b637..8884bb1292 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart @@ -346,6 +346,11 @@ class SemanticsFlag { /// affordances. static const SemanticsFlag isTextField = SemanticsFlag._(_kIsTextFieldIndex); + /// Whether the semantic node is read only. + /// + /// Only applicable when [isTextField] is true. + static const SemanticsFlag isReadOnly = SemanticsFlag._(_kIsReadOnlyIndex); + /// Whether the semantic node currently holds the user's focus. /// /// The focused element is usually the current receiver of keyboard inputs. @@ -360,12 +365,6 @@ class SemanticsFlag { static const SemanticsFlag hasEnabledState = SemanticsFlag._(_kHasEnabledStateIndex); - /// Whether the semantic node is read only. - /// - /// Only applicable when [isTextField] is true. - static const SemanticsFlag isReadOnly = - const SemanticsFlag._(_kIsReadOnlyIndex); - /// Whether a semantic node that [hasEnabledState] is currently enabled. /// /// A disabled element does not respond to user interaction. For example, a @@ -506,6 +505,9 @@ class SemanticsFlag { /// multi-line ones. static const SemanticsFlag isMultiline = SemanticsFlag._(_kIsMultilineIndex); + /// The possible semantics flags. + /// + /// The map's key is the [index] of the flag and the value is the flag itself. /// The possible semantics flags. /// /// The map's key is the [index] of the flag and the value is the flag itself. @@ -530,6 +532,7 @@ class SemanticsFlag { _kIsToggledIndex: isToggled, _kHasImplicitScrollingIndex: hasImplicitScrolling, _kIsMultilineIndex: isMultiline, + _kIsReadOnlyIndex: isReadOnly, }; @override @@ -575,6 +578,8 @@ class SemanticsFlag { return 'SemanticsFlag.hasImplicitScrolling'; case _kIsMultilineIndex: return 'SemanticsFlag.isMultiline'; + case _kIsReadOnlyIndex: + return 'SemanticsFlag.isReadOnly'; } return null; } diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/window.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/window.dart index 5ae7742a4a..bc70492dbd 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/window.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/window.dart @@ -782,7 +782,6 @@ abstract class Window { @Deprecated('Use frameTimings instead.') TimingsCallback get onReportTimings => _onReportTimings; TimingsCallback _onReportTimings; - Zone _onReportTimingsZone; @Deprecated('Use frameTimings instead.') set onReportTimings(TimingsCallback callback) { _internalSetOnReportTimings(callback); @@ -790,7 +789,6 @@ abstract class Window { void _internalSetOnReportTimings(TimingsCallback callback) { _onReportTimings = callback; - _onReportTimingsZone = Zone.current; } // ignore: deprecated_member_use_from_same_package diff --git a/engine/src/flutter/lib/web_ui/pubspec.yaml b/engine/src/flutter/lib/web_ui/pubspec.yaml index d307d8e76d..d1fc33a328 100644 --- a/engine/src/flutter/lib/web_ui/pubspec.yaml +++ b/engine/src/flutter/lib/web_ui/pubspec.yaml @@ -2,14 +2,15 @@ name: ui publish_to: none environment: - sdk: ">=2.2.0 <3.0.0" + sdk: ">=2.2.2 <3.0.0" dependencies: - meta: ^1.1.5 + meta: 1.1.7 dev_dependencies: - test: ^1.3.0 - quiver: - build_runner: - build_test: - build_web_compilers: + path: 1.6.4 + test: 1.6.5 + quiver: 2.0.5 + build_runner: 1.6.5 + build_test: 0.10.8 + build_web_compilers: 2.1.5 diff --git a/engine/src/flutter/lib/web_ui/test/alarm_clock_test.dart b/engine/src/flutter/lib/web_ui/test/alarm_clock_test.dart index 824010fadb..86faadaf51 100644 --- a/engine/src/flutter/lib/web_ui/test/alarm_clock_test.dart +++ b/engine/src/flutter/lib/web_ui/test/alarm_clock_test.dart @@ -17,7 +17,7 @@ void main() { void _alarmClockTests() { int callCount = 0; - testCallback() { + void testCallback() { callCount += 1; } @@ -43,11 +43,11 @@ void _alarmClockTests() { expect(callCount, 0); // Not enough time has passed; the callback should not be called. - fakeAsync.elapse(Duration(seconds: 30)); + fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 0); // Exactly 1 minute has passed; fire the callback. - fakeAsync.elapse(Duration(seconds: 30)); + fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 1); // Timers should be cleaned up. @@ -56,7 +56,7 @@ void _alarmClockTests() { // Rescheduling. alarm.datetime = clock.fromNow(minutes: 1); expect(fakeAsync.nonPeriodicTimerCount, 1); - fakeAsync.elapse(Duration(minutes: 1)); + fakeAsync.elapse(const Duration(minutes: 1)); expect(fakeAsync.nonPeriodicTimerCount, 0); expect(callCount, 2); }); @@ -75,13 +75,13 @@ void _alarmClockTests() { expect(fakeAsync.nonPeriodicTimerCount, 1); expect(callCount, 0); - fakeAsync.elapse(Duration(seconds: 30)); + fakeAsync.elapse(const Duration(seconds: 30)); alarm.datetime = alarm.datetime.add(Duration.zero); expect(fakeAsync.nonPeriodicTimerCount, 1); expect(callCount, 0); - fakeAsync.elapse(Duration(seconds: 30)); + fakeAsync.elapse(const Duration(seconds: 30)); expect(fakeAsync.nonPeriodicTimerCount, 0); expect(callCount, 1); }); @@ -107,18 +107,18 @@ void _alarmClockTests() { expect(fakeAsync.nonPeriodicTimerCount, 1); expect(callCount, 0); - fakeAsync.elapse(Duration(seconds: 30)); + fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 0); // Reschedule. alarm.datetime = alarm.datetime.add(const Duration(minutes: 1)); - fakeAsync.elapse(Duration(minutes: 1)); + fakeAsync.elapse(const Duration(minutes: 1)); // Still no calls because we rescheduled. expect(callCount, 0); - fakeAsync.elapse(Duration(seconds: 30)); + fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 1); expect(fakeAsync.nonPeriodicTimerCount, 0); }); @@ -132,13 +132,13 @@ void _alarmClockTests() { expect(fakeAsync.nonPeriodicTimerCount, 1); expect(callCount, 0); - fakeAsync.elapse(Duration(seconds: 30)); + fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 0); // Reschedule to an earlier time that's still in the future. alarm.datetime = alarm.datetime.subtract(const Duration(seconds: 15)); - fakeAsync.elapse(Duration(seconds: 45)); + fakeAsync.elapse(const Duration(seconds: 45)); expect(callCount, 1); expect(fakeAsync.nonPeriodicTimerCount, 0); }); @@ -158,7 +158,7 @@ void _alarmClockTests() { expect(callCount, 0); // Make sure nothing fires even if we wait long enough. - fakeAsync.elapse(Duration(minutes: 2)); + fakeAsync.elapse(const Duration(minutes: 2)); expect(callCount, 0); expect(fakeAsync.nonPeriodicTimerCount, 0); }); @@ -171,7 +171,7 @@ void _alarmClockTests() { alarm.datetime = clock.fromNow(minutes: 1); expect(fakeAsync.nonPeriodicTimerCount, 1); - fakeAsync.elapse(Duration(seconds: 30)); + fakeAsync.elapse(const Duration(seconds: 30)); expect(callCount, 0); expect(fakeAsync.nonPeriodicTimerCount, 1); @@ -181,7 +181,7 @@ void _alarmClockTests() { expect(callCount, 0); // Make sure nothing fires even if we wait long enough. - fakeAsync.elapse(Duration(minutes: 2)); + fakeAsync.elapse(const Duration(minutes: 2)); expect(callCount, 0); expect(fakeAsync.nonPeriodicTimerCount, 0); }); diff --git a/engine/src/flutter/lib/web_ui/test/canvas_test.dart b/engine/src/flutter/lib/web_ui/test/canvas_test.dart index 1e55b5292d..8a00c8c5d7 100644 --- a/engine/src/flutter/lib/web_ui/test/canvas_test.dart +++ b/engine/src/flutter/lib/web_ui/test/canvas_test.dart @@ -17,7 +17,7 @@ void main() { void testCanvas( String description, void Function(EngineCanvas canvas) testFn, {ui.Rect canvasSize, ui.VoidCallback whenDone}) { - canvasSize ??= ui.Rect.fromLTWH(0, 0, 100, 100); + canvasSize ??= const ui.Rect.fromLTWH(0, 0, 100, 100); test(description, () { testFn(BitmapCanvas(canvasSize)); testFn(DomCanvas()); @@ -31,12 +31,12 @@ void main() { testCanvas('draws laid out paragraph', (EngineCanvas canvas) { final RecordingCanvas recordingCanvas = - RecordingCanvas(ui.Rect.fromLTWH(0, 0, 100, 100)); + RecordingCanvas(const ui.Rect.fromLTWH(0, 0, 100, 100)); final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle()); builder.addText('sample'); paragraph = builder.build(); - paragraph.layout(ui.ParagraphConstraints(width: 100)); + paragraph.layout(const ui.ParagraphConstraints(width: 100)); recordingCanvas.drawParagraph(paragraph, const ui.Offset(10, 10)); canvas.clear(); recordingCanvas.apply(canvas); @@ -55,7 +55,7 @@ void main() { testCanvas('ignores paragraphs that were not laid out', (EngineCanvas canvas) { final RecordingCanvas recordingCanvas = - RecordingCanvas(ui.Rect.fromLTWH(0, 0, 100, 100)); + RecordingCanvas(const ui.Rect.fromLTWH(0, 0, 100, 100)); final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle()); builder.addText('sample'); diff --git a/engine/src/flutter/lib/web_ui/test/color_test.dart b/engine/src/flutter/lib/web_ui/test/color_test.dart index 63115d34cd..93f309fa73 100644 --- a/engine/src/flutter/lib/web_ui/test/color_test.dart +++ b/engine/src/flutter/lib/web_ui/test/color_test.dart @@ -21,7 +21,7 @@ void main() { test('paint set to black', () { const Color c = Color(0x00000000); - final Paint p = new Paint(); + final Paint p = Paint(); p.color = c; expect(c.toString(), equals('Color(0x00000000)')); }); @@ -29,7 +29,7 @@ void main() { test('color created with out of bounds value', () { try { const Color c = Color(0x100 << 24); - final Paint p = new Paint(); + final Paint p = Paint(); p.color = c; } catch (e) { expect(e != null, equals(true)); @@ -39,7 +39,7 @@ void main() { test('color created with wildly out of bounds value', () { try { const Color c = Color(1 << 1000000); - final Paint p = new Paint(); + final Paint p = Paint(); p.color = c; } catch (e) { expect(e != null, equals(true)); diff --git a/engine/src/flutter/lib/web_ui/test/colors_test.dart b/engine/src/flutter/lib/web_ui/test/colors_test.dart deleted file mode 100644 index 63115d34cd..0000000000 --- a/engine/src/flutter/lib/web_ui/test/colors_test.dart +++ /dev/null @@ -1,140 +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'; - -import 'package:test/test.dart'; - -class NotAColor extends Color { - const NotAColor(int value) : super(value); -} - -void main() { - test('color accessors should work', () { - const Color foo = Color(0x12345678); - expect(foo.alpha, equals(0x12)); - expect(foo.red, equals(0x34)); - expect(foo.green, equals(0x56)); - expect(foo.blue, equals(0x78)); - }); - - test('paint set to black', () { - const Color c = Color(0x00000000); - final Paint p = new Paint(); - p.color = c; - expect(c.toString(), equals('Color(0x00000000)')); - }); - - test('color created with out of bounds value', () { - try { - const Color c = Color(0x100 << 24); - final Paint p = new Paint(); - p.color = c; - } catch (e) { - expect(e != null, equals(true)); - } - }); - - test('color created with wildly out of bounds value', () { - try { - const Color c = Color(1 << 1000000); - final Paint p = new Paint(); - p.color = c; - } catch (e) { - expect(e != null, equals(true)); - } - }); - - test('two colors are only == if they have the same runtime type', () { - expect(const Color(123), equals(const Color(123))); - expect(const Color(123), - equals(Color(123))); // ignore: prefer_const_constructors - expect(const Color(123), isNot(equals(const Color(321)))); - expect(const Color(123), isNot(equals(const NotAColor(123)))); - expect(const NotAColor(123), isNot(equals(const Color(123)))); - expect(const NotAColor(123), equals(const NotAColor(123))); - }); - - test('Color.lerp', () { - expect( - Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 0.0), - const Color(0x00000000), - ); - expect( - Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 0.5), - const Color(0x7F7F7F7F), - ); - expect( - Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 1.0), - const Color(0xFFFFFFFF), - ); - expect( - Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), -0.1), - const Color(0x00000000), - ); - expect( - Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 1.1), - const Color(0xFFFFFFFF), - ); - }); - - test('Color.alphaBlend', () { - expect( - Color.alphaBlend(const Color(0x00000000), const Color(0x00000000)), - const Color(0x00000000), - ); - expect( - Color.alphaBlend(const Color(0x00000000), const Color(0xFFFFFFFF)), - const Color(0xFFFFFFFF), - ); - expect( - Color.alphaBlend(const Color(0xFFFFFFFF), const Color(0x00000000)), - const Color(0xFFFFFFFF), - ); - expect( - Color.alphaBlend(const Color(0xFFFFFFFF), const Color(0xFFFFFFFF)), - const Color(0xFFFFFFFF), - ); - expect( - Color.alphaBlend(const Color(0x80FFFFFF), const Color(0xFF000000)), - const Color(0xFF808080), - ); - expect( - Color.alphaBlend(const Color(0x80808080), const Color(0xFFFFFFFF)), - const Color(0xFFBFBFBF), - ); - expect( - Color.alphaBlend(const Color(0x80808080), const Color(0xFF000000)), - const Color(0xFF404040), - ); - expect( - Color.alphaBlend(const Color(0x01020304), const Color(0xFF000000)), - const Color(0xFF000000), - ); - expect( - Color.alphaBlend(const Color(0x11223344), const Color(0xFF000000)), - const Color(0xFF020304), - ); - expect( - Color.alphaBlend(const Color(0x11223344), const Color(0x80000000)), - const Color(0x88040608), - ); - }); - - test('compute gray luminance', () { - // Each color component is at 20%. - const Color lightGray = Color(0xFF333333); - // Relative luminance's formula is just the linearized color value for gray. - // ((0.2 + 0.055) / 1.055) ^ 2.4. - expect(lightGray.computeLuminance(), equals(0.033104766570885055)); - }); - - test('compute color luminance', () { - const Color brightRed = Color(0xFFFF3B30); - // 0.2126 * ((1.0 + 0.055) / 1.055) ^ 2.4 + - // 0.7152 * ((0.23137254902 +0.055) / 1.055) ^ 2.4 + - // 0.0722 * ((0.18823529411 + 0.055) / 1.055) ^ 2.4 - expect(brightRed.computeLuminance(), equals(0.24601329637099723)); - }); -} diff --git a/engine/src/flutter/lib/web_ui/test/compositing_test.dart b/engine/src/flutter/lib/web_ui/test/compositing_test.dart index c53bfe1735..10e449a0e2 100644 --- a/engine/src/flutter/lib/web_ui/test/compositing_test.dart +++ b/engine/src/flutter/lib/web_ui/test/compositing_test.dart @@ -14,25 +14,27 @@ import 'matchers.dart'; void main() { group('SceneBuilder', () { test('pushOffset implements surface lifecycle', () { - testLayerLifeCycle((sceneBuilder, paintedBy) { - return sceneBuilder.pushOffset(10, 20); + testLayerLifeCycle((SceneBuilder sceneBuilder, EngineLayer oldLayer) { + return sceneBuilder.pushOffset(10, 20, oldLayer: oldLayer); }, () { return ''''''; }); }); test('pushTransform implements surface lifecycle', () { - testLayerLifeCycle((sceneBuilder, paintedBy) { + testLayerLifeCycle((SceneBuilder sceneBuilder, EngineLayer oldLayer) { return sceneBuilder.pushTransform( - Matrix4.translationValues(10, 20, 0).storage); + Matrix4.translationValues(10, 20, 0).storage, + oldLayer: oldLayer); }, () { return ''''''; }); }); test('pushClipRect implements surface lifecycle', () { - testLayerLifeCycle((sceneBuilder, paintedBy) { - return sceneBuilder.pushClipRect(Rect.fromLTRB(10, 20, 30, 40)); + testLayerLifeCycle((SceneBuilder sceneBuilder, EngineLayer oldLayer) { + return sceneBuilder.pushClipRect(const Rect.fromLTRB(10, 20, 30, 40), + oldLayer: oldLayer); }, () { return ''' @@ -43,9 +45,10 @@ void main() { }); test('pushClipRRect implements surface lifecycle', () { - testLayerLifeCycle((sceneBuilder, paintedBy) { + testLayerLifeCycle((SceneBuilder sceneBuilder, EngineLayer oldLayer) { return sceneBuilder.pushClipRRect( - RRect.fromLTRBR(10, 20, 30, 40, Radius.circular(3))); + RRect.fromLTRBR(10, 20, 30, 40, const Radius.circular(3)), + oldLayer: oldLayer); }, () { return ''' @@ -56,9 +59,9 @@ void main() { }); test('pushClipPath implements surface lifecycle', () { - testLayerLifeCycle((sceneBuilder, paintedBy) { - final Path path = Path()..addRect(Rect.fromLTRB(10, 20, 30, 40)); - return sceneBuilder.pushClipPath(path); + testLayerLifeCycle((SceneBuilder sceneBuilder, EngineLayer oldLayer) { + final Path path = Path()..addRect(const Rect.fromLTRB(10, 20, 30, 40)); + return sceneBuilder.pushClipPath(path, oldLayer: oldLayer); }, () { return ''' @@ -71,39 +74,52 @@ void main() { }); test('pushOpacity implements surface lifecycle', () { - testLayerLifeCycle((sceneBuilder, paintedBy) { - return sceneBuilder.pushOpacity(10); + testLayerLifeCycle((SceneBuilder sceneBuilder, EngineLayer oldLayer) { + return sceneBuilder.pushOpacity(10, oldLayer: oldLayer); }, () { return ''''''; }); }); test('pushPhysicalShape implements surface lifecycle', () { - testLayerLifeCycle((sceneBuilder, paintedBy) { - final Path path = Path()..addRect(Rect.fromLTRB(10, 20, 30, 40)); + testLayerLifeCycle((SceneBuilder sceneBuilder, EngineLayer oldLayer) { + final Path path = Path()..addRect(const Rect.fromLTRB(10, 20, 30, 40)); return sceneBuilder.pushPhysicalShape( path: path, elevation: 2, - color: Color.fromRGBO(0, 0, 0, 1), - shadowColor: Color.fromRGBO(0, 0, 0, 1), + color: const Color.fromRGBO(0, 0, 0, 1), + shadowColor: const Color.fromRGBO(0, 0, 0, 1), + oldLayer: oldLayer, ); }, () { return ''''''; }); }); + + test('pushBackdropFilter implements surface lifecycle', () { + testLayerLifeCycle((SceneBuilder sceneBuilder, EngineLayer oldLayer) { + return sceneBuilder.pushBackdropFilter( + ImageFilter.blur(sigmaX: 1.0, sigmaY: 1.0), + oldLayer: oldLayer, + ); + }, () { + return '' + '' + '' + ''; + }); + }); }); group('parent child lifecycle', () { test( 'build, retain, update, and applyPaint are called the right number of times', () { - final Object paintedBy = Object(); - final PersistedScene scene1 = PersistedScene(); + final PersistedScene scene1 = PersistedScene(null); final PersistedClipRect clip1 = - PersistedClipRect(paintedBy, Rect.fromLTRB(10, 10, 20, 20)); - final PersistedOpacity opacity = - PersistedOpacity(paintedBy, 100, Offset.zero); - final MockPersistedPicture picture = MockPersistedPicture(paintedBy); + PersistedClipRect(null, const Rect.fromLTRB(10, 10, 20, 20)); + final PersistedOpacity opacity = PersistedOpacity(null, 100, Offset.zero); + final MockPersistedPicture picture = MockPersistedPicture(); scene1.appendChild(clip1); clip1.appendChild(opacity); @@ -114,7 +130,9 @@ void main() { expect(picture.updateCount, 0); expect(picture.applyPaintCount, 0); + scene1.preroll(); scene1.build(); + commitScene(scene1); expect(picture.retainCount, 0); expect(picture.buildCount, 1); expect(picture.updateCount, 0); @@ -122,14 +140,17 @@ void main() { // The second scene graph retains the opacity, but not the clip. However, // because the clip didn't change no repaints should happen. - final PersistedScene scene2 = PersistedScene(); + final PersistedScene scene2 = PersistedScene(scene1); final PersistedClipRect clip2 = - PersistedClipRect(paintedBy, Rect.fromLTRB(10, 10, 20, 20)); + PersistedClipRect(clip1, const Rect.fromLTRB(10, 10, 20, 20)); + clip1.state = PersistedSurfaceState.pendingUpdate; scene2.appendChild(clip2); - opacity.reuseStrategy = PersistedSurfaceReuseStrategy.retain; + opacity.state = PersistedSurfaceState.pendingRetention; clip2.appendChild(opacity); + scene2.preroll(); scene2.update(scene1); + commitScene(scene1); expect(picture.retainCount, 1); expect(picture.buildCount, 1); expect(picture.updateCount, 0); @@ -137,14 +158,17 @@ void main() { // The third scene graph retains the opacity, and produces a new clip. // This should cause the picture to repaint despite being retained. - final PersistedScene scene3 = PersistedScene(); + final PersistedScene scene3 = PersistedScene(scene2); final PersistedClipRect clip3 = - PersistedClipRect(paintedBy, Rect.fromLTRB(10, 10, 50, 50)); + PersistedClipRect(clip2, const Rect.fromLTRB(10, 10, 50, 50)); + clip2.state = PersistedSurfaceState.pendingUpdate; scene3.appendChild(clip3); - opacity.reuseStrategy = PersistedSurfaceReuseStrategy.retain; + opacity.state = PersistedSurfaceState.pendingRetention; clip3.appendChild(opacity); + scene3.preroll(); scene3.update(scene2); + commitScene(scene1); expect(picture.retainCount, 2); expect(picture.buildCount, 1); expect(picture.updateCount, 0); @@ -154,7 +178,7 @@ void main() { } typedef TestLayerBuilder = EngineLayer Function( - SceneBuilder sceneBuilder, Object paintedBy); + SceneBuilder sceneBuilder, EngineLayer oldLayer); typedef ExpectedHtmlGetter = String Function(); void testLayerLifeCycle( @@ -163,11 +187,9 @@ void testLayerLifeCycle( // scene starts from the "build" phase. SceneBuilder.debugForgetFrameScene(); - final Object paintedBy = Object(); - // Build: builds a brand new layer. SceneBuilder sceneBuilder = SceneBuilder(); - final EngineLayer layer1 = layerBuilder(sceneBuilder, paintedBy); + final EngineLayer layer1 = layerBuilder(sceneBuilder, null); final Type surfaceType = layer1.runtimeType; sceneBuilder.pop(); @@ -176,7 +198,7 @@ void testLayerLifeCycle( PersistedSurface findSurface() { return enumerateSurfaces() - .where((s) => s.runtimeType == surfaceType) + .where((PersistedSurface s) => s.runtimeType == surfaceType) .single; } @@ -198,7 +220,7 @@ void testLayerLifeCycle( // Reuse: reuses a layer's DOM elements by matching it. sceneBuilder = SceneBuilder(); - final EngineLayer layer3 = layerBuilder(sceneBuilder, paintedBy); + final EngineLayer layer3 = layerBuilder(sceneBuilder, layer1); sceneBuilder.pop(); expect(layer3, isNot(same(layer1))); tester = SceneTester(sceneBuilder.build()); @@ -232,22 +254,26 @@ void testLayerLifeCycle( } class MockPersistedPicture extends PersistedPicture { - factory MockPersistedPicture(Object paintedBy) { + factory MockPersistedPicture() { final PictureRecorder recorder = PictureRecorder(); // Use the largest cull rect so that layer clips are effective. The tests // rely on this. recorder.beginRecording(Rect.largest)..drawPaint(Paint()); - return MockPersistedPicture._(paintedBy, recorder.endRecording()); + return MockPersistedPicture._(recorder.endRecording()); } - MockPersistedPicture._(Object paintedBy, Picture picture) - : super(paintedBy, 0, 0, picture, 0); + MockPersistedPicture._(Picture picture) : super(0, 0, picture, 0); int retainCount = 0; int buildCount = 0; int updateCount = 0; int applyPaintCount = 0; + @override + double matchForUpdate(PersistedPicture existingSurface) { + return identical(existingSurface.picture, picture) ? 0.0 : 1.0; + } + @override void build() { super.build(); diff --git a/engine/src/flutter/lib/web_ui/test/dom_renderer_test.dart b/engine/src/flutter/lib/web_ui/test/dom_renderer_test.dart index 6de48e6e39..acada0e30e 100644 --- a/engine/src/flutter/lib/web_ui/test/dom_renderer_test.dart +++ b/engine/src/flutter/lib/web_ui/test/dom_renderer_test.dart @@ -9,102 +9,103 @@ import 'package:test/test.dart'; void main() { test('creating elements works', () { - var renderer = new DomRenderer(); - var element = renderer.createElement('div'); + final DomRenderer renderer = DomRenderer(); + final html.Element element = renderer.createElement('div'); expect(element, isNotNull); }); test('can append children to parents', () { - var renderer = new DomRenderer(); - var parent = renderer.createElement('div'); - var child = renderer.createElement('div'); + final DomRenderer renderer = DomRenderer(); + final html.Element parent = renderer.createElement('div'); + final html.Element child = renderer.createElement('div'); renderer.append(parent, child); expect(parent.children, hasLength(1)); }); test('can set text on elements', () { - var renderer = new DomRenderer(); - var element = renderer.createElement('div'); + final DomRenderer renderer = DomRenderer(); + final html.Element element = renderer.createElement('div'); renderer.setText(element, 'Hello World'); expect(element.text, 'Hello World'); }); test('can set attributes on elements', () { - var renderer = new DomRenderer(); - var element = renderer.createElement('div'); + final DomRenderer renderer = DomRenderer(); + final html.Element element = renderer.createElement('div'); renderer.setElementAttribute(element, 'id', 'foo'); expect(element.id, 'foo'); }); test('can add classes to elements', () { - var renderer = new DomRenderer(); - var element = renderer.createElement('div'); + final DomRenderer renderer = DomRenderer(); + final html.Element element = renderer.createElement('div'); renderer.addElementClass(element, 'foo'); renderer.addElementClass(element, 'bar'); - expect(element.classes, ['foo', 'bar']); + expect(element.classes, ['foo', 'bar']); }); test('can remove classes from elements', () { - var renderer = new DomRenderer(); - var element = renderer.createElement('div'); + final DomRenderer renderer = DomRenderer(); + final html.Element element = renderer.createElement('div'); renderer.addElementClass(element, 'foo'); renderer.addElementClass(element, 'bar'); - expect(element.classes, ['foo', 'bar']); + expect(element.classes, ['foo', 'bar']); renderer.removeElementClass(element, 'foo'); - expect(element.classes, ['bar']); + expect(element.classes, ['bar']); }); test('can set style properties on elements', () { - var renderer = new DomRenderer(); - var element = renderer.createElement('div'); + final DomRenderer renderer = DomRenderer(); + final html.Element element = renderer.createElement('div'); renderer.setElementStyle(element, 'color', 'red'); expect(element.style.color, 'red'); }); test('can remove style properties from elements', () { - var renderer = new DomRenderer(); - var element = renderer.createElement('div'); + final DomRenderer renderer = DomRenderer(); + final html.Element element = renderer.createElement('div'); renderer.setElementStyle(element, 'color', 'blue'); expect(element.style.color, 'blue'); renderer.setElementStyle(element, 'color', null); expect(element.style.color, ''); }); test('elements can have children', () { - var renderer = new DomRenderer(); - var element = renderer.createElement('div'); + final DomRenderer renderer = DomRenderer(); + final html.Element element = renderer.createElement('div'); renderer.createElement('div', parent: element); expect(element.children, hasLength(1)); }); test('can detach elements', () { - var renderer = new DomRenderer(); - var element = renderer.createElement('div'); - var child = renderer.createElement('div', parent: element); + final DomRenderer renderer = DomRenderer(); + final html.Element element = renderer.createElement('div'); + final html.Element child = renderer.createElement('div', parent: element); renderer.detachElement(child); expect(element.children, isEmpty); }); test('can reattach detached elements', () { - var renderer = new DomRenderer(); - var element = renderer.createElement('div'); - var child = renderer.createElement('div', parent: element); - var otherChild = renderer.createElement('foo', parent: element); + final DomRenderer renderer = DomRenderer(); + final html.Element element = renderer.createElement('div'); + final html.Element child = renderer.createElement('div', parent: element); + final html.Element otherChild = + renderer.createElement('foo', parent: element); renderer.detachElement(child); expect(element.children, hasLength(1)); renderer.attachBeforeElement(element, otherChild, child); expect(element.children, hasLength(2)); }); test('insert two elements in the middle of a child list', () { - var renderer = new DomRenderer(); - var parent = renderer.createElement('div'); + final DomRenderer renderer = DomRenderer(); + final html.Element parent = renderer.createElement('div'); renderer.createElement('a', parent: parent); - var childD = renderer.createElement('d', parent: parent); + final html.Element childD = renderer.createElement('d', parent: parent); expect(parent.innerHtml, ''); - var childB = renderer.createElement('b', parent: parent); - var childC = renderer.createElement('c', parent: parent); + final html.Element childB = renderer.createElement('b', parent: parent); + final html.Element childC = renderer.createElement('c', parent: parent); renderer.attachBeforeElement(parent, childD, childB); renderer.attachBeforeElement(parent, childD, childC); expect(parent.innerHtml, ''); }); test('replaces viewport meta tags during style reset', () { - html.MetaElement existingMeta = html.MetaElement() + final html.MetaElement existingMeta = html.MetaElement() ..name = 'viewport' ..content = 'foo=bar'; html.document.head.append(existingMeta); expect(existingMeta.isConnected, true); - var renderer = new DomRenderer(); + final DomRenderer renderer = DomRenderer(); renderer.reset(); }); } diff --git a/engine/src/flutter/lib/web_ui/test/engine/semantics/accessibility_test.dart b/engine/src/flutter/lib/web_ui/test/engine/semantics/accessibility_test.dart new file mode 100644 index 0000000000..133d30e66f --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/engine/semantics/accessibility_test.dart @@ -0,0 +1,52 @@ +// 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' show Future; +import 'dart:html'; + +import 'package:ui/src/engine.dart'; +import 'package:test/test.dart'; + +const MessageCodec codec = StandardMessageCodec(); +const String testMessage = 'This is an tooltip.'; +const Map testInput = { + 'data': {'message': testMessage} +}; + +void main() { + AccessibilityAnnouncements accessibilityAnnouncements; + + group('$AccessibilityAnnouncements', () { + setUp(() { + accessibilityAnnouncements = AccessibilityAnnouncements.instance; + }); + + test( + 'Creates element when handling a message and removes ' + 'is after a delay', () { + // Set the a11y announcement's duration on DOM to half seconds. + accessibilityAnnouncements.durationA11yMessageIsOnDom = + Duration(milliseconds: 500); + + // Initially there is no accessibility-element + expect(document.getElementById('accessibility-element'), isNull); + + accessibilityAnnouncements.handleMessage(codec.encodeMessage(testInput)); + expect( + document.getElementById('accessibility-element'), + isNotNull, + ); + final LabelElement input = + document.getElementById('accessibility-element'); + expect(input.getAttribute('aria-live'), equals('polite')); + expect(input.text, testMessage); + + // The element should have been removed after the duration. + Future.delayed( + accessibilityAnnouncements.durationA11yMessageIsOnDom, + () => + expect(document.getElementById('accessibility-element'), isNull)); + }); + }); +} diff --git a/engine/src/flutter/lib/web_ui/test/engine/semantics/semantics_test.dart b/engine/src/flutter/lib/web_ui/test/engine/semantics/semantics_test.dart new file mode 100644 index 0000000000..c2c2395b7f --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/engine/semantics/semantics_test.dart @@ -0,0 +1,1258 @@ +// 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:html' as html; +import 'dart:typed_data'; + +import 'package:quiver/testing/async.dart'; +import 'package:test/test.dart'; + +import 'package:ui/src/engine.dart'; +import 'package:ui/ui.dart' as ui; + +import '../../matchers.dart'; + +DateTime _testTime = DateTime(2018, 12, 17); + +EngineSemanticsOwner semantics() => EngineSemanticsOwner.instance; + +void main() { + setUp(() { + EngineSemanticsOwner.debugResetSemantics(); + }); + + group(EngineSemanticsOwner, () { + _testEngineSemanticsOwner(); + }); + group('longestIncreasingSubsequence', () { + _testLongestIncreasingSubsequence(); + }); + group('container', () { + _testContainer(); + }); + group('vertical scrolling', () { + _testVerticalScrolling(); + }); + group('horizontal scrolling', () { + _testHorizontalScrolling(); + }); + group('incrementable', () { + _testIncrementables(); + }); + group('text field', () { + _testTextField(); + }); + group('checkboxes, radio buttons and switches', () { + _testCheckables(); + }); + group('tappable', () { + _testTappable(); + }); + group('image', () { + _testImage(); + }); + group('header', () { + _testHeader(); + }); + group('live region', () { + _testLiveRegion(); + }); +} + +void _testEngineSemanticsOwner() { + test('instantiates a singleton', () { + expect(semantics(), same(semantics())); + }); + + test('semantics is off by default', () { + expect(semantics().semanticsEnabled, false); + }); + + test('default mode is "unknown"', () { + expect(semantics().mode, AccessibilityMode.unknown); + }); + + test('auto-enables semantics', () async { + domRenderer.reset(); // triggers `autoEnableOnTap` to be called + expect(semantics().semanticsEnabled, false); + + // Synthesize a click on the placeholder. + final html.Element placeholder = + html.document.querySelectorAll('flt-semantics-placeholder').single; + final html.Rectangle rect = placeholder.getBoundingClientRect(); + placeholder.dispatchEvent(html.MouseEvent( + 'click', + clientX: (rect.left + (rect.right - rect.left) / 2).floor(), + clientY: (rect.top + (rect.bottom - rect.top) / 2).floor(), + )); + while (!semantics().semanticsEnabled) { + await Future.delayed(const Duration(milliseconds: 50)); + } + expect(semantics().semanticsEnabled, true); + }); + + void renderLabel(String label) { + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0, + flags: 0, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 20, 20), + childrenInHitTestOrder: Int32List.fromList([1]), + childrenInTraversalOrder: Int32List.fromList([1]), + ); + builder.updateNode( + id: 1, + actions: 0, + flags: 0, + label: label, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 20, 20), + ); + semantics().updateSemantics(builder.build()); + } + + test('produces an aria-label', () async { + semantics().semanticsEnabled = true; + + // Create + renderLabel('Hello'); + + final Map tree = semantics().debugSemanticsTree; + expect(tree.length, 2); + expect(tree[0].id, 0); + expect(tree[0].element.tagName.toLowerCase(), 'flt-semantics'); + + expectSemanticsTree(''' + + + + Hello + + +'''); + + // Update + renderLabel('World'); + + expectSemanticsTree(''' + + + + World + + +'''); + + // Remove + renderLabel(''); + + expectSemanticsTree(''' + + + + +'''); + + semantics().semanticsEnabled = false; + }); + + test('clears semantics tree when disabled', () { + expect(semantics().debugSemanticsTree, isEmpty); + semantics().semanticsEnabled = true; + renderLabel('Hello'); + expect(semantics().debugSemanticsTree, isNotEmpty); + semantics().semanticsEnabled = false; + expect(semantics().debugSemanticsTree, isEmpty); + }); + + test('accepts standalone browser gestures', () { + semantics().semanticsEnabled = true; + expect(semantics().shouldAcceptBrowserGesture('click'), true); + semantics().semanticsEnabled = false; + }); + + test('rejects browser gestures accompanied by pointer click', () { + FakeAsync().run((FakeAsync fakeAsync) { + semantics() + ..debugOverrideTimestampFunction(fakeAsync.getClock(_testTime).now) + ..semanticsEnabled = true; + expect(semantics().shouldAcceptBrowserGesture('click'), true); + semantics().receiveGlobalEvent(html.Event('pointermove')); + expect(semantics().shouldAcceptBrowserGesture('click'), false); + + // After 1 second of inactivity a browser gestures counts as standalone. + fakeAsync.elapse(const Duration(seconds: 1)); + expect(semantics().shouldAcceptBrowserGesture('click'), true); + semantics().semanticsEnabled = false; + }); + }); +} + +void _testHeader() { + test('renders heading role for headers', () { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0, + flags: 0 | ui.SemanticsFlag.isHeader.index, + label: 'Header of the page', + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + Header of the page + +'''); + + semantics().semanticsEnabled = false; + }); +} + +void _testLongestIncreasingSubsequence() { + void expectLis(List list, List seq) { + expect(longestIncreasingSubsequence(list), seq); + } + + test('trivial case', () { + expectLis([], []); + }); + + test('longest in the middle', () { + expectLis([10, 1, 2, 3, 0], [1, 2, 3]); + }); + + test('longest at head', () { + expectLis([1, 2, 3, 0], [0, 1, 2]); + }); + + test('longest at tail', () { + expectLis([10, 1, 2, 3], [1, 2, 3]); + }); + + test('longest in a jagged pattern', () { + expectLis( + [0, 1, -1, 2, -2, 3, -3, 4, -4, 5, -5], [0, 1, 3, 5, 7, 9]); + }); + + test('fully sorted up', () { + for (int count = 0; count < 100; count += 1) { + expectLis( + List.generate(count, (int i) => 10 * i), + List.generate(count, (int i) => i), + ); + } + }); + + test('fully sorted down', () { + for (int count = 1; count < 100; count += 1) { + expectLis( + List.generate(count, (int i) => 10 * (count - i)), + [count - 1], + ); + } + }); +} + +void _testContainer() { + test('container node has no transform when there is no rect offset', + () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + const ui.Rect zeroOffsetRect = ui.Rect.fromLTRB(0, 0, 20, 20); + builder.updateNode( + id: 0, + actions: 0, + flags: 0, + transform: Matrix4.identity().storage, + rect: zeroOffsetRect, + childrenInHitTestOrder: Int32List.fromList([1]), + childrenInTraversalOrder: Int32List.fromList([1]), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + + + +'''); + + final html.Element parentElement = + html.document.querySelector('flt-semantics'); + final html.Element container = + html.document.querySelector('flt-semantics-container'); + + expect(parentElement.style.transform, ''); + expect(parentElement.style.transformOrigin, ''); + expect(container.style.transform, ''); + expect(container.style.transformOrigin, ''); + + semantics().semanticsEnabled = false; + }); + + test('container node compensates for rect offset', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0, + flags: 0, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(10, 10, 20, 20), + childrenInHitTestOrder: Int32List.fromList([1]), + childrenInTraversalOrder: Int32List.fromList([1]), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + + + +'''); + + final html.Element parentElement = + html.document.querySelector('flt-semantics'); + final html.Element container = + html.document.querySelector('flt-semantics-container'); + + expect(parentElement.style.transform, 'translate(10px, 10px)'); + expect(parentElement.style.transformOrigin, '0px 0px 0px'); + expect(container.style.transform, 'translate(-10px, -10px)'); + expect(container.style.transformOrigin, '0px 0px 0px'); + + semantics().semanticsEnabled = false; + }); +} + +void _testVerticalScrolling() { + test('renders an empty scrollable node', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.scrollUp.index, + flags: 0, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 50, 100), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + + test('scrollable node with children has a container node', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.scrollUp.index, + flags: 0, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 50, 100), + childrenInHitTestOrder: Int32List.fromList([1]), + childrenInTraversalOrder: Int32List.fromList([1]), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + + + +'''); + + final html.Element scrollable = findScrollable(); + expect(scrollable, isNotNull); + + // When there's less content than the available size the neutral scrollTop + // is 0. + expect(scrollable.scrollTop, 0); + + semantics().semanticsEnabled = false; + }); + + test('scrollable node dispatches scroll events', () async { + final StreamController idLogController = StreamController(); + final StreamController actionLogController = + StreamController(); + final Stream idLog = idLogController.stream.asBroadcastStream(); + final Stream actionLog = + actionLogController.stream.asBroadcastStream(); + + // The browser kicks us out of the test zone when the scroll event happens. + // We memorize the test zone so we can call expect when the callback is + // fired. + final Zone testZone = Zone.current; + + ui.window.onSemanticsAction = + (int id, ui.SemanticsAction action, ByteData args) { + idLogController.add(id); + actionLogController.add(action); + testZone.run(() { + expect(args, null); + }); + }; + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | + ui.SemanticsAction.scrollUp.index | + ui.SemanticsAction.scrollDown.index, + flags: 0, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 50, 100), + childrenInHitTestOrder: Int32List.fromList([1, 2, 3]), + childrenInTraversalOrder: Int32List.fromList([1, 2, 3]), + ); + + for (int id = 1; id <= 3; id++) { + builder.updateNode( + id: id, + actions: 0, + flags: 0, + transform: Matrix4.translationValues(0, 50.0 * id, 0).storage, + rect: const ui.Rect.fromLTRB(0, 0, 50, 50), + ); + } + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + + + + + +'''); + + final html.Element scrollable = findScrollable(); + expect(scrollable, isNotNull); + + // When there's more content than the available size the neutral scrollTop + // is greater than 0 with a maximum of 10. + expect(scrollable.scrollTop, 10); + + scrollable.scrollTop = 20; + expect(scrollable.scrollTop, 20); + expect(await idLog.first, 0); + expect(await actionLog.first, ui.SemanticsAction.scrollUp); + // Engine semantics returns scroll top back to neutral. + expect(scrollable.scrollTop, 10); + + scrollable.scrollTop = 5; + expect(scrollable.scrollTop, 5); + expect(await idLog.first, 0); + expect(await actionLog.first, ui.SemanticsAction.scrollDown); + // Engine semantics returns scroll top back to neutral. + expect(scrollable.scrollTop, 10); + + semantics().semanticsEnabled = false; + }); +} + +void _testHorizontalScrolling() { + test('renders an empty scrollable node', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.scrollLeft.index, + flags: 0, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + + test('scrollable node with children has a container node', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.scrollLeft.index, + flags: 0, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + childrenInHitTestOrder: Int32List.fromList([1]), + childrenInTraversalOrder: Int32List.fromList([1]), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + + + +'''); + + final html.Element scrollable = findScrollable(); + expect(scrollable, isNotNull); + + // When there's less content than the available size the neutral + // scrollLeft is 0. + expect(scrollable.scrollLeft, 0); + + semantics().semanticsEnabled = false; + }); + + test('scrollable node dispatches scroll events', () async { + final SemanticsActionLogger logger = SemanticsActionLogger(); + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | + ui.SemanticsAction.scrollLeft.index | + ui.SemanticsAction.scrollRight.index, + flags: 0, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + childrenInHitTestOrder: Int32List.fromList([1, 2, 3]), + childrenInTraversalOrder: Int32List.fromList([1, 2, 3]), + ); + + for (int id = 1; id <= 3; id++) { + builder.updateNode( + id: id, + actions: 0, + flags: 0, + transform: Matrix4.translationValues(50.0 * id, 0, 0).storage, + rect: const ui.Rect.fromLTRB(0, 0, 50, 50), + ); + } + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + + + + + +'''); + + final html.Element scrollable = findScrollable(); + expect(scrollable, isNotNull); + + // When there's more content than the available size the neutral scrollTop + // is greater than 0 with a maximum of 10. + expect(scrollable.scrollLeft, 10); + + scrollable.scrollLeft = 20; + expect(scrollable.scrollLeft, 20); + expect(await logger.idLog.first, 0); + expect(await logger.actionLog.first, ui.SemanticsAction.scrollLeft); + // Engine semantics returns scroll position back to neutral. + expect(scrollable.scrollLeft, 10); + + scrollable.scrollLeft = 5; + expect(scrollable.scrollLeft, 5); + expect(await logger.idLog.first, 0); + expect(await logger.actionLog.first, ui.SemanticsAction.scrollRight); + // Engine semantics returns scroll top back to neutral. + expect(scrollable.scrollLeft, 10); + + semantics().semanticsEnabled = false; + }); +} + +void _testIncrementables() { + test('renders a trivial incrementable node', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.increase.index, + flags: 0, + value: 'd', + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + +'''); + + semantics().semanticsEnabled = false; + }); + + test('increments', () async { + final SemanticsActionLogger logger = SemanticsActionLogger(); + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.increase.index, + flags: 0, + value: 'd', + increasedValue: 'e', + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + +'''); + + final html.InputElement input = + html.document.querySelectorAll('input').single; + input.value = '2'; + input.dispatchEvent(html.Event('change')); + + expect(await logger.idLog.first, 0); + expect(await logger.actionLog.first, ui.SemanticsAction.increase); + + semantics().semanticsEnabled = false; + }); + + test('decrements', () async { + final SemanticsActionLogger logger = SemanticsActionLogger(); + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.decrease.index, + flags: 0, + value: 'd', + decreasedValue: 'c', + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + +'''); + + final html.InputElement input = + html.document.querySelectorAll('input').single; + input.value = '0'; + input.dispatchEvent(html.Event('change')); + + expect(await logger.idLog.first, 0); + expect(await logger.actionLog.first, ui.SemanticsAction.decrease); + + semantics().semanticsEnabled = false; + }); + + test('renders a node that can both increment and decrement', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | + ui.SemanticsAction.decrease.index | + ui.SemanticsAction.increase.index, + flags: 0, + value: 'd', + increasedValue: 'e', + decreasedValue: 'c', + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + +'''); + + semantics().semanticsEnabled = false; + }); +} + +void _testTextField() { + test('renders a text field', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | ui.SemanticsFlag.isTextField.index, + value: 'hello', + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + +'''); + + semantics().semanticsEnabled = false; + }); + + // TODO(yjbanov): this test will need to be adjusted for Safari when we add + // Safari testing. + test('sends a tap action when text field is activated', () async { + final SemanticsActionLogger logger = SemanticsActionLogger(); + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | ui.SemanticsFlag.isTextField.index, + value: 'hello', + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + + final html.Element textField = html.document + .querySelectorAll('input[data-semantics-role="text-field"]') + .single; + + expect(html.document.activeElement, isNot(textField)); + + textField.focus(); + + expect(html.document.activeElement, textField); + expect(await logger.idLog.first, 0); + expect(await logger.actionLog.first, ui.SemanticsAction.tap); + + semantics().semanticsEnabled = false; + }); +} + +void _testCheckables() { + test('renders a switched on switch element', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | + ui.SemanticsFlag.isEnabled.index | + ui.SemanticsFlag.hasToggledState.index | + ui.SemanticsFlag.isToggled.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + + test('renders a switched on disabled switch element', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | + ui.SemanticsFlag.hasToggledState.index | + ui.SemanticsFlag.isToggled.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + + test('renders a switched off switch element', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | + ui.SemanticsFlag.hasToggledState.index | + ui.SemanticsFlag.isEnabled.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + test('renders a checked checkbox', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | + ui.SemanticsFlag.isEnabled.index | + ui.SemanticsFlag.hasCheckedState.index | + ui.SemanticsFlag.isChecked.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + + test('renders a checked disabled checkbox', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | + ui.SemanticsFlag.hasCheckedState.index | + ui.SemanticsFlag.isChecked.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + + test('renders an unchecked checkbox', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | + ui.SemanticsFlag.hasCheckedState.index | + ui.SemanticsFlag.isEnabled.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + + test('renders a checked radio button', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | + ui.SemanticsFlag.isEnabled.index | + ui.SemanticsFlag.hasCheckedState.index | + ui.SemanticsFlag.isInMutuallyExclusiveGroup.index | + ui.SemanticsFlag.isChecked.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + + test('renders a checked disabled radio button', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | + ui.SemanticsFlag.hasCheckedState.index | + ui.SemanticsFlag.isInMutuallyExclusiveGroup.index | + ui.SemanticsFlag.isChecked.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + + test('renders an unchecked checkbox', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | + ui.SemanticsFlag.isEnabled.index | + ui.SemanticsFlag.hasCheckedState.index | + ui.SemanticsFlag.isInMutuallyExclusiveGroup.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); +} + +void _testTappable() { + test('renders an enabled tappable widget', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | + ui.SemanticsFlag.hasEnabledState.index | + ui.SemanticsFlag.isEnabled.index | + ui.SemanticsFlag.isButton.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + + test('renders a disabled tappable widget', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0 | ui.SemanticsAction.tap.index, + flags: 0 | + ui.SemanticsFlag.hasEnabledState.index | + ui.SemanticsFlag.isButton.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); +} + +void _testImage() { + test('renders an image with no child nodes and with a label', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0, + flags: 0 | ui.SemanticsFlag.isImage.index, + label: 'Test Image Label', + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); + + test('renders an image with a child node and with a label', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0, + flags: 0 | ui.SemanticsFlag.isImage.index, + label: 'Test Image Label', + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + childrenInHitTestOrder: Int32List.fromList([1]), + childrenInTraversalOrder: Int32List.fromList([1]), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + + + + + +'''); + + semantics().semanticsEnabled = false; + }); + + test('renders an image with no child nodes without a label', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0, + flags: 0 | ui.SemanticsFlag.isImage.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree( + ''''''); + + semantics().semanticsEnabled = false; + }); + + test('renders an image with a child node and without a label', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0, + flags: 0 | ui.SemanticsFlag.isImage.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + childrenInHitTestOrder: Int32List.fromList([1]), + childrenInTraversalOrder: Int32List.fromList([1]), + ); + + semantics().updateSemantics(builder.build()); + expectSemanticsTree(''' + + + + + + +'''); + + semantics().semanticsEnabled = false; + }); +} + +void _testLiveRegion() { + test('renders a live region if there is a label', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0, + label: 'This is a snackbar', + flags: 0 | ui.SemanticsFlag.isLiveRegion.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + semantics().updateSemantics(builder.build()); + + expectSemanticsTree(''' +This is a snackbar +'''); + + semantics().semanticsEnabled = false; + }); + + test('does not render a live region if there is no label', () async { + semantics() + ..debugOverrideTimestampFunction(() => _testTime) + ..semanticsEnabled = true; + + final ui.SemanticsUpdateBuilder builder = ui.SemanticsUpdateBuilder(); + builder.updateNode( + id: 0, + actions: 0, + flags: 0 | ui.SemanticsFlag.isLiveRegion.index, + transform: Matrix4.identity().storage, + rect: const ui.Rect.fromLTRB(0, 0, 100, 50), + ); + semantics().updateSemantics(builder.build()); + + expectSemanticsTree(''' + +'''); + + semantics().semanticsEnabled = false; + }); +} + +void expectSemanticsTree(String semanticsHtml) { + expect( + canonicalizeHtml(html.document.querySelector('flt-semantics').outerHtml), + canonicalizeHtml(semanticsHtml), + ); +} + +html.Element findScrollable() { + return html.document.querySelectorAll('flt-semantics').firstWhere( + (html.Element element) => + element.style.overflow == 'hidden' || + element.style.overflowY == 'scroll' || + element.style.overflowX == 'scroll', + orElse: () => null, + ); +} + +class SemanticsActionLogger { + StreamController idLogController; + StreamController actionLogController; + Stream idLog; + Stream actionLog; + + SemanticsActionLogger() { + idLogController = StreamController(); + actionLogController = StreamController(); + idLog = idLogController.stream.asBroadcastStream(); + actionLog = actionLogController.stream.asBroadcastStream(); + + // The browser kicks us out of the test zone when the browser event happens. + // We memorize the test zone so we can call expect when the callback is + // fired. + final Zone testZone = Zone.current; + + ui.window.onSemanticsAction = + (int id, ui.SemanticsAction action, ByteData args) { + idLogController.add(id); + actionLogController.add(action); + testZone.run(() { + expect(args, null); + }); + }; + } +} diff --git a/engine/src/flutter/lib/web_ui/test/engine/services/serialization_test.dart b/engine/src/flutter/lib/web_ui/test/engine/services/serialization_test.dart new file mode 100644 index 0000000000..f3d07fac24 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/engine/services/serialization_test.dart @@ -0,0 +1,82 @@ +// 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'; +import 'package:ui/src/engine.dart'; +import 'package:test/test.dart'; + +void main() { + group('Write and read buffer round-trip', () { + test('of single byte', () { + final WriteBuffer write = WriteBuffer(); + write.putUint8(201); + final ByteData written = write.done(); + expect(written.lengthInBytes, equals(1)); + final ReadBuffer read = ReadBuffer(written); + expect(read.getUint8(), equals(201)); + }); + test('of 32-bit integer', () { + final WriteBuffer write = WriteBuffer(); + write.putInt32(-9); + final ByteData written = write.done(); + expect(written.lengthInBytes, equals(4)); + final ReadBuffer read = ReadBuffer(written); + expect(read.getInt32(), equals(-9)); + }); + test('of 64-bit integer', () { + final WriteBuffer write = WriteBuffer(); + write.putInt64(-9000000000000); + final ByteData written = write.done(); + expect(written.lengthInBytes, equals(8)); + final ReadBuffer read = ReadBuffer(written); + expect(read.getInt64(), equals(-9000000000000)); + }, skip: isWeb); + test('of double', () { + final WriteBuffer write = WriteBuffer(); + write.putFloat64(3.14); + final ByteData written = write.done(); + expect(written.lengthInBytes, equals(8)); + final ReadBuffer read = ReadBuffer(written); + expect(read.getFloat64(), equals(3.14)); + }); + test('of 32-bit int list when unaligned', () { + final Int32List integers = Int32List.fromList([-99, 2, 99]); + final WriteBuffer write = WriteBuffer(); + write.putUint8(9); + write.putInt32List(integers); + final ByteData written = write.done(); + expect(written.lengthInBytes, equals(16)); + final ReadBuffer read = ReadBuffer(written); + read.getUint8(); + expect(read.getInt32List(3), equals(integers)); + }); + test('of 64-bit int list when unaligned', () { + final Int64List integers = Int64List.fromList([-99, 2, 99]); + final WriteBuffer write = WriteBuffer(); + write.putUint8(9); + write.putInt64List(integers); + final ByteData written = write.done(); + expect(written.lengthInBytes, equals(32)); + final ReadBuffer read = ReadBuffer(written); + read.getUint8(); + expect(read.getInt64List(3), equals(integers)); + }, skip: isWeb); + test('of double list when unaligned', () { + final Float64List doubles = + Float64List.fromList([3.14, double.nan]); + final WriteBuffer write = WriteBuffer(); + write.putUint8(9); + write.putFloat64List(doubles); + final ByteData written = write.done(); + expect(written.lengthInBytes, equals(24)); + final ReadBuffer read = ReadBuffer(written); + read.getUint8(); + final Float64List readDoubles = read.getFloat64List(2); + expect(readDoubles[0], equals(3.14)); + expect(readDoubles[1], isNaN); + }); + }); +} diff --git a/engine/src/flutter/lib/web_ui/test/engine/surface/surface_test.dart b/engine/src/flutter/lib/web_ui/test/engine/surface/surface_test.dart new file mode 100644 index 0000000000..d9a91cbc51 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/engine/surface/surface_test.dart @@ -0,0 +1,314 @@ +// 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:html' as html; + +import 'package:ui/src/engine.dart'; +import 'package:ui/ui.dart'; + +import 'package:test/test.dart'; + +void main() { + group('Surface', () { + setUp(() { + SceneBuilder.debugForgetFrameScene(); + }); + + test('is created', () { + final SceneBuilder builder = SceneBuilder(); + final PersistedOpacity opacityLayer = builder.pushOpacity(100); + builder.pop(); + + expect(opacityLayer, isNotNull); + expect(opacityLayer.rootElement, isNull); + expect(opacityLayer.isCreated, true); + + builder.build(); + + expect(opacityLayer.rootElement.tagName.toLowerCase(), 'flt-opacity'); + expect(opacityLayer.isActive, true); + }); + + test('is released', () { + final SceneBuilder builder1 = SceneBuilder(); + final PersistedOpacity opacityLayer = builder1.pushOpacity(100); + builder1.pop(); + builder1.build(); + expect(opacityLayer.isActive, true); + + SceneBuilder().build(); + expect(opacityLayer.isReleased, true); + expect(opacityLayer.rootElement, isNull); + }); + + test('discarding is recursive', () { + final SceneBuilder builder1 = SceneBuilder(); + final PersistedOpacity opacityLayer = builder1.pushOpacity(100); + final PersistedTransform transformLayer = + builder1.pushTransform(Matrix4.identity().storage); + builder1.pop(); + builder1.pop(); + builder1.build(); + expect(opacityLayer.isActive, true); + expect(transformLayer.isActive, true); + + SceneBuilder().build(); + expect(opacityLayer.isReleased, true); + expect(transformLayer.isReleased, true); + expect(opacityLayer.rootElement, isNull); + expect(transformLayer.rootElement, isNull); + }); + + test('is updated', () { + final SceneBuilder builder1 = SceneBuilder(); + final PersistedOpacity opacityLayer1 = builder1.pushOpacity(100); + builder1.pop(); + builder1.build(); + expect(opacityLayer1.isActive, true); + final html.Element element = opacityLayer1.rootElement; + + final SceneBuilder builder2 = SceneBuilder(); + final PersistedOpacity opacityLayer2 = + builder2.pushOpacity(200, oldLayer: opacityLayer1); + expect(opacityLayer1.isPendingUpdate, true); + expect(opacityLayer2.isCreated, true); + expect(opacityLayer2.oldLayer, same(opacityLayer1)); + builder2.pop(); + + builder2.build(); + expect(opacityLayer1.isReleased, true); + expect(opacityLayer1.rootElement, isNull); + expect(opacityLayer2.isActive, true); + expect( + opacityLayer2.rootElement, element); // adopts old surface's element + expect(opacityLayer2.oldLayer, isNull); + }); + + test('ignores released surface when updated', () { + // Build a surface + final SceneBuilder builder1 = SceneBuilder(); + final PersistedOpacity opacityLayer1 = builder1.pushOpacity(100); + builder1.pop(); + builder1.build(); + expect(opacityLayer1.isActive, true); + final html.Element element = opacityLayer1.rootElement; + + // Release it + SceneBuilder().build(); + expect(opacityLayer1.isReleased, true); + expect(opacityLayer1.rootElement, isNull); + + // Attempt to update it + final SceneBuilder builder2 = SceneBuilder(); + final PersistedOpacity opacityLayer2 = + builder2.pushOpacity(200, oldLayer: opacityLayer1); + builder2.pop(); + expect(opacityLayer1.isReleased, true); + expect(opacityLayer2.isCreated, true); + + builder2.build(); + expect(opacityLayer1.isReleased, true); + expect(opacityLayer2.isActive, true); + expect(opacityLayer2.rootElement, isNot(equals(element))); + }); + + // This test creates a situation when an intermediate layer disappears, + // causing its child to become a direct child of the common ancestor. This + // often happens with opacity layers. When opacity reaches 1.0, the + // framework removes that layer (as it is no longer necessary). This test + // makes sure we reuse the child layer's DOM nodes. Here's the illustration + // of what's happening: + // + // Frame 1 Frame 2 + // + // A A + // | | + // B ┌──>C + // | │ + // C ────┘ + test('reparents DOM element when updated', () { + final SceneBuilder builder1 = SceneBuilder(); + final PersistedTransform a1 = + builder1.pushTransform(Matrix4.identity().storage); + final PersistedOpacity b1 = builder1.pushOpacity(100); + final PersistedTransform c1 = + builder1.pushTransform(Matrix4.identity().storage); + builder1.pop(); + builder1.pop(); + builder1.pop(); + builder1.build(); + + final html.Element elementA = a1.rootElement; + final html.Element elementB = b1.rootElement; + final html.Element elementC = c1.rootElement; + + expect(elementC.parent, elementB); + expect(elementB.parent, elementA); + + final SceneBuilder builder2 = SceneBuilder(); + final PersistedTransform a2 = + builder2.pushTransform(Matrix4.identity().storage, oldLayer: a1); + final PersistedTransform c2 = + builder2.pushTransform(Matrix4.identity().storage, oldLayer: c1); + builder2.pop(); + builder2.pop(); + builder2.build(); + + expect(a2.rootElement, elementA); + expect(b1.rootElement, isNull); + expect(c2.rootElement, elementC); + + expect(elementC.parent, elementA); + expect(elementB.parent, null); + }); + + test('is retained', () { + final SceneBuilder builder1 = SceneBuilder(); + final PersistedOpacity opacityLayer = builder1.pushOpacity(100); + builder1.pop(); + builder1.build(); + expect(opacityLayer.isActive, true); + final html.Element element = opacityLayer.rootElement; + + final SceneBuilder builder2 = SceneBuilder(); + builder2.addRetained(opacityLayer); + expect(opacityLayer.isPendingRetention, true); + + builder2.build(); + expect(opacityLayer.isActive, true); + expect(opacityLayer.rootElement, element); + }); + + test('revives released surface when retained', () { + final SceneBuilder builder1 = SceneBuilder(); + final PersistedOpacity opacityLayer = builder1.pushOpacity(100); + builder1.pop(); + builder1.build(); + expect(opacityLayer.isActive, true); + final html.Element element = opacityLayer.rootElement; + + SceneBuilder().build(); + expect(opacityLayer.isReleased, true); + expect(opacityLayer.rootElement, isNull); + + final SceneBuilder builder2 = SceneBuilder(); + builder2.addRetained(opacityLayer); + expect(opacityLayer.isCreated, true); // revived + + builder2.build(); + expect(opacityLayer.isActive, true); + expect(opacityLayer.rootElement, isNot(equals(element))); + }); + + test('reviving is recursive', () { + final SceneBuilder builder1 = SceneBuilder(); + final PersistedOpacity opacityLayer = builder1.pushOpacity(100); + final PersistedTransform transformLayer = + builder1.pushTransform(Matrix4.identity().storage); + builder1.pop(); + builder1.pop(); + builder1.build(); + expect(opacityLayer.isActive, true); + expect(transformLayer.isActive, true); + final html.Element opacityElement = opacityLayer.rootElement; + final html.Element transformElement = transformLayer.rootElement; + + SceneBuilder().build(); + + final SceneBuilder builder2 = SceneBuilder(); + builder2.addRetained(opacityLayer); + expect(opacityLayer.isCreated, true); // revived + expect(transformLayer.isCreated, true); // revived + + builder2.build(); + expect(opacityLayer.isActive, true); + expect(transformLayer.isActive, true); + expect(opacityLayer.rootElement, isNot(equals(opacityElement))); + expect(transformLayer.rootElement, isNot(equals(transformElement))); + }); + + // This test creates a situation when a retained layer is moved to another + // parent. We want to make sure that we move the retained layer's elements + // without rebuilding from scratch. No new elements are created in this + // situation. + // + // Here's an illustrated example where layer C is reparented onto B along + // with D: + // + // Frame 1 Frame 2 + // + // A A + // ╱ ╲ | + // B C ──┐ B + // | │ | + // D └──>C + // | + // D + test('reparents DOM elements when retained', () { + final SceneBuilder builder1 = SceneBuilder(); + final PersistedOpacity a1 = builder1.pushOpacity(10); + final PersistedOpacity b1 = builder1.pushOpacity(20); + builder1.pop(); + final PersistedOpacity c1 = builder1.pushOpacity(30); + final PersistedOpacity d1 = builder1.pushOpacity(40); + builder1.pop(); + builder1.pop(); + builder1.pop(); + builder1.build(); + + final html.Element elementA = a1.rootElement; + final html.Element elementB = b1.rootElement; + final html.Element elementC = c1.rootElement; + final html.Element elementD = d1.rootElement; + + expect(elementB.parent, elementA); + expect(elementC.parent, elementA); + expect(elementD.parent, elementC); + + final SceneBuilder builder2 = SceneBuilder(); + final PersistedOpacity a2 = builder2.pushOpacity(10, oldLayer: a1); + final PersistedOpacity b2 = builder2.pushOpacity(20, oldLayer: b1); + builder2.addRetained(c1); + builder2.pop(); + builder2.pop(); + builder2.build(); + + expect(a2.rootElement, elementA); + expect(b2.rootElement, elementB); + expect(c1.rootElement, elementC); + expect(d1.rootElement, elementD); + + expect( + [ + elementD.parent, + elementC.parent, + elementB.parent, + ], + [elementC, elementB, elementA], + ); + }); + + test('is updated by matching', () { + final SceneBuilder builder1 = SceneBuilder(); + final PersistedOpacity opacityLayer1 = builder1.pushOpacity(100); + builder1.pop(); + builder1.build(); + expect(opacityLayer1.isActive, true); + final html.Element element = opacityLayer1.rootElement; + + final SceneBuilder builder2 = SceneBuilder(); + final PersistedOpacity opacityLayer2 = builder2.pushOpacity(200); + expect(opacityLayer1.isActive, true); + expect(opacityLayer2.isCreated, true); + builder2.pop(); + + builder2.build(); + expect(opacityLayer1.isReleased, true); + expect(opacityLayer1.rootElement, isNull); + expect(opacityLayer2.isActive, true); + expect( + opacityLayer2.rootElement, element); // adopts old surface's element + }); + }); +} diff --git a/engine/src/flutter/lib/web_ui/test/geometry_test.dart b/engine/src/flutter/lib/web_ui/test/geometry_test.dart index e37e550efe..8f3507df44 100644 --- a/engine/src/flutter/lib/web_ui/test/geometry_test.dart +++ b/engine/src/flutter/lib/web_ui/test/geometry_test.dart @@ -10,137 +10,61 @@ import 'package:ui/ui.dart'; import 'package:test/test.dart'; void main() { - group('Offset', () { - test('Offset.direction', () { - expect(const Offset(0.0, 0.0).direction, 0.0); - expect(const Offset(0.0, 1.0).direction, pi / 2.0); - expect(const Offset(0.0, -1.0).direction, -pi / 2.0); - expect(const Offset(1.0, 0.0).direction, 0.0); - expect(const Offset(1.0, 1.0).direction, pi / 4.0); - expect(const Offset(1.0, -1.0).direction, -pi / 4.0); - expect(const Offset(-1.0, 0.0).direction, pi); - expect(const Offset(-1.0, 1.0).direction, pi * 3.0 / 4.0); - expect(const Offset(-1.0, -1.0).direction, -pi * 3.0 / 4.0); - }); - - test('Offset.fromDirection', () { - expect(Offset.fromDirection(0.0, 0.0), const Offset(0.0, 0.0)); - expect(Offset.fromDirection(pi / 2.0).dx, closeTo(0.0, 1e-12)); // aah, floating point math. i love you so. - expect(Offset.fromDirection(pi / 2.0).dy, 1.0); - expect(Offset.fromDirection(-pi / 2.0).dx, closeTo(0.0, 1e-12)); - expect(Offset.fromDirection(-pi / 2.0).dy, -1.0); - expect(Offset.fromDirection(0.0), const Offset(1.0, 0.0)); - expect(Offset.fromDirection(pi / 4.0).dx, closeTo(1.0 / math.sqrt(2.0), 1e-12)); - expect(Offset.fromDirection(pi / 4.0).dy, closeTo(1.0 / math.sqrt(2.0), 1e-12)); - expect(Offset.fromDirection(-pi / 4.0).dx, closeTo(1.0 / math.sqrt(2.0), 1e-12)); - expect(Offset.fromDirection(-pi / 4.0).dy, closeTo(-1.0 / math.sqrt(2.0), 1e-12)); - expect(Offset.fromDirection(pi).dx, -1.0); - expect(Offset.fromDirection(pi).dy, closeTo(0.0, 1e-12)); - expect(Offset.fromDirection(pi * 3.0 / 4.0).dx, closeTo(-1.0 / math.sqrt(2.0), 1e-12)); - expect(Offset.fromDirection(pi * 3.0 / 4.0).dy, closeTo(1.0 / math.sqrt(2.0), 1e-12)); - expect(Offset.fromDirection(-pi * 3.0 / 4.0).dx, closeTo(-1.0 / math.sqrt(2.0), 1e-12)); - expect(Offset.fromDirection(-pi * 3.0 / 4.0).dy, closeTo(-1.0 / math.sqrt(2.0), 1e-12)); - expect(Offset.fromDirection(0.0, 2.0), const Offset(2.0, 0.0)); - expect(Offset.fromDirection(pi / 6, 2.0).dx, closeTo(math.sqrt(3.0), 1e-12)); - expect(Offset.fromDirection(pi / 6, 2.0).dy, closeTo(1.0, 1e-12)); - }); + test('Offset.direction', () { + expect(const Offset(0.0, 0.0).direction, 0.0); + expect(const Offset(0.0, 1.0).direction, pi / 2.0); + expect(const Offset(0.0, -1.0).direction, -pi / 2.0); + expect(const Offset(1.0, 0.0).direction, 0.0); + expect(const Offset(1.0, 1.0).direction, pi / 4.0); + expect(const Offset(1.0, -1.0).direction, -pi / 4.0); + expect(const Offset(-1.0, 0.0).direction, pi); + expect(const Offset(-1.0, 1.0).direction, pi * 3.0 / 4.0); + expect(const Offset(-1.0, -1.0).direction, -pi * 3.0 / 4.0); }); - - group('Size', () { - test('Size created from doubles', () { - const Size size = Size(5.0, 7.0); - expect(size.width, equals(5.0)); - expect(size.height, equals(7.0)); - expect(size.shortestSide, equals(5.0)); - expect(size.longestSide, equals(7.0)); - }); - - test('Size.aspectRatio', () { - expect(const Size(0.0, 0.0).aspectRatio, 0.0); - expect(const Size(-0.0, 0.0).aspectRatio, 0.0); - expect(const Size(0.0, -0.0).aspectRatio, 0.0); - expect(const Size(-0.0, -0.0).aspectRatio, 0.0); - expect(const Size(0.0, 1.0).aspectRatio, 0.0); - expect(const Size(0.0, -1.0).aspectRatio, -0.0); - expect(const Size(1.0, 0.0).aspectRatio, double.infinity); - expect(const Size(1.0, 1.0).aspectRatio, 1.0); - expect(const Size(1.0, -1.0).aspectRatio, -1.0); - expect(const Size(-1.0, 0.0).aspectRatio, -double.infinity); - expect(const Size(-1.0, 1.0).aspectRatio, -1.0); - expect(const Size(-1.0, -1.0).aspectRatio, 1.0); - expect(const Size(3.0, 4.0).aspectRatio, 3.0 / 4.0); - }); + test('Offset.fromDirection', () { + expect(Offset.fromDirection(0.0, 0.0), const Offset(0.0, 0.0)); + expect(Offset.fromDirection(pi / 2.0).dx, + closeTo(0.0, 1e-12)); // aah, floating point math. i love you so. + expect(Offset.fromDirection(pi / 2.0).dy, 1.0); + expect(Offset.fromDirection(-pi / 2.0).dx, closeTo(0.0, 1e-12)); + expect(Offset.fromDirection(-pi / 2.0).dy, -1.0); + expect(Offset.fromDirection(0.0), const Offset(1.0, 0.0)); + expect(Offset.fromDirection(pi / 4.0).dx, + closeTo(1.0 / math.sqrt(2.0), 1e-12)); + expect(Offset.fromDirection(pi / 4.0).dy, + closeTo(1.0 / math.sqrt(2.0), 1e-12)); + expect(Offset.fromDirection(-pi / 4.0).dx, + closeTo(1.0 / math.sqrt(2.0), 1e-12)); + expect(Offset.fromDirection(-pi / 4.0).dy, + closeTo(-1.0 / math.sqrt(2.0), 1e-12)); + expect(Offset.fromDirection(pi).dx, -1.0); + expect(Offset.fromDirection(pi).dy, closeTo(0.0, 1e-12)); + expect(Offset.fromDirection(pi * 3.0 / 4.0).dx, + closeTo(-1.0 / math.sqrt(2.0), 1e-12)); + expect(Offset.fromDirection(pi * 3.0 / 4.0).dy, + closeTo(1.0 / math.sqrt(2.0), 1e-12)); + expect(Offset.fromDirection(-pi * 3.0 / 4.0).dx, + closeTo(-1.0 / math.sqrt(2.0), 1e-12)); + expect(Offset.fromDirection(-pi * 3.0 / 4.0).dy, + closeTo(-1.0 / math.sqrt(2.0), 1e-12)); + expect(Offset.fromDirection(0.0, 2.0), const Offset(2.0, 0.0)); + expect( + Offset.fromDirection(pi / 6, 2.0).dx, closeTo(math.sqrt(3.0), 1e-12)); + expect(Offset.fromDirection(pi / 6, 2.0).dy, closeTo(1.0, 1e-12)); }); - - group('Rect', () { - test('Rect accessors', () { - final Rect r = Rect.fromLTRB(1.0, 3.0, 5.0, 7.0); - expect(r.left, equals(1.0)); - expect(r.top, equals(3.0)); - expect(r.right, equals(5.0)); - expect(r.bottom, equals(7.0)); - }); - - test('Rect created by width and height', () { - final Rect r = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0); - expect(r.left, equals(1.0)); - expect(r.top, equals(3.0)); - expect(r.right, equals(6.0)); - expect(r.bottom, equals(10.0)); - expect(r.shortestSide, equals(5.0)); - expect(r.longestSide, equals(7.0)); - }); - - test('Rect intersection', () { - final Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0); - final Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0); - final Rect r3 = r1.intersect(r2); - expect(r3.left, equals(50.0)); - expect(r3.top, equals(50.0)); - expect(r3.right, equals(100.0)); - expect(r3.bottom, equals(100.0)); - - final Rect r4 = r2.intersect(r1); - expect(r4, equals(r3)); - }); - - test('Rect expandToInclude overlapping rects', () { - final Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0); - final Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0); - final Rect r3 = r1.expandToInclude(r2); - expect(r3.left, equals(0.0)); - expect(r3.top, equals(0.0)); - expect(r3.right, equals(200.0)); - expect(r3.bottom, equals(200.0)); - - final Rect r4 = r2.expandToInclude(r1); - expect(r4, equals(r3)); - }); - - test('Rect expandToInclude crossing rects', () { - final Rect r1 = Rect.fromLTRB(50.0, 0.0, 50.0, 200.0); - final Rect r2 = Rect.fromLTRB(0.0, 50.0, 200.0, 50.0); - final Rect r3 = r1.expandToInclude(r2); - expect(r3.left, equals(0.0)); - expect(r3.top, equals(0.0)); - expect(r3.right, equals(200.0)); - expect(r3.bottom, equals(200.0)); - - final Rect r4 = r2.expandToInclude(r1); - expect(r4, equals(r3)); - }); - }); - - group('RRect', () { - test('RRect.fromRectXY', () { - final Rect baseRect = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0); - final RRect r = RRect.fromRectXY(baseRect, 1.0, 1.0); - expect(r.left, equals(1.0)); - expect(r.top, equals(3.0)); - expect(r.right, equals(6.0)); - expect(r.bottom, equals(10.0)); - expect(r.shortestSide, equals(5.0)); - expect(r.longestSide, equals(7.0)); - }); + test('Size.aspectRatio', () { + expect(const Size(0.0, 0.0).aspectRatio, 0.0); + expect(const Size(-0.0, 0.0).aspectRatio, 0.0); + expect(const Size(0.0, -0.0).aspectRatio, 0.0); + expect(const Size(-0.0, -0.0).aspectRatio, 0.0); + expect(const Size(0.0, 1.0).aspectRatio, 0.0); + expect(const Size(0.0, -1.0).aspectRatio, -0.0); + expect(const Size(1.0, 0.0).aspectRatio, double.infinity); + expect(const Size(1.0, 1.0).aspectRatio, 1.0); + expect(const Size(1.0, -1.0).aspectRatio, -1.0); + expect(const Size(-1.0, 0.0).aspectRatio, -double.infinity); + expect(const Size(-1.0, 1.0).aspectRatio, -1.0); + expect(const Size(-1.0, -1.0).aspectRatio, 1.0); + expect(const Size(3.0, 4.0).aspectRatio, 3.0 / 4.0); }); } diff --git a/engine/src/flutter/lib/web_ui/test/gradient_test.dart b/engine/src/flutter/lib/web_ui/test/gradient_test.dart index f05b1abede..2906728c57 100644 --- a/engine/src/flutter/lib/web_ui/test/gradient_test.dart +++ b/engine/src/flutter/lib/web_ui/test/gradient_test.dart @@ -9,7 +9,7 @@ import 'package:test/test.dart'; void main() { test('Gradient.radial with no focal point', () { expect( - new Gradient.radial( + Gradient.radial( Offset.zero, null, [const Color(0xFFFFFFFF), const Color(0xFFFFFFFF)], @@ -23,7 +23,7 @@ void main() { test('radial center and focal == Offset.zero and focalRadius == 0.0 is ok', () { expect( - () => new Gradient.radial( + () => Gradient.radial( Offset.zero, 0.0, [const Color(0xFFFFFFFF), const Color(0xFFFFFFFF)], @@ -38,7 +38,7 @@ void main() { test('radial center != focal and focalRadius == 0.0 is ok', () { expect( - () => new Gradient.radial( + () => Gradient.radial( Offset.zero, 0.0, [const Color(0xFFFFFFFF), const Color(0xFFFFFFFF)], @@ -55,7 +55,7 @@ void main() { test('radial center and focal == Offset.zero and focalRadius != 0.0 assert', () { expect( - () => new Gradient.radial( + () => Gradient.radial( Offset.zero, 0.0, [const Color(0xFFFFFFFF), const Color(0xFFFFFFFF)], diff --git a/engine/src/flutter/lib/web_ui/test/keyboard_test.dart b/engine/src/flutter/lib/web_ui/test/keyboard_test.dart index b91d68933e..4e2ca3635f 100644 --- a/engine/src/flutter/lib/web_ui/test/keyboard_test.dart +++ b/engine/src/flutter/lib/web_ui/test/keyboard_test.dart @@ -20,11 +20,11 @@ void main() { test('dispatches keyup to flutter/keyevent channel', () { String channelReceived; - Map dataReceived; + Map dataReceived; ui.window.onPlatformMessage = (String channel, ByteData data, ui.PlatformMessageResponseCallback callback) { channelReceived = channel; - dataReceived = JSONMessageCodec().decodeMessage(data); + dataReceived = const JSONMessageCodec().decodeMessage(data); }; html.window.dispatchEvent(html.KeyboardEvent('keyup')); @@ -42,11 +42,11 @@ void main() { test('dispatches keydown to flutter/keyevent channel', () { String channelReceived; - Map dataReceived; + Map dataReceived; ui.window.onPlatformMessage = (String channel, ByteData data, ui.PlatformMessageResponseCallback callback) { channelReceived = channel; - dataReceived = JSONMessageCodec().decodeMessage(data); + dataReceived = const JSONMessageCodec().decodeMessage(data); }; html.window.dispatchEvent(html.KeyboardEvent('keydown')); diff --git a/engine/src/flutter/lib/web_ui/test/matchers.dart b/engine/src/flutter/lib/web_ui/test/matchers.dart index 049c78fa74..7ae94348bd 100644 --- a/engine/src/flutter/lib/web_ui/test/matchers.dart +++ b/engine/src/flutter/lib/web_ui/test/matchers.dart @@ -6,10 +6,10 @@ library matchers; import 'dart:html' as html; +import 'dart:math' as math; import 'package:html/parser.dart' as html_package; import 'package:html/dom.dart' as html_package; -import 'dart:math' as math; import 'package:meta/meta.dart'; import 'package:test/test.dart'; @@ -159,8 +159,12 @@ class _IsWithinDistance extends Matcher { @override bool matches(Object object, Map matchState) { - if (object is! T) return false; - if (object == value) return true; + if (object is! T) { + return false; + } + if (object == value) { + return true; + } final T test = object; final num distance = distanceFunction(test, value); if (distance < 0) { @@ -264,7 +268,7 @@ String canonicalizeHtml(String htmlContent, replacementTag = 'pshape'; break; default: - throw Exception('Unknown clip type: ${clipType}'); + throw Exception('Unknown clip type: $clipType'); } break; case 'flt-clip-interior': @@ -296,7 +300,8 @@ String canonicalizeHtml(String htmlContent, break; } - html_package.Element replacement = html_package.Element.tag(replacementTag); + final html_package.Element replacement = + html_package.Element.tag(replacementTag); if (mode != HtmlComparisonMode.noAttributes) { original.attributes.forEach((dynamic name, String value) { @@ -309,26 +314,26 @@ String canonicalizeHtml(String htmlContent, }); if (original.attributes.containsKey('style')) { - final styleValue = original.attributes['style']; + final String styleValue = original.attributes['style']; int attrCount = 0; - String processedAttributes = styleValue + final String processedAttributes = styleValue .split(';') - .map((attr) { + .map((String attr) { attr = attr.trim(); if (attr.isEmpty) { return null; } if (mode != HtmlComparisonMode.everything) { - final forLayout = mode == HtmlComparisonMode.layoutOnly; - List parts = attr.split(':'); + final bool forLayout = mode == HtmlComparisonMode.layoutOnly; + final List parts = attr.split(':'); if (parts.length == 2) { - String name = parts.first; + final String name = parts.first; // Whether the attribute is one that's set to the same value and // never changes. Such attributes are usually not interesting to // test. - bool isStaticAttribute = const [ + final bool isStaticAttribute = const [ 'top', 'left', 'position', @@ -339,7 +344,7 @@ String canonicalizeHtml(String htmlContent, } // Whether the attribute is set by the layout system. - bool isLayoutAttribute = const [ + final bool isLayoutAttribute = const [ 'top', 'left', 'bottom', @@ -363,7 +368,7 @@ String canonicalizeHtml(String htmlContent, attrCount++; return attr.trim(); }) - .where((attr) => attr != null && attr.isNotEmpty) + .where((String attr) => attr != null && attr.isNotEmpty) .join('; '); if (attrCount > 0) { @@ -390,11 +395,12 @@ String canonicalizeHtml(String htmlContent, return replacement; } - html_package.DocumentFragment originalDom = + final html_package.DocumentFragment originalDom = html_package.parseFragment(htmlContent); - html_package.DocumentFragment cleanDom = html_package.DocumentFragment(); - for (var child in originalDom.children) { + final html_package.DocumentFragment cleanDom = + html_package.DocumentFragment(); + for (html_package.Element child in originalDom.children) { cleanDom.append(_cleanup(child)); } @@ -406,7 +412,7 @@ void expectHtml(html.Element element, String expectedHtml, {HtmlComparisonMode mode = HtmlComparisonMode.nonLayoutOnly}) { expectedHtml = canonicalizeHtml(expectedHtml, mode: mode, throwOnUnusedAttributes: true); - String actualHtml = canonicalizeHtml(element.outerHtml, mode: mode); + final String actualHtml = canonicalizeHtml(element.outerHtml, mode: mode); expect(actualHtml, expectedHtml); } @@ -441,7 +447,7 @@ void expectHtml(html.Element element, String expectedHtml, void expectPageHtml(String expectedHtml, {HtmlComparisonMode mode = HtmlComparisonMode.nonLayoutOnly}) { expectedHtml = canonicalizeHtml(expectedHtml, mode: mode); - String actualHtml = canonicalizeHtml(currentHtml, mode: mode); + final String actualHtml = canonicalizeHtml(currentHtml, mode: mode); expect(actualHtml, expectedHtml); } @@ -460,3 +466,28 @@ class SceneTester { mode: HtmlComparisonMode.noAttributes); } } + +/// A matcher for functions that throw [AssertionError]. +/// +/// This is equivalent to `throwsA(isInstanceOf())`. +/// +/// If you are trying to test whether a call to [WidgetTester.pumpWidget] +/// results in an [AssertionError], see +/// [TestWidgetsFlutterBinding.takeException]. +/// +/// See also: +/// +/// * [throwsFlutterError], to test if a function throws a [FlutterError]. +/// * [throwsArgumentError], to test if a functions throws an [ArgumentError]. +/// * [isAssertionError], to test if any object is any kind of [AssertionError]. +final Matcher throwsAssertionError = throwsA(isAssertionError); + +/// A matcher for [AssertionError]. +/// +/// This is equivalent to `isInstanceOf()`. +/// +/// See also: +/// +/// * [throwsAssertionError], to test if a function throws any [AssertionError]. +/// * [isFlutterError], to test if any object is a [FlutterError]. +const Matcher isAssertionError = TypeMatcher(); diff --git a/engine/src/flutter/lib/web_ui/test/mock_engine_canvas.dart b/engine/src/flutter/lib/web_ui/test/mock_engine_canvas.dart index 2445d64d2a..2cf562f4fd 100644 --- a/engine/src/flutter/lib/web_ui/test/mock_engine_canvas.dart +++ b/engine/src/flutter/lib/web_ui/test/mock_engine_canvas.dart @@ -65,7 +65,7 @@ class MockEngineCanvas implements EngineCanvas { @override void translate(double dx, double dy) { - _called('translate', arguments: { + _called('translate', arguments: { 'dx': dx, 'dy': dy, }); @@ -73,7 +73,7 @@ class MockEngineCanvas implements EngineCanvas { @override void scale(double sx, double sy) { - _called('scale', arguments: { + _called('scale', arguments: { 'sx': sx, 'sy': sy, }); @@ -86,7 +86,7 @@ class MockEngineCanvas implements EngineCanvas { @override void skew(double sx, double sy) { - _called('skew', arguments: { + _called('skew', arguments: { 'sx': sx, 'sy': sy, }); @@ -114,7 +114,7 @@ class MockEngineCanvas implements EngineCanvas { @override void drawColor(Color color, BlendMode blendMode) { - _called('drawColor', arguments: { + _called('drawColor', arguments: { 'color': color, 'blendMode': blendMode, }); @@ -122,7 +122,7 @@ class MockEngineCanvas implements EngineCanvas { @override void drawLine(Offset p1, Offset p2, PaintData paint) { - _called('drawLine', arguments: { + _called('drawLine', arguments: { 'p1': p1, 'p2': p2, 'paint': paint, @@ -141,7 +141,7 @@ class MockEngineCanvas implements EngineCanvas { @override void drawRRect(RRect rrect, PaintData paint) { - _called('drawRRect', arguments: { + _called('drawRRect', arguments: { 'rrect': rrect, 'paint': paint, }); @@ -149,7 +149,7 @@ class MockEngineCanvas implements EngineCanvas { @override void drawDRRect(RRect outer, RRect inner, PaintData paint) { - _called('drawDRRect', arguments: { + _called('drawDRRect', arguments: { 'outer': outer, 'inner': inner, 'paint': paint, @@ -158,7 +158,7 @@ class MockEngineCanvas implements EngineCanvas { @override void drawOval(Rect rect, PaintData paint) { - _called('drawOval', arguments: { + _called('drawOval', arguments: { 'rect': rect, 'paint': paint, }); @@ -166,7 +166,7 @@ class MockEngineCanvas implements EngineCanvas { @override void drawCircle(Offset c, double radius, PaintData paint) { - _called('drawCircle', arguments: { + _called('drawCircle', arguments: { 'c': c, 'radius': radius, 'paint': paint, @@ -175,7 +175,7 @@ class MockEngineCanvas implements EngineCanvas { @override void drawPath(Path path, PaintData paint) { - _called('drawPath', arguments: { + _called('drawPath', arguments: { 'path': path, 'paint': paint, }); @@ -184,7 +184,7 @@ class MockEngineCanvas implements EngineCanvas { @override void drawShadow( Path path, Color color, double elevation, bool transparentOccluder) { - _called('drawShadow', arguments: { + _called('drawShadow', arguments: { 'path': path, 'color': color, 'elevation': elevation, @@ -194,7 +194,7 @@ class MockEngineCanvas implements EngineCanvas { @override void drawImage(Image image, Offset p, PaintData paint) { - _called('drawImage', arguments: { + _called('drawImage', arguments: { 'image': image, 'p': p, 'paint': paint, @@ -203,7 +203,7 @@ class MockEngineCanvas implements EngineCanvas { @override void drawImageRect(Image image, Rect src, Rect dst, PaintData paint) { - _called('drawImageRect', arguments: { + _called('drawImageRect', arguments: { 'image': image, 'src': src, 'dst': dst, @@ -213,7 +213,7 @@ class MockEngineCanvas implements EngineCanvas { @override void drawParagraph(Paragraph paragraph, Offset offset) { - _called('drawParagraph', arguments: { + _called('drawParagraph', arguments: { 'paragraph': paragraph, 'offset': offset, }); diff --git a/engine/src/flutter/lib/web_ui/test/paragraph_test.dart b/engine/src/flutter/lib/web_ui/test/paragraph_test.dart new file mode 100644 index 0000000000..de1796636d --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/paragraph_test.dart @@ -0,0 +1,65 @@ +// 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'; + +import 'package:test/test.dart'; + +void main() async { + await webOnlyInitializeTestDomRenderer(); + + // Ahem font uses a constant ideographic/alphabetic baseline ratio. + const double kAhemBaselineRatio = 1.25; + + test('predictably lays out a single-line paragraph', () { + for (double fontSize in [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, closeTo(fontSize, 0.001)); + expect(paragraph.width, closeTo(400.0, 0.001)); + expect(paragraph.minIntrinsicWidth, closeTo(fontSize * 4.0, 0.001)); + expect(paragraph.maxIntrinsicWidth, closeTo(fontSize * 4.0, 0.001)); + expect(paragraph.alphabeticBaseline, closeTo(fontSize * .8, 0.001)); + expect( + paragraph.ideographicBaseline, + closeTo(paragraph.alphabeticBaseline * kAhemBaselineRatio, 3.0), + ); + } + }); + + test('predictably lays out a multi-line paragraph', () { + for (double fontSize in [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, closeTo(fontSize * 2.0, 0.001)); // because it wraps + expect(paragraph.width, closeTo(fontSize * 5.0, 0.001)); + expect(paragraph.minIntrinsicWidth, closeTo(fontSize * 4.0, 0.001)); + + // TODO(yjbanov): see https://github.com/flutter/flutter/issues/21965 + expect(paragraph.maxIntrinsicWidth, closeTo(fontSize * 9.0, 0.001)); + expect(paragraph.alphabeticBaseline, closeTo(fontSize * .8, 0.001)); + expect( + paragraph.ideographicBaseline, + closeTo(paragraph.alphabeticBaseline * kAhemBaselineRatio, 3.0), + ); + } + }); +} diff --git a/engine/src/flutter/lib/web_ui/test/path_test.dart b/engine/src/flutter/lib/web_ui/test/path_test.dart index 19aa956c9c..1deadc0663 100644 --- a/engine/src/flutter/lib/web_ui/test/path_test.dart +++ b/engine/src/flutter/lib/web_ui/test/path_test.dart @@ -5,6 +5,8 @@ import 'package:test/test.dart'; import 'package:ui/ui.dart'; +import 'matchers.dart'; + void main() { test('Should have no subpaths when created', () { final Path path = Path(); @@ -55,7 +57,7 @@ void main() { final Path subPath = Path(); subPath.moveTo(50.0, 60.0); subPath.lineTo(200.0, 200.0); - path.extendWithPath(subPath, Offset(0.0, 0.0)); + path.extendWithPath(subPath, const Offset(0.0, 0.0)); path.reset(); path.relativeLineTo(5.0, 5.0); expect(path.subpaths.length, 1); @@ -65,8 +67,8 @@ void main() { test('Should detect rectangular path', () { final Path path = Path(); - path.addRect(Rect.fromLTWH(1.0, 2.0, 3.0, 4.0)); - expect(path.webOnlyPathAsRect, Rect.fromLTWH(1.0, 2.0, 3.0, 4.0)); + path.addRect(const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0)); + expect(path.webOnlyPathAsRect, const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0)); }); test('Should detect non rectangular path if empty', () { @@ -76,153 +78,163 @@ void main() { test('Should detect non rectangular path if there are multiple subpaths', () { final Path path = Path(); - path.addRect(Rect.fromLTWH(1.0, 2.0, 3.0, 4.0)); - path.addRect(Rect.fromLTWH(5.0, 6.0, 7.0, 8.0)); + path.addRect(const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0)); + path.addRect(const Rect.fromLTWH(5.0, 6.0, 7.0, 8.0)); expect(path.webOnlyPathAsRect, null); }); test('Should detect rounded rectangular path', () { final Path path = Path(); path.addRRect(RRect.fromRectAndRadius( - Rect.fromLTWH(1.0, 2.0, 3.0, 4.0), Radius.circular(2.0))); + const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0), const Radius.circular(2.0))); expect( path.webOnlyPathAsRoundedRect, - RRect.fromRectAndRadius( - Rect.fromLTWH(1.0, 2.0, 3.0, 4.0), Radius.circular(2.0))); + RRect.fromRectAndRadius(const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0), + const Radius.circular(2.0))); }); test('Should detect non rounded rectangular path if empty', () { - final Path path = new Path(); + final Path path = Path(); expect(path.webOnlyPathAsRoundedRect, null); }); test('Should detect rectangular path is not round', () { - final Path path = new Path(); - path.addRect(Rect.fromLTWH(1.0, 2.0, 3.0, 4.0)); + final Path path = Path(); + path.addRect(const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0)); expect(path.webOnlyPathAsRoundedRect, null); }); test( 'Should detect non rounded rectangular path if there are ' 'multiple subpaths', () { - final Path path = new Path(); + final Path path = Path(); path.addRRect(RRect.fromRectAndRadius( - Rect.fromLTWH(1.0, 2.0, 3.0, 4.0), Radius.circular(2.0))); + const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0), const Radius.circular(2.0))); path.addRRect(RRect.fromRectAndRadius( - Rect.fromLTWH(1.0, 2.0, 3.0, 4.0), Radius.circular(2.0))); + const Rect.fromLTWH(1.0, 2.0, 3.0, 4.0), const Radius.circular(2.0))); expect(path.webOnlyPathAsRoundedRect, null); }); test('Should compute bounds as empty for empty and moveTo only path', () { - final Path emptyPath = new Path(); + final Path emptyPath = Path(); expect(emptyPath.getBounds(), Rect.zero); - final Path path = new Path(); + final Path path = Path(); path.moveTo(50, 60); - expect(path.getBounds(), Rect.fromLTRB(50, 60, 50, 60)); + expect(path.getBounds(), const Rect.fromLTRB(50, 60, 50, 60)); }); test('Should compute bounds for lines', () { - final Path path = new Path(); + final Path path = Path(); path.moveTo(25, 30); path.lineTo(100, 200); - expect(path.getBounds(), Rect.fromLTRB(25, 30, 100, 200)); + expect(path.getBounds(), const Rect.fromLTRB(25, 30, 100, 200)); - final Path path2 = new Path(); + final Path path2 = Path(); path2.moveTo(250, 300); path2.lineTo(50, 60); - expect(path2.getBounds(), Rect.fromLTRB(50, 60, 250, 300)); + expect(path2.getBounds(), const Rect.fromLTRB(50, 60, 250, 300)); }); - // test('Should compute bounds for quadraticBezierTo', () { - // final Path path1 = new Path(); - // path1.moveTo(285.2, 682.1); - // path1.quadraticBezierTo(432.0, 431.4, 594.9, 681.2); - // expect( - // path1.getBounds(), - // within( - // distance: 0.1, from: Rect.fromLTRB(285.2, 556.5, 594.9, 682.1))); + test('Should compute bounds for quadraticBezierTo', () { + final Path path1 = Path(); + path1.moveTo(285.2, 682.1); + path1.quadraticBezierTo(432.0, 431.4, 594.9, 681.2); + expect( + path1.getBounds(), + within( + distance: 0.1, + from: const Rect.fromLTRB(285.2, 556.5, 594.9, 682.1))); - // // Control point below start , end. - // final Path path2 = new Path(); - // path2.moveTo(285.2, 682.1); - // path2.quadraticBezierTo(447.4, 946.8, 594.9, 681.2); - // expect( - // path2.getBounds(), - // within( - // distance: 0.1, from: Rect.fromLTRB(285.2, 681.2, 594.9, 814.2))); + // Control point below start , end. + final Path path2 = Path(); + path2.moveTo(285.2, 682.1); + path2.quadraticBezierTo(447.4, 946.8, 594.9, 681.2); + expect( + path2.getBounds(), + within( + distance: 0.1, + from: const Rect.fromLTRB(285.2, 681.2, 594.9, 814.2))); - // // Control point to the right of end point. - // final Path path3 = new Path(); - // path3.moveTo(468.3, 685.6); - // path3.quadraticBezierTo(644.7, 555.2, 594.9, 681.2); - // expect( - // path3.getBounds(), - // within( - // distance: 0.1, from: Rect.fromLTRB(468.3, 619.3, 605.9, 685.6))); - // }); + // Control point to the right of end point. + final Path path3 = Path(); + path3.moveTo(468.3, 685.6); + path3.quadraticBezierTo(644.7, 555.2, 594.9, 681.2); + expect( + path3.getBounds(), + within( + distance: 0.1, + from: const Rect.fromLTRB(468.3, 619.3, 605.9, 685.6))); + }); - // test('Should compute bounds for cubicTo', () { - // final Path path1 = new Path(); - // path1.moveTo(220, 300); - // path1.cubicTo(230, 120, 400, 125, 410, 280); - // expect( - // path1.getBounds(), - // within( - // distance: 0.1, from: Rect.fromLTRB(220.0, 164.3, 410.0, 300.0))); + test('Should compute bounds for cubicTo', () { + final Path path1 = Path(); + path1.moveTo(220, 300); + path1.cubicTo(230, 120, 400, 125, 410, 280); + expect( + path1.getBounds(), + within( + distance: 0.1, + from: const Rect.fromLTRB(220.0, 164.3, 410.0, 300.0))); - // // control point 1 to the right of control point 2 - // final Path path2 = new Path(); - // path2.moveTo(220, 300); - // path2.cubicTo(564.2, 13.7, 400.0, 125.0, 410.0, 280.0); - // expect( - // path2.getBounds(), - // within( - // distance: 0.1, from: Rect.fromLTRB(220.0, 122.8, 440.5, 300.0))); + // control point 1 to the right of control point 2 + final Path path2 = Path(); + path2.moveTo(220, 300); + path2.cubicTo(564.2, 13.7, 400.0, 125.0, 410.0, 280.0); + expect( + path2.getBounds(), + within( + distance: 0.1, + from: const Rect.fromLTRB(220.0, 122.8, 440.5, 300.0))); - // // control point 1 to the right of control point 2 inflection - // final Path path3 = new Path(); - // path3.moveTo(220, 300); - // path3.cubicTo(839.8, 67.9, 400.0, 125.0, 410.0, 280.0); - // expect( - // path3.getBounds(), - // within( - // distance: 0.1, from: Rect.fromLTRB(220.0, 144.5, 552.1, 300.0))); + // control point 1 to the right of control point 2 inflection + final Path path3 = Path(); + path3.moveTo(220, 300); + path3.cubicTo(839.8, 67.9, 400.0, 125.0, 410.0, 280.0); + expect( + path3.getBounds(), + within( + distance: 0.1, + from: const Rect.fromLTRB(220.0, 144.5, 552.1, 300.0))); - // // control point 1 below and between start and end points - // final Path path4 = new Path(); - // path4.moveTo(220.0, 300.0); - // path4.cubicTo(354.8, 388.3, 400.0, 125.0, 410.0, 280.0); - // expect( - // path4.getBounds(), - // within( - // distance: 0.1, from: Rect.fromLTRB(220.0, 230.0, 410.0, 318.6))); + // control point 1 below and between start and end points + final Path path4 = Path(); + path4.moveTo(220.0, 300.0); + path4.cubicTo(354.8, 388.3, 400.0, 125.0, 410.0, 280.0); + expect( + path4.getBounds(), + within( + distance: 0.1, + from: const Rect.fromLTRB(220.0, 230.0, 410.0, 318.6))); - // // control points inverted below - // final Path path5 = new Path(); - // path5.moveTo(220.0, 300.0); - // path5.cubicTo(366.5, 487.3, 256.4, 489.9, 410.0, 280.0); - // expect( - // path5.getBounds(), - // within( - // distance: 0.1, from: Rect.fromLTRB(220.0, 280.0, 410.0, 439.0))); + // control points inverted below + final Path path5 = Path(); + path5.moveTo(220.0, 300.0); + path5.cubicTo(366.5, 487.3, 256.4, 489.9, 410.0, 280.0); + expect( + path5.getBounds(), + within( + distance: 0.1, + from: const Rect.fromLTRB(220.0, 280.0, 410.0, 439.0))); - // // control points inverted below wide - // final Path path6 = new Path(); - // path6.moveTo(220.0, 300.0); - // path6.cubicTo(496.1, 485.5, 121.4, 491.6, 410.0, 280.0); - // expect( - // path6.getBounds(), - // within( - // distance: 0.1, from: Rect.fromLTRB(220.0, 280.0, 410.0, 439.0))); + // control points inverted below wide + final Path path6 = Path(); + path6.moveTo(220.0, 300.0); + path6.cubicTo(496.1, 485.5, 121.4, 491.6, 410.0, 280.0); + expect( + path6.getBounds(), + within( + distance: 0.1, + from: const Rect.fromLTRB(220.0, 280.0, 410.0, 439.0))); - // // control point 2 and end point swapped - // final Path path7 = new Path(); - // path7.moveTo(220.0, 300.0); - // path7.cubicTo(230.0, 120.0, 394.5, 296.1, 382.3, 124.1); - // expect( - // path7.getBounds(), - // within( - // distance: 0.1, from: Rect.fromLTRB(220.0, 124.1, 382.9, 300.0))); - // }); + // control point 2 and end point swapped + final Path path7 = Path(); + path7.moveTo(220.0, 300.0); + path7.cubicTo(230.0, 120.0, 394.5, 296.1, 382.3, 124.1); + expect( + path7.getBounds(), + within( + distance: 0.1, + from: const Rect.fromLTRB(220.0, 124.1, 382.9, 300.0))); + }); } diff --git a/engine/src/flutter/lib/web_ui/test/rect_test.dart b/engine/src/flutter/lib/web_ui/test/rect_test.dart new file mode 100644 index 0000000000..8ce8cda2ed --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/rect_test.dart @@ -0,0 +1,82 @@ +// 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'; + +import 'package:test/test.dart'; + +void main() { + test('rect accessors', () { + const Rect r = Rect.fromLTRB(1.0, 3.0, 5.0, 7.0); + expect(r.left, equals(1.0)); + expect(r.top, equals(3.0)); + expect(r.right, equals(5.0)); + expect(r.bottom, equals(7.0)); + }); + + test('rect created by width and height', () { + const Rect r = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0); + expect(r.left, equals(1.0)); + expect(r.top, equals(3.0)); + expect(r.right, equals(6.0)); + expect(r.bottom, equals(10.0)); + expect(r.shortestSide, equals(5.0)); + expect(r.longestSide, equals(7.0)); + }); + + test('rect intersection', () { + const Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0); + const Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0); + final Rect r3 = r1.intersect(r2); + expect(r3.left, equals(50.0)); + expect(r3.top, equals(50.0)); + expect(r3.right, equals(100.0)); + expect(r3.bottom, equals(100.0)); + final Rect r4 = r2.intersect(r1); + expect(r4, equals(r3)); + }); + + test('rect expandToInclude overlapping rects', () { + const Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0); + const Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0); + final Rect r3 = r1.expandToInclude(r2); + expect(r3.left, equals(0.0)); + expect(r3.top, equals(0.0)); + expect(r3.right, equals(200.0)); + expect(r3.bottom, equals(200.0)); + final Rect r4 = r2.expandToInclude(r1); + expect(r4, equals(r3)); + }); + + test('rect expandToInclude crossing rects', () { + const Rect r1 = Rect.fromLTRB(50.0, 0.0, 50.0, 200.0); + const Rect r2 = Rect.fromLTRB(0.0, 50.0, 200.0, 50.0); + final Rect r3 = r1.expandToInclude(r2); + expect(r3.left, equals(0.0)); + expect(r3.top, equals(0.0)); + expect(r3.right, equals(200.0)); + expect(r3.bottom, equals(200.0)); + final Rect r4 = r2.expandToInclude(r1); + expect(r4, equals(r3)); + }); + + test('size created from doubles', () { + const Size size = Size(5.0, 7.0); + expect(size.width, equals(5.0)); + expect(size.height, equals(7.0)); + expect(size.shortestSide, equals(5.0)); + expect(size.longestSide, equals(7.0)); + }); + + test('rounded rect created from rect and radii', () { + const Rect baseRect = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0); + final RRect r = RRect.fromRectXY(baseRect, 1.0, 1.0); + expect(r.left, equals(1.0)); + expect(r.top, equals(3.0)); + expect(r.right, equals(6.0)); + expect(r.bottom, equals(10.0)); + expect(r.shortestSide, equals(5.0)); + expect(r.longestSide, equals(7.0)); + }); +} diff --git a/engine/src/flutter/lib/web_ui/test/rrect_test.dart b/engine/src/flutter/lib/web_ui/test/rrect_test.dart new file mode 100644 index 0000000000..857af2c7eb --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/rrect_test.dart @@ -0,0 +1,45 @@ +// 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'; + +import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; + +void main() { + test('RRect.contains()', () { + final RRect rrect = RRect.fromRectAndCorners( + const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + topLeft: const Radius.circular(0.5), + topRight: const Radius.circular(0.25), + bottomRight: const Radius.elliptical(0.25, 0.75), + bottomLeft: Radius.zero); + + expect(rrect.contains(const Offset(1.0, 1.0)), isFalse); + expect(rrect.contains(const Offset(1.1, 1.1)), isFalse); + expect(rrect.contains(const Offset(1.15, 1.15)), isTrue); + expect(rrect.contains(const Offset(2.0, 1.0)), isFalse); + expect(rrect.contains(const Offset(1.93, 1.07)), isFalse); + expect(rrect.contains(const Offset(1.97, 1.7)), isFalse); + expect(rrect.contains(const Offset(1.7, 1.97)), isTrue); + expect(rrect.contains(const Offset(1.0, 1.99)), isTrue); + }); + + test('RRect.contains() large radii', () { + final RRect rrect = RRect.fromRectAndCorners( + const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + topLeft: const Radius.circular(5000.0), + topRight: const Radius.circular(2500.0), + bottomRight: const Radius.elliptical(2500.0, 7500.0), + bottomLeft: Radius.zero); + + expect(rrect.contains(const Offset(1.0, 1.0)), isFalse); + expect(rrect.contains(const Offset(1.1, 1.1)), isFalse); + expect(rrect.contains(const Offset(1.15, 1.15)), isTrue); + expect(rrect.contains(const Offset(2.0, 1.0)), isFalse); + expect(rrect.contains(const Offset(1.93, 1.07)), isFalse); + expect(rrect.contains(const Offset(1.97, 1.7)), isFalse); + expect(rrect.contains(const Offset(1.7, 1.97)), isTrue); + expect(rrect.contains(const Offset(1.0, 1.99)), isTrue); + }); +} diff --git a/engine/src/flutter/lib/web_ui/test/text/measurement_test.dart b/engine/src/flutter/lib/web_ui/test/text/measurement_test.dart index e787dca108..0b448a14bf 100644 --- a/engine/src/flutter/lib/web_ui/test/text/measurement_test.dart +++ b/engine/src/flutter/lib/web_ui/test/text/measurement_test.dart @@ -4,6 +4,7 @@ import 'package:ui/ui.dart' as ui; import 'package:ui/src/engine.dart'; + import 'package:test/test.dart'; final ui.ParagraphStyle ahemStyle = ui.ParagraphStyle( @@ -14,8 +15,12 @@ const ui.ParagraphConstraints constraints = ui.ParagraphConstraints(width: 50); const ui.ParagraphConstraints infiniteConstraints = ui.ParagraphConstraints(width: double.infinity); -ui.Paragraph build(ui.ParagraphStyle style, String text) { - var builder = ui.ParagraphBuilder(style); +ui.Paragraph build(ui.ParagraphStyle style, String text, + {ui.TextStyle textStyle}) { + final ui.ParagraphBuilder builder = ui.ParagraphBuilder(style); + if (textStyle != null) { + builder.pushStyle(textStyle); + } builder.addText(text); return builder.build(); } @@ -35,17 +40,19 @@ void testMeasurements(String description, MeasurementTestBody body) { ); } -void main() { +void main() async { + await ui.webOnlyInitializeTestDomRenderer(); + group('$RulerManager', () { - ui.ParagraphStyle s1 = ui.ParagraphStyle(fontFamily: 'sans-serif'); - ui.ParagraphStyle s2 = ui.ParagraphStyle( + final ui.ParagraphStyle s1 = ui.ParagraphStyle(fontFamily: 'sans-serif'); + final ui.ParagraphStyle s2 = ui.ParagraphStyle( fontWeight: ui.FontWeight.bold, ); - ui.ParagraphStyle s3 = ui.ParagraphStyle(fontSize: 22.0); + final ui.ParagraphStyle s3 = ui.ParagraphStyle(fontSize: 22.0); ParagraphGeometricStyle style1, style2, style3; - ui.Paragraph style1Text1, style1Text2; // two paragraphs sharing style - ui.Paragraph style2Text1, style3Text3; + EngineParagraph style1Text1, style1Text2; // two paragraphs sharing style + EngineParagraph style2Text1, style3Text3; setUp(() { style1Text1 = build(s1, '1'); @@ -53,12 +60,11 @@ void main() { style2Text1 = build(s2, '1'); style3Text3 = build(s3, '3'); - style1 = style1Text1.webOnlyGetParagraphGeometricStyle(); - style2 = style2Text1.webOnlyGetParagraphGeometricStyle(); - style3 = style3Text3.webOnlyGetParagraphGeometricStyle(); + style1 = style1Text1.geometricStyle; + style2 = style2Text1.geometricStyle; + style3 = style3Text3.geometricStyle; - ParagraphGeometricStyle style1_2 = - style1Text2.webOnlyGetParagraphGeometricStyle(); + final ParagraphGeometricStyle style1_2 = style1Text2.geometricStyle; expect(style1_2, style1); // styles must be equal despite different text }); @@ -149,6 +155,7 @@ void main() { expect(result.maxIntrinsicWidth, 60); expect(result.minIntrinsicWidth, 30); expect(result.height, 10); + expectLines(instance, result, [' abc']); // trailing whitespaces text = build(ahemStyle, 'abc '); @@ -156,6 +163,7 @@ void main() { expect(result.maxIntrinsicWidth, 60); expect(result.minIntrinsicWidth, 30); expect(result.height, 10); + expectLines(instance, result, ['abc ']); // mixed whitespaces text = build(ahemStyle, ' ab c '); @@ -163,6 +171,7 @@ void main() { expect(result.maxIntrinsicWidth, 100); expect(result.minIntrinsicWidth, 20); expect(result.height, 10); + expectLines(instance, result, [' ab c ']); // single whitespace text = build(ahemStyle, ' '); @@ -170,6 +179,7 @@ void main() { expect(result.maxIntrinsicWidth, 10); expect(result.minIntrinsicWidth, 0); expect(result.height, 10); + expectLines(instance, result, [' ']); // whitespace only text = build(ahemStyle, ' '); @@ -177,6 +187,7 @@ void main() { expect(result.maxIntrinsicWidth, 50); expect(result.minIntrinsicWidth, 0); expect(result.height, 10); + expectLines(instance, result, [' ']); }, ); @@ -192,21 +203,84 @@ void main() { expect(result.minIntrinsicWidth, 50); expect(result.width, 50); expect(result.height, 10); + expectLines(instance, result, ['12345']); + }, + ); + + testMeasurements( + 'simple multi-line text', + (TextMeasurementService instance) { + const ui.ParagraphConstraints constraints = + ui.ParagraphConstraints(width: 70); + MeasurementResult result; + + // The long text doesn't fit in 50px of width, so it needs to wrap. + result = instance.measure(build(ahemStyle, 'foo bar baz'), constraints); + expect(result.isSingleLine, false); + expect(result.maxIntrinsicWidth, 110); + expect(result.minIntrinsicWidth, 30); + expect(result.width, 70); + expect(result.height, 20); + expectLines(instance, result, ['foo bar ', 'baz']); }, ); testMeasurements( 'uses multi-line for long text', (TextMeasurementService instance) { - final MeasurementResult result = - instance.measure(build(ahemStyle, '1234567890'), constraints); + MeasurementResult result; // The long text doesn't fit in 50px of width, so it needs to wrap. + result = instance.measure(build(ahemStyle, '1234567890'), constraints); expect(result.isSingleLine, false); expect(result.maxIntrinsicWidth, 100); expect(result.minIntrinsicWidth, 100); expect(result.width, 50); expect(result.height, 20); + expectLines(instance, result, ['12345', '67890']); + + // The first word is force-broken twice. + result = + instance.measure(build(ahemStyle, 'abcdefghijk lm'), constraints); + expect(result.isSingleLine, false); + expect(result.maxIntrinsicWidth, 140); + expect(result.minIntrinsicWidth, 110); + expect(result.width, 50); + expect(result.height, 30); + expectLines(instance, result, ['abcde', 'fghij', 'k lm']); + + // Constraints aren't enough even for a single character. In this case, + // we show a minimum of one character per line. + const ui.ParagraphConstraints narrowConstraints = + ui.ParagraphConstraints(width: 8); + result = instance.measure(build(ahemStyle, 'AA'), narrowConstraints); + expect(result.isSingleLine, false); + expect(result.maxIntrinsicWidth, 20); + expect(result.minIntrinsicWidth, 20); + expect(result.width, 8); + expect(result.height, 20); + expectLines(instance, result, ['A', 'A']); + + // Extremely narrow constraints with new line in the middle. + result = instance.measure(build(ahemStyle, 'AA\nA'), narrowConstraints); + expect(result.isSingleLine, false); + expect(result.maxIntrinsicWidth, 20); + expect(result.minIntrinsicWidth, 20); + expect(result.width, 8); + // This can only be done correctly by the canvas-based implementation. + if (instance is CanvasTextMeasurementService) { + expect(result.height, 30); + } + expectLines(instance, result, ['A', 'A', 'A']); + + // Extremely narrow constraints with new line in the end. + result = instance.measure(build(ahemStyle, 'AAA\n'), narrowConstraints); + expect(result.isSingleLine, false); + expect(result.maxIntrinsicWidth, 30); + expect(result.minIntrinsicWidth, 30); + expect(result.width, 8); + expect(result.height, 40); + expectLines(instance, result, ['A', 'A', 'A', '']); }, ); @@ -222,6 +296,7 @@ void main() { expect(result.minIntrinsicWidth, 20); expect(result.width, 50); expect(result.height, 20); + expectLines(instance, result, ['12', '34']); }, ); @@ -233,68 +308,65 @@ void main() { expect(result.maxIntrinsicWidth, 40); expect(result.minIntrinsicWidth, 40); expect(result.height, 30); + expectLines(instance, result, ['', '', '1234']); // Empty lines in the middle. result = instance.measure(build(ahemStyle, '12\n\n345'), constraints); expect(result.maxIntrinsicWidth, 30); expect(result.minIntrinsicWidth, 30); expect(result.height, 30); + expectLines(instance, result, ['12', '', '345']); - // This can only be done correctly in the canvas-based implementation. + // Empty lines in the end. + result = instance.measure(build(ahemStyle, '1234\n\n'), constraints); + expect(result.maxIntrinsicWidth, 40); + expect(result.minIntrinsicWidth, 40); if (instance is CanvasTextMeasurementService) { - // Empty lines in the end. - result = instance.measure(build(ahemStyle, '1234\n\n'), constraints); - expect(result.maxIntrinsicWidth, 40); - expect(result.minIntrinsicWidth, 40); + // This can only be done correctly in the canvas-based implementation. expect(result.height, 30); + expectLines(instance, result, ['1234', '', '']); } }); - test('takes letter spacing into account', () { - final constraints = ui.ParagraphConstraints(width: 100); + testMeasurements( + 'takes letter spacing into account', + (TextMeasurementService instance) { + const ui.ParagraphConstraints constraints = + ui.ParagraphConstraints(width: 100); + final ui.TextStyle spacedTextStyle = ui.TextStyle(letterSpacing: 3); + final ui.Paragraph spacedText = + build(ahemStyle, 'abc', textStyle: spacedTextStyle); - final normalBuilder = ui.ParagraphBuilder(ahemStyle); - normalBuilder.addText('abc'); - final normalText = normalBuilder.build(); + final MeasurementResult spacedResult = + instance.measure(spacedText, constraints); - final spacedBuilder = ui.ParagraphBuilder(ahemStyle); - spacedBuilder.pushStyle(ui.TextStyle(letterSpacing: 1.5)); - spacedBuilder.addText('abc'); - final spacedText = spacedBuilder.build(); - - // Letter spacing is only supported via DOM measurement. - final TextMeasurementService instance = - TextMeasurementService.forParagraph(spacedText); - expect(instance, isInstanceOf()); - - final normalResult = instance.measure(normalText, constraints); - final spacedResult = instance.measure(spacedText, constraints); - - expect( - normalResult.maxIntrinsicWidth < spacedResult.maxIntrinsicWidth, - isTrue, - ); - }); + expect(spacedResult.minIntrinsicWidth, 39); + expect(spacedResult.maxIntrinsicWidth, 39); + }, + ); test('takes word spacing into account', () { - final constraints = ui.ParagraphConstraints(width: 100); + const ui.ParagraphConstraints constraints = + ui.ParagraphConstraints(width: 100); - final normalBuilder = ui.ParagraphBuilder(ahemStyle); + final ui.ParagraphBuilder normalBuilder = ui.ParagraphBuilder(ahemStyle); normalBuilder.addText('a b c'); - final normalText = normalBuilder.build(); + final ui.Paragraph normalText = normalBuilder.build(); - final spacedBuilder = ui.ParagraphBuilder(ahemStyle); + final ui.ParagraphBuilder spacedBuilder = ui.ParagraphBuilder(ahemStyle); spacedBuilder.pushStyle(ui.TextStyle(wordSpacing: 1.5)); spacedBuilder.addText('a b c'); - final spacedText = spacedBuilder.build(); + final ui.Paragraph spacedText = spacedBuilder.build(); // Word spacing is only supported via DOM measurement. final TextMeasurementService instance = TextMeasurementService.forParagraph(spacedText); - expect(instance, isInstanceOf()); + expect(instance, const TypeMatcher()); - final normalResult = instance.measure(normalText, constraints); - final spacedResult = instance.measure(spacedText, constraints); + final MeasurementResult normalResult = + instance.measure(normalText, constraints); + final MeasurementResult spacedResult = + instance.measure(spacedText, constraints); expect( normalResult.maxIntrinsicWidth < spacedResult.maxIntrinsicWidth, @@ -308,22 +380,27 @@ void main() { // Simple case. result = instance.measure(build(ahemStyle, 'abc de fghi'), constraints); expect(result.minIntrinsicWidth, 40); + expectLines(instance, result, ['abc ', 'de ', 'fghi']); // With new lines. result = instance.measure(build(ahemStyle, 'abcd\nef\nghi'), constraints); expect(result.minIntrinsicWidth, 40); + expectLines(instance, result, ['abcd', 'ef', 'ghi']); // With trailing whitespace. result = instance.measure(build(ahemStyle, 'abcd efg'), constraints); expect(result.minIntrinsicWidth, 40); + expectLines(instance, result, ['abcd ', 'efg']); // With trailing whitespace and new lines. result = instance.measure(build(ahemStyle, 'abc \ndefg'), constraints); expect(result.minIntrinsicWidth, 40); + expectLines(instance, result, ['abc ', 'defg']); // Very long text. result = instance.measure(build(ahemStyle, 'AAAAAAAAAAAA'), constraints); expect(result.minIntrinsicWidth, 120); + expectLines(instance, result, ['AAAAA', 'AAAAA', 'AA']); }); testMeasurements('maxIntrinsicWidth', (TextMeasurementService instance) { @@ -332,80 +409,93 @@ void main() { // Simple case. result = instance.measure(build(ahemStyle, 'abc de fghi'), constraints); expect(result.maxIntrinsicWidth, 110); + expectLines(instance, result, ['abc ', 'de ', 'fghi']); // With new lines. result = instance.measure(build(ahemStyle, 'abcd\nef\nghi'), constraints); expect(result.maxIntrinsicWidth, 40); + expectLines(instance, result, ['abcd', 'ef', 'ghi']); // With long whitespace. result = instance.measure(build(ahemStyle, 'abcd efg'), constraints); expect(result.maxIntrinsicWidth, 100); + expectLines(instance, result, ['abcd ', 'efg']); // With trailing whitespace. result = instance.measure(build(ahemStyle, 'abc def '), constraints); expect(result.maxIntrinsicWidth, 100); + expectLines(instance, result, ['abc ', 'def ']); // With trailing whitespace and new lines. result = instance.measure(build(ahemStyle, 'abc \ndef '), constraints); expect(result.maxIntrinsicWidth, 60); + expectLines(instance, result, ['abc ', 'def ']); // Very long text. result = instance.measure(build(ahemStyle, 'AAAAAAAAAAAA'), constraints); expect(result.maxIntrinsicWidth, 120); + expectLines(instance, result, ['AAAAA', 'AAAAA', 'AA']); }); - // TODO(mdebbar): The canvas-based measurement doesn't handle this yet. - test('respects text overflow', () { - final TextMeasurementService instance = - TextMeasurementService.domInstance; + testMeasurements( + 'respects text overflow', + (TextMeasurementService instance) { + final ui.ParagraphStyle overflowStyle = ui.ParagraphStyle( + fontFamily: 'ahem', + fontSize: 10, + ellipsis: '...', + ); - final overflowStyle = ui.ParagraphStyle( - fontFamily: 'ahem', - fontSize: 10, - ellipsis: '...', - ); + MeasurementResult result; - final constraints = ui.ParagraphConstraints(width: 50); + // The text shouldn't be broken into multiple lines, so the height should + // be equal to a height of a single line. + final ui.Paragraph longText = build( + overflowStyle, + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', + ); + result = instance.measure(longText, constraints); + expect(result.minIntrinsicWidth, 480); + expect(result.maxIntrinsicWidth, 480); + expect(result.height, 10); + expectLines(instance, result, ['AA...']); - MeasurementResult result; + // The short prefix should make the text break into two lines, but the + // second line should remain unbroken. + final ui.Paragraph longTextShortPrefix = build( + overflowStyle, + 'AAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', + ); + result = instance.measure(longTextShortPrefix, constraints); + expect(result.minIntrinsicWidth, 450); + expect(result.maxIntrinsicWidth, 450); + expect(result.height, 20); + expectLines(instance, result, ['AAA', 'AA...']); - // The text shouldn't be broken into multiple lines, so the height should - // be equal to a height of a single line. - final longText = build( - overflowStyle, - 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', - ); - result = instance.measure(longText, constraints); - expect(result.height, 10); + // Tiny constraints. + const ui.ParagraphConstraints tinyConstraints = + ui.ParagraphConstraints(width: 30); + final ui.Paragraph text = build(overflowStyle, 'AAAA'); + result = instance.measure(text, tinyConstraints); + expect(result.minIntrinsicWidth, 40); + expect(result.maxIntrinsicWidth, 40); + expect(result.height, 10); + expectLines(instance, result, ['...']); - // The short prefix should make the text break into two lines, but the - // second line should remain unbroken. - final longTextShortPrefix = build( - overflowStyle, - 'AAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', - ); - result = instance.measure(longTextShortPrefix, constraints); - expect(result.height, 20); + // Tinier constraints (not enough for the ellipsis). + const ui.ParagraphConstraints tinierConstraints = + ui.ParagraphConstraints(width: 10); + result = instance.measure(text, tinierConstraints); + expect(result.minIntrinsicWidth, 40); + expect(result.maxIntrinsicWidth, 40); + expect(result.height, 10); + // TODO(flutter_web): https://github.com/flutter/flutter/issues/34346 + // expectLines(instance, result, ['.']); + }, + ); - // This can only be done correctly in the canvas-based implementation. - // TODO(flutter_web): https://github.com/flutter/flutter/issues/33223 - // The first line is overflowing so we should stop the measurement there - // and there should be no second line (the short suffix shouldn't be rendered). - // final longTextShortSuffix = build( - // overflowStyle, - // 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAA', - // ); - // result = instance.measure(longTextShortSuffix, constraints); - // expect(result.height, 10); - }); - - // TODO(mdebbar): The canvas-based measurement doesn't handle this yet. - // https://github.com/flutter/flutter/issues/33223 - test('respects max lines', () { - final TextMeasurementService instance = - TextMeasurementService.domInstance; - - final maxlinesStyle = ui.ParagraphStyle( + testMeasurements('respects max lines', (TextMeasurementService instance) { + final ui.ParagraphStyle maxlinesStyle = ui.ParagraphStyle( fontFamily: 'ahem', fontSize: 10, maxLines: 2, @@ -414,28 +504,130 @@ void main() { MeasurementResult result; // The height should be that of a single line. - final oneline = build(maxlinesStyle, 'One line'); + final ui.Paragraph oneline = build(maxlinesStyle, 'One line'); result = instance.measure(oneline, infiniteConstraints); expect(result.height, 10); + expectLines(instance, result, ['One line']); - // This can only be done correctly in the canvas-based implementation. - // TODO(mdebbar): https://github.com/flutter/flutter/issues/33223 // The height should respect max lines and be limited to two lines here. - // final threelines = build(maxlinesStyle, 'First\nSecond\nThird'); - // result = instance.measure(threelines, infiniteConstraints); - // expect(result.height, 20); + final ui.Paragraph threelines = + build(maxlinesStyle, 'First\nSecond\nThird'); + result = instance.measure(threelines, infiniteConstraints); + expect(result.height, 20); + expectLines(instance, result, ['First', 'Second']); + + // The height should respect max lines and be limited to two lines here. + final ui.Paragraph veryLong = build( + maxlinesStyle, + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', + ); + result = instance.measure(veryLong, constraints); + expect(result.height, 20); + expectLines(instance, result, ['Lorem ', 'ipsum ']); + + // Case when last line is a long unbreakable word. + final ui.Paragraph veryLongLastLine = build( + maxlinesStyle, + 'AAA AAAAAAAAAAAAAAAAAAA', + ); + result = instance.measure(veryLongLastLine, constraints); + expect(result.height, 20); + expectLines(instance, result, ['AAA ', 'AAAAA']); }); - test('canvas line breaks', () { - // TODO(mdebbar): Add tests and make sure to cover the following edge cases: - // 1. First chunk already overflows the width constraint. - // 2. maxIntrinsicWidth in the presence of mandatory line breaks. - // 3. minIntrinsicWidth in the presence of optional line breaks. - // 4. empty lines in the middle. - // 5. long text with a short prefix. - // 6. long text with a short suffix. - // 7. whitespace at end of line (shouldn't count towards minIntWidth, but counts towards max). - // 8. long whitespace should still cause line break if not enough space for it. - }); + testMeasurements( + 'respects text overflow and max lines combined', + (TextMeasurementService instance) { + const ui.ParagraphConstraints constraints = + ui.ParagraphConstraints(width: 60); + final ui.ParagraphStyle onelineStyle = ui.ParagraphStyle( + fontFamily: 'ahem', + fontSize: 10, + maxLines: 1, + ellipsis: '...', + ); + final ui.ParagraphStyle multilineStyle = ui.ParagraphStyle( + fontFamily: 'ahem', + fontSize: 10, + maxLines: 2, + ellipsis: '...', + ); + + ui.Paragraph p; + MeasurementResult result; + + // Simple no overflow case. + p = build(onelineStyle, 'abcdef'); + result = instance.measure(p, constraints); + expect(result.height, 10); + expectLines(instance, result, ['abcdef']); + + // Simple overflow case. + p = build(onelineStyle, 'abcd efg'); + result = instance.measure(p, constraints); + expect(result.height, 10); + expectLines(instance, result, ['abc...']); + + // Another simple overflow case. + p = build(onelineStyle, 'a bcde fgh'); + result = instance.measure(p, constraints); + expect(result.height, 10); + expectLines(instance, result, ['a b...']); + + // The ellipsis is supposed to go on the second line, but because the + // 2nd line doesn't overflow, no ellipsis is shown. + p = build(multilineStyle, 'abcdef ghijkl'); + result = instance.measure(p, constraints); + // This can only be done correctly in the canvas-based implementation. + if (instance is CanvasTextMeasurementService) { + expect(result.height, 20); + } + expectLines(instance, result, ['abcdef ', 'ghijkl']); + + // But when the 2nd line is long enough, the ellipsis is shown. + p = build(multilineStyle, 'abcd efghijkl'); + result = instance.measure(p, constraints); + // This can only be done correctly in the canvas-based implementation. + if (instance is CanvasTextMeasurementService) { + expect(result.height, 20); + } + expectLines(instance, result, ['abcd ', 'efg...']); + + // Even if the second line can be broken, we don't break it, we just + // insert the ellipsis. + p = build(multilineStyle, 'abcde f gh ijk'); + result = instance.measure(p, constraints); + // This can only be done correctly in the canvas-based implementation. + if (instance is CanvasTextMeasurementService) { + expect(result.height, 20); + } + expectLines(instance, result, ['abcde ', 'f g...']); + + // First line overflows but second line doesn't. + p = build(multilineStyle, 'abcdefg hijk'); + result = instance.measure(p, constraints); + // This can only be done correctly in the canvas-based implementation. + if (instance is CanvasTextMeasurementService) { + expect(result.height, 20); + } + expectLines(instance, result, ['abcdef', 'g hijk']); + + // Both first and second lines overflow. + p = build(multilineStyle, 'abcdefg hijklmnop'); + result = instance.measure(p, constraints); + // This can only be done correctly in the canvas-based implementation. + if (instance is CanvasTextMeasurementService) { + expect(result.height, 20); + } + expectLines(instance, result, ['abcdef', 'g h...']); + }, + ); }); } + +void expectLines(TextMeasurementService instance, MeasurementResult result, + List lines) { + if (instance is CanvasTextMeasurementService) { + expect(result.lines, lines); + } +} diff --git a/engine/src/flutter/lib/web_ui/test/text/word_breaker_test.dart b/engine/src/flutter/lib/web_ui/test/text/word_breaker_test.dart index a31b4f174c..9bf9253990 100644 --- a/engine/src/flutter/lib/web_ui/test/text/word_breaker_test.dart +++ b/engine/src/flutter/lib/web_ui/test/text/word_breaker_test.dart @@ -14,14 +14,14 @@ void main() { }); test('Words and spaces', () { - expectWords('foo bar', ['foo', ' ', 'bar']); - expectWords('foo bar', ['foo', ' ', 'bar']); + expectWords('foo bar', ['foo', ' ', 'bar']); + expectWords('foo bar', ['foo', ' ', 'bar']); }); test('Single-letter words', () { - expectWords('foo a bar', ['foo', ' ', 'a', ' ', 'bar']); - expectWords('a b c', ['a', ' ', 'b', ' ', 'c']); - expectWords(' a b ', [' ', 'a', ' ', 'b', ' ']); + expectWords('foo a bar', ['foo', ' ', 'a', ' ', 'bar']); + expectWords('a b c', ['a', ' ', 'b', ' ', 'c']); + expectWords(' a b ', [' ', 'a', ' ', 'b', ' ']); }); test('Multiple consecutive spaces', () { @@ -31,41 +31,41 @@ void main() { final String mathSpace = String.fromCharCode(0x205F); final String ideographicSpace = String.fromCharCode(0x3000); expectWords( - 'foo${oghamSpace} ${punctuationSpace}bar', - ['foo', '${oghamSpace} ${punctuationSpace}', 'bar'], + 'foo$oghamSpace ${punctuationSpace}bar', + ['foo', '$oghamSpace $punctuationSpace', 'bar'], ); expectWords( - '${mathSpace}${ideographicSpace}${oghamSpace}foo', - ['${mathSpace}${ideographicSpace}${oghamSpace}', 'foo'], + '$mathSpace$ideographicSpace${oghamSpace}foo', + ['$mathSpace$ideographicSpace$oghamSpace', 'foo'], ); expectWords( - 'foo${punctuationSpace}${mathSpace} ', - ['foo', '${punctuationSpace}${mathSpace} '], + 'foo$punctuationSpace$mathSpace ', + ['foo', '$punctuationSpace$mathSpace '], ); expectWords( - '${oghamSpace} ${punctuationSpace}${mathSpace}${ideographicSpace}', - ['${oghamSpace} ${punctuationSpace}${mathSpace}${ideographicSpace}'], + '$oghamSpace $punctuationSpace$mathSpace$ideographicSpace', + ['$oghamSpace $punctuationSpace$mathSpace$ideographicSpace'], ); }); test('Punctuation', () { - expectWords('foo,bar.baz', ['foo', ',', 'bar.baz']); - expectWords('foo_bar', ['foo_bar']); - expectWords('foo-bar', ['foo', '-', 'bar']); + expectWords('foo,bar.baz', ['foo', ',', 'bar.baz']); + expectWords('foo_bar', ['foo_bar']); + expectWords('foo-bar', ['foo', '-', 'bar']); }); test('Numeric', () { - expectWords('12ab ab12', ['12ab', ' ', 'ab12']); - expectWords('ab12,34cd', ['ab12,34cd']); - expectWords('123,456_789.0', ['123,456_789.0']); + expectWords('12ab ab12', ['12ab', ' ', 'ab12']); + expectWords('ab12,34cd', ['ab12,34cd']); + expectWords('123,456_789.0', ['123,456_789.0']); }); test('Quotes', () { - expectWords("Mike's bike", ["Mike's", ' ', 'bike']); - expectWords("Students' grades", ['Students', "'", ' ', 'grades']); + expectWords("Mike's bike", ["Mike's", ' ', 'bike']); + expectWords("Students' grades", ['Students', "'", ' ', 'grades']); expectWords( 'Joe said: "I\'m here"', - ['Joe', ' ', 'said', ':', ' ', '"', "I\'m", ' ', 'here', '"'], + ['Joe', ' ', 'said', ':', ' ', '"', "I\'m", ' ', 'here', '"'], ); }); @@ -73,55 +73,55 @@ void main() { // when they are around quotes. So we need to test those rules separately. test('Hebrew with quotes', () { // A few hebrew letters: - final String h1 = 'א'; - final String h2 = 'ל'; - final String h3 = 'ט'; + 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", ["$h1$h2'$h3"]); + expectWords("$h1$h2'$h3", ["$h1$h2'$h3"]); // Single quote following a hebrew shouldn't break. - expectWords("$h1$h2'", ["$h1$h2'"]); - expectWords("$h1$h2' $h3", ["$h1$h2'", ' ', h3]); + expectWords("$h1$h2'", ["$h1$h2'"]); + expectWords("$h1$h2' $h3", ["$h1$h2'", ' ', h3]); // Double quotes around hebrew words should break. - expectWords('"$h1$h3"', ['"', '$h1$h3', '"']); + expectWords('"$h1$h3"', ['"', '$h1$h3', '"']); // Double quotes within hebrew words shouldn't break. - expectWords('$h3"$h2', ['$h3"$h2']); + expectWords('$h3"$h2', ['$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', ['foo', '\r\n', 'bar']); + expectWords('foo\r\nbar', ['foo', '\r\n', 'bar']); // All other sequences are considered word boundaries. - expectWords('foo\n\nbar', ['foo', '\n', '\n', 'bar']); - expectWords('foo\r\rbar', ['foo', '\r', '\r', 'bar']); + expectWords('foo\n\nbar', ['foo', '\n', '\n', 'bar']); + expectWords('foo\r\rbar', ['foo', '\r', '\r', 'bar']); expectWords( - 'foo${newline}${newline}bar', ['foo', newline, newline, 'bar']); + 'foo$newline${newline}bar', ['foo', newline, newline, 'bar']); - expectWords('foo\n\rbar', ['foo', '\n', '\r', 'bar']); - expectWords('foo${newline}\rbar', ['foo', newline, '\r', 'bar']); - expectWords('foo\r${newline}bar', ['foo', '\r', newline, 'bar']); - expectWords('foo${newline}\nbar', ['foo', newline, '\n', 'bar']); - expectWords('foo\n${newline}bar', ['foo', '\n', newline, 'bar']); + expectWords('foo\n\rbar', ['foo', '\n', '\r', 'bar']); + expectWords('foo$newline\rbar', ['foo', newline, '\r', 'bar']); + expectWords('foo\r${newline}bar', ['foo', '\r', newline, 'bar']); + expectWords('foo$newline\nbar', ['foo', newline, '\n', 'bar']); + expectWords('foo\n${newline}bar', ['foo', '\n', newline, 'bar']); }); test('katakana', () { // Katakana letters should stick together but not with other letters. - expectWords('ナヌ', ['ナヌ']); - expectWords('ナabcヌ', ['ナ', 'abc', 'ヌ']); + expectWords('ナヌ', ['ナヌ']); + expectWords('ナabcヌ', ['ナ', 'abc', 'ヌ']); // Katakana sometimes behaves the same as other letters. - expectWords('ナ,ヌ_イ', ['ナ', ',', 'ヌ_イ']); + expectWords('ナ,ヌ_イ', ['ナ', ',', 'ヌ_イ']); // Katakana sometimes behaves differently from other letters. - expectWords('ナ.ヌ', ['ナ', '.', 'ヌ']); - expectWords("ナ'ヌ", ['ナ', "'", 'ヌ']); - expectWords('ナ12ヌ', ['ナ', '12', 'ヌ']); + expectWords('ナ.ヌ', ['ナ', '.', 'ヌ']); + expectWords("ナ'ヌ", ['ナ', "'", 'ヌ']); + expectWords('ナ12ヌ', ['ナ', '12', 'ヌ']); }); }); } @@ -131,7 +131,7 @@ void expectWords(String text, List expectedWords) { // Forward word break lookup. for (String word in expectedWords) { - int nextBreak = WordBreaker.nextBreakIndex(text, strIndex); + final int nextBreak = WordBreaker.nextBreakIndex(text, strIndex); expect(nextBreak, strIndex + word.length); strIndex += word.length; } @@ -139,7 +139,7 @@ void expectWords(String text, List expectedWords) { // Backward word break lookup. strIndex = text.length; for (String word in expectedWords.reversed) { - int prevBreak = WordBreaker.prevBreakIndex(text, strIndex); + final int prevBreak = WordBreaker.prevBreakIndex(text, strIndex); expect(prevBreak, strIndex - word.length); strIndex -= word.length; } diff --git a/engine/src/flutter/lib/web_ui/test/text_editing_test.dart b/engine/src/flutter/lib/web_ui/test/text_editing_test.dart new file mode 100644 index 0000000000..acadba679e --- /dev/null +++ b/engine/src/flutter/lib/web_ui/test/text_editing_test.dart @@ -0,0 +1,589 @@ +// 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:html'; +import 'dart:typed_data'; + +import 'package:ui/ui.dart' as ui; +import 'package:ui/src/engine.dart'; + +import 'package:test/test.dart'; + +import 'matchers.dart'; + +const MethodCodec codec = JSONMethodCodec(); + +TextEditingElement editingElement; +EditingState lastEditingState; + +final InputConfiguration singlelineConfig = + InputConfiguration(inputType: InputType.text); +final Map flutterSinglelineConfig = { + 'inputType': { + 'name': 'TextInputType.text', + }, + 'obscureText': false, +}; + +final InputConfiguration multilineConfig = + InputConfiguration(inputType: InputType.multiline); +final Map flutterMultilineConfig = { + 'inputType': { + 'name': 'TextInputType.multiline', + }, + 'obscureText': false, +}; + +void trackEditingState(EditingState editingState) { + lastEditingState = editingState; +} + +void main() { + group('$TextEditingElement', () { + setUp(() { + editingElement = TextEditingElement(); + }); + + tearDown(() { + try { + editingElement.disable(); + } catch (e) { + if (e is AssertionError) { + // This is fine. It just means the test itself disabled the editing element. + } else { + rethrow; + } + } + }); + + test('Creates element when enabled and removes it when disabled', () { + expect( + document.getElementsByTagName('input'), + hasLength(0), + ); + // The focus initially is on the body. + expect(document.activeElement, document.body); + + editingElement.enable(singlelineConfig, onChange: trackEditingState); + expect( + document.getElementsByTagName('input'), + hasLength(1), + ); + final InputElement input = document.getElementsByTagName('input')[0]; + // Now the editing element should have focus. + expect(document.activeElement, input); + expect(editingElement.domElement, input); + + editingElement.disable(); + expect( + document.getElementsByTagName('input'), + hasLength(0), + ); + // The focus is back to the body. + expect(document.activeElement, document.body); + }); + + test('Can read editing state correctly', () { + editingElement.enable(singlelineConfig, onChange: trackEditingState); + + final InputElement input = editingElement.domElement; + input.value = 'foo bar'; + input.dispatchEvent(Event.eventType('Event', 'input')); + expect( + lastEditingState, + EditingState(text: 'foo bar', baseOffset: 7, extentOffset: 7), + ); + + input.setSelectionRange(4, 6); + document.dispatchEvent(Event.eventType('Event', 'selectionchange')); + expect( + lastEditingState, + EditingState(text: 'foo bar', baseOffset: 4, extentOffset: 6), + ); + }); + + test('Can set editing state correctly', () { + editingElement.enable(singlelineConfig, onChange: trackEditingState); + editingElement.setEditingState( + EditingState(text: 'foo bar baz', baseOffset: 2, extentOffset: 7)); + + checkInputEditingState(editingElement.domElement, 'foo bar baz', 2, 7); + }); + + test('Re-acquires focus', () async { + editingElement.enable(singlelineConfig, onChange: trackEditingState); + expect(document.activeElement, editingElement.domElement); + + editingElement.domElement.blur(); + // The focus remains on [editingElement.domElement]. + expect(document.activeElement, editingElement.domElement); + }); + + test('Multi-line mode also works', () { + // The textarea element is created lazily. + expect(document.getElementsByTagName('textarea'), hasLength(0)); + editingElement.enable(multilineConfig, onChange: trackEditingState); + expect(document.getElementsByTagName('textarea'), hasLength(1)); + + final TextAreaElement textarea = + document.getElementsByTagName('textarea')[0]; + // Now the textarea should have focus. + expect(document.activeElement, textarea); + expect(editingElement.domElement, textarea); + + textarea.value = 'foo\nbar'; + textarea.dispatchEvent(Event.eventType('Event', 'input')); + textarea.setSelectionRange(4, 6); + textarea.dispatchEvent(Event.eventType('Event', 'selectionchange')); + // Can read textarea state correctly (and preserves new lines). + expect( + lastEditingState, + EditingState(text: 'foo\nbar', baseOffset: 4, extentOffset: 6), + ); + + // Can set textarea state correctly (and preserves new lines). + editingElement.setEditingState( + EditingState(text: 'bar\nbaz', baseOffset: 2, extentOffset: 7)); + checkTextAreaEditingState(textarea, 'bar\nbaz', 2, 7); + + // Re-acquires focus. + textarea.blur(); + expect(document.activeElement, textarea); + + editingElement.disable(); + // The textarea should be cleaned up. + expect(document.getElementsByTagName('textarea'), hasLength(0)); + // The focus is back to the body. + expect(document.activeElement, document.body); + }); + + test('Same instance can be re-enabled with different config', () { + // Make sure there's nothing in the DOM yet. + expect(document.getElementsByTagName('input'), hasLength(0)); + expect(document.getElementsByTagName('textarea'), hasLength(0)); + + // Use single-line config and expect an `` to be created. + editingElement.enable(singlelineConfig, onChange: trackEditingState); + expect(document.getElementsByTagName('input'), hasLength(1)); + expect(document.getElementsByTagName('textarea'), hasLength(0)); + + // Disable and check that all DOM elements were removed. + editingElement.disable(); + expect(document.getElementsByTagName('input'), hasLength(0)); + expect(document.getElementsByTagName('textarea'), hasLength(0)); + + // Use multi-line config and expect an `