diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index dc3eaef4eb..e0ada13dee 100644 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -228,97 +228,6 @@ FILE: ../../../flutter/lib/io/dart_io.cc FILE: ../../../flutter/lib/io/dart_io.h FILE: ../../../flutter/lib/snapshot/libraries.json FILE: ../../../flutter/lib/snapshot/snapshot.h -FILE: ../../../flutter/lib/stub_ui/lib/src/engine.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/alarm_clock.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/assets.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/bitmap_canvas.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/browser_detection.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/browser_location.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/canvas.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/engine_delegate.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/initialization.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/layer.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/layer_scene_builder.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/layer_tree.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/matrix.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/path.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/picture.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/picture_recorder.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/platform_message.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/raster_cache.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/rasterizer.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/recording_canvas.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/runtime_delegate.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/surface.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/compositor/viewport_metrics.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/conic.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/dom_canvas.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/dom_renderer.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/engine_canvas.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/history.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/houdini_canvas.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/html_image_codec.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/keyboard.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/onscreen_logging.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/path_to_svg.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/platform_views.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/pointer_binding.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/recording_canvas.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/semantics/accessibility.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/semantics/checkable.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/semantics/image.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/semantics/incrementable.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/semantics/label_and_value.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/semantics/live_region.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/semantics/scrollable.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/semantics/semantics.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/semantics/tappable.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/semantics/text_field.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/services/buffers.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/services/message_codec.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/services/message_codecs.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/services/serialization.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/shadow.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/surface/backdrop_filter.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/surface/clip.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/surface/debug_canvas_reuse_overlay.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/surface/offset.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/surface/opacity.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/surface/picture.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/surface/platform_view.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/surface/scene.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/surface/surface.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/surface/transform.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/test_embedding.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/text/font_collection.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/text/line_breaker.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/text/measurement.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/text/paragraph.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/text/ruler.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/text/unicode_range.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/text/word_break_properties.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/text/word_breaker.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/text_editing.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/util.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/validators.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/vector_math.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/engine/window.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/canvas.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/compositing.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/geometry.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/hash_codes.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/initialization.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/lerp.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/natives.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/painting.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/pointer.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/semantics.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/test_embedding.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/text.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/tile_mode.dart -FILE: ../../../flutter/lib/stub_ui/lib/src/ui/window.dart -FILE: ../../../flutter/lib/stub_ui/lib/ui.dart -FILE: ../../../flutter/lib/stub_ui/tool/unicode_sync_script.dart FILE: ../../../flutter/lib/ui/compositing.dart FILE: ../../../flutter/lib/ui/compositing/scene.cc FILE: ../../../flutter/lib/ui/compositing/scene.h @@ -437,6 +346,97 @@ 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/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 +FILE: ../../../flutter/lib/web_ui/lib/src/engine/bitmap_canvas.dart +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/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 +FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/platform_message.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/compositor/raster_cache.dart +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/viewport_metrics.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/conic.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/dom_canvas.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/dom_renderer.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/engine_canvas.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/history.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/houdini_canvas.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/html_image_codec.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/keyboard.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/onscreen_logging.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/path_to_svg.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/platform_views.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/pointer_binding.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/recording_canvas.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/semantics/accessibility.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/semantics/checkable.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/semantics/image.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/semantics/incrementable.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/semantics/label_and_value.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/semantics/live_region.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/semantics/scrollable.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/semantics/tappable.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart +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/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 +FILE: ../../../flutter/lib/web_ui/lib/src/engine/surface/debug_canvas_reuse_overlay.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/surface/offset.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/surface/opacity.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/surface/picture.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/surface/platform_view.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/surface/scene.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/surface/surface.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/surface/transform.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/test_embedding.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/font_collection.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/line_breaker.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/measurement.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/paragraph.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/ruler.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/unicode_range.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/word_break_properties.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/text/word_breaker.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/text_editing.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/util.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/validators.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/vector_math.dart +FILE: ../../../flutter/lib/web_ui/lib/src/engine/window.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/canvas.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/compositing.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/geometry.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/hash_codes.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/initialization.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/lerp.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/natives.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/painting.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/pointer.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/semantics.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/test_embedding.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/text.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/tile_mode.dart +FILE: ../../../flutter/lib/web_ui/lib/src/ui/window.dart +FILE: ../../../flutter/lib/web_ui/lib/ui.dart +FILE: ../../../flutter/lib/web_ui/tool/unicode_sync_script.dart FILE: ../../../flutter/runtime/dart_isolate.cc FILE: ../../../flutter/runtime/dart_isolate.h FILE: ../../../flutter/runtime/dart_isolate_unittests.cc diff --git a/engine/src/flutter/lib/web_ui/analysis_options.yaml b/engine/src/flutter/lib/web_ui/analysis_options.yaml new file mode 100644 index 0000000000..6892f49dc7 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/analysis_options.yaml @@ -0,0 +1 @@ +# Intentionally kept empty. \ No newline at end of file diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine.dart b/engine/src/flutter/lib/web_ui/lib/src/engine.dart new file mode 100644 index 0000000000..132a7c16f3 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine.dart @@ -0,0 +1,177 @@ +// 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. + +library engine; + +import 'dart:async'; +import 'dart:collection' show ListBase; +import 'dart:convert' hide Codec; +import 'dart:developer' as developer; +import 'dart:html' as html; +import 'dart:js' as js; +import 'dart:js_util' as js_util; +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:meta/meta.dart'; + +import '../ui.dart' as ui; + +part 'engine/alarm_clock.dart'; +part 'engine/assets.dart'; +part 'engine/bitmap_canvas.dart'; +part 'engine/browser_detection.dart'; +part 'engine/browser_location.dart'; +part 'engine/compositor/canvas.dart'; +part 'engine/compositor/engine_delegate.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'; +part 'engine/compositor/platform_message.dart'; +part 'engine/compositor/raster_cache.dart'; +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/viewport_metrics.dart'; +part 'engine/conic.dart'; +part 'engine/dom_canvas.dart'; +part 'engine/dom_renderer.dart'; +part 'engine/engine_canvas.dart'; +part 'engine/history.dart'; +part 'engine/houdini_canvas.dart'; +part 'engine/html_image_codec.dart'; +part 'engine/keyboard.dart'; +part 'engine/onscreen_logging.dart'; +part 'engine/path_to_svg.dart'; +part 'engine/platform_views.dart'; +part 'engine/pointer_binding.dart'; +part 'engine/recording_canvas.dart'; +part 'engine/semantics/accessibility.dart'; +part 'engine/semantics/checkable.dart'; +part 'engine/semantics/image.dart'; +part 'engine/semantics/incrementable.dart'; +part 'engine/semantics/label_and_value.dart'; +part 'engine/semantics/live_region.dart'; +part 'engine/semantics/scrollable.dart'; +part 'engine/semantics/semantics.dart'; +part 'engine/semantics/tappable.dart'; +part 'engine/semantics/text_field.dart'; +part 'engine/services/buffers.dart'; +part 'engine/services/message_codec.dart'; +part 'engine/services/message_codecs.dart'; +part 'engine/services/serialization.dart'; +part 'engine/shadow.dart'; +part 'engine/surface/backdrop_filter.dart'; +part 'engine/surface/clip.dart'; +part 'engine/surface/debug_canvas_reuse_overlay.dart'; +part 'engine/surface/offset.dart'; +part 'engine/surface/opacity.dart'; +part 'engine/surface/picture.dart'; +part 'engine/surface/platform_view.dart'; +part 'engine/surface/scene.dart'; +part 'engine/surface/surface.dart'; +part 'engine/surface/transform.dart'; +part 'engine/test_embedding.dart'; +part 'engine/text/font_collection.dart'; +part 'engine/text/line_breaker.dart'; +part 'engine/text/measurement.dart'; +part 'engine/text/paragraph.dart'; +part 'engine/text/ruler.dart'; +part 'engine/text/unicode_range.dart'; +part 'engine/text/word_break_properties.dart'; +part 'engine/text/word_breaker.dart'; +part 'engine/text_editing.dart'; +part 'engine/util.dart'; +part 'engine/validators.dart'; +part 'engine/vector_math.dart'; +part 'engine/window.dart'; + +bool _engineInitialized = false; + +final List _hotRestartListeners = []; + +/// Requests that [listener] is called just before hot restarting the app. +void registerHotRestartListener(ui.VoidCallback listener) { + _hotRestartListeners.add(listener); +} + +/// This method performs one-time initialization of the Web environment that +/// supports the Flutter framework. +/// +/// This is only available on the Web, as native Flutter configures the +/// environment in the native embedder. +// TODO(yjbanov): we should refactor the code such that the framework does not +// call this method directly. +void webOnlyInitializeEngine() { + if (_engineInitialized) { + return; + } + + // Called by the Web runtime just before hot restarting the app. + // + // This extension cleans up resources that are registered with browser's + // global singletons that Dart compiler is unable to clean-up automatically. + // + // This extension does not need to clean-up Dart statics. Those are cleaned + // up by the compiler. + developer.registerExtension('ext.flutter.disassemble', (_, __) { + for (ui.VoidCallback listener in _hotRestartListeners) { + listener(); + } + return Future.value( + developer.ServiceExtensionResponse.result('OK')); + }); + + _engineInitialized = true; + + // Calling this getter to force the DOM renderer to initialize before we + // initialize framework bindings. + domRenderer; + + bool waitingForAnimation = false; + ui.webOnlyScheduleFrameCallback = () { + // We're asked to schedule a frame and call `frameHandler` when the frame + // fires. + if (!waitingForAnimation) { + waitingForAnimation = true; + html.window.requestAnimationFrame((num highResTime) { + // Reset immediately, because `frameHandler` can schedule more frames. + waitingForAnimation = false; + + // We have to convert high-resolution time to `int` so we can construct + // a `Duration` out of it. However, high-res time is supplied in + // milliseconds as a double value, with sub-millisecond information + // hidden in the fraction. So we first multiply it by 1000 to uncover + // microsecond precision, and only then convert to `int`. + final int highResTimeMicroseconds = (1000 * highResTime).toInt(); + + if (ui.window.onBeginFrame != null) { + ui.window + .onBeginFrame(Duration(microseconds: highResTimeMicroseconds)); + } + + if (ui.window.onDrawFrame != null) { + // TODO(yjbanov): technically Flutter flushes microtasks between + // onBeginFrame and onDrawFrame. We don't, which hasn't + // been an issue yet, but eventually we'll have to + // implement it properly. + ui.window.onDrawFrame(); + } + }); + } + }; + + Keyboard.initialize(); +} + +class _NullTreeSanitizer implements html.NodeTreeSanitizer { + @override + void sanitizeTree(html.Node node) {} +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/alarm_clock.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/alarm_clock.dart new file mode 100644 index 0000000000..5ed8288ef6 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/alarm_clock.dart @@ -0,0 +1,110 @@ +// 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; + +/// A function that returns current system time. +typedef TimestampFunction = DateTime Function(); + +/// Notifies the [callback] at the given [datetime]. +/// +/// Allows changing [datetime] in either direction before the alarm goes off. +/// +/// The implementation uses [Timer]s and therefore does not guarantee that it +/// will go off precisely at the specified time. For more details see: +/// +/// https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Notes +class AlarmClock { + AlarmClock(TimestampFunction timestampFunction) + : _timestampFunction = timestampFunction; + + /// The function used to get current time. + final TimestampFunction _timestampFunction; + + /// The underlying timer used to schedule the callback. + Timer _timer; + + /// Current target time the [callback] is scheduled for. + DateTime _datetime; + + /// The callback called when the alarm goes off. + ui.VoidCallback callback; + + /// The time when the alarm clock will go off. + /// + /// If the time is in the past or is `null` the alarm clock will not go off. + /// + /// If the value is updated before an already scheduled timer goes off, the + /// previous time will not call the [callback]. Think of the updating this + /// value as "changing your mind" about when you want the next timer to fire. + DateTime get datetime => _datetime; + set datetime(DateTime value) { + if (value == _datetime) { + return; + } + + if (value == null) { + _cancelTimer(); + _datetime = null; + return; + } + + final DateTime now = _timestampFunction(); + + // We use the "not before" logic instead of "is after" because zero-duration + // timers are valid. + final bool isInTheFuture = !value.isBefore(now); + + if (!isInTheFuture) { + _cancelTimer(); + _datetime = value; + return; + } + + // At this point we have a non-null value that's in the future, and it is + // different from the current _datetime. We need to decide whether we need + // to create a new timer, or keep the existing one. + if (_timer == null) { + // We didn't have an existing timer, so create a new one. + _timer = Timer(value.difference(now), _timerDidFire); + } else { + assert(_datetime != null, + 'We can only have a timer if there is a non-null datetime'); + if (_datetime.isAfter(value)) { + // This is the case when the value moves the target time to an earlier + // point. Because there is no way to reconfigure an existing timer, we + // must cancel the old timer and schedule a new one. + _cancelTimer(); + _timer = Timer(value.difference(now), _timerDidFire); + } + // We don't need to do anything in the "else" branch. If the new value + // is in the future relative to the current datetime, the _timerDidFire + // will reschedule. + } + + _datetime = value; + } + + void _cancelTimer() { + if (_timer != null) { + _timer.cancel(); + _timer = null; + } + } + + void _timerDidFire() { + assert(_datetime != null, + 'If _datetime is null, the timer would have been cancelled'); + final DateTime now = _timestampFunction(); + // We use the "not before" logic instead of "is after" because we may have + // zero difference between now and _datetime. + if (!now.isBefore(_datetime)) { + _timer = null; + callback(); + } else { + // The timer fired before the target date. We need to reschedule. + _timer = Timer(_datetime.difference(now), _timerDidFire); + } + } +} 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 new file mode 100644 index 0000000000..3c4bf801d0 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/assets.dart @@ -0,0 +1,98 @@ +// 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; + +/// This class downloads assets over the network. +/// +/// The assets are resolved relative to [assetsDir]. +class AssetManager { + static const String _defaultAssetsDir = 'assets'; + + /// The directory containing the assets. + final String assetsDir; + + const AssetManager({this.assetsDir = _defaultAssetsDir}); + + String getAssetUrl(String asset) { + final Uri assetUri = Uri.parse(asset); + + String url; + + if (assetUri.hasScheme) { + url = asset; + } else { + url = '$assetsDir/$asset'; + } + + return url; + } + + Future load(String asset) async { + final String url = getAssetUrl(asset); + try { + final html.HttpRequest request = + await html.HttpRequest.request(url, responseType: 'arraybuffer'); + + final ByteBuffer response = request.response; + return response.asByteData(); + } on html.ProgressEvent catch (e) { + final html.EventTarget target = e.target; + if (target is html.HttpRequest) { + if (target.status == 404 && asset == 'AssetManifest.json') { + html.window.console + .warn('Asset manifest does not exist at `$url` – ignoring.'); + return Uint8List.fromList(utf8.encode('{}')).buffer.asByteData(); + } + throw AssetManagerException(url, target.status); + } + + rethrow; + } + } +} + +class AssetManagerException implements Exception { + final String url; + final int httpStatus; + + AssetManagerException(this.url, this.httpStatus); + + @override + String toString() => 'Failed to load asset at "$url" ($httpStatus)'; +} + +/// An asset manager that gives fake empty responses for assets. +class WebOnlyMockAssetManager implements AssetManager { + String defaultAssetsDir = ''; + String defaultAssetManifest = '{}'; + String defaultFontManifest = '[]'; + + @override + String get assetsDir => defaultAssetsDir; + + @override + String getAssetUrl(String asset) => '$asset'; + + @override + Future load(String asset) { + if (asset == getAssetUrl('AssetManifest.json')) { + return Future.value( + _toByteData(utf8.encode(defaultAssetManifest))); + } + if (asset == getAssetUrl('FontManifest.json')) { + return Future.value( + _toByteData(utf8.encode(defaultFontManifest))); + } + throw AssetManagerException(asset, 404); + } + + ByteData _toByteData(List bytes) { + final ByteData byteData = ByteData(bytes.length); + for (int i = 0; i < bytes.length; i++) { + byteData.setUint8(i, bytes[i]); + } + return byteData; + } +} 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 new file mode 100644 index 0000000000..94d18c199b --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/bitmap_canvas.dart @@ -0,0 +1,1087 @@ +// 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; + +/// A raw HTML canvas that is directly written to. +class BitmapCanvas extends EngineCanvas with SaveStackTracking { + /// The rectangle positioned relative to the parent layer's coordinate + /// system's origin, within which this canvas paints. + /// + /// Painting outside these bounds will result in cropping. + ui.Rect get bounds => _bounds; + set bounds(ui.Rect newValue) { + assert(newValue != null); + _bounds = newValue; + } + + ui.Rect _bounds; + + /// The amount of padding to add around the edges of this canvas to + /// ensure that anti-aliased arcs are not clipped. + static const int paddingPixels = 1; + + @override + final html.Element rootElement = html.Element.tag('flt-canvas'); + + html.CanvasElement _canvas; + html.CanvasRenderingContext2D _ctx; + + /// The size of the paint [bounds]. + ui.Size get size => _bounds.size; + + /// The last paragraph style is cached to optimize the case where the style + /// hasn't changed. + ParagraphGeometricStyle _cachedLastStyle; + + /// List of extra sibling elements created for paragraphs and clipping. + final List _children = []; + + /// The number of pixels along the width of the bitmap that the canvas element + /// renders into. + /// + /// These pixels are different from the logical CSS pixels. Here a pixel + /// literally means 1 point with a RGBA color. + int get widthInBitmapPixels => _widthInBitmapPixels; + int _widthInBitmapPixels; + + /// The number of pixels along the width of the bitmap that the canvas element + /// renders into. + /// + /// These pixels are different from the logical CSS pixels. Here a pixel + /// literally means 1 point with a RGBA color. + int get heightInBitmapPixels => _heightInBitmapPixels; + int _heightInBitmapPixels; + + /// The number of pixels in the bitmap that the canvas element renders into. + /// + /// These pixels are different from the logical CSS pixels. Here a pixel + /// literally means 1 point with a RGBA color. + int get bitmapPixelCount => widthInBitmapPixels * heightInBitmapPixels; + + int _saveCount = 0; + + /// Keeps track of what device pixel ratio was used when this [BitmapCanvas] + /// was created. + final double _devicePixelRatio = html.window.devicePixelRatio; + + // Cached current filter, fill and stroke style to reduce updates to + // CanvasRenderingContext2D that are slow even when resetting to null. + String _prevFilter = 'none'; + Object _prevFillStyle; + Object _prevStrokeStyle; + + /// Allocates a canvas with enough memory to paint a picture within the given + /// [bounds]. + /// + /// This canvas can be reused by pictures with different paint bounds as long + /// as the [Rect.size] of the bounds fully fit within the size used to + /// initialize this canvas. + BitmapCanvas(this._bounds) : assert(_bounds != null) { + rootElement.style.position = 'absolute'; + + // Adds one extra pixel to the requested size. This is to compensate for + // _initializeViewport() snapping canvas position to 1 pixel, causing + // painting to overflow by at most 1 pixel. + final double boundsWidth = size.width + 1 + 2 * paddingPixels; + final double boundsHeight = size.height + 1 + 2 * paddingPixels; + _widthInBitmapPixels = (boundsWidth * html.window.devicePixelRatio).ceil(); + _heightInBitmapPixels = + (boundsHeight * html.window.devicePixelRatio).ceil(); + + // Compute the final CSS canvas size given the actual pixel count we + // allocated. This is done for the following reasons: + // + // * To satisfy the invariant: pixel size = css size * device pixel ratio. + // * To make sure that when we scale the canvas by devicePixelRatio (see + // _initializeViewport below) the pixels line up. + final double cssWidth = _widthInBitmapPixels / html.window.devicePixelRatio; + final double cssHeight = + _heightInBitmapPixels / html.window.devicePixelRatio; + + _canvas = html.CanvasElement( + width: _widthInBitmapPixels, + height: _heightInBitmapPixels, + ); + _canvas.style + ..position = 'absolute' + ..width = '${cssWidth}px' + ..height = '${cssHeight}px'; + _ctx = _canvas.context2D; + rootElement.append(_canvas); + _initializeViewport(); + } + + @override + void dispose() { + super.dispose(); + // Webkit has a threshold for the amount of canvas pixels an app can + // allocate. Even though our canvases are being garbage-collected as + // expected when we don't need them, Webkit keeps track of their sizes + // towards the threshold. Setting width and height to zero tricks Webkit + // into thinking that this canvas has a zero size so it doesn't count it + // towards the threshold. + if (browserEngine == BrowserEngine.webkit) { + _canvas.width = _canvas.height = 0; + } + } + + /// Prepare to reuse this canvas by clearing it's current contents. + @override + void clear() { + super.clear(); + final int len = _children.length; + for (int i = 0; i < len; i++) { + _children[i].remove(); + } + _children.clear(); + _cachedLastStyle = null; + // Restore to the state where we have only applied the scaling. + if (_ctx != null) { + _ctx.restore(); + _ctx.clearRect(0, 0, _widthInBitmapPixels, _heightInBitmapPixels); + _ctx.font = ''; + _initializeViewport(); + } + if (_canvas != null) { + _canvas.style.transformOrigin = ''; + _canvas.style.transform = ''; + } + } + + /// Checks whether this [BitmapCanvas] can still be recycled and reused. + /// + /// See also: + /// + /// * [PersistedStandardPicture._applyBitmapPaint] which uses this method to + /// decide whether to reuse this canvas or not. + /// * [PersistedStandardPicture._recycleCanvas] which also uses this method + /// for the same reason. + bool isReusable() { + return _devicePixelRatio == html.window.devicePixelRatio; + } + + /// Configures the canvas such that its coordinate system follows the scene's + /// coordinate system, and the pixel ratio is applied such that CSS pixels are + /// translated to bitmap pixels. + void _initializeViewport() { + // Save the canvas state with top-level transforms so we can undo + // any clips later when we reuse the canvas. + _ctx.save(); + + // We always start with identity transform because the surrounding transform + // is applied on the DOM elements. + _ctx.setTransform(1, 0, 0, 1, 0, 0); + + // This scale makes sure that 1 CSS pixel is translated to the correct + // number of bitmap pixels. + _ctx.scale(html.window.devicePixelRatio, html.window.devicePixelRatio); + + // Flutter emits paint operations positioned relative to the parent layer's + // coordinate system. However, canvas' coordinate system's origin is always + // in the top-left corner of the canvas. We therefore need to inject an + // initial translation so the paint operations are positioned as expected. + + // The flooring of the value is to ensure that canvas' top-left corner + // lands on the physical pixel. + final int canvasPositionX = _bounds.left.floor() - paddingPixels; + final int canvasPositionY = _bounds.top.floor() - paddingPixels; + final double canvasPositionCorrectionX = + _bounds.left - paddingPixels - canvasPositionX.toDouble(); + final double canvasPositionCorrectionY = + _bounds.top - paddingPixels - canvasPositionY.toDouble(); + + rootElement.style.transform = + 'translate(${canvasPositionX}px, ${canvasPositionY}px)'; + + // This compensates for the translate on the `rootElement`. + translate( + -_bounds.left + canvasPositionCorrectionX + paddingPixels, + -_bounds.top + canvasPositionCorrectionY + paddingPixels, + ); + } + + /// The `` element used by this bitmap canvas. + html.CanvasElement get canvas => _canvas; + + /// The 2D context of the `` element used by this bitmap canvas. + html.CanvasRenderingContext2D get ctx => _ctx; + + /// Sets the global paint styles to correspond to [paint]. + void _applyPaint(ui.PaintData paint) { + ctx.globalCompositeOperation = + _stringForBlendMode(paint.blendMode) ?? 'source-over'; + ctx.lineWidth = paint.strokeWidth ?? 1.0; + final ui.StrokeCap cap = paint.strokeCap; + if (cap != null) { + ctx.lineCap = _stringForStrokeCap(cap); + } else { + ctx.lineCap = 'butt'; + } + final ui.StrokeJoin join = paint.strokeJoin; + if (join != null) { + ctx.lineJoin = _stringForStrokeJoin(join); + } else { + ctx.lineJoin = 'miter'; + } + if (paint.shader != null) { + final Object paintStyle = paint.shader.createPaintStyle(ctx); + _setFillAndStrokeStyle(paintStyle, paintStyle); + } else if (paint.color != null) { + final String colorString = paint.color.toCssString(); + _setFillAndStrokeStyle(colorString, colorString); + } + if (paint.maskFilter != null) { + _setFilter('blur(${paint.maskFilter.webOnlySigma}px)'); + } + } + + void _strokeOrFill(ui.PaintData paint, {bool resetPaint = true}) { + switch (paint.style) { + case ui.PaintingStyle.stroke: + ctx.stroke(); + break; + case ui.PaintingStyle.fill: + default: + ctx.fill(); + break; + } + if (resetPaint) { + _resetPaint(); + } + } + + /// Resets the paint styles that were set due to a previous paint command. + /// + /// For example, if a previous paint commands has a blur filter, we need to + /// undo that filter here. + /// + /// This needs to be called after [_applyPaint]. + void _resetPaint() { + _setFilter('none'); + _setFillAndStrokeStyle(null, null); + } + + void _setFilter(String value) { + if (_prevFilter != value) { + _prevFilter = ctx.filter = value; + } + } + + void _setFillAndStrokeStyle(Object fillStyle, Object strokeStyle) { + final html.CanvasRenderingContext2D _ctx = ctx; + if (!identical(_prevFillStyle, fillStyle)) { + _prevFillStyle = _ctx.fillStyle = fillStyle; + } + if (!identical(_prevStrokeStyle, strokeStyle)) { + _prevStrokeStyle = _ctx.strokeStyle = strokeStyle; + } + } + + @override + int save() { + super.save(); + ctx.save(); + return _saveCount++; + } + + void saveLayer(ui.Rect bounds, ui.Paint paint) { + save(); + } + + @override + void restore() { + super.restore(); + ctx.restore(); + _saveCount--; + _cachedLastStyle = null; + } + + // TODO(yjbanov): not sure what this is attempting to do, but it is probably + // wrong because some clips and transforms are expressed using + // HTML DOM elements. + void restoreToCount(int count) { + assert(_saveCount >= count); + final int restores = _saveCount - count; + for (int i = 0; i < restores; i++) { + ctx.restore(); + } + _saveCount = count; + } + + @override + void translate(double dx, double dy) { + super.translate(dx, dy); + ctx.translate(dx, dy); + } + + @override + void scale(double sx, double sy) { + super.scale(sx, sy); + ctx.scale(sx, sy); + } + + @override + void rotate(double radians) { + super.rotate(radians); + ctx.rotate(radians); + } + + @override + void skew(double sx, double sy) { + super.skew(sx, sy); + ctx.transform(1, sy, sx, 1, 0, 0); + // | | | | | | + // | | | | | f - vertical translation + // | | | | e - horizontal translation + // | | | d - vertical scaling + // | | c - horizontal skewing + // | b - vertical skewing + // a - horizontal scaling + // + // Source: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/transform + } + + @override + void transform(Float64List matrix4) { + super.transform(matrix4); + + // Canvas2D transform API: + // + // ctx.transform(a, b, c, d, e, f); + // + // In 3x3 matrix form assuming vector representation of (x, y, 1): + // + // a c e + // b d f + // 0 0 1 + // + // This translates to 4x4 matrix with vector representation of (x, y, z, 1) + // as: + // + // a c 0 e + // b d 0 f + // 0 0 1 0 + // 0 0 0 1 + // + // 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], + matrix4[4], + matrix4[5], + matrix4[12], + matrix4[13], + ); + } + + @override + void clipRect(ui.Rect rect) { + super.clipRect(rect); + ctx.beginPath(); + ctx.rect(rect.left, rect.top, rect.width, rect.height); + ctx.clip(); + } + + @override + void clipRRect(ui.RRect rrect) { + super.clipRRect(rrect); + final ui.Path path = ui.Path()..addRRect(rrect); + _runPath(path); + ctx.clip(); + } + + @override + void clipPath(ui.Path path) { + super.clipPath(path); + _runPath(path); + ctx.clip(); + } + + @override + void drawColor(ui.Color color, ui.BlendMode blendMode) { + ctx.globalCompositeOperation = _stringForBlendMode(blendMode); + + // 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); + } + + @override + void drawLine(ui.Offset p1, ui.Offset p2, ui.PaintData paint) { + _applyPaint(paint); + ctx.beginPath(); + ctx.moveTo(p1.dx, p1.dy); + ctx.lineTo(p2.dx, p2.dy); + ctx.stroke(); + _resetPaint(); + } + + @override + void drawPaint(ui.PaintData paint) { + _applyPaint(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); + _resetPaint(); + } + + @override + void drawRect(ui.Rect rect, ui.PaintData paint) { + _applyPaint(paint); + ctx.beginPath(); + ctx.rect(rect.left, rect.top, rect.width, rect.height); + _strokeOrFill(paint); + } + + @override + void drawRRect(ui.RRect rrect, ui.PaintData paint) { + _applyPaint(paint); + _drawRRectPath(rrect); + _strokeOrFill(paint); + } + + void _drawRRectPath(ui.RRect rrect, {bool startNewPath = true}) { + // 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 houdini_painter.js, we need to + // fix it here too. + // To draw the rounded rectangle, perform the following 8 steps: + // 1. Flip left,right top,bottom since web doesn't support flipped + // coordinates with negative radii. + // 2. draw the line for the top + // 3. draw the arc for the top-right corner + // 4. draw the line for the right side + // 5. draw the arc for the bottom-right corner + // 6. draw the line for the bottom of the rectangle + // 7. draw the arc for the bottom-left corner + // 8. draw the line for the left side + // 9. 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 + + double left = rrect.left; + double right = rrect.right; + double top = rrect.top; + double bottom = rrect.bottom; + if (left > right) { + left = right; + right = rrect.left; + } + if (top > bottom) { + top = bottom; + bottom = rrect.top; + } + final double trRadiusX = rrect.trRadiusX.abs(); + final double tlRadiusX = rrect.tlRadiusX.abs(); + final double trRadiusY = rrect.trRadiusY.abs(); + final double tlRadiusY = rrect.tlRadiusY.abs(); + final double blRadiusX = rrect.blRadiusX.abs(); + final double brRadiusX = rrect.brRadiusX.abs(); + final double blRadiusY = rrect.blRadiusY.abs(); + final double brRadiusY = rrect.brRadiusY.abs(); + + ctx.moveTo(left + trRadiusX, top); + + if (startNewPath) { + ctx.beginPath(); + } + + // Top side and top-right corner + ctx.lineTo(right - trRadiusX, top); + ctx.ellipse( + right - trRadiusX, + top + trRadiusY, + trRadiusX, + trRadiusY, + 0, + 1.5 * math.pi, + 2.0 * math.pi, + false, + ); + + // Right side and bottom-right corner + ctx.lineTo(right, bottom - brRadiusY); + ctx.ellipse( + right - brRadiusX, + bottom - brRadiusY, + brRadiusX, + brRadiusY, + 0, + 0, + 0.5 * math.pi, + false, + ); + + // Bottom side and bottom-left corner + ctx.lineTo(left + blRadiusX, bottom); + ctx.ellipse( + left + blRadiusX, + bottom - blRadiusY, + blRadiusX, + blRadiusY, + 0, + 0.5 * math.pi, + math.pi, + false, + ); + + // Left side and top-left corner + ctx.lineTo(left, top + tlRadiusY); + ctx.ellipse( + left + tlRadiusX, + top + tlRadiusY, + tlRadiusX, + tlRadiusY, + 0, + math.pi, + 1.5 * math.pi, + false, + ); + } + + void _drawRRectPathReverse(ui.RRect rrect, {bool startNewPath = true}) { + double left = rrect.left; + double right = rrect.right; + double top = rrect.top; + double bottom = rrect.bottom; + final double trRadiusX = rrect.trRadiusX.abs(); + final double tlRadiusX = rrect.tlRadiusX.abs(); + final double trRadiusY = rrect.trRadiusY.abs(); + final double tlRadiusY = rrect.tlRadiusY.abs(); + final double blRadiusX = rrect.blRadiusX.abs(); + final double brRadiusX = rrect.brRadiusX.abs(); + final double blRadiusY = rrect.blRadiusY.abs(); + final double brRadiusY = rrect.brRadiusY.abs(); + + if (left > right) { + left = right; + right = rrect.left; + } + if (top > bottom) { + top = bottom; + bottom = rrect.top; + } + // Draw the rounded rectangle, counterclockwise. + ctx.moveTo(right - trRadiusX, top); + + if (startNewPath) { + ctx.beginPath(); + } + + // Top side and top-left corner + ctx.lineTo(left + tlRadiusX, top); + ctx.ellipse( + left + tlRadiusX, + top + tlRadiusY, + tlRadiusX, + tlRadiusY, + 0, + 1.5 * math.pi, + 1 * math.pi, + true, + ); + + // Left side and bottom-left corner + ctx.lineTo(left, bottom - blRadiusY); + ctx.ellipse( + left + blRadiusX, + bottom - blRadiusY, + blRadiusX, + blRadiusY, + 0, + 1 * math.pi, + 0.5 * math.pi, + true, + ); + + // Bottom side and bottom-right corner + ctx.lineTo(right - brRadiusX, bottom); + ctx.ellipse( + right - brRadiusX, + bottom - brRadiusY, + brRadiusX, + brRadiusY, + 0, + 0.5 * math.pi, + 0 * math.pi, + true, + ); + + // Right side and top-right corner + ctx.lineTo(right, top + trRadiusY); + ctx.ellipse( + right - trRadiusX, + top + trRadiusY, + trRadiusX, + trRadiusY, + 0, + 0 * math.pi, + 1.5 * math.pi, + true, + ); + } + + @override + void drawDRRect(ui.RRect outer, ui.RRect inner, ui.PaintData paint) { + _applyPaint(paint); + _drawRRectPath(outer); + _drawRRectPathReverse(inner, startNewPath: false); + _strokeOrFill(paint); + } + + @override + void drawOval(ui.Rect rect, ui.PaintData paint) { + _applyPaint(paint); + ctx.beginPath(); + ctx.ellipse(rect.center.dx, rect.center.dy, rect.width / 2, rect.height / 2, + 0, 0, 2.0 * math.pi, false); + _strokeOrFill(paint); + } + + @override + void drawCircle(ui.Offset c, double radius, ui.PaintData paint) { + _applyPaint(paint); + ctx.beginPath(); + ctx.ellipse(c.dx, c.dy, radius, radius, 0, 0, 2.0 * math.pi, false); + _strokeOrFill(paint); + } + + @override + void drawPath(ui.Path path, ui.PaintData paint) { + _applyPaint(paint); + _runPath(path); + _strokeOrFill(paint); + } + + @override + void drawShadow(ui.Path path, ui.Color color, double elevation, + bool transparentOccluder) { + final List shadows = + ElevationShadow.computeCanvasShadows(elevation, color); + if (shadows.isNotEmpty) { + for (final CanvasShadow shadow in shadows) { + // TODO(het): Shadows with transparent occluders are not supported + // on webkit since filter is unsupported. + if (transparentOccluder && browserEngine != BrowserEngine.webkit) { + // We paint shadows using a path and a mask filter instead of the + // built-in shadow* properties. This is because the color alpha of the + // paint is added to the shadow. The effect we're looking for is to just + // paint the shadow without the path itself, but if we use a non-zero + // alpha for the paint the path is painted in addition to the shadow, + // which is undesirable. + final ui.Paint paint = ui.Paint() + ..color = shadow.color + ..style = ui.PaintingStyle.fill + ..strokeWidth = 0.0 + ..maskFilter = ui.MaskFilter.blur(ui.BlurStyle.normal, shadow.blur); + _ctx.save(); + _ctx.translate(shadow.offsetX, shadow.offsetY); + final ui.PaintData paintData = paint.webOnlyPaintData; + _applyPaint(paintData); + _runPath(path); + _strokeOrFill(paintData, resetPaint: false); + _ctx.restore(); + } else { + // TODO(het): We fill the path with this paint, then later we clip + // by the same path and fill it with a fully opaque color (we know + // the color is fully opaque because `transparentOccluder` is false. + // However, due to anti-aliasing of the clip, a few pixels of the + // path we are about to paint may still be visible after we fill with + // the opaque occluder. For that reason, we fill with the shadow color, + // and set the shadow color to fully opaque. This way, the visible + // pixels are less opaque and less noticeable. + final ui.Paint paint = ui.Paint() + ..color = shadow.color + ..style = ui.PaintingStyle.fill + ..strokeWidth = 0.0; + _ctx.save(); + final ui.PaintData paintData = paint.webOnlyPaintData; + _applyPaint(paintData); + _ctx.shadowBlur = shadow.blur; + _ctx.shadowColor = shadow.color.withAlpha(0xff).toCssString(); + _ctx.shadowOffsetX = shadow.offsetX; + _ctx.shadowOffsetY = shadow.offsetY; + _runPath(path); + _strokeOrFill(paintData, resetPaint: false); + _ctx.restore(); + } + } + _resetPaint(); + } + } + + @override + void drawImage(ui.Image image, ui.Offset p, ui.PaintData paint) { + _applyPaint(paint); + final HtmlImage htmlImage = image; + final html.Element imgElement = htmlImage.imgElement.clone(true); + imgElement.style + ..position = 'absolute' + ..transform = 'translate(${p.dx}px, ${p.dy}px)'; + rootElement.append(imgElement); + } + + @override + void drawImageRect( + ui.Image image, ui.Rect src, ui.Rect dst, ui.PaintData paint) { + // TODO(het): Check if the src rect is the entire image, and if so just + // append the imgElement and set it's height and width. + final HtmlImage htmlImage = image; + ctx.drawImageScaledFromSource( + htmlImage.imgElement, + src.left, + src.top, + src.width, + src.height, + dst.left, + dst.top, + dst.width, + dst.height, + ); + } + + void _drawTextLine( + ParagraphGeometricStyle style, String line, double x, double y) { + final double letterSpacing = style.letterSpacing; + if (letterSpacing == null || letterSpacing == 0.0) { + ctx.fillText(line, x, y); + } else { + // When letter-spacing is set, we go through a more expensive code path + // that renders each character separately with the correct spacing + // between them. + // + // We are drawing letter spacing like the web does it, by adding the + // spacing after each letter. This is different from Flutter which puts + // the spacing around each letter i.e. for a 10px letter spacing, Flutter + // would put 5px before each letter and 5px after it, but on the web, we + // put no spacing before the letter and 10px after it. This is how the DOM + // does it. + final int len = line.length; + for (int i = 0; i < len; i++) { + final String char = line[i]; + ctx.fillText(char, x, y); + x += letterSpacing + ctx.measureText(char).width; + } + } + } + + @override + void drawParagraph(EngineParagraph paragraph, ui.Offset offset) { + assert(paragraph._isLaidOut); + + final ParagraphGeometricStyle style = paragraph._geometricStyle; + + if (paragraph._drawOnCanvas) { + final List lines = + paragraph._lines ?? [paragraph._plainText]; + + final ui.PaintData backgroundPaint = + paragraph._background?.webOnlyPaintData; + if (backgroundPaint != null) { + final ui.Rect rect = ui.Rect.fromLTWH( + offset.dx, offset.dy, paragraph.width, paragraph.height); + drawRect(rect, backgroundPaint); + } + + if (style != _cachedLastStyle) { + ctx.font = style.cssFontString; + _cachedLastStyle = style; + } + _applyPaint(paragraph._paint.webOnlyPaintData); + + final double x = offset.dx + paragraph._alignOffset; + double y = offset.dy + paragraph.alphabeticBaseline; + final int len = lines.length; + for (int i = 0; i < len; i++) { + _drawTextLine(style, lines[i], x, y); + y += paragraph._lineHeight; + } + _resetPaint(); + return; + } + + final html.Element paragraphElement = + _drawParagraphElement(paragraph, offset); + + if (isClipped) { + final List clipElements = + _clipContent(_clipStack, paragraphElement, offset, currentTransform); + for (html.Element clipElement in clipElements) { + rootElement.append(clipElement); + _children.add(clipElement); + } + } else { + final String cssTransform = + matrix4ToCssTransform(transformWithOffset(currentTransform, offset)); + paragraphElement.style.transform = cssTransform; + rootElement.append(paragraphElement); + } + _children.add(paragraphElement); + } + + /// Paints the [picture] into this canvas. + void drawPicture(ui.Picture picture) { + picture.recordingCanvas.apply(this); + } + + /// 'Runs' the given [path] by applying all of its commands to the canvas. + void _runPath(ui.Path path) { + ctx.beginPath(); + for (Subpath subpath in path.subpaths) { + for (PathCommand command in subpath.commands) { + switch (command.type) { + case PathCommandTypes.bezierCurveTo: + final BezierCurveTo curve = command; + ctx.bezierCurveTo( + curve.x1, curve.y1, curve.x2, curve.y2, curve.x3, curve.y3); + break; + case PathCommandTypes.close: + ctx.closePath(); + break; + case PathCommandTypes.ellipse: + final Ellipse ellipse = command; + ctx.ellipse( + ellipse.x, + ellipse.y, + ellipse.radiusX, + ellipse.radiusY, + ellipse.rotation, + ellipse.startAngle, + ellipse.endAngle, + ellipse.anticlockwise); + break; + case PathCommandTypes.lineTo: + final LineTo lineTo = command; + ctx.lineTo(lineTo.x, lineTo.y); + break; + case PathCommandTypes.moveTo: + final MoveTo moveTo = command; + ctx.moveTo(moveTo.x, moveTo.y); + break; + case PathCommandTypes.rRect: + final RRectCommand rrectCommand = command; + _drawRRectPath(rrectCommand.rrect, startNewPath: false); + break; + case PathCommandTypes.rect: + final RectCommand rectCommand = command; + ctx.rect(rectCommand.x, rectCommand.y, rectCommand.width, + rectCommand.height); + break; + case PathCommandTypes.quadraticCurveTo: + final QuadraticCurveTo quadraticCurveTo = command; + ctx.quadraticCurveTo(quadraticCurveTo.x1, quadraticCurveTo.y1, + quadraticCurveTo.x2, quadraticCurveTo.y2); + break; + default: + throw UnimplementedError('Unknown path command $command'); + } + } + } + } +} + +String _stringForBlendMode(ui.BlendMode blendMode) { + if (blendMode == null) { + return null; + } + switch (blendMode) { + case ui.BlendMode.srcOver: + return 'source-over'; + case ui.BlendMode.srcIn: + return 'source-in'; + case ui.BlendMode.srcOut: + return 'source-out'; + case ui.BlendMode.srcATop: + return 'source-atop'; + case ui.BlendMode.dstOver: + return 'destination-over'; + case ui.BlendMode.dstIn: + return 'destination-in'; + case ui.BlendMode.dstOut: + return 'destination-out'; + case ui.BlendMode.dstATop: + return 'destination-atop'; + case ui.BlendMode.plus: + return 'lighten'; + case ui.BlendMode.src: + return 'copy'; + case ui.BlendMode.xor: + return 'xor'; + case ui.BlendMode.multiply: + // Falling back to multiply, ignoring alpha channel. + // TODO(flutter_web): only used for debug, find better fallback for web. + case ui.BlendMode.modulate: + return 'multiply'; + case ui.BlendMode.screen: + return 'screen'; + case ui.BlendMode.overlay: + return 'overlay'; + case ui.BlendMode.darken: + return 'darken'; + case ui.BlendMode.lighten: + return 'lighten'; + case ui.BlendMode.colorDodge: + return 'color-dodge'; + case ui.BlendMode.colorBurn: + return 'color-burn'; + case ui.BlendMode.hardLight: + return 'hard-light'; + case ui.BlendMode.softLight: + return 'soft-light'; + case ui.BlendMode.difference: + return 'difference'; + case ui.BlendMode.exclusion: + return 'exclusion'; + case ui.BlendMode.hue: + return 'hue'; + case ui.BlendMode.saturation: + return 'saturation'; + case ui.BlendMode.color: + return 'color'; + case ui.BlendMode.luminosity: + return 'luminosity'; + default: + throw UnimplementedError( + 'Flutter Web does not support the blend mode: $blendMode'); + } +} + +String _stringForStrokeCap(ui.StrokeCap strokeCap) { + if (strokeCap == null) { + return null; + } + switch (strokeCap) { + case ui.StrokeCap.butt: + return 'butt'; + case ui.StrokeCap.round: + return 'round'; + case ui.StrokeCap.square: + default: + return 'square'; + } +} + +String _stringForStrokeJoin(ui.StrokeJoin strokeJoin) { + assert(strokeJoin != null); + switch (strokeJoin) { + case ui.StrokeJoin.round: + return 'round'; + case ui.StrokeJoin.bevel: + return 'bevel'; + case ui.StrokeJoin.miter: + default: + return 'miter'; + } +} + +/// Clips the content element against a stack of clip operations and returns +/// root of a tree that contains content node. +/// +/// The stack of clipping rectangles generate an element that either uses +/// overflow:hidden with bounds to clip child or sets a clip-path to clip +/// it's contents. The clipping rectangles are nested and returned together +/// with a list of svg elements that provide clip-paths. +List _clipContent(List<_SaveClipEntry> clipStack, + html.HtmlElement content, ui.Offset offset, Matrix4 currentTransform) { + html.Element root, curElement; + final List clipDefs = []; + final int len = clipStack.length; + for (int clipIndex = 0; clipIndex < len; clipIndex++) { + final _SaveClipEntry entry = clipStack[clipIndex]; + final html.HtmlElement newElement = html.DivElement(); + if (root == null) { + root = newElement; + } else { + domRenderer.append(curElement, newElement); + } + curElement = newElement; + final ui.Rect rect = entry.rect; + Matrix4 newClipTransform = entry.currentTransform; + if (rect != null) { + final double clipOffsetX = rect.left; + final double clipOffsetY = rect.top; + newClipTransform = newClipTransform.clone() + ..translate(clipOffsetX, clipOffsetY); + curElement.style + ..overflow = 'hidden' + ..transform = matrix4ToCssTransform(newClipTransform) + ..transformOrigin = '0 0 0' + ..width = '${rect.right - clipOffsetX}px' + ..height = '${rect.bottom - clipOffsetY}px'; + } else if (entry.rrect != null) { + final ui.RRect roundRect = entry.rrect; + final String borderRadius = + '${roundRect.tlRadiusX}px ${roundRect.trRadiusX}px ' + '${roundRect.brRadiusX}px ${roundRect.blRadiusX}px'; + final double clipOffsetX = roundRect.left; + final double clipOffsetY = roundRect.top; + newClipTransform = newClipTransform.clone() + ..translate(clipOffsetX, clipOffsetY); + curElement.style + ..borderRadius = borderRadius + ..overflow = 'hidden' + ..transform = matrix4ToCssTransform(newClipTransform) + ..transformOrigin = '0 0 0' + ..width = '${roundRect.right - clipOffsetX}px' + ..height = '${roundRect.bottom - clipOffsetY}px'; + } else if (entry.path != null) { + curElement.style.transform = matrix4ToCssTransform(newClipTransform); + final String svgClipPath = _pathToSvgClipPath(entry.path); + final html.Element clipElement = + html.Element.html(svgClipPath, treeSanitizer: _NullTreeSanitizer()); + domRenderer.setElementStyle( + curElement, 'clip-path', 'url(#svgClip$_clipIdCounter)'); + domRenderer.setElementStyle( + curElement, '-webkit-clip-path', 'url(#svgClip$_clipIdCounter)'); + clipDefs.add(clipElement); + } + // Reverse the transform of the clipping element so children can use + // effective transform to render. + // TODO(flutter_web): When we have more than a single clip element, + // reduce number of div nodes by merging (multiplying transforms). + final html.Element reverseTransformDiv = html.DivElement(); + reverseTransformDiv.style + ..transform = + _cssTransformAtOffset(newClipTransform.clone()..invert(), 0, 0) + ..transformOrigin = '0 0 0'; + curElement.append(reverseTransformDiv); + curElement = reverseTransformDiv; + } + + root.style.position = 'absolute'; + domRenderer.append(curElement, content); + content.style.transform = + _cssTransformAtOffset(currentTransform, offset.dx, offset.dy); + return [root]..addAll(clipDefs); +} + +String _cssTransformAtOffset( + Matrix4 transform, double offsetX, double offsetY) { + return matrix4ToCssTransform( + transformWithOffset(transform, ui.Offset(offsetX, offsetY))); +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/browser_detection.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/browser_detection.dart new file mode 100644 index 0000000000..967aea7dc9 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/browser_detection.dart @@ -0,0 +1,40 @@ +// 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; + +/// The HTML engine used by the current browser. +enum BrowserEngine { + /// The engine that powers Chrome, Samsung Internet Browser, UC Browser, + /// Microsoft Edge, Opera, and others. + blink, + + /// The engine that powers Safari. + webkit, + + /// We were unable to detect the current browser engine. + unknown, +} + +/// Lazily initialized current browser engine. +BrowserEngine _browserEngine; + +/// Returns the [BrowserEngine] used by the current browser. +/// +/// This is used to implement browser-specific behavior. +BrowserEngine get browserEngine => _browserEngine ??= _detectBrowserEngine(); + +BrowserEngine _detectBrowserEngine() { + final String vendor = html.window.navigator.vendor; + if (vendor == 'Google Inc.') { + return BrowserEngine.blink; + } else if (vendor == 'Apple Computer, Inc.') { + return BrowserEngine.webkit; + } + + // Assume blink otherwise, but issue a warning. + print('WARNING: failed to detect current browser engine.'); + + return BrowserEngine.unknown; +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/browser_location.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/browser_location.dart new file mode 100644 index 0000000000..bffbfee2c1 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/browser_location.dart @@ -0,0 +1,214 @@ +// 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; + +// TODO(mdebbar): add other strategies. + +// Some parts of this file were inspired/copied from the AngularDart router. + +/// Ensures that [str] is prefixed with [leading]. If [str] is already prefixed, +/// it'll be returned unchanged. If it's not, this function will prefix it. +/// +/// The [applyWhenEmpty] flag controls whether this function should prefix [str] +/// or not when it's an empty string. +/// +/// ```dart +/// ensureLeading('/path', '/'); // "/path" +/// ensureLeading('path', '/'); // "/path" +/// ensureLeading('', '/'); // "/" +/// ensureLeading('', '/', applyWhenEmpty: false); // "" +/// ``` +String ensureLeading(String str, String leading, {bool applyWhenEmpty = true}) { + if (str.isEmpty && !applyWhenEmpty) { + return str; + } + return str.startsWith(leading) ? str : '$leading$str'; +} + +/// `LocationStrategy` is responsible for representing and reading route state +/// from the browser's URL. At the moment, only one strategy is implemented: +/// [HashLocationStrategy]. +/// +/// This is used by [BrowserHistory] to interact with browser history APIs. +abstract class LocationStrategy { + const LocationStrategy(); + + /// Subscribes to popstate events and returns a function that could be used to + /// unsubscribe from popstate events. + ui.VoidCallback onPopState(html.EventListener fn); + + /// The active path in the browser history. + String get path; + + /// Given a path that's internal to the app, create the external url that + /// will be used in the browser. + String prepareExternalUrl(String internalUrl); + + /// Push a new history entry. + void pushState(dynamic state, String title, String url); + + /// Replace the currently active history entry. + void replaceState(dynamic state, String title, String url); + + /// Go to the previous history entry. + Future back(); +} + +/// This is an implementation of [LocationStrategy] that uses the browser URL's +/// [hash fragments](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) +/// to represent its state. +/// +/// In order to use this [LocationStrategy] for an app, it needs to be set in +/// [ui.window.webOnlyLocationStrategy]: +/// +/// ```dart +/// import 'package:flutter_web/material.dart'; +/// import 'package:flutter_web/ui.dart' as ui; +/// +/// void main() { +/// ui.window.webOnlyLocationStrategy = const ui.HashLocationStrategy(); +/// runApp(MyApp()); +/// } +/// ``` +class HashLocationStrategy extends LocationStrategy { + final PlatformLocation _platformLocation; + + const HashLocationStrategy( + [this._platformLocation = const BrowserPlatformLocation()]); + + @override + ui.VoidCallback onPopState(html.EventListener fn) { + _platformLocation.onPopState(fn); + return () => _platformLocation.offPopState(fn); + } + + @override + String get path { + // the hash value is always prefixed with a `#` + // and if it is empty then it will stay empty + String path = _platformLocation.hash ?? ''; + // Dart will complain if a call to substring is + // executed with a position value that exceeds the + // length of string. + path = path.isEmpty ? path : path.substring(1); + // The path, by convention, should always contain a leading '/'. + return ensureLeading(path, '/'); + } + + @override + String prepareExternalUrl(String internalUrl) { + // It's convention that if the hash path is empty, we omit the `#`; however, + // if the empty URL is pushed it won't replace any existing fragment. So + // when the hash path is empty, we instead return the location's path and + // query. + return internalUrl.isEmpty + ? '${_platformLocation.pathname}${_platformLocation.search}' + : '#$internalUrl'; + } + + @override + void pushState(dynamic state, String title, String url) { + _platformLocation.pushState(state, title, prepareExternalUrl(url)); + } + + @override + void replaceState(dynamic state, String title, String url) { + _platformLocation.replaceState(state, title, prepareExternalUrl(url)); + } + + @override + Future back() { + _platformLocation.back(); + return _waitForPopState(); + } + + /// Waits until the next popstate event is fired. This is useful for example + /// to wait until the browser has handled the `history.back` transition. + Future _waitForPopState() { + final Completer completer = Completer(); + ui.VoidCallback unsubscribe; + unsubscribe = onPopState((_) { + unsubscribe(); + completer.complete(); + }); + return completer.future; + } +} + +/// `PlatformLocation` encapsulates all calls to DOM apis, which allows the +/// [LocationStrategy] classes to be platform agnostic and testable. +/// +/// The `PlatformLocation` class is used directly by all implementations of +/// [LocationStrategy] when they need to interact with the DOM apis like +/// pushState, popState, etc... +abstract class PlatformLocation { + const PlatformLocation(); + + void onPopState(html.EventListener fn); + void offPopState(html.EventListener fn); + + void onHashChange(html.EventListener fn); + void offHashChange(html.EventListener fn); + + String get pathname; + String get search; + String get hash; + + void pushState(dynamic state, String title, String url); + void replaceState(dynamic state, String title, String url); + void back(); +} + +/// An implementation of [PlatformLocation] for the browser. +class BrowserPlatformLocation extends PlatformLocation { + html.Location get _location => html.window.location; + html.History get _history => html.window.history; + + const BrowserPlatformLocation(); + + @override + void onPopState(html.EventListener fn) { + html.window.addEventListener('popstate', fn); + } + + @override + void offPopState(html.EventListener fn) { + html.window.removeEventListener('popstate', fn); + } + + @override + void onHashChange(html.EventListener fn) { + html.window.addEventListener('hashchange', fn); + } + + @override + void offHashChange(html.EventListener fn) { + html.window.removeEventListener('hashchange', fn); + } + + @override + String get pathname => _location.pathname; + + @override + String get search => _location.search; + + @override + String get hash => _location.hash; + + @override + void pushState(dynamic state, String title, String url) { + _history.pushState(state, title, url); + } + + @override + void replaceState(dynamic state, String title, String url) { + _history.replaceState(state, title, url); + } + + @override + void back() { + _history.back(); + } +} 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 new file mode 100644 index 0000000000..85dd77417d --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/canvas.dart @@ -0,0 +1,105 @@ +// 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; + +/// An actual [SkCanvas] which can receive raw drawing commands. +/// +/// In order for the drawing commands to be flushed to the associated HTML +/// canvas, you must call `flush()` on the canvas's `SkSurface`. +/// +/// Although this class is backed by an `SkCanvas` and can in theory perform +/// arbitrary drawing operations, this class is only used in the final +/// compositing by the layers, and arbitrary drawings are done in a +/// [ui.Picture] which uses a Skia recording canvas. This class receives +/// drawing calls from the various `Layer` classes, e.g. [ClipRectLayer] and +/// so only exposes a subset of the drawing operations that can be performed +/// on a canvas. +class SkCanvas { + final js.JsObject skCanvas; + final html.CanvasElement htmlCanvas; + final js.JsObject skSurface; + final ui.Size size; + + SkCanvas(this.skCanvas, this.htmlCanvas, this.skSurface, this.size); + + int save() { + return skCanvas.callMethod('save'); + } + + int saveLayer(ui.Rect bounds, ui.Paint paint) { + return skCanvas.callMethod( + 'saveLayer', [_makeSkRect(bounds), _makeSkPaint(paint)]); + } + + void restore() { + skCanvas.callMethod('restore'); + } + + void restoreToCount(int count) { + skCanvas.callMethod('restoreToCount', [count]); + } + + void clear() { + skCanvas.callMethod('clear', [0xffffffff]); + } + + void translate(double dx, double dy) { + skCanvas.callMethod('translate', [dx, dy]); + } + + void transform(Float64List matrix) { + skCanvas.callMethod('concat', >[toSkMatrix(matrix)]); + } + + void clipPath(ui.Path path) { + final SkPath skPath = path; + skCanvas.callMethod('clipPath', [skPath._skPath]); + } + + void clipRect(ui.Rect rect) { + skCanvas.callMethod('clipRect', [_makeSkRect(rect)]); + } + + void clipRRect(ui.RRect rrect) { + final SkPath skPath = SkPath(); + skPath.addRRect(rrect); + clipPath(skPath); + } + + void drawPicture(ui.Picture picture) { + final SkPicture skPicture = picture; + skCanvas.callMethod('drawPicture', [skPicture.skPicture]); + } + + void drawPath(ui.Path path, ui.Paint paint) { + final SkPath skPath = path; + skCanvas.callMethod( + 'drawPath', [skPath._skPath, _makeSkPaint(paint)]); + } + + void drawPaint(ui.Paint paint) { + skCanvas.callMethod('drawPaint', [_makeSkPaint(paint)]); + } + + void drawShadow(ui.Path path, ui.Color color, double elevation, + bool transparentOccluder) { + throw 'drawShadow'; + } + + 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/engine_delegate.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/engine_delegate.dart new file mode 100644 index 0000000000..bf28ebbfb9 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/engine_delegate.dart @@ -0,0 +1,101 @@ +// 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; + +const String assetChannel = 'flutter/assets'; + +class Engine extends RuntimeDelegate { + final Animator _animator; + final dynamic _runtimeController; + final AssetManager _assetManager; + final dynamic _delegate; + + Engine(this._animator, this._runtimeController, this._assetManager, + this._delegate); + + @override + String get defaultRouteName => _initialRoute ?? '/'; + + String _initialRoute; + + bool get haveSurface => true; + + ViewportMetrics _viewportMetrics; + set viewportMetrics(ViewportMetrics metrics) { + final bool dimensionsChanged = + _viewportMetrics.physicalHeight != metrics.physicalHeight || + _viewportMetrics.physicalWidth != metrics.physicalWidth; + _viewportMetrics = metrics; + _runtimeController.viewportMetrics = _viewportMetrics; + if (_animator != null) { + if (dimensionsChanged) { + _animator.setDimensionChangePending(); + } + if (haveSurface) { + scheduleFrame(); + } + } + } + + @override + void scheduleFrame({bool regenerateLayerTree = true}) { + _animator.requestFrame(regenerateLayerTree); + } + + @override + void render(LayerTree layerTree) { + if (layerTree == null) { + return; + } + + final ui.Size frameSize = ui.Size( + _viewportMetrics.physicalWidth, _viewportMetrics.physicalHeight); + + if (frameSize.isEmpty) { + return; + } + + layerTree.frameSize = frameSize; + _animator.render(layerTree); + } + + @override + void handlePlatformMessage(PlatformMessage message) { + if (message.channel == assetChannel) { + handleAssetPlatformMessage(message); + } else { + _delegate.onEngineHandlePlatformMessage(message); + } + } + + void handleAssetPlatformMessage(PlatformMessage message) { + final PlatformMessageResponse response = message.response; + if (response == null) { + return; + } + + final String asset = utf8.decode(message.data.buffer.asUint8List()); + if (_assetManager != null) { + _assetManager.load(asset).then((ByteData data) { + if (data != null) { + response.complete(data.buffer.asUint8List()); + } else { + response.completeEmpty(); + } + }); + } else { + response.completeEmpty(); + } + } + + @override + FontCollection getFontCollection() => null; +} + +class Animator { + void setDimensionChangePending() {} + void render(LayerTree layerTree) {} + void requestFrame(bool regenerateLayerTree) {} +} 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 new file mode 100644 index 0000000000..dcf38d6fc1 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/initialization.dart @@ -0,0 +1,40 @@ +// 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; + +/// EXPERIMENTAL: Enable the Skia-based rendering backend. +const bool experimentalUseSkia = 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/'; + +/// Initialize the Skia backend. +/// +/// This calls `CanvasKitInit` and assigns the global [canvasKit] object. +Future initializeSkia() { + final Completer canvasKitCompleter = Completer(); + 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 canvasKitInit = + js.JsObject(js.context['CanvasKitInit'], [canvasKitInitArgs]); + final js.JsObject canvasKitInitPromise = canvasKitInit.callMethod('ready'); + canvasKitInitPromise.callMethod('then', [ + js.allowInterop((js.JsObject ck) { + canvasKit = ck; + canvasKitCompleter.complete(); + }) + ]); + }); + return canvasKitCompleter.future; +} + +/// The entrypoint into all CanvasKit functions and classes. +/// +/// This is created by [initializeSkia]. +js.JsObject canvasKit; 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 new file mode 100644 index 0000000000..65dd3499e3 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer.dart @@ -0,0 +1,370 @@ +// 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; + +/// A layer to be composed into a scene. +/// +/// A layer is the lowest-level rendering primitive. It represents an atomic +/// painting command. +abstract class Layer implements ui.EngineLayer { + /// The layer that contains us as a child. + ContainerLayer parent; + + /// An estimated rectangle that this layer will draw into. + ui.Rect paintBounds = ui.Rect.zero; + + /// Whether or not this layer actually needs to be painted in the scene. + bool get needsPainting => !paintBounds.isEmpty; + + /// Pre-process this layer before painting. + /// + /// In this step, we compute the estimated [paintBounds] as well as + /// apply heuristics to prepare the render cache for pictures that + /// should be cached. + void preroll(PrerollContext prerollContext, Matrix4 matrix); + + /// Paint this layer into the scene. + void paint(PaintContext paintContext); +} + +/// A context shared by all layers during the preroll pass. +class PrerollContext { + /// A raster cache. Used to register candidates for caching. + final RasterCache rasterCache; + + PrerollContext(this.rasterCache); +} + +/// A context shared by all layers during the paint pass. +class PaintContext { + /// The canvas to paint to. + final SkCanvas canvas; + + /// A raster cache potentially containing pre-rendered pictures. + final RasterCache rasterCache; + + PaintContext(this.canvas, this.rasterCache); +} + +/// A layer that contains child layers. +abstract class ContainerLayer extends Layer { + final List _layers = []; + + /// Register [child] as a child of this layer. + void add(Layer child) { + child.parent = this; + _layers.add(child); + } + + @override + void preroll(PrerollContext prerollContext, Matrix4 matrix) { + paintBounds = prerollChildren(prerollContext, matrix); + } + + /// Run [preroll] on all of the child layers. + /// + /// Returns a [Rect] that covers the paint bounds of all of the child layers. + /// If all of the child layers have empty paint bounds, then the returned + /// [Rect] is empty. + ui.Rect prerollChildren(PrerollContext context, Matrix4 childMatrix) { + ui.Rect childPaintBounds = ui.Rect.zero; + for (Layer layer in _layers) { + layer.preroll(context, childMatrix); + if (childPaintBounds.isEmpty) { + childPaintBounds = layer.paintBounds; + } else if (!layer.paintBounds.isEmpty) { + childPaintBounds = childPaintBounds.expandToInclude(layer.paintBounds); + } + } + return childPaintBounds; + } + + /// Calls [paint] on all child layers that need painting. + void paintChildren(PaintContext context) { + assert(needsPainting); + + for (Layer layer in _layers) { + if (layer.needsPainting) { + layer.paint(context); + } + } + } +} + +/// A layer that clips its child layers by a given [Path]. +class ClipPathLayer extends ContainerLayer { + /// The path used to clip child layers. + final ui.Path _clipPath; + + ClipPathLayer(this._clipPath); + + @override + void preroll(PrerollContext prerollContext, Matrix4 matrix) { + final ui.Rect childPaintBounds = prerollChildren(prerollContext, matrix); + final ui.Rect clipBounds = _clipPath.getBounds(); + if (childPaintBounds.overlaps(clipBounds)) { + paintBounds = childPaintBounds.intersect(clipBounds); + } + } + + @override + void paint(PaintContext paintContext) { + assert(needsPainting); + + paintContext.canvas.save(); + paintContext.canvas.clipPath(_clipPath); + paintChildren(paintContext); + paintContext.canvas.restore(); + } +} + +/// A layer that clips its child layers by a given [Rect]. +class ClipRectLayer extends ContainerLayer { + /// The rectangle used to clip child layers. + final ui.Rect _clipRect; + + ClipRectLayer(this._clipRect); + + @override + void preroll(PrerollContext prerollContext, Matrix4 matrix) { + final ui.Rect childPaintBounds = prerollChildren(prerollContext, matrix); + if (childPaintBounds.overlaps(_clipRect)) { + paintBounds = childPaintBounds.intersect(_clipRect); + } + } + + @override + void paint(PaintContext paintContext) { + assert(needsPainting); + + paintContext.canvas.save(); + paintContext.canvas.clipRect(_clipRect); + paintChildren(paintContext); + paintContext.canvas.restore(); + } +} + +/// A layer that clips its child layers by a given [RRect]. +class ClipRRectLayer extends ContainerLayer { + /// The rounded rectangle used to clip child layers. + final ui.RRect _clipRRect; + + ClipRRectLayer(this._clipRRect); + + @override + void preroll(PrerollContext prerollContext, Matrix4 matrix) { + final ui.Rect childPaintBounds = prerollChildren(prerollContext, matrix); + if (childPaintBounds.overlaps(_clipRRect.outerRect)) { + paintBounds = childPaintBounds.intersect(_clipRRect.outerRect); + } + } + + @override + void paint(PaintContext paintContext) { + assert(needsPainting); + + paintContext.canvas.save(); + paintContext.canvas.clipRRect(_clipRRect); + paintChildren(paintContext); + paintContext.canvas.restore(); + } +} + +/// A layer that transforms its child layers by the given transform matrix. +class TransformLayer extends ContainerLayer + implements ui.OffsetEngineLayer, ui.TransformEngineLayer { + /// The matrix with which to transform the child layers. + final Matrix4 _transform; + + TransformLayer(this._transform); + + @override + void preroll(PrerollContext prerollContext, Matrix4 matrix) { + final Matrix4 childMatrix = matrix * _transform; + final ui.Rect childPaintBounds = + prerollChildren(prerollContext, childMatrix); + paintBounds = _transformRect(_transform, childPaintBounds); + } + + /// Applies the given matrix as a perspective transform to the given point. + /// + /// This function assumes the given point has a z-coordinate of 0.0. The + /// z-coordinate of the result is ignored. + static ui.Offset _transformPoint(Matrix4 transform, ui.Offset point) { + final Vector3 position3 = Vector3(point.dx, point.dy, 0.0); + final Vector3 transformed3 = transform.perspectiveTransform(position3); + return ui.Offset(transformed3.x, transformed3.y); + } + + /// Returns a rect that bounds the result of applying the given matrix as a + /// perspective transform to the given rect. + /// + /// This function assumes the given rect is in the plane with z equals 0.0. + /// The transformed rect is then projected back into the plane with z equals + /// 0.0 before computing its bounding rect. + static ui.Rect _transformRect(Matrix4 transform, ui.Rect rect) { + final ui.Offset point1 = _transformPoint(transform, rect.topLeft); + final ui.Offset point2 = _transformPoint(transform, rect.topRight); + final ui.Offset point3 = _transformPoint(transform, rect.bottomLeft); + final ui.Offset point4 = _transformPoint(transform, rect.bottomRight); + return ui.Rect.fromLTRB( + _min4(point1.dx, point2.dx, point3.dx, point4.dx), + _min4(point1.dy, point2.dy, point3.dy, point4.dy), + _max4(point1.dx, point2.dx, point3.dx, point4.dx), + _max4(point1.dy, point2.dy, point3.dy, point4.dy)); + } + + static double _min4(double a, double b, double c, double d) { + return math.min(a, math.min(b, math.min(c, d))); + } + + static double _max4(double a, double b, double c, double d) { + return math.max(a, math.max(b, math.max(c, d))); + } + + @override + void paint(PaintContext paintContext) { + assert(needsPainting); + + paintContext.canvas.save(); + paintContext.canvas.transform(_transform.storage); + paintChildren(paintContext); + paintContext.canvas.restore(); + } +} + +/// A layer containing a [Picture]. +class PictureLayer extends Layer { + /// The picture to paint into the canvas. + final ui.Picture picture; + + /// The offset at which to paint the picture. + final ui.Offset offset; + + /// A hint to the compositor about whether this picture is complex. + final bool isComplex; + + /// A hint to the compositor that this picture is likely to change. + final bool willChange; + + PictureLayer(this.picture, this.offset, this.isComplex, this.willChange); + + @override + void preroll(PrerollContext prerollContext, Matrix4 matrix) { + final RasterCache cache = prerollContext.rasterCache; + if (cache != null) { + final Matrix4 translateMatrix = Matrix4.identity() + ..setTranslationRaw(offset.dx, offset.dy, 0); + final Matrix4 cacheMatrix = translateMatrix * matrix; + cache.prepare(picture, cacheMatrix, isComplex, willChange); + } + + paintBounds = picture.cullRect.shift(offset); + } + + @override + void paint(PaintContext paintContext) { + assert(picture != null); + assert(needsPainting); + + paintContext.canvas.save(); + paintContext.canvas.translate(offset.dx, offset.dy); + + if (paintContext.rasterCache != null) { + final Matrix4 cacheMatrix = paintContext.canvas.currentTransform; + final RasterCacheResult result = + paintContext.rasterCache.get(picture, cacheMatrix); + if (result.isValid) { + result.draw(paintContext.canvas); + return; + } + } + paintContext.canvas.drawPicture(picture); + paintContext.canvas.restore(); + } +} + +/// A layer representing a physical shape. +/// +/// The shape clips its children to a given [Path], and casts a shadow based +/// on the given elevation. +class PhysicalShapeLayer extends ContainerLayer + implements ui.PhysicalShapeEngineLayer { + final double _elevation; + final ui.Color _color; + final ui.Color _shadowColor; + final ui.Path _path; + final ui.Clip _clipBehavior; + + PhysicalShapeLayer( + this._elevation, + this._color, + this._shadowColor, + this._path, + this._clipBehavior, + ); + + @override + void preroll(PrerollContext prerollContext, Matrix4 matrix) { + prerollChildren(prerollContext, matrix); + paintBounds = + ElevationShadow.computeShadowRect(_path.getBounds(), _elevation); + } + + @override + void paint(PaintContext paintContext) { + assert(needsPainting); + + if (_elevation != 0) { + drawShadow(paintContext.canvas, _path, _shadowColor, _elevation, + _color.alpha != 0xff); + } + + final ui.Paint paint = ui.Paint()..color = _color; + if (_clipBehavior != ui.Clip.antiAliasWithSaveLayer) { + paintContext.canvas.drawPath(_path, paint); + } + + final int saveCount = paintContext.canvas.save(); + switch (_clipBehavior) { + case ui.Clip.hardEdge: + paintContext.canvas.clipPath(_path); + 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); + break; + case ui.Clip.antiAliasWithSaveLayer: + paintContext.canvas.clipPath(_path); + paintContext.canvas.saveLayer(paintBounds, null); + break; + case ui.Clip.none: + break; + } + + if (_clipBehavior == ui.Clip.antiAliasWithSaveLayer) { + // If we want to avoid the bleeding edge artifact + // (https://github.com/flutter/flutter/issues/18057#issue-328003931) + // using saveLayer, we have to call drawPaint instead of drawPath as + // anti-aliased drawPath will always have such artifacts. + paintContext.canvas.drawPaint(paint); + } + + paintChildren(paintContext); + + paintContext.canvas.restoreToCount(saveCount); + } + + /// Draws a shadow on the given [canvas] for the given [path]. + /// + /// The blur of the shadow is decided by the [elevation], and the + /// shadow is painted with the given [color]. + static void drawShadow(SkCanvas canvas, ui.Path path, ui.Color color, + double elevation, bool transparentOccluder) { + canvas.drawShadow(path, color, elevation, transparentOccluder); + } +} 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 new file mode 100644 index 0000000000..ee7a7991c1 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer_scene_builder.dart @@ -0,0 +1,206 @@ +// 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 LayerScene implements ui.Scene { + final LayerTree layerTree; + + LayerScene(Layer rootLayer) : layerTree = LayerTree() { + layerTree.rootLayer = rootLayer; + } + + @override + void dispose() {} + + @override + Future toImage(int width, int height) => null; + + @override + html.Element get webOnlyRootElement => null; +} + +class LayerSceneBuilder implements ui.SceneBuilder { + Layer rootLayer; + ContainerLayer currentLayer; + + @override + void addChildScene( + {ui.Offset offset = ui.Offset.zero, + double width = 0.0, + double height = 0.0, + ui.SceneHost sceneHost, + bool hitTestable = true}) { + throw UnimplementedError(); + } + + @override + void addPerformanceOverlay(int enabledOptions, ui.Rect bounds) { + // We don't plan to implement this on the web. + throw UnimplementedError(); + } + + @override + void addPicture(ui.Offset offset, ui.Picture picture, + {bool isComplexHint = false, bool willChangeHint = false}) { + currentLayer + .add(PictureLayer(picture, offset, isComplexHint, willChangeHint)); + } + + @override + void addRetained(ui.EngineLayer retainedLayer) { + if (currentLayer == null) { + return; + } + currentLayer.add(retainedLayer); + } + + @override + void addTexture(int textureId, + {ui.Offset offset = ui.Offset.zero, + double width = 0.0, + double height = 0.0, + bool freeze = false}) { + // TODO(b/128315641): implement addTexture. + } + + @override + void addPlatformView( + int viewId, { + ui.Offset offset = ui.Offset.zero, + double width = 0.0, + double height = 0.0, + Object webOnlyPaintedBy, + }) { + // TODO(b/128317425): implement addPlatformView. + } + + @override + ui.Scene build() { + return LayerScene(rootLayer); + } + + @override + void pop() { + if (currentLayer == null) { + return; + } + currentLayer = currentLayer.parent; + } + + @override + ui.BackdropFilterEngineLayer pushBackdropFilter(ui.ImageFilter filter, + {ui.EngineLayer oldLayer}) { + throw UnimplementedError(); + } + + @override + ui.ClipPathEngineLayer pushClipPath(ui.Path path, + {ui.Clip clipBehavior = ui.Clip.antiAlias, ui.EngineLayer oldLayer}) { + pushLayer(ClipPathLayer(path)); + return null; + } + + @override + ui.ClipRRectEngineLayer pushClipRRect(ui.RRect rrect, + {ui.Clip clipBehavior, ui.EngineLayer oldLayer}) { + pushLayer(ClipRRectLayer(rrect)); + return null; + } + + @override + ui.ClipRectEngineLayer pushClipRect(ui.Rect rect, + {ui.Clip clipBehavior = ui.Clip.antiAlias, ui.EngineLayer oldLayer}) { + pushLayer(ClipRectLayer(rect)); + return null; + } + + @override + ui.ColorFilterEngineLayer pushColorFilter(ui.ColorFilter filter, + {ui.EngineLayer oldLayer}) { + throw UnimplementedError(); + } + + @override + ui.OffsetEngineLayer pushOffset(double dx, double dy, + {ui.EngineLayer oldLayer}) { + final Matrix4 matrix = Matrix4.translationValues(dx, dy, 0.0); + final TransformLayer layer = TransformLayer(matrix); + pushLayer(layer); + return layer; + } + + @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; + } + + @override + ui.PhysicalShapeEngineLayer pushPhysicalShape({ + ui.Path path, + double elevation, + ui.Color color, + ui.Color shadowColor, + ui.Clip clipBehavior = ui.Clip.none, + ui.EngineLayer oldLayer, + }) { + final PhysicalShapeLayer layer = + PhysicalShapeLayer(elevation, color, shadowColor, path, clipBehavior); + pushLayer(layer); + return layer; + } + + @override + ui.ShaderMaskEngineLayer pushShaderMask( + ui.Shader shader, ui.Rect maskRect, ui.BlendMode blendMode, + {ui.EngineLayer oldLayer}) { + throw UnimplementedError(); + } + + @override + ui.TransformEngineLayer pushTransform(Float64List matrix4, + {ui.EngineLayer oldLayer}) { + final Matrix4 matrix = Matrix4.fromList(matrix4); + pushLayer(TransformLayer(matrix)); + return null; + } + + @override + void setCheckerboardOffscreenLayers(bool checkerboard) { + // TODO: implement setCheckerboardOffscreenLayers + } + + @override + void setCheckerboardRasterCacheImages(bool checkerboard) { + // TODO: implement setCheckerboardRasterCacheImages + } + + @override + void setRasterizerTracingThreshold(int frameInterval) { + // TODO: implement setRasterizerTracingThreshold + } + + void pushLayer(ContainerLayer layer) { + if (rootLayer == null) { + rootLayer = currentLayer = layer; + return; + } + + if (currentLayer == null) { + return; + } + + currentLayer.add(layer); + currentLayer = layer; + } + + @override + void setProperties(double width, double height, double insetTop, + double insetRight, double insetBottom, double insetLeft, bool focusable) { + throw UnimplementedError(); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer_tree.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer_tree.dart new file mode 100644 index 0000000000..ee428f5947 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/layer_tree.dart @@ -0,0 +1,67 @@ +// 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; + +/// A tree of [Layer]s that, together with a [Size] compose a frame. +class LayerTree { + /// The root of the layer tree. + Layer rootLayer; + + /// The size (in physical pixels) of the frame to paint this layer tree into. + ui.Size frameSize; + + /// Performs a preroll phase before painting the layer tree. + /// + /// In this phase, the paint boundary for each layer is computed and + /// pictures are registered with the raster cache as potential candidates + /// to raster. If [ignoreRasterCache] is `true`, then there will be no + /// attempt to register pictures to cache. + void preroll(Frame frame, {bool ignoreRasterCache = false}) { + final PrerollContext context = + PrerollContext(ignoreRasterCache ? null : frame.rasterCache); + rootLayer.preroll(context, Matrix4.identity()); + } + + /// Paints the layer tree into the given [frame]. + /// + /// If [ignoreRasterCache] is `true`, then the raster cache will + /// not be used. + void paint(Frame frame, {bool ignoreRasterCache = false}) { + final PaintContext context = PaintContext( + frame.canvas, ignoreRasterCache ? null : frame.rasterCache); + if (rootLayer.needsPainting) { + rootLayer.paint(context); + } + } +} + +/// A single frame to be rendered. +class Frame { + /// The canvas to render this frame to. + final SkCanvas canvas; + + /// A cache of pre-rastered pictures. + final RasterCache rasterCache; + + Frame(this.canvas, this.rasterCache); + + /// Rasterize the given layer tree into this frame. + bool raster(LayerTree layerTree, {bool ignoreRasterCache = false}) { + layerTree.preroll(this, ignoreRasterCache: ignoreRasterCache); + layerTree.paint(this, ignoreRasterCache: ignoreRasterCache); + return true; + } +} + +/// The state of the compositor, which is persisted between frames. +class CompositorContext { + /// A cache of pictures, which is shared between successive frames. + RasterCache rasterCache; + + /// Acquire a frame using this compositor's settings. + Frame acquireFrame(SkCanvas canvas) { + return Frame(canvas, rasterCache); + } +} 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 new file mode 100644 index 0000000000..23962cef1d --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/matrix.dart @@ -0,0 +1,27 @@ +// 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 new file mode 100644 index 0000000000..4b7dbe6de2 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/path.dart @@ -0,0 +1,202 @@ +// 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; + +/// An implementation of [ui.Path] which is backed by an `SkPath`. +/// +/// The `SkPath` is required for `SkCanvas` methods which take a path. +class SkPath implements ui.Path { + js.JsObject _skPath; + + SkPath() { + _skPath = js.JsObject(canvasKit['SkPath']); + } + + js.JsObject _makeSkRect(ui.Rect rect) { + return js.JsObject(canvasKit['LTRBRect'], + [rect.left, rect.top, rect.right, rect.bottom]); + } + + @override + ui.PathFillType fillType; + + @override + void addArc(ui.Rect oval, double startAngle, double sweepAngle) { + throw 'addArc'; + } + + @override + void addOval(ui.Rect oval) { + throw 'addOval'; + } + + @override + void addPath(ui.Path path, ui.Offset offset, {Float64List matrix4}) { + throw 'addPath'; + } + + @override + void addPolygon(List points, bool close) { + throw 'addPolygon'; + } + + @override + void addRRect(ui.RRect rrect) { + final js.JsObject skRect = _makeSkRect(rrect.outerRect); + final List radii = [ + rrect.tlRadiusX, + rrect.tlRadiusY, + rrect.trRadiusX, + rrect.trRadiusY, + rrect.brRadiusX, + rrect.brRadiusY, + rrect.blRadiusX, + rrect.blRadiusY, + ]; + _skPath.callMethod('addRoundRect', [skRect, radii]); + } + + @override + void addRect(ui.Rect rect) { + throw 'addRect'; + } + + @override + void arcTo( + ui.Rect rect, double startAngle, double sweepAngle, bool forceMoveTo) { + throw 'arcTo'; + } + + @override + void arcToPoint(ui.Offset arcEnd, + {ui.Radius radius = ui.Radius.zero, + double rotation = 0.0, + bool largeArc = false, + bool clockwise = true}) { + throw 'arcToPoint'; + } + + @override + void close() { + throw 'close'; + } + + @override + ui.PathMetrics computeMetrics({bool forceClosed = false}) { + throw 'computeMetrics'; + } + + @override + void conicTo(double x1, double y1, double x2, double y2, double w) { + throw 'conicTo'; + } + + @override + bool contains(ui.Offset point) { + throw 'contains'; + } + + @override + void cubicTo( + double x1, double y1, double x2, double y2, double x3, double y3) { + throw 'cubicTo'; + } + + @override + void extendWithPath(ui.Path path, ui.Offset offset, {Float64List matrix4}) { + throw 'extendWithPath'; + } + + @override + ui.Rect getBounds() { + throw 'getBounds'; + } + + @override + void lineTo(double x, double y) { + throw 'lineTo'; + } + + @override + void moveTo(double x, double y) { + throw 'moveTo'; + } + + @override + void quadraticBezierTo(double x1, double y1, double x2, double y2) { + throw 'quadraticBezierTo'; + } + + @override + void relativeArcToPoint(ui.Offset arcEndDelta, + {ui.Radius radius = ui.Radius.zero, + double rotation = 0.0, + bool largeArc = false, + bool clockwise = true}) { + throw 'relativeArcToPoint'; + } + + @override + void relativeConicTo(double x1, double y1, double x2, double y2, double w) { + throw 'relativeConicTo'; + } + + @override + void relativeCubicTo( + double x1, double y1, double x2, double y2, double x3, double y3) { + throw 'relativeCubicTo'; + } + + @override + void relativeLineTo(double dx, double dy) { + throw 'relativeLineTo'; + } + + @override + void relativeMoveTo(double dx, double dy) { + throw 'relativeMoveTo'; + } + + @override + void relativeQuadraticBezierTo(double x1, double y1, double x2, double y2) { + throw 'relativeQuadraticBezierTo'; + } + + @override + void reset() { + throw 'reset'; + } + + @override + ui.Path shift(ui.Offset offset) { + throw 'shift'; + } + + @override + List get subpaths => throw 'subpaths'; + + @override + ui.Path transform(Float64List matrix4) { + throw 'transform'; + } + + @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 + return null; + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/picture.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/picture.dart new file mode 100644 index 0000000000..0796c75ea2 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/picture.dart @@ -0,0 +1,32 @@ +// 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 SkPicture implements ui.Picture { + final js.JsObject skPicture; + + SkPicture(this.skPicture, this.cullRect); + + @override + int get approximateBytesUsed => 0; + + @override + final ui.Rect cullRect; + + @override + void dispose() { + // TODO: implement dispose + } + + @override + // TODO: implement recordingCanvas + RecordingCanvas get recordingCanvas => null; + + @override + Future toImage(int width, int height) { + // TODO: implement toImage + 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 new file mode 100644 index 0000000000..0dd491fa6a --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/picture_recorder.dart @@ -0,0 +1,33 @@ +// 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 SkPictureRecorder implements ui.PictureRecorder { + @override + ui.Rect cullRect; + + js.JsObject _recorder; + + @override + RecordingCanvas beginRecording(ui.Rect bounds) { + cullRect = bounds; + _recorder = js.JsObject(canvasKit['SkPictureRecorder']); + final js.JsObject skRect = js.JsObject(canvasKit['LTRBRect'], + [bounds.left, bounds.top, bounds.right, bounds.bottom]); + final js.JsObject skCanvas = + _recorder.callMethod('beginRecording', [skRect]); + return SkRecordingCanvas(skCanvas); + } + + @override + ui.Picture endRecording() { + js.JsObject skPicture = _recorder.callMethod('finishRecordingAsPicture'); + _recorder.callMethod('delete'); + return SkPicture(skPicture, cullRect); + } + + @override + bool get isRecording => false; +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/platform_message.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/platform_message.dart new file mode 100644 index 0000000000..793f266222 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/platform_message.dart @@ -0,0 +1,18 @@ +// 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 PlatformMessage { + final String channel; + final ByteData data; + final PlatformMessageResponse response; + + PlatformMessage(this.channel, this.data, this.response); +} + +class PlatformMessageResponse { + void complete(Uint8List data) {} + void completeEmpty() {} +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/raster_cache.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/raster_cache.dart new file mode 100644 index 0000000000..b8cb30ef4c --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/raster_cache.dart @@ -0,0 +1,51 @@ +// 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; + +/// A cache of [Picture]s that have already been rasterized. +/// +/// In the case of a [Picture] with a lot of complex drawing commands, it can +/// be faster to rasterize that [Picture] into it's own canvas and composite +/// that canvas into the scene rather than replay the drawing commands for that +/// picture into the overall scene. +/// +/// This class is responsible for deciding if a [Picture] should be cached and +/// for creating the cached [Picture]s that can be drawn directly into the +/// canvas. +class RasterCache { + /// Make a decision on whether to cache [picture] under transform [matrix]. + /// + /// This is based on heuristics such as how many times [picture] has been + /// drawn before and the complexity of the drawing commands in [picture]. + /// + /// We also take into account the current transform [matrix], because, for + /// example, a picture may be rasterized with the identity transform, but + /// when it is used, the transform is a 3x scale. In this case, compositing + /// the rendered picture would result in pixelation. So, we must use both + /// the picture and the transform as a cache key. + /// + /// The flag [isComplex] is a hint to the raster cache that this picture + /// contains complex drawing commands, and as such should be more strongly + /// considered for caching. + /// + /// The flag [willChange] is a hint to the raster cache that this picture + /// will change, and so should be less likely to be cached. + void prepare( + ui.Picture picture, Matrix4 matrix, bool isComplex, bool willChange) {} + + /// Gets a raster cache result for the [picture] at transform [matrix]. + RasterCacheResult get(ui.Picture picture, Matrix4 matrix) => + RasterCacheResult(); +} + +/// A cache entry for a given picture and matrix. +class RasterCacheResult { + /// Whether or not this result represents a rasterized picture that can be + /// drawn into the scene. + bool get isValid => false; + + /// Draws the rasterized picture into the [canvas]. + void draw(SkCanvas canvas) {} +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/rasterizer.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/rasterizer.dart new file mode 100644 index 0000000000..5a6dfcdda0 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/rasterizer.dart @@ -0,0 +1,26 @@ +// 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; + +/// A class that can rasterize [LayerTree]s into a given [Surface]. +class Rasterizer { + final Surface surface; + final CompositorContext context = CompositorContext(); + + Rasterizer(this.surface); + + /// Creates a new frame from this rasterizer's surface, draws the given + /// [LayerTree] into it, and then submits the frame. + void draw(LayerTree layerTree) { + final SurfaceFrame frame = surface.acquireFrame(ui.window.physicalSize); + final SkCanvas canvas = frame.canvas; + final Frame compositorFrame = context.acquireFrame(canvas); + + canvas.clear(); + + compositorFrame.raster(layerTree, ignoreRasterCache: true); + frame.submit(); + } +} 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 new file mode 100644 index 0000000000..71ec4cb2c8 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/recording_canvas.dart @@ -0,0 +1,211 @@ +// 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 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; + + @override + bool _hasArbitraryPaint = true; + + @override + int saveCount; + + @override + // TODO: implement _commands + List get _commands => null; + + @override + // TODO: implement _paintBounds + _PaintBounds get _paintBounds => null; + + @override + void apply(EngineCanvas engineCanvas) { + throw 'apply'; + } + + @override + void clipPath(ui.Path path) { + throw 'clipPath'; + } + + @override + void clipRRect(ui.RRect rrect) { + throw 'clipRRect'; + } + + @override + void clipRect(ui.Rect rect) { + throw 'clipRect'; + } + + @override + ui.Rect computePaintBounds() { + throw 'computePaintBounds'; + } + + @override + void debugDumpCommands() { + throw 'debugDumpCommands'; + } + + @override + void debugEnforceArbitraryPaint() { + throw 'debugEnforceArbitraryPaint'; + } + + @override + String debugPrintCommands() { + throw 'debugPrintCommands'; + } + + @override + bool get didDraw => true; + + @override + void drawCircle(ui.Offset c, double radius, ui.Paint paint) { + throw 'drawCircle'; + } + + @override + void drawColor(ui.Color color, ui.BlendMode blendMode) { + throw 'drawColor'; + } + + @override + void drawDRRect(ui.RRect outer, ui.RRect inner, ui.Paint paint) { + throw 'drawDRRect'; + } + + @override + void drawImage(ui.Image image, ui.Offset offset, ui.Paint paint) { + throw 'drawImage'; + } + + @override + void drawImageRect(ui.Image image, ui.Rect src, ui.Rect dst, ui.Paint paint) { + throw 'drawImageRect'; + } + + @override + void drawLine(ui.Offset p1, ui.Offset p2, ui.Paint paint) { + throw 'drawLine'; + } + + @override + void drawOval(ui.Rect rect, ui.Paint paint) { + throw 'drawOval'; + } + + @override + void drawPaint(ui.Paint paint) { + throw 'drawPaint'; + } + + @override + void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) { + throw 'drawParagraph'; + } + + @override + void drawPath(ui.Path path, ui.Paint paint) { + throw 'drawPath'; + } + + @override + void drawRRect(ui.RRect rrect, ui.Paint paint) { + throw 'drawRRect'; + } + + @override + void drawRect(ui.Rect rect, ui.Paint 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'; + } + + @override + bool get hasArbitraryPaint => true; + + @override + void restore() { + throw 'restore'; + } + + @override + void rotate(double radians) { + throw 'rotate'; + } + + @override + void save() { + throw 'save'; + } + + @override + void saveLayer(ui.Rect bounds, ui.Paint paint) { + throw 'saveLayer'; + } + + @override + void saveLayerWithoutBounds(ui.Paint paint) { + throw 'saveLayerWithoutBounds'; + } + + @override + void scale(double sx, double sy) { + throw 'scale'; + } + + @override + void skew(double sx, double sy) { + throw 'skew'; + } + + @override + void transform(Float64List matrix4) { + throw 'transform'; + } + + @override + void translate(double dx, double dy) { + throw 'translate'; + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/runtime_delegate.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/runtime_delegate.dart new file mode 100644 index 0000000000..c0c0aa0b04 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/runtime_delegate.dart @@ -0,0 +1,13 @@ +// 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; + +abstract class RuntimeDelegate { + String get defaultRouteName; + void scheduleFrame({bool regenerateLayerTree = true}); + void render(LayerTree layerTree); + void handlePlatformMessage(PlatformMessage message); + FontCollection getFontCollection(); +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/surface.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/surface.dart new file mode 100644 index 0000000000..d372ad1371 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/surface.dart @@ -0,0 +1,60 @@ +// 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; + +/// A frame which contains a canvas to be drawn into. +class SurfaceFrame { + final void Function(SkCanvas) submitFn; + final SkCanvas canvas; + SurfaceFrame(this.submitFn, this.canvas); + + /// Submit this frame to be drawn. + void submit() { + submitFn(canvas); + } +} + +/// A surface which can be drawn into by the compositor. +/// +/// The underlying representation is a [BitmapCanvas], which can be reused by +/// successive frames if they are the same size. Otherwise, a new canvas is +/// created. +class Surface { + final _CanvasCache canvasCache = _CanvasCache(); + + /// This function is called with the canvas once drawing on it has been + /// completed for a frame. + final void Function(SkCanvas) submitFunction; + + Surface(this.submitFunction); + + /// Acquire a frame of the given [size] containing a drawable canvas. + SurfaceFrame acquireFrame(ui.Size size) { + final SkCanvas canvas = canvasCache.acquireCanvas(size); + return SurfaceFrame(submitFunction, canvas); + } + + Matrix4 get rootTransformation => null; +} + +class _CanvasCache { + SkCanvas _canvas; + + SkCanvas acquireCanvas(ui.Size size) { + assert(size != null); + if (size == _canvas?.size) { + return _canvas; + } + final html.CanvasElement htmlCanvas = + html.CanvasElement(width: size.width.ceil(), height: size.height.ceil()) + ..id = 'flt-sk-canvas'; + domRenderer.renderScene(htmlCanvas); + final js.JsObject surface = + canvasKit.callMethod('MakeCanvasSurface', ['flt-sk-canvas']); + final js.JsObject skCanvas = surface.callMethod('getCanvas'); + _canvas = SkCanvas(skCanvas, htmlCanvas, surface, size); + return _canvas; + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/viewport_metrics.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/viewport_metrics.dart new file mode 100644 index 0000000000..d53d021748 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/compositor/viewport_metrics.dart @@ -0,0 +1,17 @@ +// 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 ViewportMetrics { + final double devicePixelRatio; + final double physicalWidth; + final double physicalHeight; + + const ViewportMetrics( + this.devicePixelRatio, + this.physicalWidth, + this.physicalHeight, + ); +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/conic.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/conic.dart new file mode 100644 index 0000000000..fd05604ae1 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/conic.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. + +part of engine; + +/// Converts conic curve to a list of quadratic curves for rendering on +/// canvas or conversion to svg. +/// +/// See "High order approximation of conic sections by quadratic splines" +/// by Michael Floater, 1993. +/// Skia implementation reference: +/// https://github.com/google/skia/blob/master/src/core/SkGeometry.cpp +class Conic { + double p0x, p0y, p1x, p1y, p2x, p2y; + final double fW; + static const int _maxSubdivisionCount = 5; + + Conic(this.p0x, this.p0y, this.p1x, this.p1y, this.p2x, this.p2y, this.fW); + + /// Returns array of points for the approximation of the conic as quad(s). + /// + /// First offset is start Point. Each pair of offsets after are quadratic + /// control and end points. + List toQuads() { + final List pointList = []; + // This value specifies error bound. + const double conicTolerance = 1.0 / 4.0; + + // Based on error bound, compute how many times we should subdivide + final int subdivideCount = _computeSubdivisionCount(conicTolerance); + + // Split conic into quads, writes quad coordinates into [_pointList] and + // returns number of quads. + assert(subdivideCount > 0); + int quadCount = 1 << subdivideCount; + bool skipSubdivide = false; + pointList.add(ui.Offset(p0x, p0y)); + if (subdivideCount == _maxSubdivisionCount) { + // We have an extreme number of quads, chop this conic and check if + // it generates a pair of lines, in which case we should not subdivide. + final List dst = List(2); + _chop(dst); + final Conic conic0 = dst[0]; + final Conic conic1 = dst[1]; + // If this chop generates pair of lines no need to subdivide. + if (conic0.p1x == conic0.p2x && + conic0.p1y == conic0.p2y && + conic1.p0x == conic1.p1x && + conic1.p0y == conic1.p1y) { + final ui.Offset controlPointOffset = ui.Offset(conic0.p1x, conic0.p1y); + pointList.add(controlPointOffset); + pointList.add(controlPointOffset); + pointList.add(controlPointOffset); + pointList.add(ui.Offset(conic1.p2x, conic1.p2y)); + quadCount = 2; + skipSubdivide = true; + } + } + if (!skipSubdivide) { + _subdivide(this, subdivideCount, pointList); + } + + // If there are any non-finite generated points, pin to middle of hull. + final int pointCount = 2 * quadCount + 1; + bool hasNonFinitePoints = false; + for (int p = 0; p < pointCount; ++p) { + if (pointList[p].dx.isNaN || pointList[p].dy.isNaN) { + hasNonFinitePoints = true; + break; + } + } + if (hasNonFinitePoints) { + for (int p = 1; p < pointCount - 1; ++p) { + pointList[p] = ui.Offset(p1x, p1y); + } + } + return pointList; + } + + static bool _between(double a, double b, double c) { + return (a - b) * (c - b) <= 0; + } + + // Subdivides a conic and writes to points list. + static void _subdivide(Conic src, int level, List pointList) { + assert(level >= 0); + if (0 == level) { + // At lowest subdivision point, copy control point and end point to + // target. + pointList.add(ui.Offset(src.p1x, src.p1y)); + pointList.add(ui.Offset(src.p2x, src.p2y)); + return; + } + final List dst = List(2); + src._chop(dst); + final Conic conic0 = dst[0]; + final Conic conic1 = dst[1]; + final double startY = src.p0y; + final double endY = src.p2y; + final double cpY = src.p1y; + if (_between(startY, cpY, endY)) { + // Ensure that chopped conics maintain their y-order. + final double midY = conic0.p2y; + if (!_between(startY, midY, endY)) { + // The computed midpoint is outside end points, move it to + // closer one. + final double closerY = + (midY - startY).abs() < (midY - endY).abs() ? startY : endY; + conic0.p2y = conic1.p0y = closerY; + } + if (!_between(startY, conic0.p1y, conic0.p2y)) { + // First control point not between start and end points, move it + // to start. + conic0.p1y = startY; + } + if (!_between(conic1.p0y, conic1.p1y, endY)) { + // Second control point not between start and end points, move it + // to end. + conic1.p1y = endY; + } + // Verify that conics points are ordered. + assert(_between(startY, conic0.p1y, conic0.p2y)); + assert(_between(conic0.p1y, conic0.p2y, conic1.p1y)); + assert(_between(conic0.p2y, conic1.p1y, endY)); + } + --level; + _subdivide(conic0, level, pointList); + _subdivide(conic1, level, pointList); + } + + static double _subdivideWeightValue(double w) { + return math.sqrt(0.5 + w * 0.5); + } + + // Splits conic into 2 parts based on weight. + void _chop(List dst) { + final double scale = 1.0 / (1.0 + fW); + final double newW = _subdivideWeightValue(fW); + final ui.Offset wp1 = ui.Offset(fW * p1x, fW * p1y); + ui.Offset m = ui.Offset((p0x + (2 * wp1.dx) + p2x) * scale * 0.5, + (p0y + 2 * wp1.dy + p2y) * scale * 0.5); + if (m.dx.isNaN || m.dy.isNaN) { + final double w2 = fW * 2; + final double scaleHalf = 1.0 / (1 + fW) * 0.5; + m = ui.Offset((p0x + (w2 * p1x) + p2x) * scaleHalf, + (p0y + (w2 * p1y) + p2y) * scaleHalf); + } + dst[0] = Conic(p0x, p0y, (p0x + wp1.dx) * scale, (p0y + wp1.dy) * scale, + m.dx, m.dy, newW); + dst[1] = Conic(m.dx, m.dy, (p2x + wp1.dx) * scale, (p2y + wp1.dy) * scale, + p2x, p2y, newW); + } + + /// Computes number of binary subdivisions of the curve given + /// the tolerance. + /// + /// The number of subdivisions never exceed [_maxSubdivisionCount]. + int _computeSubdivisionCount(double tolerance) { + assert(tolerance.isFinite); + // Expecting finite coordinates. + assert(p0x.isFinite && + p1x.isFinite && + p2x.isFinite && + p0y.isFinite && + p1y.isFinite && + p2y.isFinite); + if (tolerance < 0) { + return 0; + } + // See "High order approximation of conic sections by quadratic splines" + // by Michael Floater, 1993. + // Error bound e0 = |a| |p0 - 2p1 + p2| / 4(2 + a). + final double a = fW - 1; + final double k = a / (4.0 * (2.0 + a)); + final double x = k * (p0x - 2 * p1x + p2x); + final double y = k * (p0y - 2 * p1y + p2y); + + double error = math.sqrt(x * x + y * y); + int pow2 = 0; + for (; pow2 < _maxSubdivisionCount; ++pow2) { + if (error <= tolerance) { + break; + } + error *= 0.25; + } + return pow2; + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/dom_canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/dom_canvas.dart new file mode 100644 index 0000000000..93df70a24b --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/dom_canvas.dart @@ -0,0 +1,176 @@ +// 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; + +/// A canvas that renders to DOM elements and CSS properties. +class DomCanvas extends EngineCanvas with SaveElementStackTracking { + @override + final html.Element rootElement = html.Element.tag('flt-dom-canvas'); + + DomCanvas() { + rootElement.style + ..position = 'absolute' + ..top = '0' + ..right = '0' + ..bottom = '0' + ..left = '0'; + } + + /// Prepare to reuse this canvas by clearing it's current contents. + @override + void clear() { + super.clear(); + // TODO(yjbanov): we should measure if reusing old elements is beneficial. + domRenderer.clearDom(rootElement); + } + + @override + void clipRect(ui.Rect rect) { + throw UnimplementedError(); + } + + @override + void clipRRect(ui.RRect rrect) { + throw UnimplementedError(); + } + + @override + void clipPath(ui.Path path) { + throw UnimplementedError(); + } + + @override + void drawColor(ui.Color color, ui.BlendMode blendMode) { + // TODO(yjbanov): implement blendMode + final html.Element box = html.Element.tag('draw-color'); + box.style + ..position = 'absolute' + ..top = '0' + ..right = '0' + ..bottom = '0' + ..left = '0' + ..backgroundColor = color.toCssString(); + currentElement.append(box); + } + + @override + void drawLine(ui.Offset p1, ui.Offset p2, ui.PaintData paint) { + throw UnimplementedError(); + } + + @override + void drawPaint(ui.PaintData paint) { + throw UnimplementedError(); + } + + @override + void drawRect(ui.Rect rect, ui.PaintData paint) { + assert(paint.shader == null); + final html.Element rectangle = html.Element.tag('draw-rect'); + assert(() { + rectangle.setAttribute('flt-rect', '$rect'); + rectangle.setAttribute('flt-paint', '$paint'); + return true; + }()); + String effectiveTransform; + final bool isStroke = paint.style == ui.PaintingStyle.stroke; + final double left = math.min(rect.left, rect.right); + final double right = math.max(rect.left, rect.right); + final double top = math.min(rect.top, rect.bottom); + final double bottom = math.max(rect.top, rect.bottom); + if (currentTransform.isIdentity()) { + if (isStroke) { + effectiveTransform = + 'translate(${left - (paint.strokeWidth / 2.0)}px, ${top - (paint.strokeWidth / 2.0)}px)'; + } else { + effectiveTransform = 'translate(${left}px, ${top}px)'; + } + } else { + // Clone to avoid mutating _transform. + final Matrix4 translated = currentTransform.clone(); + if (isStroke) { + translated.translate( + left - (paint.strokeWidth / 2.0), top - (paint.strokeWidth / 2.0)); + } else { + translated.translate(left, top); + } + effectiveTransform = matrix4ToCssTransform(translated); + } + final html.CssStyleDeclaration style = rectangle.style; + style + ..position = 'absolute' + ..transformOrigin = '0 0 0' + ..transform = effectiveTransform; + + final String cssColor = paint.color?.toCssString() ?? '#000000'; + + if (paint.maskFilter != null) { + style.filter = 'blur(${paint.maskFilter.webOnlySigma}px)'; + } + + if (isStroke) { + style + ..width = '${right - left - paint.strokeWidth}px' + ..height = '${bottom - top - paint.strokeWidth}px' + ..border = '${paint.strokeWidth}px solid $cssColor'; + } else { + style + ..width = '${right - left}px' + ..height = '${bottom - top}px' + ..backgroundColor = cssColor; + } + + currentElement.append(rectangle); + } + + @override + void drawRRect(ui.RRect rrect, ui.PaintData paint) { + throw UnimplementedError(); + } + + @override + void drawDRRect(ui.RRect outer, ui.RRect inner, ui.PaintData paint) { + throw UnimplementedError(); + } + + @override + void drawOval(ui.Rect rect, ui.PaintData paint) { + throw UnimplementedError(); + } + + @override + void drawCircle(ui.Offset c, double radius, ui.PaintData paint) { + throw UnimplementedError(); + } + + @override + void drawPath(ui.Path path, ui.PaintData paint) { + throw UnimplementedError(); + } + + @override + void drawShadow(ui.Path path, ui.Color color, double elevation, + bool transparentOccluder) { + throw UnimplementedError(); + } + + @override + void drawImage(ui.Image image, ui.Offset p, ui.PaintData paint) { + throw UnimplementedError(); + } + + @override + void drawImageRect( + ui.Image image, ui.Rect src, ui.Rect dst, ui.PaintData paint) { + throw UnimplementedError(); + } + + @override + void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) { + final html.Element paragraphElement = + _drawParagraphElement(paragraph, offset, transform: currentTransform); + currentElement.append(paragraphElement); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/dom_renderer.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/dom_renderer.dart new file mode 100644 index 0000000000..8252d7ea47 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/dom_renderer.dart @@ -0,0 +1,503 @@ +// 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 DomRenderer { + DomRenderer() { + if (assertionsEnabled) { + _debugFrameStatistics = DebugDomRendererFrameStatistics(); + } + + reset(); + + TextMeasurementService.initialize(rulerCacheCapacity: 10); + + assert(() { + _setupHotRestart(); + return true; + }()); + } + + static const int vibrateLongPress = 50; + static const int vibrateLightImpact = 10; + static const int vibrateMediumImpact = 20; + static const int vibrateHeavyImpact = 30; + static const int vibrateSelectionClick = 10; + + /// Listens to window resize events. + StreamSubscription _resizeSubscription; + + /// Contains Flutter-specific CSS rules, such as default margins and + /// paddings. + html.StyleElement _styleElement; + + /// Configures the screen, such as scaling. + html.MetaElement _viewportMeta; + + /// The canvaskit script, downloaded from a CDN. Only created if + /// [experimentalUseSkia] is set to true. + html.ScriptElement get canvasKitScript => _canvasKitScript; + html.ScriptElement _canvasKitScript; + + /// The element that contains the [sceneElement]. + /// + /// This element is created and inserted in the HTML DOM once. It is never + /// removed or moved. However the [sceneElement] may be replaced inside it. + /// + /// This element precedes the [glassPaneElement] so that it never receives + /// input events. All input events are processed by [glassPaneElement] and the + /// semantics tree. + html.Element get sceneHostElement => _sceneHostElement; + html.Element _sceneHostElement; + + /// The last scene element rendered by the [render] method. + html.Element get sceneElement => _sceneElement; + html.Element _sceneElement; + + /// This is state persistant across hot restarts that indicates what + /// to clear. We delay removal of old visible state to make the + /// transition appear smooth. + static const String _staleHotRestartStore = '__flutter_state'; + List _staleHotRestartState; + + void _setupHotRestart() { + // This persists across hot restarts to clear stale DOM. + _staleHotRestartState = + js_util.getProperty(html.window, _staleHotRestartStore); + if (_staleHotRestartState == null) { + _staleHotRestartState = []; + js_util.setProperty( + html.window, _staleHotRestartStore, _staleHotRestartState); + } + + registerHotRestartListener(() { + _resizeSubscription?.cancel(); + _staleHotRestartState.addAll([ + _glassPaneElement, + _styleElement, + _viewportMeta, + _canvasKitScript, + ]); + }); + } + + void _clearOnHotRestart() { + if (_staleHotRestartState.isNotEmpty) { + for (html.Element element in _staleHotRestartState) { + element?.remove(); + } + _staleHotRestartState.clear(); + } + } + + /// We don't want to unnecessarily move DOM nodes around. If a DOM node is + /// already in the right place, skip DOM mutation. This is both faster and + /// more correct, because moving DOM nodes loses internal state, such as + /// text selection. + void renderScene(html.Element sceneElement) { + if (sceneElement != _sceneElement) { + _sceneElement?.remove(); + _sceneElement = sceneElement; + append(_sceneHostElement, sceneElement); + } + assert(() { + _clearOnHotRestart(); + return true; + }()); + } + + /// The element that captures input events, such as pointer events. + /// + /// If semantics is enabled this element also contains the semantics DOM tree, + /// which captures semantics input events. The semantics DOM tree must be a + /// child of the glass pane element so that events bubble up to the glass pane + /// if they are not handled by semantics. + html.Element get glassPaneElement => _glassPaneElement; + html.Element _glassPaneElement; + + final html.Element rootElement = html.document.body; + + void addElementClass(html.Element element, String className) { + element.classes.add(className); + } + + void attachBeforeElement( + html.Element parent, html.Element before, html.Element newElement) { + assert(parent != null); + if (parent != null) { + assert(() { + if (before == null) { + return true; + } + if (before.parent != parent) { + throw Exception( + 'attachBeforeElement was called with `before` element that\'s ' + 'not a child of the `parent` element:\n' + ' before: $before\n' + ' parent: $parent', + ); + } + return true; + }()); + parent.insertBefore(newElement, before); + } + } + + html.Element createElement(String tagName, {html.Element parent}) { + final html.Element element = html.document.createElement(tagName); + parent?.append(element); + return element; + } + + void append(html.Element parent, html.Element child) { + parent.append(child); + } + + void appendText(html.Element parent, String text) { + parent.appendText(text); + } + + void detachElement(html.Element element) { + element.remove(); + } + + void removeElementClass(html.Element element, String className) { + element.classes.remove(className); + } + + void setElementAttribute(html.Element element, String name, String value) { + element.setAttribute(name, value); + } + + void setElementProperty(html.Element element, String name, Object value) { + js_util.setProperty(element, name, value); + } + + void setElementStyle(html.Element element, String name, String value) { + if (value == null) { + element.style.removeProperty(name); + } else { + element.style.setProperty(name, value); + } + } + + void setText(html.Element element, String text) { + element.text = text; + } + + void removeAllChildren(html.Element element) { + element.children.clear(); + } + + html.Element getParent(html.Element element) => element.parent; + + void setTitle(String title) { + html.document.title = title; + } + + void setThemeColor(ui.Color color) { + html.MetaElement theme = html.document.querySelector('#flutterweb-theme'); + if (theme == null) { + theme = html.MetaElement() + ..id = 'flutterweb-theme' + ..name = 'theme-color'; + html.document.head.append(theme); + } + theme.content = color.toCssString(); + } + + static const String defaultFontStyle = 'normal'; + static const String defaultFontWeight = 'normal'; + static const String defaultFontSize = '14px'; + static const String defaultFontFamily = 'sans-serif'; + static const String defaultCssFont = + '$defaultFontStyle $defaultFontWeight $defaultFontSize $defaultFontFamily'; + + void reset() { + _styleElement?.remove(); + _styleElement = html.StyleElement(); + html.document.head.append(_styleElement); + final html.CssStyleSheet sheet = _styleElement.sheet; + + // TODO(butterfly): use more efficient CSS selectors; descendant selectors + // are slow. More info: + // + // https://csswizardry.com/2011/09/writing-efficient-css-selectors/ + + // This undoes browser's default layout attributes for paragraphs. We + // compute paragraph layout ourselves. + sheet.insertRule(''' +flt-ruler-host p, flt-scene p { + margin: 0; +}''', sheet.cssRules.length); + + // This undoes browser's default painting and layout attributes of range + // input, which is used in semantics. + sheet.insertRule(''' +flt-semantics input[type=range] { + appearance: none; + -webkit-appearance: none; + width: 100%; + position: absolute; + border: none; + top: 0; + right: 0; + bottom: 0; + left: 0; +}''', sheet.cssRules.length); + + if (browserEngine == BrowserEngine.webkit) { + sheet.insertRule( + 'flt-semantics input[type=range]::-webkit-slider-thumb {' + ' -webkit-appearance: none;' + '}', + sheet.cssRules.length); + + // On iOS, the invisible semantic text field has a visible cursor and + // selection highlight. The following 2 CSS rules force everything to be + // transparent. + sheet.insertRule( + 'flt-semantics ::selection {' + ' background-color: transparent;' + '}', + sheet.cssRules.length); + } + sheet.insertRule(''' +flt-semantics input, +flt-semantics textarea, +flt-semantics [contentEditable="true"] { + caret-color: transparent; +} +''', sheet.cssRules.length); + + // By default on iOS, Safari would highlight the element that's being tapped + // on using gray background. This CSS rule disables that. + if (browserEngine == BrowserEngine.webkit) { + sheet.insertRule(''' +flt-glass-pane * { + -webkit-tap-highlight-color: transparent; +} +''', sheet.cssRules.length); + } + + final html.BodyElement bodyElement = html.document.body; + setElementStyle(bodyElement, 'position', 'fixed'); + setElementStyle(bodyElement, 'top', '0'); + setElementStyle(bodyElement, 'right', '0'); + setElementStyle(bodyElement, 'bottom', '0'); + setElementStyle(bodyElement, 'left', '0'); + setElementStyle(bodyElement, 'overflow', 'hidden'); + setElementStyle(bodyElement, 'padding', '0'); + setElementStyle(bodyElement, 'margin', '0'); + + // TODO(yjbanov): fix this when we support KVM I/O. Currently we scroll + // using drag, and text selection interferes. + setElementStyle(bodyElement, 'user-select', 'none'); + setElementStyle(bodyElement, '-webkit-user-select', 'none'); + setElementStyle(bodyElement, '-ms-user-select', 'none'); + setElementStyle(bodyElement, '-moz-user-select', 'none'); + + // This is required to prevent the browser from doing any native touch + // handling. If we don't do this, the browser doesn't report 'pointermove' + // events properly. + setElementStyle(bodyElement, 'touch-action', 'none'); + + // These are intentionally outrageous font parameters to make sure that the + // apps fully specifies their text styles. + setElementStyle(bodyElement, 'font', defaultCssFont); + setElementStyle(bodyElement, 'color', 'red'); + + for (html.Element viewportMeta + in html.document.head.querySelectorAll('meta[name="viewport"]')) { + if (assertionsEnabled) { + // Filter out the meta tag that we ourselves placed on the page. This is + // to avoid UI flicker during hot restart. Hot restart will clean up the + // old meta tag synchronously with the first post-restart frame. + if (!viewportMeta.hasAttribute('flt-viewport')) { + print( + 'WARNING: found an existing tag. Flutter ' + 'Web uses its own viewport configuration for better compatibility ' + 'with Flutter. This tag will be replaced.', + ); + } + } + viewportMeta.remove(); + } + + // This removes a previously created meta tag. Note, however, that this does + // not remove the meta tag during hot restart. Hot restart resets all static + // variables, so this will be null upon hot restart. Instead, this tag is + // removed by _clearOnHotRestart. + _viewportMeta?.remove(); + _viewportMeta = html.MetaElement() + ..setAttribute('flt-viewport', '') + ..name = 'viewport' + ..content = 'width=device-width, initial-scale=1.0, ' + 'maximum-scale=1.0, user-scalable=no'; + html.document.head.append(_viewportMeta); + + // IMPORTANT: the glass pane element must come after the scene element in the DOM node list so + // it can intercept input events. + _glassPaneElement?.remove(); + _glassPaneElement = createElement('flt-glass-pane'); + _glassPaneElement.style + ..position = 'absolute' + ..top = '0' + ..right = '0' + ..bottom = '0' + ..left = '0'; + bodyElement.append(_glassPaneElement); + + _sceneHostElement = createElement('flt-scene-host'); + + // Don't allow the scene to receive pointer events. + _sceneHostElement.style.pointerEvents = 'none'; + + _glassPaneElement.append(_sceneHostElement); + + EngineSemanticsOwner.instance.autoEnableOnTap(this); + PointerBinding(this); + + // Hide the DOM nodes used to render the scene from accessibility, because + // the accessibility tree is built from the SemanticsNode tree as a parallel + // DOM tree. + setElementAttribute(_sceneHostElement, 'aria-hidden', 'true'); + + // We treat browser pixels as device pixels because pointer events, + // position, and sizes all use browser pixel as the unit (i.e. "px" in CSS). + // Therefore, as far as the framework is concerned the device pixel ratio + // is 1.0. + window.debugOverrideDevicePixelRatio(1.0); + + if (browserEngine == BrowserEngine.webkit) { + // Safari sometimes gives us bogus innerWidth/innerHeight values when the + // page loads. When it changes the values to correct ones it does not + // notify of the change via `onResize`. As a workaround, we setup a + // temporary periodic timer that polls innerWidth and triggers the + // resizeListener so that the framework can react to the change. + final int initialInnerWidth = html.window.innerWidth; + // Counts how many times we checked screen size. We check up to 5 times. + int checkCount = 0; + Timer.periodic(const Duration(milliseconds: 100), (Timer t) { + checkCount += 1; + if (initialInnerWidth != html.window.innerWidth) { + // Window size changed. Notify. + t.cancel(); + _metricsDidChange(null); + } else if (checkCount > 5) { + // Checked enough times. Stop. + t.cancel(); + } + }); + } + + if (experimentalUseSkia) { + _canvasKitScript?.remove(); + _canvasKitScript = html.ScriptElement(); + _canvasKitScript.src = canvasKitBaseUrl + 'canvaskit.js'; + html.document.head.append(_canvasKitScript); + } + + _resizeSubscription = html.window.onResize.listen(_metricsDidChange); + } + + /// Called immediately after browser window metrics change. + void _metricsDidChange(html.Event event) { + if (ui.window.onMetricsChanged != null) { + ui.window.onMetricsChanged(); + } + } + + void focus(html.Element element) { + element.focus(); + } + + /// Removes all children of a DOM node. + void clearDom(html.Node node) { + while (node.lastChild != null) { + node.lastChild.remove(); + } + } + + /// The element corresponding to the only child of the root surface. + html.Element get _rootApplicationElement { + final html.Element lastElement = rootElement.children.last; + return lastElement.children.singleWhere((html.Element element) { + return element.tagName == 'FLT-SCENE'; + }, orElse: () => null); + } + + /// Provides haptic feedback. + void vibrate(int durationMs) { + final html.Navigator navigator = html.window.navigator; + if (js_util.hasProperty(navigator, 'vibrate')) { + js_util.callMethod(navigator, 'vibrate', [durationMs]); + } + } + + String get currentHtml => _rootApplicationElement?.outerHtml ?? ''; + + DebugDomRendererFrameStatistics _debugFrameStatistics; + + DebugDomRendererFrameStatistics debugFlushFrameStatistics() { + if (!assertionsEnabled) { + throw Exception('This code should not be reachable in production.'); + } + final DebugDomRendererFrameStatistics current = _debugFrameStatistics; + _debugFrameStatistics = DebugDomRendererFrameStatistics(); + return current; + } + + void debugRulerCacheHit() => _debugFrameStatistics.paragraphRulerCacheHits++; + void debugRulerCacheMiss() => + _debugFrameStatistics.paragraphRulerCacheMisses++; + void debugRichTextLayout() => _debugFrameStatistics.richTextLayouts++; + void debugPlainTextLayout() => _debugFrameStatistics.plainTextLayouts++; +} + +/// Miscellaneous statistics collecting during a single frame's execution. +/// +/// This is useful when profiling the app. This class should only be used when +/// assertions are enabled and therefore is not suitable for collecting any +/// time measurements. It is mostly useful for counting certain events. +class DebugDomRendererFrameStatistics { + /// The number of times we reused a previously initialized paragraph ruler to + /// measure a paragraph of text. + int paragraphRulerCacheHits = 0; + + /// The number of times we had to create a new paragraph ruler to measure a + /// paragraph of text. + int paragraphRulerCacheMisses = 0; + + /// The number of times we used a paragraph ruler to measure a paragraph of + /// text. + int get totalParagraphRulerAccesses => + paragraphRulerCacheHits + paragraphRulerCacheMisses; + + /// The number of times a paragraph of rich text was laid out this frame. + int richTextLayouts = 0; + + /// The number of times a paragraph of plain text was laid out this frame. + int plainTextLayouts = 0; + + @override + String toString() { + return ''' +Frame statistics: + Paragraph ruler cache hits: $paragraphRulerCacheHits + Paragraph ruler cache misses: $paragraphRulerCacheMisses + Paragraph ruler accesses: $totalParagraphRulerAccesses + Rich text layouts: $richTextLayouts + Plain text layouts: $plainTextLayouts +''' + .trim(); + } +} + +// TODO(yjbanov): Replace this with an explicit initialization function. The +// lazy initialization of statics makes it very unpredictable, as +// the constructor has side-effects. +/// Singleton DOM renderer. +final DomRenderer domRenderer = DomRenderer(); diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/engine_canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/engine_canvas.dart new file mode 100644 index 0000000000..66854a3d59 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/engine_canvas.dart @@ -0,0 +1,274 @@ +// 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; + +/// Defines canvas interface common across canvases that the [SceneBuilder] +/// renders to. +/// +/// This can be used either as an interface or super-class. +abstract class EngineCanvas { + /// The element that is attached to the DOM. + html.Element get rootElement; + + void dispose() { + clear(); + } + + void clear(); + + void save(); + + void restore(); + + void translate(double dx, double dy); + + void scale(double sx, double sy); + + void rotate(double radians); + + void skew(double sx, double sy); + + void transform(Float64List matrix4); + + void clipRect(ui.Rect rect); + + void clipRRect(ui.RRect rrect); + + void clipPath(ui.Path path); + + void drawColor(ui.Color color, ui.BlendMode blendMode); + + void drawLine(ui.Offset p1, ui.Offset p2, ui.PaintData paint); + + void drawPaint(ui.PaintData paint); + + void drawRect(ui.Rect rect, ui.PaintData paint); + + void drawRRect(ui.RRect rrect, ui.PaintData paint); + + void drawDRRect(ui.RRect outer, ui.RRect inner, ui.PaintData paint); + + void drawOval(ui.Rect rect, ui.PaintData paint); + + void drawCircle(ui.Offset c, double radius, ui.PaintData paint); + + void drawPath(ui.Path path, ui.PaintData paint); + + void drawShadow( + ui.Path path, ui.Color color, double elevation, bool transparentOccluder); + + void drawImage(ui.Image image, ui.Offset p, ui.PaintData paint); + + void drawImageRect( + ui.Image image, ui.Rect src, ui.Rect dst, ui.PaintData paint); + + void drawParagraph(EngineParagraph paragraph, ui.Offset offset); +} + +/// Adds an [offset] transformation to a [transform] matrix and returns the +/// combined result. +/// +/// If the given offset is zero, returns [transform] matrix as is. Otherwise, +/// returns a new [Matrix4] object representing the combined transformation. +Matrix4 transformWithOffset(Matrix4 transform, ui.Offset offset) { + if (offset == ui.Offset.zero) { + return transform; + } + + // Clone to avoid mutating transform. + final Matrix4 effectiveTransform = transform.clone(); + effectiveTransform.translate(offset.dx, offset.dy, 0.0); + return effectiveTransform; +} + +class _SaveStackEntry { + _SaveStackEntry({ + @required this.transform, + @required this.clipStack, + }); + + final Matrix4 transform; + final List<_SaveClipEntry> clipStack; +} + +/// Tagged union of clipping parameters used for canvas. +class _SaveClipEntry { + final ui.Rect rect; + final ui.RRect rrect; + final ui.Path path; + final Matrix4 currentTransform; + _SaveClipEntry.rect(this.rect, this.currentTransform) + : rrect = null, + path = null; + _SaveClipEntry.rrect(this.rrect, this.currentTransform) + : rect = null, + path = null; + _SaveClipEntry.path(this.path, this.currentTransform) + : rect = null, + rrect = null; +} + +/// Provides save stack tracking functionality to implementations of +/// [EngineCanvas]. +mixin SaveStackTracking on EngineCanvas { + static final Vector3 _unitZ = Vector3(0.0, 0.0, 1.0); + + final List<_SaveStackEntry> _saveStack = <_SaveStackEntry>[]; + + /// The stack that maintains clipping operations used when text is painted + /// onto bitmap canvas but is composited as separate element. + List<_SaveClipEntry> _clipStack; + + /// Returns whether there are active clipping regions on the canvas. + bool get isClipped => _clipStack != null; + + /// Empties the save stack and the element stack, and resets the transform + /// and clip parameters. + /// + /// Classes that override this method must call `super.clear()`. + @override + void clear() { + _saveStack.clear(); + _clipStack = null; + _currentTransform = Matrix4.identity(); + } + + /// The current transformation matrix. + Matrix4 get currentTransform => _currentTransform; + Matrix4 _currentTransform = Matrix4.identity(); + + /// Saves current clip and transform on the save stack. + /// + /// Classes that override this method must call `super.save()`. + @override + void save() { + _saveStack.add(_SaveStackEntry( + transform: _currentTransform.clone(), + clipStack: + _clipStack == null ? null : List<_SaveClipEntry>.from(_clipStack), + )); + } + + /// Restores current clip and transform from the save stack. + /// + /// Classes that override this method must call `super.restore()`. + @override + void restore() { + if (_saveStack.isEmpty) { + return; + } + final _SaveStackEntry entry = _saveStack.removeLast(); + _currentTransform = entry.transform; + _clipStack = entry.clipStack; + } + + /// Multiplies the [currentTransform] matrix by a translation. + /// + /// Classes that override this method must call `super.translate()`. + @override + void translate(double dx, double dy) { + _currentTransform.translate(dx, dy); + } + + /// Scales the [currentTransform] matrix. + /// + /// Classes that override this method must call `super.scale()`. + @override + void scale(double sx, double sy) { + _currentTransform.scale(sx, sy); + } + + /// Rotates the [currentTransform] matrix. + /// + /// Classes that override this method must call `super.rotate()`. + @override + void rotate(double radians) { + _currentTransform.rotate(_unitZ, radians); + } + + /// Skews the [currentTransform] matrix. + /// + /// Classes that override this method must call `super.skew()`. + @override + void skew(double sx, double sy) { + final Matrix4 skewMatrix = Matrix4.identity(); + final Float64List storage = skewMatrix.storage; + storage[1] = sy; + storage[4] = sx; + _currentTransform.multiply(skewMatrix); + } + + /// Multiplies the [currentTransform] matrix by another matrix. + /// + /// Classes that override this method must call `super.transform()`. + @override + void transform(Float64List matrix4) { + _currentTransform.multiply(Matrix4.fromFloat64List(matrix4)); + } + + /// Adds a rectangle to clipping stack. + /// + /// Classes that override this method must call `super.clipRect()`. + @override + void clipRect(ui.Rect rect) { + _clipStack ??= <_SaveClipEntry>[]; + _clipStack.add(_SaveClipEntry.rect(rect, _currentTransform.clone())); + } + + /// Adds a round rectangle to clipping stack. + /// + /// Classes that override this method must call `super.clipRRect()`. + @override + void clipRRect(ui.RRect rrect) { + _clipStack ??= <_SaveClipEntry>[]; + _clipStack.add(_SaveClipEntry.rrect(rrect, _currentTransform.clone())); + } + + /// Adds a path to clipping stack. + /// + /// Classes that override this method must call `super.clipPath()`. + @override + void clipPath(ui.Path path) { + _clipStack ??= <_SaveClipEntry>[]; + _clipStack.add(_SaveClipEntry.path(path, _currentTransform.clone())); + } +} + +html.Element _drawParagraphElement( + EngineParagraph paragraph, + ui.Offset offset, { + Matrix4 transform, +}) { + assert(paragraph._isLaidOut); + + final html.Element paragraphElement = paragraph._paragraphElement.clone(true); + + final html.CssStyleDeclaration paragraphStyle = paragraphElement.style; + paragraphStyle + ..position = 'absolute' + ..whiteSpace = 'pre-wrap' + ..overflowWrap = 'break-word' + ..overflow = 'hidden' + ..height = '${paragraph.height}px' + ..width = '${paragraph.width}px'; + + if (transform != null) { + paragraphStyle + ..transformOrigin = '0 0 0' + ..transform = + matrix4ToCssTransform(transformWithOffset(transform, offset)); + } + + final ParagraphGeometricStyle style = paragraph._geometricStyle; + + // TODO(flutter_web): https://github.com/flutter/flutter/issues/33223 + if (style.ellipsis != null && + (style.maxLines == null || style.maxLines == 1)) { + paragraphStyle + ..whiteSpace = 'pre' + ..textOverflow = 'ellipsis'; + } + return paragraphElement; +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/history.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/history.dart new file mode 100644 index 0000000000..749c7fd884 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/history.dart @@ -0,0 +1,190 @@ +// 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; + +const MethodCall _popRouteMethodCall = MethodCall('popRoute'); + +Map _originState = {'origin': true}; +Map _flutterState = {'flutter': true}; + +/// The origin entry is the history entry that the Flutter app landed on. It's +/// created by the browser when the user navigates to the url of the app. +bool _isOriginEntry(dynamic state) { + return state is Map && state['origin'] == true; +} + +/// The flutter entry is a history entry that we maintain on top of the origin +/// entry. It allows us to catch popstate events when the user hits the back +/// button. +bool _isFlutterEntry(dynamic state) { + return state is Map && state['flutter'] == true; +} + +/// The [BrowserHistory] class is responsible for integrating Flutter Web apps +/// with the browser history so that the back button works as expected. +/// +/// It does that by always keeping a single entry (conventionally called the +/// "flutter" entry) at the top of the browser history. That way, the browser's +/// back button always triggers a `popstate` event and never closes the app (we +/// close the app programmatically by calling [SystemNavigator.pop] when there +/// are no more app routes to be popped). +/// +/// There should only be one global instance of this class. +class BrowserHistory { + LocationStrategy _locationStrategy; + ui.VoidCallback _unsubscribe; + + /// Changing the location strategy will unsubscribe from the old strategy's + /// event listeners, and subscribe to the new one. + /// + /// If the given [strategy] is the same as the existing one, nothing will + /// happen. + /// + /// If the given strategy is null, it will render this [BrowserHistory] + /// instance inactive. + set locationStrategy(LocationStrategy strategy) { + if (strategy != _locationStrategy) { + _tearoffStrategy(_locationStrategy); + _locationStrategy = strategy; + _setupStrategy(_locationStrategy); + } + } + + /// The path of the current location of the user's browser. + String get currentPath => _locationStrategy?.path ?? '/'; + + /// Update the url with the given [routeName]. + void setRouteName(String routeName) { + if (_locationStrategy != null) { + _setupFlutterEntry(_locationStrategy, replace: true, path: routeName); + } + } + + /// This method does the same thing as the browser back button. + Future back() { + if (_locationStrategy != null) { + return _locationStrategy.back(); + } + return Future.value(); + } + + /// This method exits the app and goes to whatever website was active before. + Future exit() { + if (_locationStrategy != null) { + _tearoffStrategy(_locationStrategy); + // After tearing off the location strategy, we should be on the "origin" + // entry. So we need to go back one more time to exit the app. + final Future backFuture = _locationStrategy.back(); + _locationStrategy = null; + return backFuture; + } + return Future.value(); + } + + String _userProvidedRouteName; + void _popStateListener(covariant html.PopStateEvent event) { + if (_isOriginEntry(event.state)) { + // If we find ourselves in the origin entry, it means that the user + // clicked the back button. + + // 1. Re-push the flutter entry to keep it always at the top of history. + _setupFlutterEntry(_locationStrategy); + + // 2. Send a 'popRoute' platform message so the app can handle it accordingly. + ui.window.onPlatformMessage( + 'flutter/navigation', + const JSONMethodCodec().encodeMethodCall(_popRouteMethodCall), + (_) {}, + ); + } else if (_isFlutterEntry(event.state)) { + // We get into this scenario when the user changes the url manually. It + // causes a new entry to be pushed on top of our "flutter" one. When this + // happens it first goes to the "else" section below where we capture the + // path into `_userProvidedRouteName` then trigger a history back which + // brings us here. + assert(_userProvidedRouteName != null); + + final String newRouteName = _userProvidedRouteName; + _userProvidedRouteName = null; + + // Send a 'pushRoute' platform message so the app handles it accordingly. + ui.window.onPlatformMessage( + 'flutter/navigation', + const JSONMethodCodec().encodeMethodCall( + MethodCall('pushRoute', newRouteName), + ), + (_) {}, + ); + } else { + // The user has pushed a new entry on top of our flutter entry. This could + // happen when the user modifies the hash part of the url directly, for + // example. + + // 1. We first capture the user's desired path. + _userProvidedRouteName = currentPath; + + // 2. Then we remove the new entry. + // This will take us back to our "flutter" entry and it causes a new + // popstate event that will be handled in the "else if" section above. + _locationStrategy.back(); + } + } + + /// This method should be called when the Origin Entry is active. It just + /// replaces the state of the entry so that we can recognize it later using + /// [_isOriginEntry] inside [_popStateListener]. + void _setupOriginEntry(LocationStrategy strategy) { + assert(strategy != null); + strategy.replaceState(_originState, 'origin', ''); + } + + /// This method is used manipulate the Flutter Entry which is always the + /// active entry while the Flutter app is running. + void _setupFlutterEntry( + LocationStrategy strategy, { + bool replace = false, + String path, + }) { + assert(strategy != null); + path ??= currentPath; + if (replace) { + strategy.replaceState(_flutterState, 'flutter', path); + } else { + strategy.pushState(_flutterState, 'flutter', path); + } + } + + void _setupStrategy(LocationStrategy strategy) { + if (strategy == null) { + return; + } + + final String path = currentPath; + if (_isFlutterEntry(html.window.history.state)) { + // This could happen if the user, for example, refreshes the page. They + // will land directly on the "flutter" entry, so there's no need to setup + // the "origin" and "flutter" entries, we can safely assume they are + // already setup. + } else { + _setupOriginEntry(strategy); + _setupFlutterEntry(strategy, replace: false, path: path); + } + _unsubscribe = strategy.onPopState(_popStateListener); + } + + void _tearoffStrategy(LocationStrategy strategy) { + if (strategy == null) { + return; + } + + assert(_unsubscribe != null); + _unsubscribe(); + _unsubscribe = null; + + // Remove the "flutter" entry and go back to the "origin" entry so that the + // next location strategy can start from the right spot. + strategy.back(); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/houdini_canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/houdini_canvas.dart new file mode 100644 index 0000000000..53e3fd9275 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/houdini_canvas.dart @@ -0,0 +1,354 @@ +// 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): optimization opportunities (see also houdini_painter.js) +// - collapse non-drawing paint operations +// - avoid producing DOM-based clips if there is no text +// - evaluate using stylesheets for static CSS properties +// - evaluate reusing houdini canvases +part of engine; + +/// A canvas that renders to a combination of HTML DOM and CSS Custom Paint API. +/// +/// This canvas produces paint commands for houdini_painter.js to apply. This +/// class must be kept in sync with houdini_painter.js. +class HoudiniCanvas extends EngineCanvas with SaveElementStackTracking { + @override + final html.Element rootElement = html.Element.tag('flt-houdini'); + + /// The rectangle positioned relative to the parent layer's coordinate system + /// where this canvas paints. + /// + /// Painting outside the bounds of this rectangle is cropped. + final ui.Rect bounds; + + HoudiniCanvas(this.bounds) { + // TODO(yjbanov): would it be faster to specify static values in a + // stylesheet and let the browser apply them? + rootElement.style + ..position = 'absolute' + ..top = '0' + ..left = '0' + ..width = '${bounds.size.width}px' + ..height = '${bounds.size.height}px' + ..backgroundImage = 'paint(flt)'; + } + + /// Prepare to reuse this canvas by clearing it's current contents. + @override + void clear() { + super.clear(); + _serializedCommands = >[]; + // TODO(yjbanov): we should measure if reusing old elements is beneficial. + domRenderer.clearDom(rootElement); + } + + /// Paint commands serialized for sending to the CSS custom painter. + List> _serializedCommands = >[]; + + void apply(PaintCommand command) { + // Some commands are applied purely in HTML DOM and do not need to be + // serialized. + if (command is! PaintDrawParagraph && + command is! PaintDrawImageRect && + command is! PaintTransform) { + command.serializeToCssPaint(_serializedCommands); + } + command.apply(this); + } + + /// Sends the paint commands to the CSS custom painter for painting. + void commit() { + if (_serializedCommands.isNotEmpty) { + rootElement.style.setProperty('--flt', json.encode(_serializedCommands)); + } else { + rootElement.style.removeProperty('--flt'); + } + } + + @override + void clipRect(ui.Rect rect) { + final html.Element clip = html.Element.tag('flt-clip-rect'); + final String cssTransform = matrix4ToCssTransform( + transformWithOffset(currentTransform, ui.Offset(rect.left, rect.top))); + clip.style + ..overflow = 'hidden' + ..position = 'absolute' + ..transform = cssTransform + ..width = '${rect.width}px' + ..height = '${rect.height}px'; + + // The clipping element will translate the coordinate system as well, which + // is not what a clip should do. To offset that we translate in the opposite + // direction. + super.translate(-rect.left, -rect.top); + + currentElement.append(clip); + pushElement(clip); + } + + @override + void clipRRect(ui.RRect rrect) { + final ui.Rect outer = rrect.outerRect; + if (rrect.isRect) { + clipRect(outer); + return; + } + + final html.Element clip = html.Element.tag('flt-clip-rrect'); + final html.CssStyleDeclaration style = clip.style; + style + ..overflow = 'hidden' + ..position = 'absolute' + ..transform = 'translate(${outer.left}px, ${outer.right}px)' + ..width = '${outer.width}px' + ..height = '${outer.height}px'; + + if (rrect.tlRadiusY == rrect.tlRadiusX) { + style.borderTopLeftRadius = '${rrect.tlRadiusX}px'; + } else { + style.borderTopLeftRadius = '${rrect.tlRadiusX}px ${rrect.tlRadiusY}px'; + } + + if (rrect.trRadiusY == rrect.trRadiusX) { + style.borderTopRightRadius = '${rrect.trRadiusX}px'; + } else { + style.borderTopRightRadius = '${rrect.trRadiusX}px ${rrect.trRadiusY}px'; + } + + if (rrect.brRadiusY == rrect.brRadiusX) { + style.borderBottomRightRadius = '${rrect.brRadiusX}px'; + } else { + style.borderBottomRightRadius = + '${rrect.brRadiusX}px ${rrect.brRadiusY}px'; + } + + if (rrect.blRadiusY == rrect.blRadiusX) { + style.borderBottomLeftRadius = '${rrect.blRadiusX}px'; + } else { + style.borderBottomLeftRadius = + '${rrect.blRadiusX}px ${rrect.blRadiusY}px'; + } + + // The clipping element will translate the coordinate system as well, which + // is not what a clip should do. To offset that we translate in the opposite + // direction. + super.translate(-rrect.left, -rrect.top); + + currentElement.append(clip); + pushElement(clip); + } + + @override + void clipPath(ui.Path path) { + // TODO(yjbanov): implement. + } + + @override + void drawColor(ui.Color color, ui.BlendMode blendMode) { + // Drawn using CSS Paint. + } + + @override + void drawLine(ui.Offset p1, ui.Offset p2, ui.PaintData paint) { + // Drawn using CSS Paint. + } + + @override + void drawPaint(ui.PaintData paint) { + // Drawn using CSS Paint. + } + + @override + void drawRect(ui.Rect rect, ui.PaintData paint) { + // Drawn using CSS Paint. + } + + @override + void drawRRect(ui.RRect rrect, ui.PaintData paint) { + // Drawn using CSS Paint. + } + + @override + void drawDRRect(ui.RRect outer, ui.RRect inner, ui.PaintData paint) { + // Drawn using CSS Paint. + } + + @override + void drawOval(ui.Rect rect, ui.PaintData paint) { + // Drawn using CSS Paint. + } + + @override + void drawCircle(ui.Offset c, double radius, ui.PaintData paint) { + // Drawn using CSS Paint. + } + + @override + void drawPath(ui.Path path, ui.PaintData paint) { + // Drawn using CSS Paint. + } + + @override + void drawShadow(ui.Path path, ui.Color color, double elevation, + bool transparentOccluder) { + // Drawn using CSS Paint. + } + + @override + void drawImage(ui.Image image, ui.Offset p, ui.PaintData paint) { + // TODO(yjbanov): implement. + } + + @override + void drawImageRect( + ui.Image image, ui.Rect src, ui.Rect dst, ui.PaintData paint) { + // TODO(yjbanov): implement src rectangle + final HtmlImage htmlImage = image; + final html.Element imageBox = html.Element.tag('flt-img'); + final String cssTransform = matrix4ToCssTransform( + transformWithOffset(currentTransform, ui.Offset(dst.left, dst.top))); + imageBox.style + ..position = 'absolute' + ..transformOrigin = '0 0 0' + ..width = '${dst.width.toInt()}px' + ..height = '${dst.height.toInt()}px' + ..transform = cssTransform + ..backgroundImage = 'url(${htmlImage.imgElement.src})' + ..backgroundRepeat = 'norepeat' + ..backgroundSize = '${dst.width}px ${dst.height}px'; + currentElement.append(imageBox); + } + + @override + void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) { + final html.Element paragraphElement = + _drawParagraphElement(paragraph, offset, transform: currentTransform); + currentElement.append(paragraphElement); + } +} + +class _SaveElementStackEntry { + _SaveElementStackEntry({ + @required this.savedElement, + @required this.transform, + }); + + final html.Element savedElement; + final Matrix4 transform; +} + +/// Provides save stack tracking functionality to implementations of +/// [EngineCanvas]. +mixin SaveElementStackTracking on EngineCanvas { + static final Vector3 _unitZ = Vector3(0.0, 0.0, 1.0); + + final List<_SaveElementStackEntry> _saveStack = <_SaveElementStackEntry>[]; + + /// The element at the top of the element stack, or [rootElement] if the stack + /// is empty. + html.Element get currentElement => + _elementStack.isEmpty ? rootElement : _elementStack.last; + + /// The stack that maintains the DOM elements used to express certain paint + /// operations, such as clips. + final List _elementStack = []; + + /// Pushes the [element] onto the element stack for the purposes of applying + /// a paint effect using a DOM element, e.g. for clipping. + /// + /// The [restore] method automatically pops the element off the stack. + void pushElement(html.Element element) { + _elementStack.add(element); + } + + /// Empties the save stack and the element stack, and resets the transform + /// and clip parameters. + /// + /// Classes that override this method must call `super.clear()`. + @override + void clear() { + _saveStack.clear(); + _elementStack.clear(); + _currentTransform = Matrix4.identity(); + } + + /// The current transformation matrix. + Matrix4 get currentTransform => _currentTransform; + Matrix4 _currentTransform = Matrix4.identity(); + + /// Saves current clip and transform on the save stack. + /// + /// Classes that override this method must call `super.save()`. + @override + void save() { + _saveStack.add(_SaveElementStackEntry( + savedElement: currentElement, + transform: _currentTransform.clone(), + )); + } + + /// Restores current clip and transform from the save stack. + /// + /// Classes that override this method must call `super.restore()`. + @override + void restore() { + if (_saveStack.isEmpty) { + return; + } + final _SaveElementStackEntry entry = _saveStack.removeLast(); + _currentTransform = entry.transform; + + // Pop out of any clips. + while (currentElement != entry.savedElement) { + _elementStack.removeLast(); + } + } + + /// Multiplies the [currentTransform] matrix by a translation. + /// + /// Classes that override this method must call `super.translate()`. + @override + void translate(double dx, double dy) { + _currentTransform.translate(dx, dy); + } + + /// Scales the [currentTransform] matrix. + /// + /// Classes that override this method must call `super.scale()`. + @override + void scale(double sx, double sy) { + _currentTransform.scale(sx, sy); + } + + /// Rotates the [currentTransform] matrix. + /// + /// Classes that override this method must call `super.rotate()`. + @override + void rotate(double radians) { + _currentTransform.rotate(_unitZ, radians); + } + + /// Skews the [currentTransform] matrix. + /// + /// Classes that override this method must call `super.skew()`. + @override + void skew(double sx, double sy) { + // DO NOT USE Matrix4.skew(sx, sy)! It treats sx and sy values as radians, + // but in our case they are transform matrix values. + final Matrix4 skewMatrix = Matrix4.identity(); + final Float64List storage = skewMatrix.storage; + storage[1] = sy; + storage[4] = sx; + _currentTransform.multiply(skewMatrix); + } + + /// Multiplies the [currentTransform] matrix by another matrix. + /// + /// Classes that override this method must call `super.transform()`. + @override + void transform(Float64List matrix4) { + _currentTransform.multiply(Matrix4.fromFloat64List(matrix4)); + } +} 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 new file mode 100644 index 0000000000..290267b605 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/html_image_codec.dart @@ -0,0 +1,119 @@ +// 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; + +final _supportsDecode = + js_util.hasProperty(js.JsObject(js.context['Image']), 'decode'); + +class HtmlCodec implements ui.Codec { + final String src; + + HtmlCodec(this.src); + + @override + int get frameCount => 1; + + @override + int get repetitionCount => 0; + + @override + Future getNextFrame() async { + StreamSubscription loadSubscription; + StreamSubscription errorSubscription; + final Completer completer = Completer(); + final html.ImageElement imgElement = html.ImageElement(); + // If the browser doesn't support asynchronous decoding of an image, + // then use the `onload` event to decide when it's ready to paint to the + // DOM. Unfortunately, this will case the image to be decoded synchronously + // on the main thread, and may cause dropped framed. + if (!_supportsDecode) { + loadSubscription = imgElement.onLoad.listen((html.Event event) { + loadSubscription.cancel(); + errorSubscription.cancel(); + final HtmlImage image = HtmlImage( + imgElement, + imgElement.naturalWidth, + imgElement.naturalHeight, + ); + completer.complete(SingleFrameInfo(image)); + }); + } + errorSubscription = imgElement.onError.listen((html.Event event) { + loadSubscription?.cancel(); + errorSubscription.cancel(); + completer.completeError(event); + }); + imgElement.src = src; + // If the browser supports asynchronous image decoding, use that instead + // of `onload`. + if (_supportsDecode) { + imgElement.decode().then((dynamic _) { + errorSubscription.cancel(); + final HtmlImage image = HtmlImage( + imgElement, + imgElement.naturalWidth, + imgElement.naturalHeight, + ); + completer.complete(SingleFrameInfo(image)); + }); + } + return completer.future; + } + + @override + void dispose() {} +} + +class HtmlBlobCodec extends HtmlCodec { + final html.Blob blob; + + HtmlBlobCodec(this.blob) : super(html.Url.createObjectUrlFromBlob(blob)); + + @override + void dispose() { + html.Url.revokeObjectUrl(src); + } +} + +class SingleFrameInfo implements ui.FrameInfo { + SingleFrameInfo(this.image); + + @override + Duration get duration => const Duration(milliseconds: 0); + + @override + final ui.Image image; +} + +class HtmlImage implements ui.Image { + final html.ImageElement imgElement; + + HtmlImage(this.imgElement, this.width, this.height); + + @override + void dispose() { + // Do nothing. The codec that owns this image should take care of + // releasing the object url. + } + + @override + final int width; + + @override + final int height; + + @override + Future toByteData( + {ui.ImageByteFormat format = ui.ImageByteFormat.rawRgba}) { + return futurize((Callback callback) { + return _toByteData(format.index, (Uint8List encoded) { + callback(encoded?.buffer?.asByteData()); + }); + }); + } + + /// Returns an error message on failure, null on success. + String _toByteData(int format, Callback callback) => null; +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard.dart new file mode 100644 index 0000000000..36983e1a1b --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard.dart @@ -0,0 +1,79 @@ +// 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; + +/// Provides keyboard bindings, such as the `flutter/keyevent` channel. +class Keyboard { + /// Initializes the [Keyboard] singleton. + /// + /// Use the [instance] getter to get the singleton after calling this method. + static void initialize() { + _instance ??= Keyboard._(); + } + + /// The [Keyboard] singleton. + static Keyboard get instance => _instance; + static Keyboard _instance; + + html.EventListener _keydownListener; + html.EventListener _keyupListener; + + Keyboard._() { + _keydownListener = (html.Event event) { + _handleHtmlEvent(event); + }; + html.window.addEventListener('keydown', _keydownListener); + + _keyupListener = (html.Event event) { + _handleHtmlEvent(event); + }; + html.window.addEventListener('keyup', _keyupListener); + registerHotRestartListener(() { + dispose(); + }); + } + + /// Uninitializes the [Keyboard] singleton. + /// + /// After calling this method this object becomes unusable and [instance] + /// becomes `null`. Call [initialize] again to initialize a new singleton. + void dispose() { + html.window.removeEventListener('keydown', _keydownListener); + html.window.removeEventListener('keyup', _keyupListener); + _keydownListener = null; + _keyupListener = null; + _instance = null; + } + + static const JSONMessageCodec _messageCodec = JSONMessageCodec(); + + void _handleHtmlEvent(html.KeyboardEvent event) { + final Map eventData = { + 'type': event.type, + // TODO(yjbanov): this emulates Android because that the only reasonable + // thing to map to right now (the other choice is fuchsia). + // However, eventually we need to have something that maps + // better to Web. + 'keymap': 'android', + 'keyCode': event.keyCode, + }; + + // TODO(yjbanov): The browser does not report `charCode` for 'keydown' and + // 'keyup', only for 'keypress'. This restores the value + // from the 'key' field. However, we need to verify how + // many code units a single key can have. Right now it + // assumes exactly one unit (that's what Flutter framework + // expects). But we'll need a different strategy if other + // code unit counts are possible. + if (event.key.codeUnits.length == 1) { + eventData['codePoint'] = event.key.codeUnits.first; + } + + ui.window.onPlatformMessage('flutter/keyevent', + _messageCodec.encodeMessage(eventData), _noopCallback); + } +} + +void _noopCallback(ByteData data) {} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/onscreen_logging.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/onscreen_logging.dart new file mode 100644 index 0000000000..8c65a945ca --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/onscreen_logging.dart @@ -0,0 +1,147 @@ +// 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; + +html.Element _logElement; +html.Element _logContainer; +List<_LogMessage> _logBuffer = <_LogMessage>[]; + +class _LogMessage { + _LogMessage(this.message); + + int duplicateCount = 1; + final String message; + + @override + String toString() { + if (duplicateCount == 1) { + return message; + } + return '${duplicateCount}x $message'; + } +} + +/// A drop-in replacement for [print] that prints on the screen into a +/// fixed-positioned element. +/// +/// This is useful, for example, for print-debugging on iOS when debugging over +/// USB is not available. +void printOnScreen(Object object) { + if (_logElement == null) { + _initialize(); + } + + final String message = '$object'; + if (_logBuffer.isNotEmpty && _logBuffer.last.message == message) { + _logBuffer.last.duplicateCount += 1; + } else { + _logBuffer.add(_LogMessage(message)); + } + + if (_logBuffer.length > 80) { + _logBuffer = _logBuffer.sublist(_logBuffer.length - 50); + } + + _logContainer.text = _logBuffer.join('\n'); + + // Also log to console for browsers that give you access to it. + print(message); +} + +void _initialize() { + _logElement = html.Element.tag('flt-onscreen-log'); + _logElement.setAttribute('aria-hidden', 'true'); + _logElement.style + ..position = 'fixed' + ..left = '0' + ..right = '0' + ..bottom = '0' + ..height = '25%' + ..backgroundColor = 'rgba(0, 0, 0, 0.85)' + ..color = 'white' + ..fontSize = '8px' + ..whiteSpace = 'pre-wrap' + ..overflow = 'hidden' + ..zIndex = '1000'; + + _logContainer = html.Element.tag('flt-log-container'); + _logContainer.setAttribute('aria-hidden', 'true'); + _logContainer.style + ..position = 'absolute' + ..bottom = '0'; + _logElement.append(_logContainer); + + html.document.body.append(_logElement); +} + +/// Dump the current stack to the console using [print] and +/// [defaultStackFilter]. +/// +/// The current stack is obtained using [StackTrace.current]. +/// +/// The `maxFrames` argument can be given to limit the stack to the given number +/// of lines. By default, all non-filtered stack lines are shown. +/// +/// The `label` argument, if present, will be printed before the stack. +void debugPrintStack({String label, int maxFrames}) { + if (label != null) print(label); + Iterable lines = + StackTrace.current.toString().trimRight().split('\n'); + if (maxFrames != null) lines = lines.take(maxFrames); + print(defaultStackFilter(lines).join('\n')); +} + +/// Converts a stack to a string that is more readable by omitting stack +/// frames that correspond to Dart internals. +/// +/// This function expects its input to be in the format used by +/// [StackTrace.toString()]. The output of this function is similar to that +/// format but the frame numbers will not be consecutive (frames are elided) +/// and the final line may be prose rather than a stack frame. +Iterable defaultStackFilter(Iterable frames) { + const List filteredPackages = [ + 'dart:async-patch', + 'dart:async', + 'dart:_runtime', + ]; + final RegExp stackParser = + RegExp(r'^#[0-9]+ +([^.]+).* \(([^/\\]*)[/\\].+:[0-9]+(?::[0-9]+)?\)$'); + final RegExp packageParser = RegExp(r'^([^:]+):(.+)$'); + final List result = []; + final List skipped = []; + for (String line in frames) { + final Match match = stackParser.firstMatch(line); + if (match != null) { + assert(match.groupCount == 2); + if (filteredPackages.contains(match.group(2))) { + final Match packageMatch = packageParser.firstMatch(match.group(2)); + if (packageMatch != null && packageMatch.group(1) == 'package') { + skipped.add( + 'package ${packageMatch.group(2)}'); // avoid "package package:foo" + } else { + skipped.add('package ${match.group(2)}'); + } + continue; + } + } + result.add(line); + } + if (skipped.length == 1) { + result.add('(elided one frame from ${skipped.single})'); + } else if (skipped.length > 1) { + final List where = Set.from(skipped).toList()..sort(); + if (where.length > 1) where[where.length - 1] = 'and ${where.last}'; + if (where.length > 2) { + result.add('(elided ${skipped.length} frames from ${where.join(", ")})'); + } else { + result.add('(elided ${skipped.length} frames from ${where.join(" ")})'); + } + } + return result; +} + +String debugIdentify(Object object) { + return '${object.runtimeType}(@${object.hashCode})'; +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/path_to_svg.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/path_to_svg.dart new file mode 100644 index 0000000000..10dc545574 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/path_to_svg.dart @@ -0,0 +1,191 @@ +// 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; + +/// Converts [path] to SVG path syntax to be used as "d" attribute in path +/// element. +void pathToSvg(ui.Path path, StringBuffer sb, + {double offsetX = 0, double offsetY = 0}) { + for (Subpath subPath in path.subpaths) { + for (PathCommand command in subPath.commands) { + switch (command.type) { + case PathCommandTypes.moveTo: + final MoveTo moveTo = command; + sb.write('M ${moveTo.x + offsetX} ${moveTo.y + offsetY}'); + break; + case PathCommandTypes.lineTo: + final LineTo lineTo = command; + sb.write('L ${lineTo.x + offsetX} ${lineTo.y + offsetY}'); + break; + case PathCommandTypes.bezierCurveTo: + final BezierCurveTo curve = command; + sb.write('C ${curve.x1 + offsetX} ${curve.y1 + offsetY} ' + '${curve.x2 + offsetX} ${curve.y2 + offsetY} ${curve.x3 + offsetX} ${curve.y3 + offsetY}'); + break; + case PathCommandTypes.quadraticCurveTo: + final QuadraticCurveTo quadraticCurveTo = command; + sb.write( + 'Q ${quadraticCurveTo.x1 + offsetX} ${quadraticCurveTo.y1 + offsetY} ' + '${quadraticCurveTo.x2 + offsetX} ${quadraticCurveTo.y2 + offsetY}'); + break; + case PathCommandTypes.close: + sb.write('Z'); + break; + case PathCommandTypes.ellipse: + final Ellipse ellipse = command; + // Handle edge case where start and end points are the same by drawing + // 2 half arcs. + if ((ellipse.endAngle - ellipse.startAngle) % (2 * math.pi) == 0.0) { + _writeEllipse( + sb, + ellipse.x + offsetX, + ellipse.y + offsetY, + ellipse.radiusX, + ellipse.radiusY, + ellipse.rotation, + -math.pi, + 0, + ellipse.anticlockwise, + moveToStartPoint: true); + _writeEllipse( + sb, + ellipse.x + offsetX, + ellipse.y + offsetY, + ellipse.radiusX, + ellipse.radiusY, + ellipse.rotation, + 0, + math.pi, + ellipse.anticlockwise); + } else { + _writeEllipse( + sb, + ellipse.x + offsetX, + ellipse.y + offsetY, + ellipse.radiusX, + ellipse.radiusY, + ellipse.rotation, + ellipse.startAngle, + ellipse.endAngle, + ellipse.anticlockwise); + } + break; + case PathCommandTypes.rRect: + final RRectCommand rrectCommand = command; + final ui.RRect rrect = rrectCommand.rrect; + double left = rrect.left + offsetX; + double right = rrect.right + offsetX; + double top = rrect.top + offsetY; + double bottom = rrect.bottom + offsetY; + if (left > right) { + left = right; + right = rrect.left + offsetX; + } + if (top > bottom) { + top = bottom; + bottom = rrect.top + offsetY; + } + final double trRadiusX = rrect.trRadiusX.abs(); + final double tlRadiusX = rrect.tlRadiusX.abs(); + final double trRadiusY = rrect.trRadiusY.abs(); + final double tlRadiusY = rrect.tlRadiusY.abs(); + final double blRadiusX = rrect.blRadiusX.abs(); + final double brRadiusX = rrect.brRadiusX.abs(); + final double blRadiusY = rrect.blRadiusY.abs(); + final double brRadiusY = rrect.brRadiusY.abs(); + + sb.write('L ${left + trRadiusX} $top '); + // Top side and top-right corner + sb.write('M ${right - trRadiusX} $top '); + _writeEllipse(sb, right - trRadiusX, top + trRadiusY, trRadiusX, + trRadiusY, 0, 1.5 * math.pi, 2.0 * math.pi, false); + // Right side and bottom-right corner + sb.write('L $right ${bottom - brRadiusY} '); + _writeEllipse(sb, right - brRadiusX, bottom - brRadiusY, brRadiusX, + brRadiusY, 0, 0, 0.5 * math.pi, false); + // Bottom side and bottom-left corner + sb.write('L ${left + blRadiusX} $bottom '); + _writeEllipse(sb, left + blRadiusX, bottom - blRadiusY, blRadiusX, + blRadiusY, 0, 0.5 * math.pi, math.pi, false); + // Left side and top-left corner + sb.write('L $left ${top + tlRadiusY} '); + _writeEllipse( + sb, + left + tlRadiusX, + top + tlRadiusY, + tlRadiusX, + tlRadiusY, + 0, + math.pi, + 1.5 * math.pi, + false, + ); + break; + case PathCommandTypes.rect: + final RectCommand rectCommand = command; + final bool horizontalSwap = rectCommand.width < 0; + final double left = offsetX + + (horizontalSwap + ? rectCommand.x - rectCommand.width + : rectCommand.x); + final double width = + horizontalSwap ? -rectCommand.width : rectCommand.width; + final bool verticalSwap = rectCommand.height < 0; + final double top = offsetY + + (verticalSwap + ? rectCommand.y - rectCommand.height + : rectCommand.y); + final double height = + verticalSwap ? -rectCommand.height : rectCommand.height; + sb.write('M $left $top '); + sb.write('L ${left + width} $top '); + sb.write('L ${left + width} ${top + height} '); + sb.write('L $left ${top + height} '); + sb.write('L $left $top '); + break; + default: + throw UnimplementedError('Unknown path command $command'); + } + } + } +} + +// See https://www.w3.org/TR/SVG/implnote.html B.2.3. Conversion from center to +// endpoint parameterization. +void _writeEllipse( + StringBuffer sb, + double cx, + double cy, + double radiusX, + double radiusY, + double rotation, + double startAngle, + double endAngle, + bool antiClockwise, + {bool moveToStartPoint = false}) { + final double cosRotation = math.cos(rotation); + final double sinRotation = math.sin(rotation); + final double x = math.cos(startAngle) * radiusX; + final double y = math.sin(startAngle) * radiusY; + + final double startPx = cx + (cosRotation * x - sinRotation * y); + final double startPy = cy + (sinRotation * x + cosRotation * y); + + final double xe = math.cos(endAngle) * radiusX; + final double ye = math.sin(endAngle) * radiusY; + + final double endPx = cx + (cosRotation * xe - sinRotation * ye); + final double endPy = cy + (sinRotation * xe + cosRotation * ye); + + final double delta = endAngle - startAngle; + final bool largeArc = delta.abs() > math.pi; + + final double rotationDeg = rotation / math.pi * 180.0; + if (moveToStartPoint) { + sb.write('M $startPx $startPy '); + } + sb.write('A $radiusX $radiusY $rotationDeg ' + '${largeArc ? 1 : 0} ${antiClockwise ? 0 : 1} $endPx $endPy'); +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/platform_views.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/platform_views.dart new file mode 100644 index 0000000000..8cebc951e2 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/platform_views.dart @@ -0,0 +1,73 @@ +// 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; + +/// A registry for factories that create platform views. +class PlatformViewRegistry { + final Map _registeredFactories = + {}; + + final Map _createdViews = {}; + + /// Private constructor so this class can be a singleton. + PlatformViewRegistry._(); + + /// Register [viewTypeId] as being creating by the given [factory]. + bool registerViewFactory(String viewTypeId, PlatformViewFactory factory) { + if (_registeredFactories.containsKey(viewTypeId)) { + return false; + } + _registeredFactories[viewTypeId] = factory; + return true; + } + + /// Returns the view that has been created with the given [id], or `null` if + /// no such view exists. + html.Element getCreatedView(int id) { + return _createdViews[id]; + } +} + +/// A function which takes a unique [id] and creates an HTML element. +typedef PlatformViewFactory = html.Element Function(int viewId); + +/// The platform view registry for this app. +final PlatformViewRegistry platformViewRegistry = PlatformViewRegistry._(); + +/// Handles a platform call to `flutter/platform_views`. +/// +/// Used to create platform views. +void handlePlatformViewCall( + ByteData data, + ui.PlatformMessageResponseCallback callback, +) { + const MethodCodec codec = StandardMethodCodec(); + final MethodCall decoded = codec.decodeMethodCall(data); + + switch (decoded.method) { + case 'create': + _createPlatformView(decoded, callback); + return; + } + callback(null); +} + +void _createPlatformView( + MethodCall methodCall, ui.PlatformMessageResponseCallback callback) { + final Map args = methodCall.arguments; + final int id = args['id']; + final String viewType = args['viewType']; + // TODO(het): Use 'direction', 'width', and 'height'. + if (!platformViewRegistry._registeredFactories.containsKey(viewType)) { + // TODO(het): Do we have a way of nicely reporting errors during platform + // channel calls? + callback(null); + } + // TODO(het): Use creation parameters. + final html.Element element = + platformViewRegistry._registeredFactories[viewType](id); + + platformViewRegistry._createdViews[id] = element; +} 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 new file mode 100644 index 0000000000..bd1ad440b0 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/pointer_binding.dart @@ -0,0 +1,486 @@ +// 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; + +/// Set this flag to true to see all the fired events in the console. +const bool _debugLogPointerEvents = false; + +/// The signature of a callback that handles pointer events. +typedef PointerDataCallback = void Function(List); + +class PointerBinding { + /// The singleton instance of this object. + static PointerBinding get instance => _instance; + static PointerBinding _instance; + + PointerBinding(this.domRenderer) { + if (_instance == null) { + _instance = this; + _detector = const PointerSupportDetector(); + _adapter = _createAdapter(); + } + assert(() { + registerHotRestartListener(() { + _adapter?.clearListeners(); + }); + return true; + }()); + } + + final DomRenderer domRenderer; + PointerSupportDetector _detector; + BaseAdapter _adapter; + + /// Should be used in tests to define custom detection of pointer support. + /// + /// ```dart + /// // Forces PointerBinding to use mouse events. + /// class MyTestDetector extends PointerSupportDetector { + /// @override + /// final bool hasPointerEvents = false; + /// + /// @override + /// final bool hasTouchEvents = false; + /// + /// @override + /// final bool hasMouseEvents = true; + /// } + /// + /// PointerBinding.instance.debugOverrideDetector(MyTestDetector()); + /// ``` + void debugOverrideDetector(PointerSupportDetector newDetector) { + newDetector ??= const PointerSupportDetector(); + // When changing the detector, we need to swap the adapter. + if (newDetector != _detector) { + _detector = newDetector; + _adapter?.clearListeners(); + _adapter = _createAdapter(); + } + } + + BaseAdapter _createAdapter() { + if (_detector.hasPointerEvents) { + return PointerAdapter(_onPointerData, domRenderer); + } + if (_detector.hasTouchEvents) { + return TouchAdapter(_onPointerData, domRenderer); + } + if (_detector.hasMouseEvents) { + return MouseAdapter(_onPointerData, domRenderer); + } + return null; + } + + void _onPointerData(List data) { + final ui.PointerDataPacket packet = ui.PointerDataPacket(data: data); + ui.window.onPointerDataPacket(packet); + } +} + +class PointerSupportDetector { + const PointerSupportDetector(); + + bool get hasPointerEvents => js_util.hasProperty(html.window, 'PointerEvent'); + bool get hasTouchEvents => js_util.hasProperty(html.window, 'TouchEvent'); + bool get hasMouseEvents => js_util.hasProperty(html.window, 'MouseEvent'); + + @override + String toString() => + 'pointers:$hasPointerEvents, touch:$hasTouchEvents, mouse:$hasMouseEvents'; +} + +/// Common functionality that's shared among adapters. +abstract class BaseAdapter { + static final Map _listeners = + {}; + + final DomRenderer domRenderer; + PointerDataCallback _callback; + Map _isDownMap = {}; + bool _isButtonDown(int button) { + return _isDownMap[button] == true; + } + + void _updateButtonDownState(int button, bool value) { + _isDownMap[button] = value; + } + + BaseAdapter(this._callback, this.domRenderer) { + _setup(); + } + + /// Each subclass is expected to override this method to attach its own event + /// listeners and convert events into pointer events. + void _setup(); + + /// Remove all active event listeners. + void clearListeners() { + final html.Element glassPane = domRenderer.glassPaneElement; + _listeners.forEach((String eventName, html.EventListener listener) { + glassPane.removeEventListener(eventName, listener); + }); + _listeners.clear(); + } + + void _addEventListener(String eventName, html.EventListener handler) { + final html.EventListener loggedHandler = (html.Event event) { + if (_debugLogPointerEvents) { + print(event.type); + } + // Report the event to semantics. This information is used to debounce + // browser gestures. Semantics tells us whether it is safe to forward + // the event to the framework. + if (EngineSemanticsOwner.instance.receiveGlobalEvent(event)) { + handler(event); + } + }; + _listeners[eventName] = loggedHandler; + domRenderer.glassPaneElement + .addEventListener(eventName, loggedHandler, true); + } +} + +const int _kPrimaryMouseButton = 0x1; +const int _kSecondaryMouseButton = 0x2; + +int _pointerButtonFromHtmlEvent(html.Event event) { + if (event is html.PointerEvent) { + final html.PointerEvent pointerEvent = event; + return pointerEvent.button == 2 + ? _kSecondaryMouseButton + : _kPrimaryMouseButton; + } else if (event is html.MouseEvent) { + final html.MouseEvent mouseEvent = event; + return mouseEvent.button == 2 + ? _kSecondaryMouseButton + : _kPrimaryMouseButton; + } + return _kPrimaryMouseButton; +} + +/// Adapter class to be used with browsers that support native pointer events. +class PointerAdapter extends BaseAdapter { + PointerAdapter(PointerDataCallback callback, DomRenderer domRenderer) + : super(callback, domRenderer); + + @override + void _setup() { + _addEventListener('pointerdown', (html.Event event) { + final int pointerButton = _pointerButtonFromHtmlEvent(event); + if (_isButtonDown(pointerButton)) { + // TODO(flutter_web): Remove this temporary fix for right click + // on web platform once context guesture is implemented. + _callback(_convertEventToPointerData(ui.PointerChange.up, event)); + } + _updateButtonDownState(pointerButton, true); + _callback(_convertEventToPointerData(ui.PointerChange.down, event)); + }); + + _addEventListener('pointermove', (html.Event event) { + // TODO(flutter_web): During a drag operation pointermove will set + // 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)); + }); + + _addEventListener('pointerup', (html.Event event) { + // The pointer could have been released by a `pointerout` event, in which + // case `pointerup` should have no effect. + final int pointerButton = _pointerButtonFromHtmlEvent(event); + if (!_isButtonDown(pointerButton)) { + return; + } + _updateButtonDownState(pointerButton, false); + _callback(_convertEventToPointerData(ui.PointerChange.up, event)); + }); + + // 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) { + _callback(_convertEventToPointerData(ui.PointerChange.cancel, event)); + }); + + _addWheelEventListener((html.WheelEvent event) { + if (_debugLogPointerEvents) { + print(event.type); + } + _callback(_convertWheelEventToPointerData(event)); + // Prevent default so mouse wheel event doesn't get converted to + // a scroll event that semantic nodes would process. + event.preventDefault(); + }); + } + + List _convertEventToPointerData( + ui.PointerChange change, + html.PointerEvent evt, + ) { + final List allEvents = _expandEvents(evt); + final List data = List(allEvents.length); + for (int i = 0; i < allEvents.length; i++) { + final html.PointerEvent event = allEvents[i]; + data[i] = ui.PointerData( + change: change, + timeStamp: _eventTimeStampToDuration(event.timeStamp), + kind: _pointerTypeToDeviceKind(event.pointerType), + device: event.pointerId, + physicalX: event.client.x, + physicalY: event.client.y, + buttons: event.buttons, + pressure: event.pressure, + pressureMin: 0.0, + pressureMax: 1.0, + tilt: _computeHighestTilt(event), + ); + } + return data; + } + + List _expandEvents(html.PointerEvent event) { + // For browsers that don't support `getCoalescedEvents`, we fallback to + // using the original event. + if (js_util.hasProperty(event, 'getCoalescedEvents')) { + final List coalescedEvents = + event.getCoalescedEvents(); + // Some events don't perform coalescing, so they return an empty list. In + // that case, we also fallback to using the original event. + if (coalescedEvents.isNotEmpty) { + return coalescedEvents; + } + } + return [event]; + } + + ui.PointerDeviceKind _pointerTypeToDeviceKind(String pointerType) { + switch (pointerType) { + case 'mouse': + return ui.PointerDeviceKind.mouse; + case 'pen': + return ui.PointerDeviceKind.stylus; + case 'touch': + return ui.PointerDeviceKind.touch; + default: + return ui.PointerDeviceKind.unknown; + } + } + + /// Tilt angle is -90 to + 90. Take maximum deflection and convert to radians. + double _computeHighestTilt(html.PointerEvent e) => + (e.tiltX.abs() > e.tiltY.abs() ? e.tiltX : e.tiltY).toDouble() / + 180.0 * + math.pi; +} + +/// Adapter to be used with browsers that support touch events. +class TouchAdapter extends BaseAdapter { + TouchAdapter(PointerDataCallback callback, DomRenderer domRenderer) + : super(callback, domRenderer); + + @override + void _setup() { + _addEventListener('touchstart', (html.Event event) { + _updateButtonDownState(_kPrimaryMouseButton, true); + _callback(_convertEventToPointerData(ui.PointerChange.down, event)); + }); + + _addEventListener('touchmove', (html.Event event) { + event.preventDefault(); // Prevents standard overscroll on iOS/Webkit. + if (!_isButtonDown(_kPrimaryMouseButton)) { + return; + } + _callback(_convertEventToPointerData(ui.PointerChange.move, event)); + }); + + _addEventListener('touchend', (html.Event event) { + _updateButtonDownState(_kPrimaryMouseButton, false); + _callback(_convertEventToPointerData(ui.PointerChange.up, event)); + }); + + _addEventListener('touchcancel', (html.Event event) { + _callback(_convertEventToPointerData(ui.PointerChange.cancel, event)); + }); + } + + List _convertEventToPointerData( + ui.PointerChange change, + html.TouchEvent event, + ) { + final html.TouchList touches = event.changedTouches; + final List data = List(touches.length); + final int len = touches.length; + for (int i = 0; i < len; i++) { + final html.Touch touch = touches[i]; + data[i] = ui.PointerData( + change: change, + timeStamp: _eventTimeStampToDuration(event.timeStamp), + kind: ui.PointerDeviceKind.touch, + signalKind: ui.PointerSignalKind.none, + device: touch.identifier, + physicalX: touch.client.x, + physicalY: touch.client.y, + pressure: 1.0, + pressureMin: 0.0, + pressureMax: 1.0, + ); + } + + return data; + } +} + +/// Intentionally set to -1 so it doesn't conflict with other device IDs. +const int _mouseDeviceId = -1; + +/// Adapter to be used with browsers that support mouse events. +class MouseAdapter extends BaseAdapter { + MouseAdapter(PointerDataCallback callback, DomRenderer domRenderer) + : super(callback, domRenderer); + + @override + void _setup() { + _addEventListener('mousedown', (html.Event event) { + final int pointerButton = _pointerButtonFromHtmlEvent(event); + if (_isButtonDown(pointerButton)) { + // TODO(flutter_web): Remove this temporary fix for right click + // on web platform once context guesture is implemented. + _callback(_convertEventToPointerData(ui.PointerChange.up, event)); + } + _updateButtonDownState(pointerButton, true); + _callback(_convertEventToPointerData(ui.PointerChange.down, event)); + }); + + _addEventListener('mousemove', (html.Event event) { + if (!_isButtonDown(_pointerButtonFromHtmlEvent(event))) { + return; + } + _callback(_convertEventToPointerData(ui.PointerChange.move, event)); + }); + + _addEventListener('mouseup', (html.Event event) { + _updateButtonDownState(_pointerButtonFromHtmlEvent(event), false); + _callback(_convertEventToPointerData(ui.PointerChange.up, event)); + }); + + _addWheelEventListener((html.WheelEvent event) { + if (_debugLogPointerEvents) { + print(event.type); + } + _callback(_convertWheelEventToPointerData(event)); + event.preventDefault(); + }); + } + + List _convertEventToPointerData( + 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, + ) + ]; + } +} + +/// Convert a floating number timestamp (in milliseconds) to a [Duration] by +/// splitting it into two integer components: milliseconds + microseconds. +Duration _eventTimeStampToDuration(num milliseconds) { + final int ms = milliseconds.toInt(); + final int micro = + ((milliseconds - ms) * Duration.microsecondsPerMillisecond).toInt(); + return Duration(milliseconds: ms, microseconds: micro); +} + +bool _isWheelDeviceAdded = false; + +List _convertWheelEventToPointerData( + html.WheelEvent event, +) { + const int domDeltaPixel = 0x00; + const int domDeltaLine = 0x01; + const int domDeltaPage = 0x02; + + // Flutter only supports pixel scroll delta. Convert deltaMode values + // to pixels. + double deltaX = event.deltaX; + double deltaY = event.deltaY; + switch (event.deltaMode) { + case domDeltaLine: + deltaX *= 32.0; + deltaY *= 32.0; + break; + case domDeltaPage: + deltaX *= ui.window.physicalSize.width; + deltaY *= ui.window.physicalSize.height; + break; + case domDeltaPixel: + default: + break; + } + + 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, + )); + } + data.add(ui.PointerData( + change: ui.PointerChange.hover, + timeStamp: _eventTimeStampToDuration(event.timeStamp), + kind: ui.PointerDeviceKind.mouse, + signalKind: ui.PointerSignalKind.scroll, + 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, + )); + return data; +} + +void _addWheelEventListener(void listener(html.WheelEvent e)) { + final dynamic eventOptions = js_util.newObject(); + js_util.setProperty(eventOptions, 'passive', false); + js_util.callMethod(PointerBinding.instance.domRenderer.glassPaneElement, + 'addEventListener', [ + 'wheel', + js.allowInterop((html.WheelEvent event) => listener(event)), + eventOptions + ]); +} 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 new file mode 100644 index 0000000000..07b6f9dd82 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/recording_canvas.dart @@ -0,0 +1,1571 @@ +// 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; + +/// Enable this to print every command applied by a canvas. +const bool _debugDumpPaintCommands = false; + +/// Records canvas commands to be applied to a [EngineCanvas]. +/// +/// See [Canvas] for docs for these methods. +class RecordingCanvas { + /// Maximum paintable bounds for this canvas. + final _PaintBounds _paintBounds; + final List _commands = []; + + RecordingCanvas(ui.Rect bounds) : _paintBounds = _PaintBounds(bounds); + + /// Whether this canvas is doing arbitrary paint operations not expressible + /// via DOM elements. + bool get hasArbitraryPaint => _hasArbitraryPaint; + bool _hasArbitraryPaint = false; + + /// Forces arbitrary paint even for simple pictures. + /// + /// This is useful for testing bitmap canvas when otherwise the compositor + /// would prefer a DOM canvas. + void debugEnforceArbitraryPaint() { + _hasArbitraryPaint = true; + } + + /// Whether this canvas contain drawing operations. + /// + /// Some pictures are created but only contain operations that do not result + /// in any pixels on the screen. For example, they will only contain saves, + /// restores, and translates. This happens when a parent [RenderObject] + /// prepares the canvas for its children to paint to, but the child ends up + /// not painting anything, such as when an empty [SizedBox] is used to add a + /// margin between two widgets. + bool get didDraw => _didDraw; + bool _didDraw = false; + + /// Computes paint bounds based on estimated [bounds] and transforms. + ui.Rect computePaintBounds() { + return _paintBounds.computeBounds(); + } + + /// Applies the recorded commands onto an [engineCanvas]. + void apply(EngineCanvas engineCanvas) { + if (_debugDumpPaintCommands) { + final StringBuffer debugBuf = StringBuffer(); + debugBuf.writeln( + '--- Applying RecordingCanvas to ${engineCanvas.runtimeType} ' + 'with bounds $_paintBounds'); + for (int i = 0; i < _commands.length; i++) { + final PaintCommand command = _commands[i]; + debugBuf.writeln('ctx.$command;'); + command.apply(engineCanvas); + } + debugBuf.writeln('--- End of command stream'); + print(debugBuf); + } else { + for (int i = 0; i < _commands.length; i++) { + _commands[i].apply(engineCanvas); + } + } + } + + /// Prints recorded commands. + String debugPrintCommands() { + if (assertionsEnabled) { + final StringBuffer debugBuf = StringBuffer(); + for (int i = 0; i < _commands.length; i++) { + final PaintCommand command = _commands[i]; + debugBuf.writeln('ctx.$command;'); + } + return debugBuf.toString(); + } + return null; + } + + void save() { + _paintBounds.saveTransformsAndClip(); + _commands.add(const PaintSave()); + saveCount++; + } + + void saveLayerWithoutBounds(ui.Paint paint) { + _hasArbitraryPaint = true; + // TODO(het): Implement this correctly using another canvas. + _commands.add(const PaintSave()); + _paintBounds.saveTransformsAndClip(); + saveCount++; + } + + void saveLayer(ui.Rect bounds, ui.Paint paint) { + _hasArbitraryPaint = true; + // TODO(het): Implement this correctly using another canvas. + _commands.add(const PaintSave()); + _paintBounds.saveTransformsAndClip(); + saveCount++; + } + + void restore() { + _paintBounds.restoreTransformsAndClip(); + if (_commands.isNotEmpty && _commands.last is PaintSave) { + // A restore followed a save without any drawing operations in between. + // This means that the save didn't have any effect on drawing operations + // and can be omitted. This makes our communication with the canvas less + // chatty. + _commands.removeLast(); + } else { + _commands.add(const PaintRestore()); + } + saveCount--; + } + + void translate(double dx, double dy) { + _paintBounds.translate(dx, dy); + _commands.add(PaintTranslate(dx, dy)); + } + + void scale(double sx, double sy) { + _paintBounds.scale(sx, sy); + _commands.add(PaintScale(sx, sy)); + } + + void rotate(double radians) { + _paintBounds.rotateZ(radians); + _commands.add(PaintRotate(radians)); + } + + void transform(Float64List matrix4) { + _paintBounds.transform(matrix4); + _commands.add(PaintTransform(matrix4)); + } + + void skew(double sx, double sy) { + _hasArbitraryPaint = true; + _paintBounds.skew(sx, sy); + _commands.add(PaintSkew(sx, sy)); + } + + void clipRect(ui.Rect rect) { + _paintBounds.clipRect(rect); + _hasArbitraryPaint = true; + _commands.add(PaintClipRect(rect)); + } + + void clipRRect(ui.RRect rrect) { + _paintBounds.clipRect(rrect.outerRect); + _hasArbitraryPaint = true; + _commands.add(PaintClipRRect(rrect)); + } + + void clipPath(ui.Path path) { + _paintBounds.clipRect(path.getBounds()); + _hasArbitraryPaint = true; + _commands.add(PaintClipPath(path)); + } + + void drawColor(ui.Color color, ui.BlendMode blendMode) { + _hasArbitraryPaint = true; + _didDraw = true; + _paintBounds.grow(_paintBounds.maxPaintBounds); + _commands.add(PaintDrawColor(color, blendMode)); + } + + void drawLine(ui.Offset p1, ui.Offset p2, ui.Paint paint) { + final double strokeWidth = math.max(paint.strokeWidth, 1.0); + // TODO(yjbanov): This can be optimized. Currently we create a box around + // the line and then apply the transform on the box to get + // the bounding box. If you have a 45-degree line and a + // 45-degree transform, the bounding box should be the length + // of the line long and stroke width wide, but our current + // algorithm produces a square with each side of the length + // matching the length of the line. + _paintBounds.growLTRB( + math.min(p1.dx, p2.dx) - strokeWidth, + math.min(p1.dy, p2.dy) - strokeWidth, + math.max(p1.dx, p2.dx) + strokeWidth, + math.max(p1.dy, p2.dy) + strokeWidth); + _hasArbitraryPaint = true; + _didDraw = true; + _commands.add(PaintDrawLine(p1, p2, paint.webOnlyPaintData)); + } + + void drawPaint(ui.Paint paint) { + _hasArbitraryPaint = true; + _didDraw = true; + _paintBounds.grow(_paintBounds.maxPaintBounds); + _commands.add(PaintDrawPaint(paint.webOnlyPaintData)); + } + + void drawRect(ui.Rect rect, ui.Paint paint) { + if (paint.shader != null) { + _hasArbitraryPaint = true; + } + _didDraw = true; + if (paint.strokeWidth != null && paint.strokeWidth != 0) { + _paintBounds.grow(rect.inflate(paint.strokeWidth / 2.0)); + } else { + _paintBounds.grow(rect); + } + _commands.add(PaintDrawRect(rect, paint.webOnlyPaintData)); + } + + void drawRRect(ui.RRect rrect, ui.Paint paint) { + _hasArbitraryPaint = true; + _didDraw = true; + final double strokeWidth = + paint.strokeWidth == null ? 0 : paint.strokeWidth; + final double left = math.min(rrect.left, rrect.right) - strokeWidth; + final double right = math.max(rrect.left, rrect.right) + strokeWidth; + final double top = math.min(rrect.top, rrect.bottom) - strokeWidth; + final double bottom = math.max(rrect.top, rrect.bottom) + strokeWidth; + _paintBounds.growLTRB(left, top, right, bottom); + _commands.add(PaintDrawRRect(rrect, paint.webOnlyPaintData)); + } + + void drawDRRect(ui.RRect outer, ui.RRect inner, ui.Paint paint) { + // If inner rect is not contained inside outer, flutter engine skips + // painting rectangle. + if (!(outer.contains(ui.Offset(inner.left, inner.top)) && + outer.contains(ui.Offset(inner.right, inner.bottom)))) { + return; + } + _hasArbitraryPaint = true; + _didDraw = true; + final double strokeWidth = + paint.strokeWidth == null ? 0 : paint.strokeWidth; + _paintBounds.growLTRB(outer.left - strokeWidth, outer.top - strokeWidth, + outer.right + strokeWidth, outer.bottom + strokeWidth); + _commands.add(PaintDrawDRRect(outer, inner, paint.webOnlyPaintData)); + } + + void drawOval(ui.Rect rect, ui.Paint paint) { + _hasArbitraryPaint = true; + _didDraw = true; + if (paint.strokeWidth != null) { + _paintBounds.grow(rect.inflate(paint.strokeWidth)); + } else { + _paintBounds.grow(rect); + } + _commands.add(PaintDrawOval(rect, paint.webOnlyPaintData)); + } + + void drawCircle(ui.Offset c, double radius, ui.Paint paint) { + _hasArbitraryPaint = true; + _didDraw = true; + final double strokeWidth = + paint.strokeWidth == null ? 0 : paint.strokeWidth; + _paintBounds.growLTRB( + c.dx - radius - strokeWidth, + c.dy - radius - strokeWidth, + c.dx + radius + strokeWidth, + c.dy + radius + strokeWidth); + _commands.add(PaintDrawCircle(c, radius, paint.webOnlyPaintData)); + } + + void drawPath(ui.Path path, ui.Paint paint) { + _hasArbitraryPaint = true; + _didDraw = true; + ui.Rect pathBounds = path.getBounds(); + if (paint.strokeWidth != null) { + pathBounds = pathBounds.inflate(paint.strokeWidth); + } + _paintBounds.grow(pathBounds); + _commands.add(PaintDrawPath(path, paint.webOnlyPaintData)); + } + + void drawImage(ui.Image image, ui.Offset offset, ui.Paint paint) { + _hasArbitraryPaint = true; + _didDraw = true; + final double left = offset.dx; + final double top = offset.dy; + _paintBounds.growLTRB(left, top, left + image.width, top + image.height); + _commands.add(PaintDrawImage(image, offset, paint.webOnlyPaintData)); + } + + void drawImageRect(ui.Image image, ui.Rect src, ui.Rect dst, ui.Paint paint) { + _hasArbitraryPaint = true; + _didDraw = true; + _paintBounds.grow(dst); + _commands.add(PaintDrawImageRect(image, src, dst, paint.webOnlyPaintData)); + } + + void drawParagraph(ui.Paragraph paragraph, ui.Offset offset) { + final EngineParagraph engineParagraph = paragraph; + if (!engineParagraph._isLaidOut) { + // Ignore non-laid out paragraphs. This matches Flutter's behavior. + return; + } + + _didDraw = true; + if (engineParagraph._geometricStyle.ellipsis != null) { + _hasArbitraryPaint = true; + } + final double left = offset.dx; + final double top = offset.dy; + _paintBounds.growLTRB( + left, top, left + engineParagraph.width, top + engineParagraph.height); + _commands.add(PaintDrawParagraph(engineParagraph, offset)); + } + + void drawShadow(ui.Path path, ui.Color color, double elevation, + bool transparentOccluder) { + _hasArbitraryPaint = true; + _didDraw = true; + final ui.Rect shadowRect = + ElevationShadow.computeShadowRect(path.getBounds(), elevation); + _paintBounds.grow(shadowRect); + _commands.add(PaintDrawShadow(path, color, elevation, transparentOccluder)); + } + + int saveCount = 1; + + /// Prints the commands recorded by this canvas to the console. + void debugDumpCommands() { + print('/' * 40 + ' CANVAS COMMANDS ' + '/' * 40); + _commands.forEach(print); + print('/' * 37 + ' END OF CANVAS COMMANDS ' + '/' * 36); + } +} + +abstract class PaintCommand { + const PaintCommand(); + + void apply(EngineCanvas canvas); + + void serializeToCssPaint(List> serializedCommands); +} + +class PaintSave extends PaintCommand { + const PaintSave(); + + @override + void apply(EngineCanvas canvas) { + canvas.save(); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'save()'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add(const [1]); + } +} + +class PaintRestore extends PaintCommand { + const PaintRestore(); + + @override + void apply(EngineCanvas canvas) { + canvas.restore(); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'restore()'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add(const [2]); + } +} + +class PaintTranslate extends PaintCommand { + final double dx; + final double dy; + + PaintTranslate(this.dx, this.dy); + + @override + void apply(EngineCanvas canvas) { + canvas.translate(dx, dy); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'translate($dx, $dy)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([3, dx, dy]); + } +} + +class PaintScale extends PaintCommand { + final double sx; + final double sy; + + PaintScale(this.sx, this.sy); + + @override + void apply(EngineCanvas canvas) { + canvas.scale(sx, sy); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'scale($sx, $sy)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([4, sx, sy]); + } +} + +class PaintRotate extends PaintCommand { + final double radians; + + PaintRotate(this.radians); + + @override + void apply(EngineCanvas canvas) { + canvas.rotate(radians); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'rotate($radians)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([5, radians]); + } +} + +class PaintTransform extends PaintCommand { + final Float64List matrix4; + + PaintTransform(this.matrix4); + + @override + void apply(EngineCanvas canvas) { + canvas.transform(matrix4); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'transform(Matrix4.fromFloat64List(Float64List.fromList([${matrix4.join(', ')}])))'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([6]..addAll(matrix4)); + } +} + +class PaintSkew extends PaintCommand { + final double sx; + final double sy; + + PaintSkew(this.sx, this.sy); + + @override + void apply(EngineCanvas canvas) { + canvas.skew(sx, sy); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'skew($sx, $sy)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([7, sx, sy]); + } +} + +class PaintClipRect extends PaintCommand { + final ui.Rect rect; + + PaintClipRect(this.rect); + + @override + void apply(EngineCanvas canvas) { + canvas.clipRect(rect); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'clipRect($rect)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([8, _serializeRectToCssPaint(rect)]); + } +} + +class PaintClipRRect extends PaintCommand { + final ui.RRect rrect; + + PaintClipRRect(this.rrect); + + @override + void apply(EngineCanvas canvas) { + canvas.clipRRect(rrect); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'clipRRect($rrect)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([ + 9, + _serializeRRectToCssPaint(rrect), + ]); + } +} + +class PaintClipPath extends PaintCommand { + final ui.Path path; + + PaintClipPath(this.path); + + @override + void apply(EngineCanvas canvas) { + canvas.clipPath(path); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'clipPath($path)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([10, path.webOnlySerializeToCssPaint()]); + } +} + +class PaintDrawColor extends PaintCommand { + final ui.Color color; + final ui.BlendMode blendMode; + + PaintDrawColor(this.color, this.blendMode); + + @override + void apply(EngineCanvas canvas) { + canvas.drawColor(color, blendMode); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawColor($color, $blendMode)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([11, color.toCssString(), blendMode.index]); + } +} + +class PaintDrawLine extends PaintCommand { + final ui.Offset p1; + final ui.Offset p2; + final ui.PaintData paint; + + PaintDrawLine(this.p1, this.p2, this.paint); + + @override + void apply(EngineCanvas canvas) { + canvas.drawLine(p1, p2, paint); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawLine($p1, $p2, $paint)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([ + 12, + p1.dx, + p1.dy, + p2.dx, + p2.dy, + _serializePaintToCssPaint(paint) + ]); + } +} + +class PaintDrawPaint extends PaintCommand { + final ui.PaintData paint; + + PaintDrawPaint(this.paint); + + @override + void apply(EngineCanvas canvas) { + canvas.drawPaint(paint); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawPaint($paint)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([13, _serializePaintToCssPaint(paint)]); + } +} + +class PaintDrawRect extends PaintCommand { + final ui.Rect rect; + final ui.PaintData paint; + + PaintDrawRect(this.rect, this.paint); + + @override + void apply(EngineCanvas canvas) { + canvas.drawRect(rect, paint); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawRect($rect, $paint)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([ + 14, + _serializeRectToCssPaint(rect), + _serializePaintToCssPaint(paint) + ]); + } +} + +class PaintDrawRRect extends PaintCommand { + final ui.RRect rrect; + final ui.PaintData paint; + + PaintDrawRRect(this.rrect, this.paint); + + @override + void apply(EngineCanvas canvas) { + canvas.drawRRect(rrect, paint); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawRRect($rrect, $paint)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([ + 15, + _serializeRRectToCssPaint(rrect), + _serializePaintToCssPaint(paint), + ]); + } +} + +class PaintDrawDRRect extends PaintCommand { + final ui.RRect outer; + final ui.RRect inner; + final ui.PaintData paint; + + PaintDrawDRRect(this.outer, this.inner, this.paint); + + @override + void apply(EngineCanvas canvas) { + canvas.drawDRRect(outer, inner, paint); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawDRRect($outer, $inner, $paint)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([ + 16, + _serializeRRectToCssPaint(outer), + _serializeRRectToCssPaint(inner), + _serializePaintToCssPaint(paint), + ]); + } +} + +class PaintDrawOval extends PaintCommand { + final ui.Rect rect; + final ui.PaintData paint; + + PaintDrawOval(this.rect, this.paint); + + @override + void apply(EngineCanvas canvas) { + canvas.drawOval(rect, paint); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawOval($rect, $paint)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([ + 17, + _serializeRectToCssPaint(rect), + _serializePaintToCssPaint(paint), + ]); + } +} + +class PaintDrawCircle extends PaintCommand { + final ui.Offset c; + final double radius; + final ui.PaintData paint; + + PaintDrawCircle(this.c, this.radius, this.paint); + + @override + void apply(EngineCanvas canvas) { + canvas.drawCircle(c, radius, paint); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawCircle($c, $radius, $paint)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([ + 18, + c.dx, + c.dy, + radius, + _serializePaintToCssPaint(paint), + ]); + } +} + +class PaintDrawPath extends PaintCommand { + final ui.Path path; + final ui.PaintData paint; + + PaintDrawPath(this.path, this.paint); + + @override + void apply(EngineCanvas canvas) { + canvas.drawPath(path, paint); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawPath($path, $paint)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([ + 19, + path.webOnlySerializeToCssPaint(), + _serializePaintToCssPaint(paint), + ]); + } +} + +class PaintDrawShadow extends PaintCommand { + PaintDrawShadow( + this.path, this.color, this.elevation, this.transparentOccluder); + + final ui.Path path; + final ui.Color color; + final double elevation; + final bool transparentOccluder; + + @override + void apply(EngineCanvas canvas) { + canvas.drawShadow(path, color, elevation, transparentOccluder); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawShadow($path, $color, $elevation, $transparentOccluder)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + serializedCommands.add([ + 20, + path.webOnlySerializeToCssPaint(), + [ + color.alpha, + color.red, + color.green, + color.blue, + ], + elevation, + transparentOccluder, + ]); + } +} + +class PaintDrawImage extends PaintCommand { + final ui.Image image; + final ui.Offset offset; + final ui.PaintData paint; + + PaintDrawImage(this.image, this.offset, this.paint); + + @override + void apply(EngineCanvas canvas) { + canvas.drawImage(image, offset, paint); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawImage($image, $offset, $paint)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + if (assertionsEnabled) { + throw UnsupportedError('drawImage not serializable'); + } + } +} + +class PaintDrawImageRect extends PaintCommand { + final ui.Image image; + final ui.Rect src; + final ui.Rect dst; + final ui.PaintData paint; + + PaintDrawImageRect(this.image, this.src, this.dst, this.paint); + + @override + void apply(EngineCanvas canvas) { + canvas.drawImageRect(image, src, dst, paint); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'drawImageRect($image, $src, $dst, $paint)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + if (assertionsEnabled) { + throw UnsupportedError('drawImageRect not serializable'); + } + } +} + +class PaintDrawParagraph extends PaintCommand { + final EngineParagraph paragraph; + final ui.Offset offset; + + PaintDrawParagraph(this.paragraph, this.offset); + + @override + void apply(EngineCanvas canvas) { + canvas.drawParagraph(paragraph, offset); + } + + @override + String toString() { + if (assertionsEnabled) { + return 'DrawParagraph(${paragraph._plainText}, $offset)'; + } else { + return super.toString(); + } + } + + @override + void serializeToCssPaint(List> serializedCommands) { + if (assertionsEnabled) { + throw UnsupportedError('drawParagraph not serializable'); + } + } +} + +List _serializePaintToCssPaint(ui.PaintData paint) { + return [ + paint.blendMode?.index, + paint.style?.index, + paint.strokeWidth, + paint.strokeCap?.index, + paint.isAntiAlias, + paint.color.toCssString(), + paint.shader?.webOnlySerializeToCssPaint(), + paint.maskFilter?.webOnlySerializeToCssPaint(), + paint.filterQuality?.index, + paint.colorFilter?.webOnlySerializeToCssPaint(), + ]; +} + +List _serializeRectToCssPaint(ui.Rect rect) { + return [ + rect.left, + rect.top, + rect.right, + rect.bottom, + ]; +} + +List _serializeRRectToCssPaint(ui.RRect rrect) { + return [ + rrect.left, + rrect.top, + rrect.right, + rrect.bottom, + rrect.tlRadiusX, + rrect.tlRadiusY, + rrect.trRadiusX, + rrect.trRadiusY, + rrect.brRadiusX, + rrect.brRadiusY, + rrect.blRadiusX, + rrect.blRadiusY, + ]; +} + +class Subpath { + double startX = 0.0; + double startY = 0.0; + double currentX = 0.0; + double currentY = 0.0; + + final List commands; + + Subpath(this.startX, this.startY) : commands = []; + + Subpath shift(ui.Offset offset) { + final Subpath result = Subpath(startX + offset.dx, startY + offset.dy) + ..currentX = currentX + offset.dx + ..currentY = currentY + offset.dy; + + for (final PathCommand command in commands) { + result.commands.add(command.shifted(offset)); + } + + return result; + } + + List serializeToCssPaint() { + final List serialization = []; + for (int i = 0; i < commands.length; i++) { + serialization.add(commands[i].serializeToCssPaint()); + } + return serialization; + } + + @override + String toString() { + if (assertionsEnabled) { + return 'Subpath(${commands.join(', ')})'; + } else { + return super.toString(); + } + } +} + +/// ! Houdini implementation relies on indices here. Keep in sync. +class PathCommandTypes { + static const int moveTo = 0; + static const int lineTo = 1; + static const int ellipse = 2; + static const int close = 3; + static const int quadraticCurveTo = 4; + static const int bezierCurveTo = 5; + static const int rect = 6; + static const int rRect = 7; +} + +abstract class PathCommand { + final int type; + const PathCommand(this.type); + + PathCommand shifted(ui.Offset offset); + + List serializeToCssPaint(); +} + +class MoveTo extends PathCommand { + final double x; + final double y; + + const MoveTo(this.x, this.y) : super(PathCommandTypes.moveTo); + + @override + MoveTo shifted(ui.Offset offset) { + return MoveTo(x + offset.dx, y + offset.dy); + } + + @override + List serializeToCssPaint() { + return [1, x, y]; + } + + @override + String toString() { + if (assertionsEnabled) { + return 'MoveTo($x, $y)'; + } else { + return super.toString(); + } + } +} + +class LineTo extends PathCommand { + final double x; + final double y; + + const LineTo(this.x, this.y) : super(PathCommandTypes.lineTo); + + @override + LineTo shifted(ui.Offset offset) { + return LineTo(x + offset.dx, y + offset.dy); + } + + @override + List serializeToCssPaint() { + return [2, x, y]; + } + + @override + String toString() { + if (assertionsEnabled) { + return 'LineTo($x, $y)'; + } else { + return super.toString(); + } + } +} + +class Ellipse extends PathCommand { + final double x; + final double y; + final double radiusX; + final double radiusY; + final double rotation; + final double startAngle; + final double endAngle; + final bool anticlockwise; + + const Ellipse(this.x, this.y, this.radiusX, this.radiusY, this.rotation, + this.startAngle, this.endAngle, this.anticlockwise) + : super(PathCommandTypes.ellipse); + + @override + Ellipse shifted(ui.Offset offset) { + return Ellipse(x + offset.dx, y + offset.dy, radiusX, radiusY, rotation, + startAngle, endAngle, anticlockwise); + } + + @override + List serializeToCssPaint() { + return [ + 3, + x, + y, + radiusX, + radiusY, + rotation, + startAngle, + endAngle, + anticlockwise, + ]; + } + + @override + String toString() { + if (assertionsEnabled) { + return 'Ellipse($x, $y, $radiusX, $radiusY)'; + } else { + return super.toString(); + } + } +} + +class QuadraticCurveTo extends PathCommand { + final double x1; + final double y1; + final double x2; + final double y2; + + const QuadraticCurveTo(this.x1, this.y1, this.x2, this.y2) + : super(PathCommandTypes.quadraticCurveTo); + + @override + QuadraticCurveTo shifted(ui.Offset offset) { + return QuadraticCurveTo( + x1 + offset.dx, y1 + offset.dy, x2 + offset.dx, y2 + offset.dy); + } + + @override + List serializeToCssPaint() { + return [4, x1, y1, x2, y2]; + } + + @override + String toString() { + if (assertionsEnabled) { + return 'QuadraticCurveTo($x1, $y1, $x2, $y2)'; + } else { + return super.toString(); + } + } +} + +class BezierCurveTo extends PathCommand { + final double x1; + final double y1; + final double x2; + final double y2; + final double x3; + final double y3; + + const BezierCurveTo(this.x1, this.y1, this.x2, this.y2, this.x3, this.y3) + : super(PathCommandTypes.bezierCurveTo); + + @override + BezierCurveTo shifted(ui.Offset offset) { + return BezierCurveTo(x1 + offset.dx, y1 + offset.dy, x2 + offset.dx, + y2 + offset.dy, x3 + offset.dx, y3 + offset.dy); + } + + @override + List serializeToCssPaint() { + return [5, x1, y1, x2, y2, x3, y3]; + } + + @override + String toString() { + if (assertionsEnabled) { + return 'BezierCurveTo($x1, $y1, $x2, $y2, $x3, $y3)'; + } else { + return super.toString(); + } + } +} + +class RectCommand extends PathCommand { + final double x; + final double y; + final double width; + final double height; + + const RectCommand(this.x, this.y, this.width, this.height) + : super(PathCommandTypes.rect); + + @override + RectCommand shifted(ui.Offset offset) { + return RectCommand(x + offset.dx, y + offset.dy, width, height); + } + + @override + List serializeToCssPaint() { + return [6, x, y, width, height]; + } + + @override + String toString() { + if (assertionsEnabled) { + return 'Rect($x, $y, $width, $height)'; + } else { + return super.toString(); + } + } +} + +class RRectCommand extends PathCommand { + final ui.RRect rrect; + + const RRectCommand(this.rrect) : super(PathCommandTypes.rRect); + + @override + RRectCommand shifted(ui.Offset offset) { + return RRectCommand(rrect.shift(offset)); + } + + @override + List serializeToCssPaint() { + return [7, _serializeRRectToCssPaint(rrect)]; + } + + @override + String toString() { + if (assertionsEnabled) { + return '$rrect'; + } else { + return super.toString(); + } + } +} + +class CloseCommand extends PathCommand { + const CloseCommand() : super(PathCommandTypes.close); + + @override + CloseCommand shifted(ui.Offset offset) { + return this; + } + + @override + List serializeToCssPaint() { + return [8]; + } + + @override + String toString() { + if (assertionsEnabled) { + return 'Close()'; + } else { + return super.toString(); + } + } +} + +class _PaintBounds { + // Bounds of maximum area that is paintable by canvas ops. + final ui.Rect maxPaintBounds; + + bool _didPaintInsideClipArea = false; + // Bounds of actually painted area. If _left is not set, reported paintBounds + // should be empty since growLTRB calls were outside active clipping + // region. + double _left, _top, _right, _bottom; + // Stack of transforms. + List _transforms; + // Stack of clip bounds. + List _clipStack; + bool _currentMatrixIsIdentity = true; + Matrix4 _currentMatrix = Matrix4.identity(); + bool _clipRectInitialized = false; + double _currentClipLeft = 0.0, + _currentClipTop = 0.0, + _currentClipRight = 0.0, + _currentClipBottom = 0.0; + + _PaintBounds(this.maxPaintBounds); + + void translate(double dx, double dy) { + if (dx != 0.0 || dy != 0.0) { + _currentMatrixIsIdentity = false; + } + _currentMatrix.translate(dx, dy); + } + + void scale(double sx, double sy) { + if (sx != 1.0 || sy != 1.0) { + _currentMatrixIsIdentity = false; + } + _currentMatrix.scale(sx, sy); + } + + void rotateZ(double radians) { + if (radians != 0.0) { + _currentMatrixIsIdentity = false; + } + _currentMatrix.rotateZ(radians); + } + + void transform(Float64List matrix4) { + final Matrix4 m4 = Matrix4.fromFloat64List(matrix4); + _currentMatrix.multiply(m4); + _currentMatrixIsIdentity = _currentMatrix.isIdentity(); + } + + void skew(double sx, double sy) { + _currentMatrixIsIdentity = false; + + // DO NOT USE Matrix4.skew(sx, sy)! It treats sx and sy values as radians, + // but in our case they are transform matrix values. + final Matrix4 skewMatrix = Matrix4.identity(); + final Float64List storage = skewMatrix.storage; + storage[1] = sy; + storage[4] = sx; + _currentMatrix.multiply(skewMatrix); + } + + void clipRect(ui.Rect rect) { + // If we have an active transform, calculate screen relative clipping + // rectangle and union with current clipping rectangle. + if (!_currentMatrixIsIdentity) { + final Vector3 leftTop = + _currentMatrix.transform3(Vector3(rect.left, rect.top, 0.0)); + final Vector3 rightTop = + _currentMatrix.transform3(Vector3(rect.right, rect.top, 0.0)); + final Vector3 leftBottom = + _currentMatrix.transform3(Vector3(rect.left, rect.bottom, 0.0)); + final Vector3 rightBottom = + _currentMatrix.transform3(Vector3(rect.right, rect.bottom, 0.0)); + rect = ui.Rect.fromLTRB( + math.min(math.min(math.min(leftTop.x, rightTop.x), leftBottom.x), + rightBottom.x), + math.min(math.min(math.min(leftTop.y, rightTop.y), leftBottom.y), + rightBottom.y), + math.max(math.max(math.max(leftTop.x, rightTop.x), leftBottom.x), + rightBottom.x), + math.max(math.max(math.max(leftTop.y, rightTop.y), leftBottom.y), + rightBottom.y)); + } + if (!_clipRectInitialized) { + _currentClipLeft = rect.left; + _currentClipTop = rect.top; + _currentClipRight = rect.right; + _currentClipBottom = rect.bottom; + _clipRectInitialized = true; + } else { + if (rect.left > _currentClipLeft) { + _currentClipLeft = rect.left; + } + if (rect.top > _currentClipTop) { + _currentClipTop = rect.top; + } + if (rect.right < _currentClipRight) { + _currentClipRight = rect.right; + } + if (rect.bottom < _currentClipBottom) { + _currentClipBottom = rect.bottom; + } + } + } + + /// Grow painted area to include given rectangle. + void grow(ui.Rect r) { + growLTRB(r.left, r.top, r.right, r.bottom); + } + + /// Grow painted area to include given rectangle. + void growLTRB(double left, double top, double right, double bottom) { + if (left == right || top == bottom) { + return; + } + + double transformedPointLeft = left; + double transformedPointTop = top; + double transformedPointRight = right; + double transformedPointBottom = bottom; + + if (!_currentMatrixIsIdentity) { + final ui.Rect transformedRect = localClipToGlobalClip( + localLeft: left, + localTop: top, + localRight: right, + localBottom: bottom, + transform: _currentMatrix, + ); + transformedPointLeft = transformedRect.left; + transformedPointTop = transformedRect.top; + transformedPointRight = transformedRect.right; + transformedPointBottom = transformedRect.bottom; + } + + if (_clipRectInitialized) { + if (transformedPointLeft > _currentClipRight) { + return; + } + if (transformedPointRight < _currentClipLeft) { + return; + } + if (transformedPointTop > _currentClipBottom) { + return; + } + if (transformedPointBottom < _currentClipTop) { + return; + } + if (transformedPointLeft < _currentClipLeft) { + transformedPointLeft = _currentClipLeft; + } + if (transformedPointRight > _currentClipRight) { + transformedPointRight = _currentClipRight; + } + if (transformedPointTop < _currentClipTop) { + transformedPointTop = _currentClipTop; + } + if (transformedPointBottom > _currentClipBottom) { + transformedPointBottom = _currentClipBottom; + } + } + + if (_didPaintInsideClipArea) { + _left = math.min( + math.min(_left, transformedPointLeft), transformedPointRight); + _right = math.max( + math.max(_right, transformedPointLeft), transformedPointRight); + _top = + math.min(math.min(_top, transformedPointTop), transformedPointBottom); + _bottom = math.max( + math.max(_bottom, transformedPointTop), transformedPointBottom); + } else { + _left = math.min(transformedPointLeft, transformedPointRight); + _right = math.max(transformedPointLeft, transformedPointRight); + _top = math.min(transformedPointTop, transformedPointBottom); + _bottom = math.max(transformedPointTop, transformedPointBottom); + } + _didPaintInsideClipArea = true; + } + + void saveTransformsAndClip() { + _clipStack ??= []; + _transforms ??= []; + _transforms.add(_currentMatrix?.clone()); + _clipStack.add(_clipRectInitialized + ? ui.Rect.fromLTRB(_currentClipLeft, _currentClipTop, _currentClipRight, + _currentClipBottom) + : null); + } + + void restoreTransformsAndClip() { + _currentMatrix = _transforms.removeLast(); + final ui.Rect clipRect = _clipStack.removeLast(); + if (clipRect != null) { + _currentClipLeft = clipRect.left; + _currentClipTop = clipRect.top; + _currentClipRight = clipRect.right; + _currentClipBottom = clipRect.bottom; + _clipRectInitialized = true; + } else if (_clipRectInitialized) { + _clipRectInitialized = false; + } + } + + ui.Rect computeBounds() { + if (!_didPaintInsideClipArea) { + return ui.Rect.zero; + } + + // The framework may send us NaNs in the case when it attempts to invert an + // infinitely size rect. + final double maxLeft = maxPaintBounds.left.isNaN + ? double.negativeInfinity + : maxPaintBounds.left; + final double maxRight = + maxPaintBounds.right.isNaN ? double.infinity : maxPaintBounds.right; + final double maxTop = + maxPaintBounds.top.isNaN ? double.negativeInfinity : maxPaintBounds.top; + final double maxBottom = + maxPaintBounds.bottom.isNaN ? double.infinity : maxPaintBounds.bottom; + + final double left = math.min(_left, _right); + final double right = math.max(_left, _right); + final double top = math.min(_top, _bottom); + final double bottom = math.max(_top, _bottom); + + if (right < maxLeft || bottom < maxTop) { + // Computed and max bounds do not intersect. + return ui.Rect.zero; + } + + return ui.Rect.fromLTRB( + math.max(left, maxLeft), + math.max(top, maxTop), + math.min(right, maxRight), + math.min(bottom, maxBottom), + ); + } + + @override + String toString() { + if (assertionsEnabled) { + final ui.Rect bounds = computeBounds(); + return '_PaintBounds($bounds of size ${bounds.size})'; + } else { + return super.toString(); + } + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/accessibility.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/accessibility.dart new file mode 100644 index 0000000000..31ed9511d6 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/accessibility.dart @@ -0,0 +1,84 @@ +// 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; + +/// Singleton for accessing accessibility announcements from the platform. +final AccessibilityAnnouncements accessibilityAnnouncements = + AccessibilityAnnouncements.instance; + +/// Attaches accessibility announcements coming from the 'flutter/accessibility' +/// channel as temporary elements to the DOM. +class AccessibilityAnnouncements { + /// Initializes the [AccessibilityAnnouncements] singleton if it is not + /// already initialized. + static AccessibilityAnnouncements get instance { + return _instance ??= AccessibilityAnnouncements._(); + } + + static AccessibilityAnnouncements _instance; + + AccessibilityAnnouncements._() { + registerHotRestartListener(() { + _removeElementTimer?.cancel(); + }); + } + + /// Timer that times when the accessibility element should be removed from the + /// DOM. + /// + /// The element is added to the DOM temporarily for announcing the + /// message to the assistive technology. + Timer _removeElementTimer; + + /// The duration the accessibility announcements stay on the DOM. + /// + /// It is removed after this time expired. + Duration durationA11yMessageIsOnDom = const Duration(seconds: 5); + + /// Element which is used to communicate the message from the + /// 'flutter/accessibility' to the assistive technologies. + /// + /// This element gets attached to the DOM temporarily. It gets removed + /// after a duration. See [durationA11yMessageIsOnDom]. + /// + /// This element has aria-live attribute. + /// + /// It also has id 'accessibility-element' for testing purposes. + html.HtmlElement _element; + + html.HtmlElement get _domElement => _element ??= _createElement(); + + /// Decodes the message coming from the 'flutter/accessibility' channel. + void handleMessage(ByteData data) { + final Map inputMap = + const StandardMessageCodec().decodeMessage(data); + final Map dataMap = inputMap['data']; + final String message = dataMap['message']; + if (message != null && message.isNotEmpty) { + _initLiveRegion(message); + _removeElementTimer = Timer(durationA11yMessageIsOnDom, () { + _element.remove(); + }); + } + } + + void _initLiveRegion(String message) { + _domElement.setAttribute('aria-live', 'polite'); + _domElement.text = message; + html.document.body.append(_domElement); + } + + html.LabelElement _createElement() { + final html.LabelElement liveRegion = html.LabelElement(); + liveRegion.setAttribute('id', 'accessibility-element'); + liveRegion.style + ..position = 'fixed' + ..overflow = 'hidden' + ..transform = 'translate(-99999px, -99999px)' + ..width = '1px' + ..height = '1px'; + return liveRegion; + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/checkable.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/checkable.dart new file mode 100644 index 0000000000..6c63c06da6 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/checkable.dart @@ -0,0 +1,112 @@ +// 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): TalkBack on Android incorrectly reads state changes for radio +// buttons. When checking a radio button it reads +// "Checked, not checked". This is likely due to another radio +// button automatically becoming unchecked. VoiceOver reads it +// correctly. It is possible we can fix this by using +// "radiogroup" and "aria-owns". This may require a change in the +// framework. Currently the framework does not report the +// grouping of radio buttons. + +part of engine; + +/// The specific type of checkable control. +enum _CheckableKind { + /// A checkbox. An element, which has [ui.SemanticsFlag.hasCheckedState] set + /// and does not have [ui.SemanticsFlag.isInMutuallyExclusiveGroup] or + /// [ui.SemanticsFlag.hasToggledState] state, is marked as a checkbox. + checkbox, + + /// A radio button, defined by [ui.SemanticsFlag.isInMutuallyExclusiveGroup]. + radio, + + /// A switch, defined by [ui.SemanticsFlag.hasToggledState]. + toggle, +} + +/// Renders semantics objects that have checkable (on/off) states. +/// +/// Three objects which are implemented by this class are checkboxes, radio +/// buttons and switches. +/// +/// See also [ui.SemanticsFlag.hasCheckedState], [ui.SemanticsFlag.isChecked], +/// [ui.SemanticsFlag.isInMutuallyExclusiveGroup], [ui.SemanticsFlag.isToggled], +/// [ui.SemanticsFlag.hasToggledState] +class Checkable extends RoleManager { + _CheckableKind _kind; + + Checkable(SemanticsObject semanticsObject) + : super(Role.checkable, semanticsObject) { + if (semanticsObject.hasFlag(ui.SemanticsFlag.isInMutuallyExclusiveGroup)) { + _kind = _CheckableKind.radio; + } else if (semanticsObject.hasFlag(ui.SemanticsFlag.hasToggledState)) { + _kind = _CheckableKind.toggle; + } else { + _kind = _CheckableKind.checkbox; + } + } + + @override + void update() { + if (semanticsObject.isFlagsDirty) { + switch (_kind) { + case _CheckableKind.checkbox: + semanticsObject.setAriaRole('checkbox', true); + break; + case _CheckableKind.radio: + semanticsObject.setAriaRole('radio', true); + break; + case _CheckableKind.toggle: + semanticsObject.setAriaRole('switch', true); + break; + } + + /// Adding disabled and aria-disabled attribute to notify the assistive + /// technologies of disabled elements. + _updateDisabledAttribute(); + + semanticsObject.element.setAttribute( + 'aria-checked', + (semanticsObject.hasFlag(ui.SemanticsFlag.isChecked) || + semanticsObject.hasFlag(ui.SemanticsFlag.isToggled)) + ? 'true' + : 'false', + ); + } + } + + @override + void dispose() { + switch (_kind) { + case _CheckableKind.checkbox: + semanticsObject.setAriaRole('checkbox', false); + break; + case _CheckableKind.radio: + semanticsObject.setAriaRole('radio', false); + break; + case _CheckableKind.toggle: + semanticsObject.setAriaRole('switch', false); + break; + } + _removeDisabledAttribute(); + } + + void _updateDisabledAttribute() { + if (!semanticsObject.hasFlag(ui.SemanticsFlag.isEnabled)) { + final html.Element element = semanticsObject.element; + element + ..setAttribute('aria-disabled', 'true') + ..setAttribute('disabled', 'true'); + } else { + _removeDisabledAttribute(); + } + } + + void _removeDisabledAttribute() { + final html.Element element = semanticsObject.element; + element..removeAttribute('aria-disabled')..removeAttribute('disabled'); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/image.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/image.dart new file mode 100644 index 0000000000..0577d02f43 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/image.dart @@ -0,0 +1,78 @@ +// 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; + +/// Represents semantic objects that deliver information in a visual manner. +/// +/// Uses aria img role to convey this semantic information to the element. +/// +/// Screen-readers takes advantage of "aria-label" to describe the visual. +class ImageRoleManager extends RoleManager { + ImageRoleManager(SemanticsObject semanticsObject) + : super(Role.image, semanticsObject); + + /// The element with role="img" and aria-label could block access to all + /// children elements, therefore create an auxiliary element and describe the + /// image in that if the semantic object have child nodes. + html.Element _auxiliaryImageElement; + + @override + void update() { + if (semanticsObject.isVisualOnly && semanticsObject.hasChildren) { + if (_auxiliaryImageElement == null) { + _auxiliaryImageElement = html.Element.tag('flt-semantics-img'); + // Absolute positioning and sizing of leaf text elements confuses + // VoiceOver. So we let the browser size the value node. The node will + // still have a bigger tap area. However, if the node is a parent to + // other nodes, then VoiceOver behaves as expected with absolute + // positioning and sizing. + if (semanticsObject.hasChildren) { + _auxiliaryImageElement.style + ..position = 'absolute' + ..top = '0' + ..left = '0' + ..width = '${semanticsObject.rect.width}px' + ..height = '${semanticsObject.rect.height}px'; + } + _auxiliaryImageElement.style.fontSize = '6px'; + semanticsObject.element.append(_auxiliaryImageElement); + } + + _auxiliaryImageElement.setAttribute('role', 'img'); + _setLabel(_auxiliaryImageElement); + } else if (semanticsObject.isVisualOnly) { + semanticsObject.setAriaRole('img', true); + _setLabel(semanticsObject.element); + _cleanUpAuxiliaryElement(); + } else { + _cleanUpAuxiliaryElement(); + _cleanupElement(); + } + } + + void _setLabel(html.Element element) { + if (semanticsObject.hasLabel) { + element.setAttribute('aria-label', semanticsObject.label); + } + } + + void _cleanUpAuxiliaryElement() { + if (_auxiliaryImageElement != null) { + _auxiliaryImageElement.remove(); + _auxiliaryImageElement = null; + } + } + + void _cleanupElement() { + semanticsObject.setAriaRole('img', false); + semanticsObject.element.attributes.remove('aria-label'); + } + + @override + void dispose() { + _cleanUpAuxiliaryElement(); + _cleanupElement(); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/incrementable.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/incrementable.dart new file mode 100644 index 0000000000..0e3780e5aa --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/incrementable.dart @@ -0,0 +1,140 @@ +// 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; + +/// Adds increment/decrement event handling to a semantics object. +/// +/// The implementation uses a hidden `` element with ARIA +/// attributes to cause the browser to render increment/decrement controls to +/// the assistive technology. +/// +/// The input element is disabled whenever the gesture mode switches to pointer +/// events. This is to prevent the browser from taking over drag gestures. Drag +/// gestures must be interpreted by the Flutter framework. +class Incrementable extends RoleManager { + /// The HTML element used to render semantics to the browser. + final html.InputElement _element = html.InputElement(); + + /// The value used by the input element. + /// + /// Flutter values are strings, and are not necessarily numbers. In order to + /// convey to the browser what the available "range" of values is we + /// substitute the framework value with a generated `int` surrogate. + /// "aria-valuetext" attribute is used to cause the browser to announce the + /// framework value to the user. + int _currentSurrogateValue = 1; + + /// Disables the input [_element] when the gesture mode switches to + /// [GestureMode.pointerEvents], and enables it when the mode switches back to + /// [GestureMode.browserGestures]. + GestureModeCallback _gestureModeListener; + + /// Whether we forwarded a semantics action to the framework and awaiting an + /// update. + /// + /// This field is used to determine whether the HTML DOM of the semantics + /// tree should be updated. + bool _pendingResync = false; + + Incrementable(SemanticsObject semanticsObject) + : super(Role.incrementable, semanticsObject) { + semanticsObject.element.append(_element); + _element.type = 'range'; + _element.setAttribute('role', 'slider'); + + _element.addEventListener('change', (_) { + if (_element.disabled) { + return; + } + _pendingResync = true; + final int newInputValue = int.parse(_element.value); + if (newInputValue > _currentSurrogateValue) { + _currentSurrogateValue += 1; + ui.window.onSemanticsAction( + semanticsObject.id, ui.SemanticsAction.increase, null); + } else if (newInputValue < _currentSurrogateValue) { + _currentSurrogateValue -= 1; + ui.window.onSemanticsAction( + semanticsObject.id, ui.SemanticsAction.decrease, null); + } + }); + + // Store the callback as a closure because Dart does not guarantee that + // tear-offs produce the same function object. + _gestureModeListener = (GestureMode mode) { + update(); + }; + semanticsObject.owner.addGestureModeListener(_gestureModeListener); + } + + @override + void update() { + switch (semanticsObject.owner.gestureMode) { + case GestureMode.browserGestures: + _enableBrowserGestureHandling(); + _updateInputValues(); + break; + case GestureMode.pointerEvents: + _disableBrowserGestureHandling(); + break; + } + } + + void _enableBrowserGestureHandling() { + assert(semanticsObject.owner.gestureMode == GestureMode.browserGestures); + if (!_element.disabled) { + return; + } + _element.disabled = false; + } + + void _updateInputValues() { + assert(semanticsObject.owner.gestureMode == GestureMode.browserGestures); + + final bool updateNeeded = _pendingResync || + semanticsObject.isValueDirty || + semanticsObject.isIncreasedValueDirty || + semanticsObject.isDecreasedValueDirty; + + if (!updateNeeded) { + return; + } + + _pendingResync = false; + + final String surrogateTextValue = '$_currentSurrogateValue'; + _element.value = surrogateTextValue; + _element.setAttribute('aria-valuenow', surrogateTextValue); + _element.setAttribute('aria-valuetext', semanticsObject.value); + + final bool canIncrease = semanticsObject.increasedValue != null; + final String surrogateMaxTextValue = + canIncrease ? '${_currentSurrogateValue + 1}' : surrogateTextValue; + _element.max = surrogateMaxTextValue; + _element.setAttribute('aria-valuemax', surrogateMaxTextValue); + + final bool canDecrease = semanticsObject.decreasedValue != null; + final String surrogateMinTextValue = + canDecrease ? '${_currentSurrogateValue - 1}' : surrogateTextValue; + _element.min = surrogateMinTextValue; + _element.setAttribute('aria-valuemin', surrogateMinTextValue); + } + + void _disableBrowserGestureHandling() { + if (_element.disabled) { + return; + } + _element.disabled = true; + } + + @override + void dispose() { + assert(_gestureModeListener != null); + semanticsObject.owner.removeGestureModeListener(_gestureModeListener); + _gestureModeListener = null; + _disableBrowserGestureHandling(); + _element.remove(); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/label_and_value.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/label_and_value.dart new file mode 100644 index 0000000000..91a660b7ed --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/label_and_value.dart @@ -0,0 +1,117 @@ +// 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; + +/// Renders [_label] and [_value] to the semantics DOM. +/// +/// The rendering method is browser-dependent. There is no explicit ARIA +/// attribute to express "value". Instead, you are expected to render the +/// value as text content of HTML. +/// +/// VoiceOver only supports "aria-label" for certain ARIA roles. For plain +/// text it expects that the label is part of the text content of the element. +/// The strategy for VoiceOver is to combine [_label] and [_value] and stamp +/// out a single child element that contains the value. +/// +/// TalkBack supports the "aria-label" attribute. However, when present, +/// TalkBack ignores the text content. Therefore, we cannot split [_label] +/// and [_value] between "aria-label" and text content. The strategy for +/// TalkBack is to combine [_label] and [_value] into a single "aria-label". +/// +/// The [_value] is not always rendered. Some semantics nodes correspond to +/// interactive controls, such as an `` element. In such case the value +/// is reported via that element's `value` attribute rather than rendering it +/// separately. +/// +/// Aria role image is not managed by this role manager. Img role and label +/// describes the visual are added in [ImageRoleManager]. +class LabelAndValue extends RoleManager { + LabelAndValue(SemanticsObject semanticsObject) + : super(Role.labelAndValue, semanticsObject); + + /// Supplements the "aria-label" that renders the combination of [_label] and + /// [_value] to semantics as text content. + /// + /// This extra element is needed for the following reasons: + /// + /// - VoiceOver on iOS Safari does not recognize standalone "aria-label". It + /// only works for specific roles. + /// - TalkBack does support "aria-label". However, if an element has children + /// its label is not reachable via accessibility focus. This happens, for + /// example in popup dialogs, such as the alert dialog. The text of the + /// alert is supplied as a label on the parent node. + html.Element _auxiliaryValueElement; + + @override + void update() { + final bool hasValue = semanticsObject.hasValue; + final bool hasLabel = semanticsObject.hasLabel; + + // If the node is incrementable or a text field the value is reported to the + // browser via the respective role managers. We do not need to also render + // it again here. + final bool shouldDisplayValue = hasValue && + !semanticsObject.isIncrementable && + !semanticsObject.isTextField; + + if (!hasLabel && !shouldDisplayValue) { + _cleanUpDom(); + return; + } + + final StringBuffer combinedValue = StringBuffer(); + if (hasLabel) { + combinedValue.write(semanticsObject.label); + if (shouldDisplayValue) { + combinedValue.write(' '); + } + } + + if (shouldDisplayValue) { + combinedValue.write(semanticsObject.value); + } + + semanticsObject.element + .setAttribute('aria-label', combinedValue.toString()); + + if (semanticsObject.hasFlag(ui.SemanticsFlag.isHeader)) { + semanticsObject.setAriaRole('heading', true); + } + + if (_auxiliaryValueElement == null) { + _auxiliaryValueElement = html.Element.tag('flt-semantics-value'); + // Absolute positioning and sizing of leaf text elements confuses + // VoiceOver. So we let the browser size the value node. The node will + // still have a bigger tap area. However, if the node is a parent to other + // nodes, then VoiceOver behaves as expected with absolute positioning and + // sizing. + if (semanticsObject.hasChildren) { + _auxiliaryValueElement.style + ..position = 'absolute' + ..top = '0' + ..left = '0' + ..width = '${semanticsObject.rect.width}px' + ..height = '${semanticsObject.rect.height}px'; + } + _auxiliaryValueElement.style.fontSize = '6px'; + semanticsObject.element.append(_auxiliaryValueElement); + } + _auxiliaryValueElement.text = combinedValue.toString(); + } + + void _cleanUpDom() { + if (_auxiliaryValueElement != null) { + _auxiliaryValueElement.remove(); + _auxiliaryValueElement = null; + } + semanticsObject.element.attributes.remove('aria-label'); + semanticsObject.setAriaRole('heading', false); + } + + @override + void dispose() { + _cleanUpDom(); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/live_region.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/live_region.dart new file mode 100644 index 0000000000..7d739899d0 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/live_region.dart @@ -0,0 +1,41 @@ +// 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; + +/// Manages semantics configurations that represent live regions. +/// +/// "aria-live" attribute is added to communicate the live region to the +/// assistive technology. +/// +/// The usage of "aria-live" is browser-dependent. +/// +/// VoiceOver only supports "aria-live" with "polite" politeness setting. When +/// the inner html content is changed. It doesn't read the "aria-label". +/// +/// When there is an aria-live attribute added, assistive technologies read the +/// label of the element. See [LabelAndValue]. If there is no label provided +/// no content will be read, therefore DOM is cleaned. +class LiveRegion extends RoleManager { + LiveRegion(SemanticsObject semanticsObject) + : super(Role.labelAndValue, semanticsObject); + + @override + void update() { + if (semanticsObject.hasLabel) { + semanticsObject.element.setAttribute('aria-live', 'polite'); + } else { + _cleanupDom(); + } + } + + void _cleanupDom() { + semanticsObject.element.attributes.remove('aria-live'); + } + + @override + void dispose() { + _cleanupDom(); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/scrollable.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/scrollable.dart new file mode 100644 index 0000000000..c0898cd939 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/scrollable.dart @@ -0,0 +1,199 @@ +// 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; + +/// Implements vertical and horizontal scrolling functionality for semantics +/// objects. +/// +/// Scrolling is implemented using a "joystick" method. The absolute value of +/// "scrollTop" in HTML is not important. We only need to know in whether the +/// value changed in the positive or negative direction. If it changes in the +/// positive direction we send a [ui.SemanticsAction.scrollUp]. Otherwise, we +/// send [ui.SemanticsAction.scrollDown]. The actual scrolling is then handled +/// by the framework and we receive a [ui.SemanticsUpdate] containing the new +/// [scrollPosition] and child positions. +/// +/// "scrollTop" or "scrollLeft" is always reset to an arbitrarily chosen non- +/// zero "neutral" scroll position value. This is done so we have a +/// predictable range of DOM scroll position values. When the amount of +/// contents is less than the size of the viewport the browser snaps +/// "scrollTop" back to zero. If there is more content than available in the +/// viewport "scrollTop" may take positive values. +class Scrollable extends RoleManager { + Scrollable(SemanticsObject semanticsObject) + : super(Role.scrollable, semanticsObject); + + /// Disables browser-driven scrolling in the presence of pointer events. + GestureModeCallback _gestureModeListener; + + /// Listens to HTML "scroll" gestures detected by the browser. + /// + /// This gesture is converted to [ui.SemanticsAction.scrollUp] or + /// [ui.SemanticsAction.scrollDown], depending on the direction. + html.EventListener _scrollListener; + + /// The value of the "scrollTop" or "scrollLeft" property of this object's + /// [element] that has zero offset relative to the [scrollPosition]. + int _effectiveNeutralScrollPosition = 0; + + /// Responds to browser-detected "scroll" gestures. + void _recomputeScrollPosition() { + if (_domScrollPosition != _effectiveNeutralScrollPosition) { + if (!semanticsObject.owner.shouldAcceptBrowserGesture('scroll')) { + return; + } + final bool doScrollForward = + _domScrollPosition > _effectiveNeutralScrollPosition; + _neutralizeDomScrollPosition(); + semanticsObject.recomputePositionAndSize(); + + final int semanticsId = semanticsObject.id; + if (doScrollForward) { + if (semanticsObject.isVerticalScrollContainer) { + ui.window.onSemanticsAction( + semanticsId, ui.SemanticsAction.scrollUp, null); + } else { + assert(semanticsObject.isHorizontalScrollContainer); + ui.window.onSemanticsAction( + semanticsId, ui.SemanticsAction.scrollLeft, null); + } + } else { + if (semanticsObject.isVerticalScrollContainer) { + ui.window.onSemanticsAction( + semanticsId, ui.SemanticsAction.scrollDown, null); + } else { + assert(semanticsObject.isHorizontalScrollContainer); + ui.window.onSemanticsAction( + semanticsId, ui.SemanticsAction.scrollRight, null); + } + } + } + } + + @override + void update() { + if (_scrollListener == null) { + // We need to set touch-action:none explicitly here, despite the fact + // that we already have it on the tag because overflow:scroll + // still causes the browser to take over pointer events in order to + // process scrolling. We don't want that when scrolling is handled by + // the framework. + // + // This is effective only in Chrome. Safari does not implement this + // CSS property. In Safari the `PointerBinding` uses `preventDefault` + // to prevent browser scrolling. + semanticsObject.element.style.touchAction = 'none'; + _gestureModeDidChange(); + + // We neutralize the scroll position after all children have been + // updated. Otherwise the browser does not yet have the sizes of the + // child nodes and resets the scrollTop value back to zero. + semanticsObject.owner.addOneTimePostUpdateCallback(() { + _neutralizeDomScrollPosition(); + }); + + // Memoize the tear-off because Dart does not guarantee that two + // tear-offs of a method on the same instance will produce the same + // object. + _gestureModeListener = (_) { + _gestureModeDidChange(); + }; + semanticsObject.owner.addGestureModeListener(_gestureModeListener); + + _scrollListener = (_) { + _recomputeScrollPosition(); + }; + semanticsObject.element.addEventListener('scroll', _scrollListener); + } + } + + /// The value of "scrollTop" or "scrollLeft", depending on the scroll axis. + int get _domScrollPosition { + if (semanticsObject.isVerticalScrollContainer) { + return semanticsObject.element.scrollTop; + } else { + assert(semanticsObject.isHorizontalScrollContainer); + return semanticsObject.element.scrollLeft; + } + } + + /// Resets the scroll position (top or left) to the neutral value. + /// + /// The scroll position of the scrollable HTML node that's considered to + /// have zero offset relative to Flutter's notion of scroll position is + /// referred to as "neutral scroll position". + /// + /// We always set the the scroll position to a non-zero value in order to + /// be able to scroll in the negative direction. When scrollTop/scrollLeft is + /// zero the browser will refuse to scroll back even when there is more + /// content available. + void _neutralizeDomScrollPosition() { + // This value is arbitrary. + const int _canonicalNeutralScrollPosition = 10; + + final html.Element element = semanticsObject.element; + if (semanticsObject.isVerticalScrollContainer) { + element.scrollTop = _canonicalNeutralScrollPosition; + // Read back because the effective value depends on the amount of content. + _effectiveNeutralScrollPosition = element.scrollTop; + semanticsObject + ..verticalContainerAdjustment = + _effectiveNeutralScrollPosition.toDouble() + ..horizontalContainerAdjustment = 0.0; + } else { + element.scrollLeft = _canonicalNeutralScrollPosition; + // Read back because the effective value depends on the amount of content. + _effectiveNeutralScrollPosition = element.scrollLeft; + semanticsObject + ..verticalContainerAdjustment = 0.0 + ..horizontalContainerAdjustment = + _effectiveNeutralScrollPosition.toDouble(); + } + } + + void _gestureModeDidChange() { + final html.Element element = semanticsObject.element; + switch (semanticsObject.owner.gestureMode) { + case GestureMode.browserGestures: + // overflow:scroll will cause the browser report "scroll" events when + // the accessibility focus shifts outside the visible bounds. + // + // Note that on Android overflow:hidden also works. However, we prefer + // "scroll" because it works both on Android and iOS. + if (semanticsObject.isVerticalScrollContainer) { + element.style.overflowY = 'scroll'; + } else { + assert(semanticsObject.isHorizontalScrollContainer); + element.style.overflowX = 'scroll'; + } + break; + case GestureMode.pointerEvents: + // We use "hidden" instead of "scroll" so that the browser does + // not "steal" pointer events. Flutter gesture recognizers need + // all pointer events in order to recognize gestures correctly. + if (semanticsObject.isVerticalScrollContainer) { + element.style.overflowY = 'hidden'; + } else { + assert(semanticsObject.isHorizontalScrollContainer); + element.style.overflowX = 'hidden'; + } + break; + } + } + + @override + void dispose() { + final html.CssStyleDeclaration style = semanticsObject.element.style; + assert(_gestureModeListener != null); + style.removeProperty('overflowY'); + style.removeProperty('overflowX'); + style.removeProperty('touch-action'); + if (_scrollListener != null) { + semanticsObject.element.removeEventListener('scroll', _scrollListener); + } + semanticsObject.owner.removeGestureModeListener(_gestureModeListener); + _gestureModeListener = null; + } +} 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 new file mode 100644 index 0000000000..b7fba09978 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/semantics.dart @@ -0,0 +1,1732 @@ +// 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; + +/// Set this flag to `true` to cause the engine to visualize the semantics tree +/// on the screen. +/// +/// This is useful for debugging. +const bool _debugShowSemanticsNodes = false; + +/// Contains updates for the semantics tree. +/// +/// This class provides private engine-side API that's not available in the +/// `dart:ui` [ui.SemanticsUpdate]. +class SemanticsUpdate implements ui.SemanticsUpdate { + SemanticsUpdate({List nodeUpdates}) + : _nodeUpdates = nodeUpdates; + + /// Updates for individual nodes. + final List _nodeUpdates; + + @override + void dispose() { + // Intentionally left blank. This method exists for API compatibility with + // Flutter, but it is not required as memory resource management is handled + // by JavaScript's garbage collector. + } +} + +/// Updates the properties of a particular semantics node. +class SemanticsNodeUpdate { + SemanticsNodeUpdate({ + this.id, + this.flags, + this.actions, + this.textSelectionBase, + this.textSelectionExtent, + this.platformViewId, + this.scrollChildren, + this.scrollIndex, + this.scrollPosition, + this.scrollExtentMax, + this.scrollExtentMin, + this.rect, + this.label, + this.hint, + this.value, + this.increasedValue, + this.decreasedValue, + this.textDirection, + this.transform, + this.elevation, + this.thickness, + this.childrenInTraversalOrder, + this.childrenInHitTestOrder, + this.additionalActions, + }); + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final int id; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final int flags; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final int actions; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final int textSelectionBase; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final int textSelectionExtent; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final int platformViewId; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final int scrollChildren; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final int scrollIndex; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final double scrollPosition; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final double scrollExtentMax; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final double scrollExtentMin; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final ui.Rect rect; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final String label; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final String hint; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final String value; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final String increasedValue; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final String decreasedValue; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final ui.TextDirection textDirection; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final Float64List transform; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final Int32List childrenInTraversalOrder; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final Int32List childrenInHitTestOrder; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final Int32List additionalActions; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final double elevation; + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + final double thickness; +} + +/// Identifies one of the roles a [SemanticsObject] plays. +enum Role { + /// Supports incrementing and/or decrementing its value. + incrementable, + + /// Able to scroll its contents vertically or horizontally. + scrollable, + + /// Contains a label or a value. + /// + /// The two are combined into the same role because they interact with each + /// other. + labelAndValue, + + /// Accepts tap or click gestures. + tappable, + + /// Contains editable text. + textField, + + /// A control that has a checked state, such as a check box or a radio button. + checkable, + + /// Visual only element. + image, + + /// Contains a region whose changes will be announced to the screen reader + /// without having to be in focus. + /// + /// These regions can be a snackbar or a text field error. Once identified + /// with this role, they will be able to get the assistive technology's + /// attention right away. + liveRegion, +} + +/// A function that creates a [RoleManager] for a [SemanticsObject]. +typedef RoleManagerFactory = RoleManager Function(SemanticsObject object); + +final Map _roleFactories = { + Role.incrementable: (SemanticsObject object) => Incrementable(object), + Role.scrollable: (SemanticsObject object) => Scrollable(object), + Role.labelAndValue: (SemanticsObject object) => LabelAndValue(object), + Role.tappable: (SemanticsObject object) => Tappable(object), + Role.textField: (SemanticsObject object) => TextField(object), + Role.checkable: (SemanticsObject object) => Checkable(object), + Role.image: (SemanticsObject object) => ImageRoleManager(object), + Role.liveRegion: (SemanticsObject object) => LiveRegion(object), +}; + +/// Provides the functionality associated with the role of the given +/// [semanticsObject]. +/// +/// The role is determined by [ui.SemanticsFlag]s and [ui.SemanticsAction]s set +/// on the object. +abstract class RoleManager { + /// Initializes a role for [semanticsObject]. + /// + /// A single role object manages exactly one [SemanticsObject]. + RoleManager(this.role, this.semanticsObject) + : assert(semanticsObject != null); + + /// Role identifier. + final Role role; + + /// The semantics object managed by this role. + final SemanticsObject semanticsObject; + + /// Called immediately after the [semanticsObject] updates some of its fields. + /// + /// A concrete implementation of this method would typically use some of the + /// "is*Dirty" getters to find out exactly what's changed and apply the + /// minimum DOM updates. + void update(); + + /// Called when [semanticsObject] is removed, or when it changes its role such + /// that this role is no longer relevant. + /// + /// This method is expected to remove role-specific functionality from the + /// DOM. In particular, this method is the appropriate place to call + /// [EngineSemanticsOwner.removeGestureModeListener] if this role reponds to + /// gesture mode changes. + void dispose(); +} + +/// Instantiation of a framework-side semantics node in the DOM. +/// +/// Instances of this class are retained from frame to frame. Each instance is +/// permanently attached to an [id] and a DOM [element] used to convey semantics +/// information to the browser. +class SemanticsObject { + /// Creates a semantics tree node with the given [id] and [owner]. + SemanticsObject(this.id, this.owner) { + // DOM nodes created for semantics objects are positioned absolutely using + // transforms. We use a transparent color instead of "visibility:hidden" or + // "display:none" so that a screen reader does not ignore these elements. + element.style.position = 'absolute'; + + // The root node has some properties that other nodes do not. + if (id == 0) { + // Make all semantics transparent. We use `filter` instead of `opacity` + // attribute because `filter` is stronger. `opacity` does not apply to + // some elements, particularly on iOS, such as the slider thumb and track. + element.style.filter = 'opacity(0%)'; + + // Make text explicitly transparent to signal to the browser that no + // rasterization needs to be done. + element.style.color = 'rgba(0,0,0,0)'; + } + + if (_debugShowSemanticsNodes) { + element.style + ..filter = 'opacity(90%)' + ..outline = '1px solid green' + ..color = 'purple'; + } + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + int get flags => _flags; + int _flags; + + /// Whether the [flags] field has been updated but has not been applied to the + /// DOM yet. + bool get isFlagsDirty => _isDirty(_flagsIndex); + static const int _flagsIndex = 1 << 0; + void _markFlagsDirty() { + _dirtyFields |= _flagsIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + int get actions => _actions; + int _actions; + + static const int _actionsIndex = 1 << 1; + + /// Whether the [actions] field has been updated but has not been applied to + /// the DOM yet. + bool get isActionsDirty => _isDirty(_actionsIndex); + void _markActionsDirty() { + _dirtyFields |= _actionsIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + int get textSelectionBase => _textSelectionBase; + int _textSelectionBase; + + static const int _textSelectionBaseIndex = 1 << 2; + + /// Whether the [textSelectionBase] field has been updated but has not been + /// applied to the DOM yet. + bool get isTextSelectionBaseDirty => _isDirty(_textSelectionBaseIndex); + void _markTextSelectionBaseDirty() { + _dirtyFields |= _textSelectionBaseIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + int get textSelectionExtent => _textSelectionExtent; + int _textSelectionExtent; + + static const int _textSelectionExtentIndex = 1 << 3; + + /// Whether the [textSelectionExtent] field has been updated but has not been + /// applied to the DOM yet. + bool get isTextSelectionExtentDirty => _isDirty(_textSelectionExtentIndex); + void _markTextSelectionExtentDirty() { + _dirtyFields |= _textSelectionExtentIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + int get scrollChildren => _scrollChildren; + int _scrollChildren; + + static const int _scrollChildrenIndex = 1 << 4; + + /// Whether the [scrollChildren] field has been updated but has not been + /// applied to the DOM yet. + bool get isScrollChildrenDirty => _isDirty(_scrollChildrenIndex); + void _markScrollChildrenDirty() { + _dirtyFields |= _scrollChildrenIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + int get scrollIndex => _scrollIndex; + int _scrollIndex; + + static const int _scrollIndexIndex = 1 << 5; + + /// Whether the [scrollIndex] field has been updated but has not been + /// applied to the DOM yet. + bool get isScrollIndexDirty => _isDirty(_scrollIndexIndex); + void _markScrollIndexDirty() { + _dirtyFields |= _scrollIndexIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + double get scrollPosition => _scrollPosition; + double _scrollPosition; + + static const int _scrollPositionIndex = 1 << 6; + + /// Whether the [scrollPosition] field has been updated but has not been + /// applied to the DOM yet. + bool get isScrollPositionDirty => _isDirty(_scrollPositionIndex); + void _markScrollPositionDirty() { + _dirtyFields |= _scrollPositionIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + double get scrollExtentMax => _scrollExtentMax; + double _scrollExtentMax; + + static const int _scrollExtentMaxIndex = 1 << 7; + + /// Whether the [scrollExtentMax] field has been updated but has not been + /// applied to the DOM yet. + bool get isScrollExtentMaxDirty => _isDirty(_scrollExtentMaxIndex); + void _markScrollExtentMaxDirty() { + _dirtyFields |= _scrollExtentMaxIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + double get scrollExtentMin => _scrollExtentMin; + double _scrollExtentMin; + + static const int _scrollExtentMinIndex = 1 << 8; + + /// Whether the [scrollExtentMin] field has been updated but has not been + /// applied to the DOM yet. + bool get isScrollExtentMinDirty => _isDirty(_scrollExtentMinIndex); + void _markScrollExtentMinDirty() { + _dirtyFields |= _scrollExtentMinIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + ui.Rect get rect => _rect; + ui.Rect _rect; + + static const int _rectIndex = 1 << 9; + + /// Whether the [rect] field has been updated but has not been + /// applied to the DOM yet. + bool get isRectDirty => _isDirty(_rectIndex); + void _markRectDirty() { + _dirtyFields |= _rectIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + String get label => _label; + String _label; + + /// Whether this object contains a non-empty label. + bool get hasLabel => _label != null && _label.isNotEmpty; + + static const int _labelIndex = 1 << 10; + + /// Whether the [label] field has been updated but has not been + /// applied to the DOM yet. + bool get isLabelDirty => _isDirty(_labelIndex); + void _markLabelDirty() { + _dirtyFields |= _labelIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + String get hint => _hint; + String _hint; + + static const int _hintIndex = 1 << 11; + + /// Whether the [hint] field has been updated but has not been + /// applied to the DOM yet. + bool get isHintDirty => _isDirty(_hintIndex); + void _markHintDirty() { + _dirtyFields |= _hintIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + String get value => _value; + String _value; + + /// Whether this object contains a non-empty value. + bool get hasValue => _value != null && _value.isNotEmpty; + + static const int _valueIndex = 1 << 12; + + /// Whether the [value] field has been updated but has not been + /// applied to the DOM yet. + bool get isValueDirty => _isDirty(_valueIndex); + void _markValueDirty() { + _dirtyFields |= _valueIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + String get increasedValue => _increasedValue; + String _increasedValue; + + static const int _increasedValueIndex = 1 << 13; + + /// Whether the [increasedValue] field has been updated but has not been + /// applied to the DOM yet. + bool get isIncreasedValueDirty => _isDirty(_increasedValueIndex); + void _markIncreasedValueDirty() { + _dirtyFields |= _increasedValueIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + String get decreasedValue => _decreasedValue; + String _decreasedValue; + + static const int _decreasedValueIndex = 1 << 14; + + /// Whether the [decreasedValue] field has been updated but has not been + /// applied to the DOM yet. + bool get isDecreasedValueDirty => _isDirty(_decreasedValueIndex); + void _markDecreasedValueDirty() { + _dirtyFields |= _decreasedValueIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + ui.TextDirection get textDirection => _textDirection; + ui.TextDirection _textDirection; + + static const int _textDirectionIndex = 1 << 15; + + /// Whether the [textDirection] field has been updated but has not been + /// applied to the DOM yet. + bool get isTextDirectionDirty => _isDirty(_textDirectionIndex); + void _markTextDirectionDirty() { + _dirtyFields |= _textDirectionIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + Float64List get transform => _transform; + Float64List _transform; + + static const int _transformIndex = 1 << 16; + + /// Whether the [transform] field has been updated but has not been + /// applied to the DOM yet. + bool get isTransformDirty => _isDirty(_transformIndex); + void _markTransformDirty() { + _dirtyFields |= _transformIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + Int32List get childrenInTraversalOrder => _childrenInTraversalOrder; + Int32List _childrenInTraversalOrder; + + static const int _childrenInTraversalOrderIndex = 1 << 19; + + /// Whether the [childrenInTraversalOrder] field has been updated but has not + /// been applied to the DOM yet. + bool get isChildrenInTraversalOrderDirty => + _isDirty(_childrenInTraversalOrderIndex); + void _markChildrenInTraversalOrderDirty() { + _dirtyFields |= _childrenInTraversalOrderIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + Int32List get childrenInHitTestOrder => _childrenInHitTestOrder; + Int32List _childrenInHitTestOrder; + + static const int _childrenInHitTestOrderIndex = 1 << 20; + + /// Whether the [childrenInHitTestOrder] field has been updated but has not + /// been applied to the DOM yet. + bool get isChildrenInHitTestOrderDirty => + _isDirty(_childrenInHitTestOrderIndex); + void _markChildrenInHitTestOrderDirty() { + _dirtyFields |= _childrenInHitTestOrderIndex; + } + + /// See [ui.SemanticsUpdateBuilder.updateNode]. + Int32List get additionalActions => _additionalActions; + Int32List _additionalActions; + + static const int _additionalActionsIndex = 1 << 21; + + /// Whether the [additionalActions] field has been updated but has not been + /// applied to the DOM yet. + bool get isAdditionalActionsDirty => _isDirty(_additionalActionsIndex); + void _markAdditionalActionsDirty() { + _dirtyFields |= _additionalActionsIndex; + } + + /// A unique permanent identifier of the semantics node in the tree. + final int id; + + /// Controls the semantics tree that this node participates in. + final EngineSemanticsOwner owner; + + /// The DOM element used to convey semantics information to the browser. + final html.Element element = html.Element.tag('flt-semantics'); + + /// Bitfield showing which fields have been updated but have not yet been + /// applied to the DOM. + /// + /// Instead of use this field directly, prefer using one of the "is*Dirty" + /// getters, e.g. [isFlagsDirty]. + /// + /// The bitfield supports up to 31 bits. + int _dirtyFields = -1; // initial value is when all relevant bits are set + + /// Whether the field corresponding to the [fieldIndex] has been updated. + bool _isDirty(int fieldIndex) => (_dirtyFields & fieldIndex) != 0; + + /// Returns the HTML element that contains the HTML elements of direct + /// children of this object. + /// + /// The element is created lazily. When the child list is empty this element + /// is not created. This is necessary for "aria-label" to function correctly. + /// The browser will ignore the [label] of HTML element that contain child + /// elements. + html.Element getOrCreateChildContainer() { + if (_childContainerElement == null) { + _childContainerElement = html.Element.tag('flt-semantics-container'); + _childContainerElement.style.position = 'absolute'; + element.append(_childContainerElement); + } + return _childContainerElement; + } + + /// The element that contains the elements belonging to the child semantics + /// nodes. + /// + /// This element is used to correct for [_rect] offsets. It is only non-`null` + /// when there are non-zero children (i.e. when [hasChildren] is `true`). + html.Element _childContainerElement; + + /// The parent of this semantics object. + SemanticsObject _parent; + + /// Whether this node currently has a given [SemanticsFlag]. + bool hasFlag(ui.SemanticsFlag flag) => _flags & flag.index != 0; + + /// Whether [actions] contains the given action. + bool hasAction(ui.SemanticsAction action) => (_actions & action.index) != 0; + + /// Whether this object represents a vertically scrollable area. + bool get isVerticalScrollContainer => + hasAction(ui.SemanticsAction.scrollDown) || + hasAction(ui.SemanticsAction.scrollUp); + + /// Whether this object represents a hotizontally scrollable area. + bool get isHorizontalScrollContainer => + hasAction(ui.SemanticsAction.scrollLeft) || + hasAction(ui.SemanticsAction.scrollRight); + + /// Whether this object has a non-empty list of children. + bool get hasChildren => + _childrenInTraversalOrder != null && _childrenInTraversalOrder.isNotEmpty; + + /// 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) && + !hasFlag(ui.SemanticsFlag.isHidden); + + /// Whether this object represents an image with no tappable functionality. + bool get isVisualOnly => + hasFlag(ui.SemanticsFlag.isImage) && + !hasAction(ui.SemanticsAction.tap) && + !hasFlag(ui.SemanticsFlag.isButton); + + /// Updates this object from data received from a semantics [update]. + /// + /// This method creates [SemanticsObject]s for the direct children of this + /// object. However, it does not recursively populate them. + void updateWith(SemanticsNodeUpdate update) { + // Update all field values and their corresponding dirty flags before + // applying the updates to the DOM. + assert(update.flags != null); + if (_flags != update.flags) { + _flags = update.flags; + _markFlagsDirty(); + } + + if (_value != update.value) { + _value = update.value; + _markValueDirty(); + } + + if (_label != update.label) { + _label = update.label; + _markLabelDirty(); + } + + if (_rect != update.rect) { + _rect = update.rect; + _markRectDirty(); + } + + if (_transform != update.transform) { + _transform = update.transform; + _markTransformDirty(); + } + + if (_scrollPosition != update.scrollPosition) { + _scrollPosition = update.scrollPosition; + _markScrollPositionDirty(); + } + + if (_actions != update.actions) { + _actions = update.actions; + _markActionsDirty(); + } + + if (_textSelectionBase != update.textSelectionBase) { + _textSelectionBase = update.textSelectionBase; + _markTextSelectionBaseDirty(); + } + + if (_textSelectionExtent != update.textSelectionExtent) { + _textSelectionExtent = update.textSelectionExtent; + _markTextSelectionExtentDirty(); + } + + if (_scrollChildren != update.scrollChildren) { + _scrollChildren = update.scrollChildren; + _markScrollChildrenDirty(); + } + + if (_scrollIndex != update.scrollIndex) { + _scrollIndex = update.scrollIndex; + _markScrollIndexDirty(); + } + + if (_scrollExtentMax != update.scrollExtentMax) { + _scrollExtentMax = update.scrollExtentMax; + _markScrollExtentMaxDirty(); + } + + if (_scrollExtentMin != update.scrollExtentMin) { + _scrollExtentMin = update.scrollExtentMin; + _markScrollExtentMinDirty(); + } + + if (_hint != update.hint) { + _hint = update.hint; + _markHintDirty(); + } + + if (_increasedValue != update.increasedValue) { + _increasedValue = update.increasedValue; + _markIncreasedValueDirty(); + } + + if (_decreasedValue != update.decreasedValue) { + _decreasedValue = update.decreasedValue; + _markDecreasedValueDirty(); + } + + if (_textDirection != update.textDirection) { + _textDirection = update.textDirection; + _markTextDirectionDirty(); + } + + if (_childrenInHitTestOrder != update.childrenInHitTestOrder) { + _childrenInHitTestOrder = update.childrenInHitTestOrder; + _markChildrenInHitTestOrderDirty(); + } + + if (_childrenInTraversalOrder != update.childrenInTraversalOrder) { + _childrenInTraversalOrder = update.childrenInTraversalOrder; + _markChildrenInTraversalOrderDirty(); + } + + if (_additionalActions != update.additionalActions) { + _additionalActions = update.additionalActions; + _markAdditionalActionsDirty(); + } + + // Apply updates to the DOM. + _updateRoles(); + _updateChildrenInTraversalOrder(); + + // All properties that affect positioning and sizing are checked together + // any one of them triggers position and size recomputation. + if (isRectDirty || isTransformDirty || isScrollPositionDirty) { + recomputePositionAndSize(); + } + + // Make sure we create a child container only when there are children. + assert(_childContainerElement == null || hasChildren); + _dirtyFields = 0; + } + + /// Populates the HTML "role" attribute based on a [condition]. + /// + /// If [condition] is true, sets the value to [ariaRoleName]. + /// + /// If [condition] is false, removes the HTML "role" attribute from [element] + /// if the current role is set to [ariaRoleName]. Otherwise, leaves the value + /// unchanged. This is done so we gracefully handle multiple competing roles. + /// For example, if the role changes from "button" to "img" and tappable role + /// manager attempts to clean up after the image role manager applied the new + /// role, we do not want it to erase the new role. + void setAriaRole(String ariaRoleName, bool condition) { + if (condition) { + element.setAttribute('role', ariaRoleName); + } else if (element.getAttribute('role') == ariaRoleName) { + element.attributes.remove('role'); + } + } + + /// Role managers. + /// + /// The [_roleManagers] map needs to have a stable order for easier debugging + /// and testing. Dart's map literal guarantees the order as described in the + /// spec: + /// + /// > A map literal is ordered: iterating over the keys and/or values of the maps always happens in the order the keys appeared in the source code. + final Map _roleManagers = {}; + + /// Detects the roles that this semantics object corresponds to and manages + /// the lifecycles of [SemanticsObjectRole] objects. + void _updateRoles() { + _updateRole(Role.labelAndValue, (hasLabel || hasValue) && !isVisualOnly); + _updateRole(Role.textField, isTextField); + _updateRole( + Role.tappable, + hasAction(ui.SemanticsAction.tap) || + hasFlag(ui.SemanticsFlag.isButton)); + _updateRole(Role.incrementable, isIncrementable); + _updateRole(Role.scrollable, + isVerticalScrollContainer || isHorizontalScrollContainer); + _updateRole( + Role.checkable, + hasFlag(ui.SemanticsFlag.hasCheckedState) || + hasFlag(ui.SemanticsFlag.hasToggledState)); + _updateRole(Role.image, isVisualOnly); + _updateRole(Role.liveRegion, isLiveRegion); + } + + void _updateRole(Role role, bool enabled) { + RoleManager manager = _roleManagers[role]; + if (enabled) { + if (manager == null) { + manager = _roleFactories[role](this); + _roleManagers[role] = manager; + } + manager.update(); + } else if (manager != null) { + manager.dispose(); + _roleManagers.remove(role); + } + // Nothing to do in the "else case" as it means that we want to disable a + // role that we don't currently have in the first place. + } + + /// Whether the object represents an UI element with "increase" or "decrease" + /// controls, e.g. a slider. + /// + /// Such objects are expressed in HTML using ``. + bool get isIncrementable => + hasAction(ui.SemanticsAction.increase) || + hasAction(ui.SemanticsAction.decrease); + + /// Role-specific adjustment of the vertical position of the child container. + /// + /// This is used, for example, by the [Scrollable] to compensate for the + /// `scrollTop` offset in the DOM. + /// + /// This field must not be null. + double verticalContainerAdjustment = 0.0; + + /// Role-specific adjustment of the horizontal position of the child + /// container. + /// + /// This is used, for example, by the [Scrollable] to compensate for the + /// `scrollLeft` offset in the DOM. + /// + /// This field must not be null. + double horizontalContainerAdjustment = 0.0; + + /// Computes the size and position of [element] and, if this element + /// [hasChildren], of [getOrCreateChildContainer]. + void recomputePositionAndSize() { + element.style + ..width = '${_rect.width}px' + ..height = '${_rect.height}px'; + + final html.Element containerElement = + hasChildren ? getOrCreateChildContainer() : null; + + final bool hasZeroRectOffset = _rect.top == 0.0 && _rect.left == 0.0; + final bool hasIdentityTransform = + _transform == null || isIdentityFloat64ListTransform(_transform); + + if (hasZeroRectOffset && + hasIdentityTransform && + verticalContainerAdjustment == 0.0 && + horizontalContainerAdjustment == 0.0) { + element.style + ..removeProperty('transform-origin') + ..removeProperty('transform'); + if (containerElement != null) { + containerElement.style + ..removeProperty('transform-origin') + ..removeProperty('transform'); + } + return; + } + + Matrix4 effectiveTransform; + bool effectiveTransformIsIdentity = true; + if (!hasZeroRectOffset) { + if (_transform == null) { + final double left = _rect.left; + final double top = _rect.top; + effectiveTransform = Matrix4.translationValues(left, top, 0.0); + effectiveTransformIsIdentity = left == 0.0 && top == 0.0; + } else { + // Clone to avoid mutating _transform. + effectiveTransform = Matrix4.fromFloat64List(_transform).clone() + ..translate(_rect.left, _rect.top, 0.0); + effectiveTransformIsIdentity = effectiveTransform.isIdentity(); + } + } else if (!hasIdentityTransform) { + effectiveTransform = Matrix4.fromFloat64List(_transform); + effectiveTransformIsIdentity = false; + } + + if (!effectiveTransformIsIdentity) { + element.style + ..transformOrigin = '0 0 0' + ..transform = matrix4ToCssTransform(effectiveTransform); + } else { + element.style + ..removeProperty('transform-origin') + ..removeProperty('transform'); + } + + if (containerElement != null) { + if (!hasZeroRectOffset || + verticalContainerAdjustment != 0.0 || + horizontalContainerAdjustment != 0.0) { + final double translateX = -_rect.left + horizontalContainerAdjustment; + final double translateY = -_rect.top + verticalContainerAdjustment; + containerElement.style + ..transformOrigin = '0 0 0' + ..transform = 'translate(${translateX}px, ${translateY}px)'; + } else { + containerElement.style + ..removeProperty('transform-origin') + ..removeProperty('transform'); + } + } + } + + Int32List _previousChildrenInTraversalOrder; + + /// Updates the traversal child list of [object] from the given [update]. + /// + /// This method does not recursively update child elements' properties or + /// their grandchildren. This is handled by [updateSemantics] method walking + /// all the update nodes. + void _updateChildrenInTraversalOrder() { + // Remove all children case. + if (_childrenInTraversalOrder == null || + _childrenInTraversalOrder.isEmpty) { + if (_previousChildrenInTraversalOrder == null || + _previousChildrenInTraversalOrder.isEmpty) { + // We must not have created a container element when child list is empty. + assert(_childContainerElement == null); + _previousChildrenInTraversalOrder = _childrenInTraversalOrder; + return; + } + + // We must have created a container element when child list is not empty. + assert(_childContainerElement != null); + + // Remove all children from this semantics object. + final int len = _previousChildrenInTraversalOrder.length; + for (int i = 0; i < len; i++) { + owner._detachObject(_previousChildrenInTraversalOrder[i]); + } + _previousChildrenInTraversalOrder = null; + _childContainerElement.remove(); + _childContainerElement = null; + _previousChildrenInTraversalOrder = _childrenInTraversalOrder; + return; + } + + final html.Element containerElement = getOrCreateChildContainer(); + + // Empty case. + if (_previousChildrenInTraversalOrder == null || + _previousChildrenInTraversalOrder.isEmpty) { + _previousChildrenInTraversalOrder = _childrenInTraversalOrder; + for (int id in _previousChildrenInTraversalOrder) { + final SemanticsObject child = owner.getOrCreateObject(id); + containerElement.append(child.element); + owner._attachObject(parent: this, child: child); + } + _previousChildrenInTraversalOrder = _childrenInTraversalOrder; + return; + } + + // Both non-empty case. + + // Indices into the new child list pointing at children that also exist in + // the old child list. + final List intersectionIndicesNew = []; + + // Indices into the old child list pointing at children that also exist in + // the new child list. + final List intersectionIndicesOld = []; + + int newIndex = 0; + + // The smallest of the two child list lengths. + final int minLength = math.min( + _previousChildrenInTraversalOrder.length, + _childrenInTraversalOrder.length, + ); + + // Scan forward until first discrepancy. + while (newIndex < minLength && + _previousChildrenInTraversalOrder[newIndex] == + _childrenInTraversalOrder[newIndex]) { + intersectionIndicesNew.add(newIndex); + intersectionIndicesOld.add(newIndex); + newIndex += 1; + } + + // If child lists are identical, do nothing. + if (_previousChildrenInTraversalOrder.length == + _childrenInTraversalOrder.length && + newIndex == _childrenInTraversalOrder.length) { + return; + } + + // If child lists are not identical, continue computing the intersection + // between the two lists. + while (newIndex < _childrenInTraversalOrder.length) { + for (int oldIndex = 0; + oldIndex < _previousChildrenInTraversalOrder.length; + oldIndex += 1) { + if (_previousChildrenInTraversalOrder[oldIndex] == + _childrenInTraversalOrder[newIndex]) { + intersectionIndicesNew.add(newIndex); + intersectionIndicesOld.add(oldIndex); + break; + } + } + newIndex += 1; + } + + // The longest sub-sequence in the old list maximizes the number of children + // that do not need to be moved. + final List longestSequence = + longestIncreasingSubsequence(intersectionIndicesOld); + final List stationaryIds = []; + for (int i = 0; i < longestSequence.length; i += 1) { + stationaryIds.add(_previousChildrenInTraversalOrder[ + intersectionIndicesOld[longestSequence[i]]]); + } + + // Remove children that are no longer in the list. + for (int i = 0; i < _previousChildrenInTraversalOrder.length; i++) { + if (!intersectionIndicesOld.contains(i)) { + // Child not in the intersection. Must be removed. + final int childId = _previousChildrenInTraversalOrder[i]; + owner._detachObject(childId); + } + } + + html.Element refNode; + for (int i = _childrenInTraversalOrder.length - 1; i >= 0; i -= 1) { + final int childId = _childrenInTraversalOrder[i]; + final SemanticsObject child = owner.getOrCreateObject(childId); + if (!stationaryIds.contains(childId)) { + if (refNode == null) { + containerElement.append(child.element); + } else { + containerElement.insertBefore(child.element, refNode); + } + owner._attachObject(parent: this, child: child); + } else { + assert(child._parent == this); + } + refNode = child.element; + } + + _previousChildrenInTraversalOrder = _childrenInTraversalOrder; + } + + @override + String toString() { + if (assertionsEnabled) { + final String children = _childrenInTraversalOrder != null && + _childrenInTraversalOrder.isNotEmpty + ? '[${_childrenInTraversalOrder.join(', ')}]' + : ''; + return '$runtimeType(#$id, children: $children)'; + } else { + return super.toString(); + } + } +} + +/// Controls how pointer events and browser-detected gestures are treated by +/// the Web Engine. +enum AccessibilityMode { + /// We are not told whether the assistive technology is enabled or not. + /// + /// This is the default mode. + /// + /// In this mode we use a gesture recognition system that deduplicates + /// gestures detected by Flutter with gestures detected by the browser. + unknown, + + /// We are told whether the assistive technology is enabled. + known, +} + +/// Called when the current [GestureMode] changes. +typedef GestureModeCallback = void Function(GestureMode mode); + +/// The method used to detect user gestures. +enum GestureMode { + /// Send pointer events to Flutter to detect gestures using framework-level + /// gesture recognizers and gesture arenas. + pointerEvents, + + /// Listen to browser-detected gestures and report them to the framework as + /// [ui.SemanticsAction]. + browserGestures, +} + +/// The top-level service that manages everything semantics-related. +class EngineSemanticsOwner { + EngineSemanticsOwner._() { + registerHotRestartListener(() { + _rootSemanticsElement?.remove(); + }); + } + + /// The singleton instance that manages semantics. + static EngineSemanticsOwner get instance { + return _instance ??= EngineSemanticsOwner._(); + } + + static EngineSemanticsOwner _instance; + + /// Disables semantics and uninitializes the singleton [instance]. + /// + /// Instances of [EngineSemanticsOwner] are no longer valid after calling this + /// method. Using them will lead to undefined behavior. This method is only + /// meant to be used for testing. + static void debugResetSemantics() { + if (_instance == null) { + return; + } + _instance.semanticsEnabled = false; + _instance = null; + } + + final Map _semanticsTree = {}; + + /// Map [SemanticsObject.id] to parent [SemanticsObject] it was attached to + /// this frame. + Map _attachments = {}; + + /// Declares that the [child] must be attached to the [parent]. + /// + /// Attachments take precendence over detachments (see [_detachObject]). This + /// allows the same node to be detached from one parent in the tree and + /// reattached to another parent. + void _attachObject({SemanticsObject parent, SemanticsObject child}) { + assert(child != null); + assert(parent != null); + child._parent = parent; + _attachments[child.id] = parent; + } + + /// List of objects that were detached this frame. + /// + /// The objects in this list will be detached permanently unless they are + /// reattached via the [_attachObject] method. + List _detachments = []; + + /// Declares that the [SemanticsObject] with the given [id] was detached from + /// its current parent object. + /// + /// The object will be detached permanently unless it is reattached via the + /// [_attachObject] method. + void _detachObject(int id) { + assert(_semanticsTree.containsKey(id)); + final SemanticsObject object = _semanticsTree[id]; + _detachments.add(object); + } + + /// Callbacks called after all objects in the tree have their properties + /// populated and their sizes and locations computed. + /// + /// This list is reset to empty after all callbacks are called. + List _oneTimePostUpdateCallbacks = []; + + /// Schedules a one-time callback to be called after all objects in the tree + /// have their properties populated and their sizes and locations computed. + void addOneTimePostUpdateCallback(ui.VoidCallback callback) { + _oneTimePostUpdateCallbacks.add(callback); + } + + /// Reconciles [_attachments] and [_detachments], and after that calls all + /// the one-time callbacks scheduled via the [addOneTimePostUpdateCallback] + /// method. + void _finalizeTree() { + for (SemanticsObject object in _detachments) { + final SemanticsObject parent = _attachments[object.id]; + if (parent == null) { + // Was not reparented and is removed permanently from the tree. + _semanticsTree.remove(object.id); + object._parent = null; + object.element.remove(); + } else { + assert(object._parent == parent); + assert(object.element.parent == parent._childContainerElement); + } + } + _detachments = []; + _attachments = {}; + + if (_oneTimePostUpdateCallbacks.isNotEmpty) { + for (ui.VoidCallback callback in _oneTimePostUpdateCallbacks) { + callback(); + } + _oneTimePostUpdateCallbacks = []; + } + } + + /// Returns the entire semantics tree for testing. + /// + /// Works only in debug mode. + Map get debugSemanticsTree { + Map result; + assert(() { + result = _semanticsTree; + return true; + }()); + return result; + } + + /// The top-level DOM element of the semantics DOM element tree. + html.Element _rootSemanticsElement; + + TimestampFunction _now = () => DateTime.now(); + + void debugOverrideTimestampFunction(TimestampFunction value) { + _now = value; + } + + void debugResetTimestampFunction() { + _now = () => DateTime.now(); + } + + /// A temporary placeholder used to capture a request to activate semantics. + html.Element _semanticsPlaceholder; + + /// We do not immediately enable semantics when the user requests it, but + /// instead wait for a short period of time before doing it. This is because + /// the request comes as a tap on the [_semanticsPlaceholder]. The tap, + /// depending on the browser, comes as a burst of events. For example, Safari + /// sends "touchstart", "touchend", and "click". So during a short time period + /// we consume all events and prevent forwarding to the framework. Otherwise, + /// the events will be interpreted twice, once as a request to activate + /// semantics, and a second time by Flutter's gesture recognizers. + Timer _semanticsActivationTimer; + + /// The number of events we processed that could potentially activate + /// semantics. + int _semanticsActivationAttempts = 0; + + /// The maximum [_semanticsActivationAttempts] before we give up waiting for + /// the user to enable semantics. + /// + /// This number is arbitrary and can be adjusted if it doesn't work well. + static const int _kMaxSemanticsActivationAttempts = 20; + + /// Whether we are waiting for the user to enable semantics. + bool get _isWaitingToEnableSemantics => _semanticsPlaceholder != null; + + /// Instructs [_tryEnableSemantics] to remove [_semanticsPlaceholder]. + /// + /// On Chrome the placeholder is removed upon any next event. + /// + /// On Safari the placeholder is removed upon the next "touchend" event. This + /// is to prevent Safari from swallowing the event that happens on an element + /// that's being removed. Chrome doesn't have this issue. + bool _schedulePlaceholderRemoval = false; + + /// Attempts to activate semantics. + /// + /// Returns true if the `event` is not related to semantics activation and + /// should be forwarded to the framework. + bool _tryEnableSemantics(html.Event event) { + if (_schedulePlaceholderRemoval) { + final bool removeNow = + browserEngine != BrowserEngine.webkit || event.type == 'touchend'; + if (removeNow) { + _semanticsPlaceholder.remove(); + _semanticsPlaceholder = null; + _semanticsActivationTimer = null; + } + return true; + } + + if (semanticsEnabled) { + // Semantics already enabled, forward to framework as normal. + return true; + } + + _semanticsActivationAttempts += 1; + if (_semanticsActivationAttempts >= _kMaxSemanticsActivationAttempts) { + // We have received multiple user events, none of which resulted in + // semantics activation. This is a signal that the user is not interested + // in semantics, and so we will stop waiting for it. + _schedulePlaceholderRemoval = true; + return true; + } + + const List kInterestingEventTypes = [ + 'click', + 'touchstart', + 'touchend', + ]; + + if (!kInterestingEventTypes.contains(event.type)) { + // The event is not relevant, forward to framework as normal. + return true; + } + + if (_semanticsActivationTimer != null) { + // We are in a waiting period to activate a timer. While the timer is + // active we should consume events pertaining to semantics activation. + // Otherwise the event will also be interpreted by the framework and + // potentially result in activating a gesture in the app. + return false; + } + + // In Chrome the debouncing works well enough to detect accessibility + // request. + final bool blinkEnableConditionPassed = + browserEngine == BrowserEngine.blink && + _gestureMode == GestureMode.browserGestures; + + // In Safari debouncing doesn't work. Instead we look at where exactly + // (within 1 pixel) the event landed. If it landed exactly in the middle of + // the placeholder we interpret it as a signal to enable accessibility. This + // is because when VoiceOver generates a tap it lands it in the middle of + // the focused element. This method is a bit flawed in that a user's finger + // could theoretically land in the middle of the element too. However, the + // chance of that happening is very small. Even low-end phones typically + // have >2 million pixels (e.g. Moto G4). It is very unlikely that a user + // will land their finger exactly in the middle. In the worst case an + // unlucky user would accidentally enable accessibility and the app will be + // slightly slower than normal, but the app will continue functioning as + // normal. Our semantics tree is designed to not interfere with Flutter's + // gesture detection. + bool safariEnableConditionPassed = false; + if (browserEngine == BrowserEngine.webkit) { + html.Point activationPoint; + + switch (event.type) { + case 'click': + final html.MouseEvent click = event; + activationPoint = click.offset; + break; + case 'touchstart': + case 'touchend': + final html.TouchEvent touch = event; + activationPoint = touch.changedTouches.first.client; + break; + default: + // The event is not relevant, forward to framework as normal. + return true; + } + + assert(activationPoint != null); + + final html.Rectangle activatingElementRect = + domRenderer.glassPaneElement.getBoundingClientRect(); + final double midX = activatingElementRect.left + + (activatingElementRect.right - activatingElementRect.left) / 2; + final double midY = activatingElementRect.top + + (activatingElementRect.bottom - activatingElementRect.top) / 2; + final double deltaX = activationPoint.x - midX; + final double deltaY = activationPoint.y - midY; + final double deltaSquared = deltaX * deltaX + deltaY * deltaY; + if (deltaSquared < 1.0) { + safariEnableConditionPassed = true; + } + } + + if (blinkEnableConditionPassed || safariEnableConditionPassed) { + assert(_semanticsActivationTimer == null); + _semanticsActivationTimer = Timer(const Duration(milliseconds: 300), () { + semanticsEnabled = true; + _schedulePlaceholderRemoval = true; + }); + return false; + } + + // This was not a semantics activating event; forward as normal. + return true; + } + + /// The message in the label for the placeholder element used to enable + /// accessibility. + /// + /// This uses US English as the default message. Set this value prior to + /// calling `runApp` to translate to another language. + static String placeholderMessage = 'Enable accessibility'; + + /// Enables accessibility when the user taps on the glasspane via an + /// accessibility focus. + /// + /// This creates a placeholder inside the glasspane, which, when focused, + /// announces that accessibility can be enabled by tapping. + void autoEnableOnTap(DomRenderer domRenderer) { + _semanticsPlaceholder = html.Element.tag('flt-semantics-placeholder'); + + // Only listen to "click" because other kinds of events are reported via + // PointerBinding. + _semanticsPlaceholder.addEventListener('click', (html.Event event) { + _tryEnableSemantics(event); + }, true); + + _semanticsPlaceholder + ..setAttribute('role', 'button') + ..setAttribute('aria-label', placeholderMessage); + _semanticsPlaceholder.style + ..position = 'absolute' + ..left = '0' + ..top = '0' + ..right = '0' + ..bottom = '0'; + // Insert the semantics placeholder after the scene host. For all widgets + // in the scene, except for platform widgets, the scene host will pass the + // pointer events through to the semantics tree. However, for platform + // views, the pointer events will not pass through, and will be handled + // by the platform view. + domRenderer.glassPaneElement + .insertBefore(_semanticsPlaceholder, domRenderer.sceneHostElement); + } + + /// Whether the user has requested that [updateSemantics] be called when + /// the semantic contents of window changes. + /// + /// The [ui.Window.onSemanticsEnabledChanged] callback is called whenever this + /// value changes. + /// + /// This is separate from accessibility [mode], which controls how gestures + /// are interpreted when this value is true. + bool get semanticsEnabled => _semanticsEnabled; + bool _semanticsEnabled = false; + set semanticsEnabled(bool value) { + if (value == _semanticsEnabled) { + return; + } + _semanticsEnabled = value; + + if (!_semanticsEnabled) { + // We do not process browser events at all when semantics is explicitly + // disabled. All gestures are handled by the framework-level gesture + // recognizers from pointer events. + if (_gestureMode != GestureMode.pointerEvents) { + _gestureMode = GestureMode.pointerEvents; + _notifyGestureModeListeners(); + } + final List keys = _semanticsTree.keys.toList(); + final int len = keys.length; + for (int i = 0; i < len; i++) { + _detachObject(keys[i]); + } + _finalizeTree(); + _rootSemanticsElement?.remove(); + _rootSemanticsElement = null; + _gestureModeClock?.datetime = null; + } + + if (ui.window.onSemanticsEnabledChanged != null) { + ui.window.onSemanticsEnabledChanged(); + } + } + + /// Controls how pointer events and browser-detected gestures are treated by + /// the Web Engine. + /// + /// The default mode is [AccessibilityMode.unknown]. + AccessibilityMode get mode => _mode; + set mode(AccessibilityMode value) { + assert(value != null); + _mode = value; + } + + AccessibilityMode _mode = AccessibilityMode.unknown; + + /// Currently used [GestureMode]. + /// + /// This value changes automatically depending on the incoming input events. + /// Functionality that implements different strategies depending on this mode + /// would use [addGestureModeListener] and [removeGestureModeListener] to get + /// notifications about when the value of this field changes. + GestureMode get gestureMode => _gestureMode; + GestureMode _gestureMode = GestureMode.browserGestures; + + AlarmClock _gestureModeClock; + + AlarmClock _getGestureModeClock() { + if (_gestureModeClock == null) { + _gestureModeClock = AlarmClock(_now); + _gestureModeClock.callback = () { + if (_gestureMode == GestureMode.browserGestures) { + return; + } + + _gestureMode = GestureMode.browserGestures; + _notifyGestureModeListeners(); + }; + } + return _gestureModeClock; + } + + /// Disables browser gestures temporarily because we have detected pointer + /// events. + /// + /// This is used to deduplicate gestures detected by Flutter and gestures + /// detected by the browser. Flutter-detected gestures have higher precedence. + void _temporarilyDisableBrowserGestureMode() { + const Duration _kDebounceThreshold = Duration(milliseconds: 500); + _getGestureModeClock().datetime = _now().add(_kDebounceThreshold); + if (_gestureMode != GestureMode.pointerEvents) { + _gestureMode = GestureMode.pointerEvents; + _notifyGestureModeListeners(); + } + } + + /// Receives DOM events from the pointer event system to correlate with the + /// semantics events; returns true if the event should be forwarded to the + /// framework. + /// + /// The browser sends us both raw pointer events and gestures from + /// [SemanticsObject.element]s. There could be three possibilities: + /// + /// 1. Assistive technology is enabled and we know that it is. + /// 2. Assistive technology is disabled and we know that it isn't. + /// 3. We do not know whether an assistive technology is enabled. + /// + /// If [autoEnableOnTap] was called, this will automatically enable semantics + /// if the user requests it. + /// + /// In the first case we can ignore raw pointer events and only interpret + /// high-level gestures, e.g. "click". + /// + /// In the second case we can ignore high-level gestures and interpret the raw + /// pointer events directly. + /// + /// Finally, in a mode when we do not know if an assistive technology is + /// enabled or not we do a best-effort estimate which to respond to, raw + /// pointer or high-level gestures. We avoid doing both because that will + /// result in double-firing of event listeners, such as `onTap` on a button. + /// An approach we use is to measure the distance between the last pointer + /// event and a gesture event. If a gesture is receive "soon" after the last + /// received pointer event (determined by a heuristic), it is debounced as it + /// is likely that the gesture detected from the pointer even will do the + /// right thing. However, if we receive a standalone gesture we will map it + /// onto a [ui.SemanticsAction] to be processed by the framework. + bool receiveGlobalEvent(html.Event event) { + // For pointer event reference see: + // + // https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events + const List _pointerEventTypes = [ + 'pointerdown', + 'pointermove', + 'pointerup', + 'pointercancel', + 'touchstart', + 'touchend', + 'touchmove', + 'touchcancel', + 'mousedown', + 'mousemove', + 'mouseup', + ]; + + if (_pointerEventTypes.contains(event.type)) { + _temporarilyDisableBrowserGestureMode(); + } + + if (!_isWaitingToEnableSemantics) { + // Forward to framework as normal. + return true; + } else { + return _tryEnableSemantics(event); + } + } + + /// Callbacks called when the [GestureMode] changes. + /// + /// Callbacks are called synchronously. HTML DOM updates made in a callback + /// take effect in the current animation frame and/or the current message loop + /// event. + List _gestureModeListeners = []; + + /// Calls the [callback] every time the current [GestureMode] changes. + /// + /// The callback is called synchronously. HTML DOM updates made in the + /// callback take effect in the current animation frame and/or the current + /// message loop event. + void addGestureModeListener(GestureModeCallback callback) { + _gestureModeListeners.add(callback); + } + + /// Stops calling the [callback] when the [GestureMode] changes. + /// + /// The passed [callback] must be the exact same object as the one passed to + /// [addGestureModeListener]. + void removeGestureModeListener(GestureModeCallback callback) { + assert(_gestureModeListeners.contains(callback)); + _gestureModeListeners.remove(callback); + } + + void _notifyGestureModeListeners() { + for (int i = 0; i < _gestureModeListeners.length; i++) { + _gestureModeListeners[i](_gestureMode); + } + } + + /// Whether a gesture event of type [eventType] should be accepted as a + /// semantic action. + /// + /// If [mode] is [AccessibilityMode.known] the gesture is always accepted if + /// [semanticsEnabled] is `true`, and it is always rejected if + /// [semanticsEnabled] is `false`. + /// + /// If [mode] is [AccessibilityMode.unknown] the gesture is accepted if it is + /// not accompanied by pointer events. In the presence of pointer events we + /// delegate to Flutter's gesture detection system to produce gestures. + bool shouldAcceptBrowserGesture(String eventType) { + if (_mode == AccessibilityMode.known) { + // Do not ignore accessibility gestures in known mode, unless semantics + // is explicitly disabled. + return semanticsEnabled; + } + + const List pointerDebouncedGestures = [ + 'click', + 'scroll', + ]; + + if (pointerDebouncedGestures.contains(eventType)) { + return _gestureMode == GestureMode.browserGestures; + } + + return false; + } + + /// Looks up a [SemanticsObject] in the semantics tree by ID, or creates a new + /// instance if it does not exist. + SemanticsObject getOrCreateObject(int id) { + SemanticsObject object = _semanticsTree[id]; + if (object == null) { + object = SemanticsObject(id, this); + _semanticsTree[id] = object; + } + return object; + } + + /// Updates the semantics tree from data in the [uiUpdate]. + void updateSemantics(ui.SemanticsUpdate uiUpdate) { + if (!_semanticsEnabled) { + return; + } + + final SemanticsUpdate update = uiUpdate; + for (SemanticsNodeUpdate nodeUpdate in update._nodeUpdates) { + final SemanticsObject object = getOrCreateObject(nodeUpdate.id); + object.updateWith(nodeUpdate); + } + + if (_rootSemanticsElement == null) { + final SemanticsObject root = _semanticsTree[0]; + _rootSemanticsElement = root.element; + // We render semantics inside the glasspane for proper focus and event + // handling. If semantics is behind the glasspane, the phone will disable + // focusing by touch, only by tabbing around the UI. If semantics is in + // front of glasspane, then DOM event won't bubble up to the glasspane so + // it can forward events to the framework. + // + // We insert the semantics root before the scene host. For all widgets + // in the scene, except for platform widgets, the scene host will pass the + // pointer events through to the semantics tree. However, for platform + // views, the pointer events will not pass through, and will be handled + // by the platform view. + domRenderer.glassPaneElement + .insertBefore(_rootSemanticsElement, domRenderer.sceneHostElement); + } + + _finalizeTree(); + + assert(_semanticsTree.containsKey(0)); // must contain root node + assert(() { + // Validate tree + _semanticsTree.forEach((int id, SemanticsObject object) { + assert(id == object.id); + // Ensure child ID list is consistent with the parent-child + // relationship of the semantics tree. + if (object._childrenInTraversalOrder != null) { + for (int childId in object._childrenInTraversalOrder) { + final SemanticsObject child = _semanticsTree[childId]; + if (child == null) { + throw AssertionError('Child #$childId is missing in the tree.'); + } + if (child._parent == null) { + throw AssertionError( + 'Child #$childId of parent #${object.id} has null parent ' + 'reference.'); + } + if (!identical(child._parent, object)) { + throw AssertionError( + 'Parent #${object.id} has child #$childId. However, the ' + 'child is attached to #${child._parent.id}.'); + } + } + } + }); + + // Validate that all updates were applied + for (SemanticsNodeUpdate update in update._nodeUpdates) { + // Node was added to the tree. + assert(_semanticsTree.containsKey(update.id)); + // We created a DOM element for it. + assert(_semanticsTree[update.id].element != null); + } + + return true; + }()); + } +} + +/// Computes the [longest increasing subsequence](http://en.wikipedia.org/wiki/Longest_increasing_subsequence). +/// +/// Returns list of indices (rather than values) into [list]. +/// +/// Complexity: n*log(n) +List longestIncreasingSubsequence(List list) { + final int len = list.length; + final List predecessors = []; + final List mins = [0]; + int longest = 0; + for (int i = 0; i < len; i++) { + // Binary search for the largest positive `j ≤ longest` + // such that `list[mins[j]] < list[i]` + final int elem = list[i]; + int lo = 1; + int hi = longest; + while (lo <= hi) { + final int mid = (lo + hi) ~/ 2; + if (list[mins[mid]] < elem) { + lo = mid + 1; + } else { + hi = mid - 1; + } + } + // After searching, `lo` is 1 greater than the + // length of the longest prefix of `list[i]` + final int expansionIndex = lo; + // The predecessor of `list[i]` is the last index of + // the subsequence of length `newLongest - 1` + predecessors.add(mins[expansionIndex - 1]); + if (expansionIndex >= mins.length) { + mins.add(i); + } else { + mins[expansionIndex] = i; + } + if (expansionIndex > longest) { + // If we found a subsequence longer than any we've + // found yet, update `longest` + longest = expansionIndex; + } + } + // Reconstruct the longest subsequence + final List seq = List(longest); + int k = mins[longest]; + for (int i = longest - 1; i >= 0; i--) { + seq[i] = k; + k = predecessors[k]; + } + return seq; +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/tappable.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/tappable.dart new file mode 100644 index 0000000000..dafb91c65b --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/tappable.dart @@ -0,0 +1,66 @@ +// 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; + +/// Listens to HTML "click" gestures detected by the browser. +/// +/// This gestures is different from the click and tap gestures detected by the +/// framework from raw pointer events. When an assistive technology is enabled +/// the browser may not send us pointer events. In that mode we forward HTML +/// click as [ui.SemanticsAction.tap]. +class Tappable extends RoleManager { + Tappable(SemanticsObject semanticsObject) + : super(Role.tappable, semanticsObject); + + html.EventListener _clickListener; + + @override + void update() { + final html.Element element = semanticsObject.element; + + semanticsObject.setAriaRole( + 'button', semanticsObject.hasFlag(ui.SemanticsFlag.isButton)); + + if (!semanticsObject.hasFlag(ui.SemanticsFlag.isEnabled) && + semanticsObject.hasFlag(ui.SemanticsFlag.isButton)) { + semanticsObject.element.setAttribute('aria-disabled', 'true'); + _stopListening(); + } else { + // Excluding text fields because text fields have browser-specific logic + // for recognizing taps and activating the keyboard. + if (semanticsObject.hasAction(ui.SemanticsAction.tap) && + !semanticsObject.hasFlag(ui.SemanticsFlag.isTextField)) { + if (_clickListener == null) { + _clickListener = (_) { + if (semanticsObject.owner.gestureMode != + GestureMode.browserGestures) { + return; + } + ui.window.onSemanticsAction( + semanticsObject.id, ui.SemanticsAction.tap, null); + }; + element.addEventListener('click', _clickListener); + } + } else { + _stopListening(); + } + } + } + + void _stopListening() { + if (_clickListener == null) { + return; + } + + semanticsObject.element.removeEventListener('click', _clickListener); + _clickListener = null; + } + + @override + void dispose() { + _stopListening(); + semanticsObject.setAriaRole('button', false); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart new file mode 100644 index 0000000000..a30dee46b9 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/semantics/text_field.dart @@ -0,0 +1,145 @@ +// 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; + +/// Manages semantics objects that represent editable text fields. +/// +/// This role is implemented via a content-editable HTML element. This role does +/// not proactively switch modes depending on the current +/// [EngineSemanticsOwner.gestureMode]. However, in Chrome on Android it ignores +/// browser gestures when in pointer mode. In Safari on iOS touch events are +/// used to detect text box invocation. This is because Safari issues touch +/// events even when Voiceover is enabled. +class TextField extends RoleManager { + TextField(SemanticsObject semanticsObject) + : super(Role.textField, semanticsObject) { + final html.HtmlElement editableDomElement = + semanticsObject.hasFlag(ui.SemanticsFlag.isMultiline) + ? html.TextAreaElement() + : html.InputElement(); + persistentTextEditingElement = PersistentTextEditingElement( + editableDomElement, + onDomElementSwap: _setupDomElement, + ); + _setupDomElement(); + } + + PersistentTextEditingElement persistentTextEditingElement; + html.Element get _textFieldElement => persistentTextEditingElement.domElement; + + void _setupDomElement() { + // On iOS, even though the semantic text field is transparent, the cursor + // and text highlighting are still visible. The cursor and text selection + // are made invisible by CSS in [DomRenderer.reset]. + // But there's one more case where iOS highlights text. That's when there's + // and autocorrect suggestion. To disable that, we have to do the following: + _textFieldElement + ..spellcheck = false + ..setAttribute('spellcheck', 'false') + ..setAttribute('autocorrect', 'off') + ..setAttribute('autocomplete', 'off') + ..setAttribute('data-semantics-role', 'text-field'); + + _textFieldElement.style + ..position = 'absolute' + // `top` and `left` are intentionally set to zero here. + // + // The text field would live inside a `` which should + // already be positioned using semantics.rect. + // + // See also: + // + // * [SemanticsObject.recomputePositionAndSize], which sets the position + // and size of the parent `` element. + ..top = '0' + ..left = '0' + ..width = '${semanticsObject.rect.width}px' + ..height = '${semanticsObject.rect.height}px'; + semanticsObject.element.append(_textFieldElement); + + switch (browserEngine) { + case BrowserEngine.blink: + case BrowserEngine.unknown: + _initializeForBlink(); + break; + case BrowserEngine.webkit: + _initializeForWebkit(); + break; + } + } + + /// Chrome on Android reports text field activation as a "click" event. + /// + /// When in browser gesture mode, the focus is forwarded to the framework as + /// a tap to initialize editing. + void _initializeForBlink() { + _textFieldElement.addEventListener('focus', (html.Event event) { + if (semanticsObject.owner.gestureMode != GestureMode.browserGestures) { + return; + } + + textEditing.useCustomEditableElement(persistentTextEditingElement); + ui.window + .onSemanticsAction(semanticsObject.id, ui.SemanticsAction.tap, null); + }); + } + + /// Safari on iOS reports text field activation via touch events. + /// + /// This emulates a tap recognizer to detect the activation. Because touch + /// events are present regardless of whether accessibility is enabled or not, + /// this mode is always enabled. + void _initializeForWebkit() { + num lastTouchStartOffsetX; + num lastTouchStartOffsetY; + + _textFieldElement.addEventListener('touchstart', (html.Event event) { + textEditing.useCustomEditableElement(persistentTextEditingElement); + final html.TouchEvent touchEvent = event; + lastTouchStartOffsetX = touchEvent.changedTouches.last.client.x; + lastTouchStartOffsetY = touchEvent.changedTouches.last.client.y; + }, true); + + _textFieldElement.addEventListener('touchend', (html.Event event) { + final html.TouchEvent touchEvent = event; + + if (lastTouchStartOffsetX != null) { + assert(lastTouchStartOffsetY != null); + final num offsetX = touchEvent.changedTouches.last.client.x; + final num offsetY = touchEvent.changedTouches.last.client.y; + + // This should match the similar constant define in: + // + // lib/src/gestures/constants.dart + // + // The value is pre-squared so we have to do less math at runtime. + const double kTouchSlop = 18.0 * 18.0; // Logical pixels squared + + if (offsetX * offsetX + offsetY * offsetY < kTouchSlop) { + // Recognize it as a tap that requires a keyboard. + ui.window.onSemanticsAction( + semanticsObject.id, ui.SemanticsAction.tap, null); + } + } else { + assert(lastTouchStartOffsetY == null); + } + + lastTouchStartOffsetX = null; + lastTouchStartOffsetY = null; + }, true); + } + + @override + void update() { + // The user is editing the semantic text field directly, so there's no need + // to do any update here. + } + + @override + void dispose() { + _textFieldElement.remove(); + textEditing.stopUsingCustomEditableElement(); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/services/buffers.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/services/buffers.dart new file mode 100644 index 0000000000..e2b053b979 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/services/buffers.dart @@ -0,0 +1,340 @@ +// 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; + +abstract class _TypedDataBuffer extends ListBase { + static const int _initialLength = 8; + + /// The underlying data buffer. + /// + /// This is always both a List and a TypedData, which we don't have a type + /// for here. For example, for a `Uint8Buffer`, this is a `Uint8List`. + List _buffer; + + /// Returns a view of [_buffer] as a [TypedData]. + TypedData get _typedBuffer => _buffer as TypedData; + + /// The length of the list being built. + int _length; + + _TypedDataBuffer(List buffer) + : _buffer = buffer, + _length = buffer.length; + + @override + int get length => _length; + + @override + E operator [](int index) { + if (index >= length) { + throw RangeError.index(index, this); + } + return _buffer[index]; + } + + @override + void operator []=(int index, E value) { + if (index >= length) { + throw RangeError.index(index, this); + } + _buffer[index] = value; + } + + @override + set length(int newLength) { + if (newLength < _length) { + final E defaultValue = _defaultValue; + for (int i = newLength; i < _length; i++) { + _buffer[i] = defaultValue; + } + } else if (newLength > _buffer.length) { + List newBuffer; + if (_buffer.isEmpty) { + newBuffer = _createBuffer(newLength); + } else { + newBuffer = _createBiggerBuffer(newLength); + } + newBuffer.setRange(0, _length, _buffer); + _buffer = newBuffer; + } + _length = newLength; + } + + void _add(E value) { + if (_length == _buffer.length) { + _grow(_length); + } + _buffer[_length++] = value; + } + + // We override the default implementation of `add` because it grows the list + // by setting the length in increments of one. We want to grow by doubling + // capacity in most cases. + @override + void add(E value) { + _add(value); + } + + /// Appends all objects of [values] to the end of this buffer. + /// + /// This adds values from [start] (inclusive) to [end] (exclusive) in + /// [values]. If [end] is omitted, it defaults to adding all elements of + /// [values] after [start]. + /// + /// The [start] value must be non-negative. The [values] iterable must have at + /// least [start] elements, and if [end] is specified, it must be greater than + /// or equal to [start] and [values] must have at least [end] elements. + @override + void addAll(Iterable values, [int start = 0, int end]) { + RangeError.checkNotNegative(start, 'start'); + if (end != null && start > end) { + throw RangeError.range(end, start, null, 'end'); + } + + _addAll(values, start, end); + } + + /// Inserts all objects of [values] at position [index] in this list. + /// + /// This adds values from [start] (inclusive) to [end] (exclusive) in + /// [values]. If [end] is omitted, it defaults to adding all elements of + /// [values] after [start]. + /// + /// The [start] value must be non-negative. The [values] iterable must have at + /// least [start] elements, and if [end] is specified, it must be greater than + /// or equal to [start] and [values] must have at least [end] elements. + @override + void insertAll(int index, Iterable values, [int start = 0, int end]) { + RangeError.checkValidIndex(index, this, 'index', _length + 1); + RangeError.checkNotNegative(start, 'start'); + if (end != null) { + if (start > end) { + throw RangeError.range(end, start, null, 'end'); + } + if (start == end) { + return; + } + } + + // If we're adding to the end of the list anyway, use [_addAll]. This lets + // us avoid converting [values] into a list even if [end] is null, since we + // can add values iteratively to the end of the list. We can't do so in the + // center because copying the trailing elements every time is non-linear. + if (index == _length) { + _addAll(values, start, end); + return; + } + + if (end == null && values is List) { + end = values.length; + } + if (end != null) { + _insertKnownLength(index, values, start, end); + return; + } + + // Add elements at end, growing as appropriate, then put them back at + // position [index] using flip-by-double-reverse. + int writeIndex = _length; + int skipCount = start; + for (E value in values) { + if (skipCount > 0) { + skipCount--; + continue; + } + if (writeIndex == _buffer.length) { + _grow(writeIndex); + } + _buffer[writeIndex++] = value; + } + + if (skipCount > 0) { + throw StateError('Too few elements'); + } + if (end != null && writeIndex < end) { + throw RangeError.range(end, start, writeIndex, 'end'); + } + + // Swap [index.._length) and [_length..writeIndex) by double-reversing. + _reverse(_buffer, index, _length); + _reverse(_buffer, _length, writeIndex); + _reverse(_buffer, index, writeIndex); + _length = writeIndex; + return; + } + + // Reverses the range [start..end) of buffer. + static void _reverse(List buffer, int start, int end) { + end--; // Point to last element, not after last element. + while (start < end) { + final Object first = buffer[start]; + final Object last = buffer[end]; + buffer[end] = first; + buffer[start] = last; + start++; + end--; + } + } + + /// Does the same thing as [addAll]. + /// + /// This allows [addAll] and [insertAll] to share implementation without a + /// subclass unexpectedly overriding both when it intended to only override + /// [addAll]. + void _addAll(Iterable values, [int start = 0, int end]) { + if (values is List) { + end ??= values.length; + } + + // If we know the length of the segment to add, do so with [addRange]. This + // way we know how much to grow the buffer in advance, and it may be even + // more efficient for typed data input. + if (end != null) { + _insertKnownLength(_length, values, start, end); + return; + } + + // Otherwise, just add values one at a time. + int i = 0; + for (E value in values) { + if (i >= start) { + add(value); + } + i++; + } + if (i < start) { + throw StateError('Too few elements'); + } + } + + /// Like [insertAll], but with a guaranteed non-`null` [start] and [end]. + void _insertKnownLength(int index, Iterable values, int start, int end) { + if (values is List) { + end ??= values.length; + if (start > values.length || end > values.length) { + throw StateError('Too few elements'); + } + } else { + assert(end != null); + } + + final int valuesLength = end - start; + final int newLength = _length + valuesLength; + _ensureCapacity(newLength); + + _buffer.setRange( + index + valuesLength, _length + valuesLength, _buffer, index); + _buffer.setRange(index, index + valuesLength, values, start); + _length = newLength; + } + + @override + void insert(int index, E element) { + if (index < 0 || index > _length) { + throw RangeError.range(index, 0, _length); + } + if (_length < _buffer.length) { + _buffer.setRange(index + 1, _length + 1, _buffer, index); + _buffer[index] = element; + _length++; + return; + } + final List newBuffer = _createBiggerBuffer(null); + newBuffer.setRange(0, index, _buffer); + newBuffer.setRange(index + 1, _length + 1, _buffer, index); + newBuffer[index] = element; + _length++; + _buffer = newBuffer; + } + + /// Ensures that [_buffer] is at least [requiredCapacity] long, + /// + /// Grows the buffer if necessary, preserving existing data. + void _ensureCapacity(int requiredCapacity) { + if (requiredCapacity <= _buffer.length) return; + var newBuffer = _createBiggerBuffer(requiredCapacity); + newBuffer.setRange(0, _length, _buffer); + _buffer = newBuffer; + } + + /// Create a bigger buffer. + /// + /// This method determines how much bigger a bigger buffer should + /// be. If [requiredCapacity] is not null, it will be at least that + /// size. It will always have at least have double the capacity of + /// the current buffer. + List _createBiggerBuffer(int requiredCapacity) { + int newLength = _buffer.length * 2; + if (requiredCapacity != null && newLength < requiredCapacity) { + newLength = requiredCapacity; + } else if (newLength < _initialLength) { + newLength = _initialLength; + } + return _createBuffer(newLength); + } + + /// Grows the buffer. + /// + /// This copies the first [length] elements into the new buffer. + void _grow(int length) { + _buffer = _createBiggerBuffer(null)..setRange(0, length, _buffer); + } + + @override + void setRange(int start, int end, Iterable source, [int skipCount = 0]) { + if (end > _length) { + throw RangeError.range(end, 0, _length); + } + _setRange(start, end, source, skipCount); + } + + /// Like [setRange], but with no bounds checking. + void _setRange(int start, int end, Iterable source, int skipCount) { + if (source is _TypedDataBuffer) { + _buffer.setRange(start, end, source._buffer, skipCount); + } else { + _buffer.setRange(start, end, source, skipCount); + } + } + + // TypedData. + + int get elementSizeInBytes => _typedBuffer.elementSizeInBytes; + + int get lengthInBytes => _length * _typedBuffer.elementSizeInBytes; + + int get offsetInBytes => _typedBuffer.offsetInBytes; + + /// Returns the underlying [ByteBuffer]. + /// + /// The returned buffer may be replaced by operations that change the [length] + /// of this list. + /// + /// The buffer may be larger than [lengthInBytes] bytes, but never smaller. + ByteBuffer get buffer => _typedBuffer.buffer; + + // Specialization for the specific type. + + // Return zero for integers, 0.0 for floats, etc. + // Used to fill buffer when changing length. + E get _defaultValue; + + // Create a new typed list to use as buffer. + List _createBuffer(int size); +} + +abstract class _IntBuffer extends _TypedDataBuffer { + _IntBuffer(List buffer) : super(buffer); + + @override + int get _defaultValue => 0; +} + +class Uint8Buffer extends _IntBuffer { + Uint8Buffer([int initialLength = 0]) : super(Uint8List(initialLength)); + + @override + Uint8List _createBuffer(int size) => Uint8List(size); +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/services/message_codec.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/services/message_codec.dart new file mode 100644 index 0000000000..076658911d --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/services/message_codec.dart @@ -0,0 +1,137 @@ +// 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; + +/// A message encoding/decoding mechanism. +/// +/// Both operations throw an exception, if conversion fails. Such situations +/// should be treated as programming errors. +/// +/// See also: +/// +/// * [BasicMessageChannel], which use [MessageCodec]s for communication +/// between Flutter and platform plugins. +abstract class MessageCodec { + /// Encodes the specified [message] in binary. + /// + /// Returns null if the message is null. + ByteData encodeMessage(T message); + + /// Decodes the specified [message] from binary. + /// + /// Returns null if the message is null. + T decodeMessage(ByteData message); +} + +/// An command object representing the invocation of a named method. +@immutable +class MethodCall { + /// Creates a [MethodCall] representing the invocation of [method] with the + /// specified [arguments]. + const MethodCall(this.method, [this.arguments]) : assert(method != null); + + /// The name of the method to be called. + final String method; + + /// The arguments for the method. + /// + /// Must be a valid value for the [MethodCodec] used. + final dynamic arguments; + + @override + String toString() => '$runtimeType($method, $arguments)'; +} + +/// A codec for method calls and enveloped results. +/// +/// All operations throw an exception, if conversion fails. +/// +/// See also: +/// +/// * [MethodChannel], which use [MethodCodec]s for communication +/// between Flutter and platform plugins. +/// * [EventChannel], which use [MethodCodec]s for communication +/// between Flutter and platform plugins. +abstract class MethodCodec { + /// Encodes the specified [methodCall] into binary. + ByteData encodeMethodCall(MethodCall methodCall); + + /// Decodes the specified [methodCall] from binary. + MethodCall decodeMethodCall(ByteData methodCall); + + /// Decodes the specified result [envelope] from binary. + /// + /// Throws [PlatformException], if [envelope] represents an error, otherwise + /// returns the enveloped result. + dynamic decodeEnvelope(ByteData envelope); + + /// Encodes a successful [result] into a binary envelope. + ByteData encodeSuccessEnvelope(dynamic result); + + /// Encodes an error result into a binary envelope. + /// + /// The specified error [code], human-readable error [message], and error + /// [details] correspond to the fields of [PlatformException]. + ByteData encodeErrorEnvelope( + {@required String code, String message, dynamic details}); +} + +/// Thrown to indicate that a platform interaction failed in the platform +/// plugin. +/// +/// See also: +/// +/// * [MethodCodec], which throws a [PlatformException], if a received result +/// envelope represents an error. +/// * [MethodChannel.invokeMethod], which completes the returned future +/// with a [PlatformException], if invoking the platform plugin method +/// results in an error envelope. +/// * [EventChannel.receiveBroadcastStream], which emits +/// [PlatformException]s as error events, whenever an event received from the +/// platform plugin is wrapped in an error envelope. +class PlatformException implements Exception { + /// Creates a [PlatformException] with the specified error [code] and optional + /// [message], and with the optional error [details] which must be a valid + /// value for the [MethodCodec] involved in the interaction. + PlatformException({ + @required this.code, + this.message, + this.details, + }) : assert(code != null); + + /// An error code. + final String code; + + /// A human-readable error message, possibly null. + final String message; + + /// Error details, possibly null. + final dynamic details; + + @override + String toString() => 'PlatformException($code, $message, $details)'; +} + +/// Thrown to indicate that a platform interaction failed to find a handling +/// plugin. +/// +/// See also: +/// +/// * [MethodChannel.invokeMethod], which completes the returned future +/// with a [MissingPluginException], if no plugin handler for the method call +/// was found. +/// * [OptionalMethodChannel.invokeMethod], which completes the returned future +/// with null, if no plugin handler for the method call was found. +class MissingPluginException implements Exception { + /// Creates a [MissingPluginException] with an optional human-readable + /// error message. + MissingPluginException([this.message]); + + /// A human-readable error message, possibly null. + final String message; + + @override + String toString() => 'MissingPluginException($message)'; +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/services/message_codecs.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/services/message_codecs.dart new file mode 100644 index 0000000000..223618f9bc --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/services/message_codecs.dart @@ -0,0 +1,558 @@ +// 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; + +/// [MessageCodec] with unencoded binary messages represented using [ByteData]. +/// +/// On Android, messages will be represented using `java.nio.ByteBuffer`. +/// On iOS, messages will be represented using `NSData`. +class BinaryCodec implements MessageCodec { + /// Creates a [MessageCodec] with unencoded binary messages represented using + /// [ByteData]. + const BinaryCodec(); + + @override + ByteData decodeMessage(ByteData message) => message; + + @override + ByteData encodeMessage(ByteData message) => message; +} + +/// [MessageCodec] with UTF-8 encoded String messages. +/// +/// On Android, messages will be represented using `java.util.String`. +/// On iOS, messages will be represented using `NSString`. +class StringCodec implements MessageCodec { + /// Creates a [MessageCodec] with UTF-8 encoded String messages. + const StringCodec(); + + @override + String decodeMessage(ByteData message) { + if (message == null) { + return null; + } + return utf8.decoder.convert(message.buffer.asUint8List()); + } + + @override + ByteData encodeMessage(String message) { + if (message == null) { + return null; + } + final Uint8List encoded = utf8.encoder.convert(message); + return encoded.buffer.asByteData(); + } +} + +/// [MessageCodec] with UTF-8 encoded JSON messages. +/// +/// Supported messages are acyclic values of these forms: +/// +/// * null +/// * [bool]s +/// * [num]s +/// * [String]s +/// * [List]s of supported values +/// * [Map]s from strings to supported values +/// +/// On Android, messages are decoded using the `org.json` library. +/// On iOS, messages are decoded using the `NSJSONSerialization` library. +/// In both cases, the use of top-level simple messages (null, [bool], [num], +/// and [String]) is supported (by the Flutter SDK). The decoded value will be +/// null/nil for null, and identical to what would result from decoding a +/// singleton JSON array with a Boolean, number, or string value, and then +/// extracting its single element. +class JSONMessageCodec implements MessageCodec { + // The codec serializes messages as defined by the JSON codec of the + // dart:convert package. The format used must match the Android and + // iOS counterparts. + + /// Creates a [MessageCodec] with UTF-8 encoded JSON messages. + const JSONMessageCodec(); + + @override + ByteData encodeMessage(dynamic message) { + if (message == null) { + return null; + } + return const StringCodec().encodeMessage(json.encode(message)); + } + + @override + dynamic decodeMessage(ByteData message) { + if (message == null) { + return message; + } + return json.decode(const StringCodec().decodeMessage(message)); + } +} + +/// [MethodCodec] with UTF-8 encoded JSON method calls and result envelopes. +/// +/// Values supported as method arguments and result payloads are those supported +/// by [JSONMessageCodec]. +class JSONMethodCodec implements MethodCodec { + // The codec serializes method calls, and result envelopes as outlined below. + // This format must match the Android and iOS counterparts. + // + // * Individual values are serialized as defined by the JSON codec of the + // dart:convert package. + // * Method calls are serialized as two-element maps, with the method name + // keyed by 'method' and the arguments keyed by 'args'. + // * Reply envelopes are serialized as either: + // * one-element lists containing the successful result as its single + // element, or + // * three-element lists containing, in order, an error code String, an + // error message String, and an error details value. + + /// Creates a [MethodCodec] with UTF-8 encoded JSON method calls and result + /// envelopes. + const JSONMethodCodec(); + + @override + ByteData encodeMethodCall(MethodCall call) { + return const JSONMessageCodec().encodeMessage({ + 'method': call.method, + 'args': call.arguments, + }); + } + + @override + MethodCall decodeMethodCall(ByteData methodCall) { + final dynamic decoded = const JSONMessageCodec().decodeMessage(methodCall); + if (decoded is! Map) { + throw FormatException('Expected method call Map, got $decoded'); + } + final dynamic method = decoded['method']; + final dynamic arguments = decoded['args']; + if (method is String) { + return MethodCall(method, arguments); + } + throw FormatException('Invalid method call: $decoded'); + } + + @override + dynamic decodeEnvelope(ByteData envelope) { + final dynamic decoded = const JSONMessageCodec().decodeMessage(envelope); + if (decoded is! List) { + throw FormatException('Expected envelope List, got $decoded'); + } + if (decoded.length == 1) { + return decoded[0]; + } + if (decoded.length == 3 && + decoded[0] is String && + (decoded[1] == null || decoded[1] is String)) { + throw PlatformException( + code: decoded[0], + message: decoded[1], + details: decoded[2], + ); + } + throw FormatException('Invalid envelope: $decoded'); + } + + @override + ByteData encodeSuccessEnvelope(dynamic result) { + return const JSONMessageCodec().encodeMessage([result]); + } + + @override + ByteData encodeErrorEnvelope( + {@required String code, String message, dynamic details}) { + assert(code != null); + return const JSONMessageCodec() + .encodeMessage([code, message, details]); + } +} + +/// [MessageCodec] using the Flutter standard binary encoding. +/// +/// Supported messages are acyclic values of these forms: +/// +/// * null +/// * [bool]s +/// * [num]s +/// * [String]s +/// * [Uint8List]s, [Int32List]s, [Int64List]s, [Float64List]s +/// * [List]s of supported values +/// * [Map]s from supported values to supported values +/// +/// Decoded values will use `List` and `Map` +/// irrespective of content. +/// +/// On Android, messages are represented as follows: +/// +/// * null: null +/// * [bool]\: `java.lang.Boolean` +/// * [int]\: `java.lang.Integer` for values that are representable using 32-bit +/// two's complement; `java.lang.Long` otherwise +/// * [double]\: `java.lang.Double` +/// * [String]\: `java.lang.String` +/// * [Uint8List]\: `byte[]` +/// * [Int32List]\: `int[]` +/// * [Int64List]\: `long[]` +/// * [Float64List]\: `double[]` +/// * [List]\: `java.util.ArrayList` +/// * [Map]\: `java.util.HashMap` +/// +/// On iOS, messages are represented as follows: +/// +/// * null: nil +/// * [bool]\: `NSNumber numberWithBool:` +/// * [int]\: `NSNumber numberWithInt:` for values that are representable using +/// 32-bit two's complement; `NSNumber numberWithLong:` otherwise +/// * [double]\: `NSNumber numberWithDouble:` +/// * [String]\: `NSString` +/// * [Uint8List], [Int32List], [Int64List], [Float64List]\: +/// `FlutterStandardTypedData` +/// * [List]\: `NSArray` +/// * [Map]\: `NSDictionary` +/// +/// The codec is extensible by subclasses overriding [writeValue] and +/// [readValueOfType]. +class StandardMessageCodec implements MessageCodec { + // The codec serializes messages as outlined below. This format must + // match the Android and iOS counterparts. + // + // * A single byte with one of the constant values below determines the + // type of the value. + // * The serialization of the value itself follows the type byte. + // * Numbers are represented using the host endianness throughout. + // * Lengths and sizes of serialized parts are encoded using an expanding + // format optimized for the common case of small non-negative integers: + // * values 0..253 inclusive using one byte with that value; + // * values 254..2^16 inclusive using three bytes, the first of which is + // 254, the next two the usual unsigned representation of the value; + // * values 2^16+1..2^32 inclusive using five bytes, the first of which is + // 255, the next four the usual unsigned representation of the value. + // * null, true, and false have empty serialization; they are encoded directly + // in the type byte (using _kNull, _kTrue, _kFalse) + // * Integers representable in 32 bits are encoded using 4 bytes two's + // complement representation. + // * Larger integers are encoded using 8 bytes two's complement + // representation. + // * doubles are encoded using the IEEE 754 64-bit double-precision binary + // format. + // * Strings are encoded using their UTF-8 representation. First the length + // of that in bytes is encoded using the expanding format, then follows the + // UTF-8 encoding itself. + // * Uint8Lists, Int32Lists, Int64Lists, and Float64Lists are encoded by first + // encoding the list's element count in the expanding format, then the + // smallest number of zero bytes needed to align the position in the full + // message with a multiple of the number of bytes per element, then the + // encoding of the list elements themselves, end-to-end with no additional + // type information, using two's complement or IEEE 754 as applicable. + // * Lists are encoded by first encoding their length in the expanding format, + // then follows the recursive encoding of each element value, including the + // type byte (Lists are assumed to be heterogeneous). + // * Maps are encoded by first encoding their length in the expanding format, + // then follows the recursive encoding of each key/value pair, including the + // type byte for both (Maps are assumed to be heterogeneous). + static const int _valueNull = 0; + static const int _valueTrue = 1; + static const int _valueFalse = 2; + static const int _valueInt32 = 3; + static const int _valueInt64 = 4; + static const int _valueLargeInt = 5; + static const int _valueFloat64 = 6; + static const int _valueString = 7; + static const int _valueUint8List = 8; + static const int _valueInt32List = 9; + static const int _valueInt64List = 10; + static const int _valueFloat64List = 11; + static const int _valueList = 12; + static const int _valueMap = 13; + + /// Creates a [MessageCodec] using the Flutter standard binary encoding. + const StandardMessageCodec(); + + @override + ByteData encodeMessage(dynamic message) { + if (message == null) return null; + final WriteBuffer buffer = WriteBuffer(); + writeValue(buffer, message); + return buffer.done(); + } + + @override + dynamic decodeMessage(ByteData message) { + if (message == null) return null; + final ReadBuffer buffer = ReadBuffer(message); + final dynamic result = readValue(buffer); + if (buffer.hasRemaining) throw const FormatException('Message corrupted'); + return result; + } + + /// Writes [value] to [buffer] by first writing a type discriminator + /// byte, then the value itself. + /// + /// This method may be called recursively to serialize container values. + /// + /// Type discriminators 0 through 127 inclusive are reserved for use by the + /// base class. + /// + /// The codec can be extended by overriding this method, calling super + /// for values that the extension does not handle. Type discriminators + /// used by extensions must be greater than or equal to 128 in order to avoid + /// clashes with any later extensions to the base class. + void writeValue(WriteBuffer buffer, dynamic value) { + if (value == null) { + buffer.putUint8(_valueNull); + } else if (value is bool) { + buffer.putUint8(value ? _valueTrue : _valueFalse); + // TODO(flutter_web): upstream double/int if/else swap. + } else if (value is double) { + buffer.putUint8(_valueFloat64); + buffer.putFloat64(value); + } else if (value is int) { + if (-0x7fffffff - 1 <= value && value <= 0x7fffffff) { + buffer.putUint8(_valueInt32); + buffer.putInt32(value); + } else { + buffer.putUint8(_valueInt64); + buffer.putInt64(value); + } + } else if (value is String) { + buffer.putUint8(_valueString); + final List bytes = utf8.encoder.convert(value); + writeSize(buffer, bytes.length); + buffer.putUint8List(bytes); + } else if (value is Uint8List) { + buffer.putUint8(_valueUint8List); + writeSize(buffer, value.length); + buffer.putUint8List(value); + } else if (value is Int32List) { + buffer.putUint8(_valueInt32List); + writeSize(buffer, value.length); + buffer.putInt32List(value); + } else if (value is Int64List) { + buffer.putUint8(_valueInt64List); + writeSize(buffer, value.length); + buffer.putInt64List(value); + } else if (value is Float64List) { + buffer.putUint8(_valueFloat64List); + writeSize(buffer, value.length); + buffer.putFloat64List(value); + } else if (value is List) { + buffer.putUint8(_valueList); + writeSize(buffer, value.length); + for (final dynamic item in value) { + writeValue(buffer, item); + } + } else if (value is Map) { + buffer.putUint8(_valueMap); + writeSize(buffer, value.length); + value.forEach((dynamic key, dynamic value) { + writeValue(buffer, key); + writeValue(buffer, value); + }); + } else { + throw new ArgumentError.value(value); + } + } + + /// Reads a value from [buffer] as written by [writeValue]. + /// + /// This method is intended for use by subclasses overriding + /// [readValueOfType]. + dynamic readValue(ReadBuffer buffer) { + if (!buffer.hasRemaining) throw const FormatException('Message corrupted'); + final int type = buffer.getUint8(); + return readValueOfType(type, buffer); + } + + /// Reads a value of the indicated [type] from [buffer]. + /// + /// The codec can be extended by overriding this method, calling super + /// for types that the extension does not handle. + dynamic readValueOfType(int type, ReadBuffer buffer) { + dynamic result; + switch (type) { + case _valueNull: + result = null; + break; + case _valueTrue: + result = true; + break; + case _valueFalse: + result = false; + break; + case _valueInt32: + result = buffer.getInt32(); + break; + case _valueInt64: + result = buffer.getInt64(); + break; + case _valueLargeInt: + // Flutter Engine APIs to use large ints have been deprecated on + // 2018-01-09 and will be made unavailable. + // TODO(mravn): remove this case once the APIs are unavailable. + final int length = readSize(buffer); + final String hex = utf8.decoder.convert(buffer.getUint8List(length)); + result = int.parse(hex, radix: 16); + break; + case _valueFloat64: + result = buffer.getFloat64(); + break; + case _valueString: + final int length = readSize(buffer); + result = utf8.decoder.convert(buffer.getUint8List(length)); + break; + case _valueUint8List: + final int length = readSize(buffer); + result = buffer.getUint8List(length); + break; + case _valueInt32List: + final int length = readSize(buffer); + result = buffer.getInt32List(length); + break; + case _valueInt64List: + final int length = readSize(buffer); + result = buffer.getInt64List(length); + break; + case _valueFloat64List: + final int length = readSize(buffer); + result = buffer.getFloat64List(length); + break; + case _valueList: + final int length = readSize(buffer); + result = List(length); + for (int i = 0; i < length; i++) { + result[i] = readValue(buffer); + } + break; + case _valueMap: + final int length = readSize(buffer); + result = {}; + for (int i = 0; i < length; i++) { + result[readValue(buffer)] = readValue(buffer); + } + break; + default: + throw const FormatException('Message corrupted'); + } + return result; + } + + /// Writes a non-negative 32-bit integer [value] to [buffer] + /// using an expanding 1-5 byte encoding that optimizes for small values. + /// + /// This method is intended for use by subclasses overriding + /// [writeValue]. + void writeSize(WriteBuffer buffer, int value) { + assert(0 <= value && value <= 0xffffffff); + if (value < 254) { + buffer.putUint8(value); + } else if (value <= 0xffff) { + buffer.putUint8(254); + buffer.putUint16(value); + } else { + buffer.putUint8(255); + buffer.putUint32(value); + } + } + + /// Reads a non-negative int from [buffer] as written by [writeSize]. + /// + /// This method is intended for use by subclasses overriding + /// [readValueOfType]. + int readSize(ReadBuffer buffer) { + final int value = buffer.getUint8(); + switch (value) { + case 254: + return buffer.getUint16(); + case 255: + return buffer.getUint32(); + default: + return value; + } + } +} + +/// [MethodCodec] using the Flutter standard binary encoding. +/// +/// The standard codec is guaranteed to be compatible with the corresponding +/// standard codec for FlutterMethodChannels on the host platform. These parts +/// of the Flutter SDK are evolved synchronously. +/// +/// Values supported as method arguments and result payloads are those supported +/// by [StandardMessageCodec]. +class StandardMethodCodec implements MethodCodec { + // The codec method calls, and result envelopes as outlined below. This format + // must match the Android and iOS counterparts. + // + // * Individual values are encoded using [StandardMessageCodec]. + // * Method calls are encoded using the concatenation of the encoding + // of the method name String and the arguments value. + // * Reply envelopes are encoded using first a single byte to distinguish the + // success case (0) from the error case (1). Then follows: + // * In the success case, the encoding of the result value. + // * In the error case, the concatenation of the encoding of the error code + // string, the error message string, and the error details value. + + /// Creates a [MethodCodec] using the Flutter standard binary encoding. + const StandardMethodCodec([this.messageCodec = const StandardMessageCodec()]); + + /// The message codec that this method codec uses for encoding values. + final StandardMessageCodec messageCodec; + + @override + ByteData encodeMethodCall(MethodCall call) { + final WriteBuffer buffer = WriteBuffer(); + messageCodec.writeValue(buffer, call.method); + messageCodec.writeValue(buffer, call.arguments); + return buffer.done(); + } + + @override + MethodCall decodeMethodCall(ByteData methodCall) { + final ReadBuffer buffer = ReadBuffer(methodCall); + final dynamic method = messageCodec.readValue(buffer); + final dynamic arguments = messageCodec.readValue(buffer); + if (method is String && !buffer.hasRemaining) + return MethodCall(method, arguments); + else + throw const FormatException('Invalid method call'); + } + + @override + ByteData encodeSuccessEnvelope(dynamic result) { + final WriteBuffer buffer = WriteBuffer(); + buffer.putUint8(0); + messageCodec.writeValue(buffer, result); + return buffer.done(); + } + + @override + ByteData encodeErrorEnvelope( + {@required String code, String message, dynamic details}) { + final WriteBuffer buffer = WriteBuffer(); + buffer.putUint8(1); + messageCodec.writeValue(buffer, code); + messageCodec.writeValue(buffer, message); + messageCodec.writeValue(buffer, details); + return buffer.done(); + } + + @override + dynamic decodeEnvelope(ByteData envelope) { + // First byte is zero in success case, and non-zero otherwise. + if (envelope.lengthInBytes == 0) + throw const FormatException('Expected envelope, got nothing'); + final ReadBuffer buffer = ReadBuffer(envelope); + if (buffer.getUint8() == 0) return messageCodec.readValue(buffer); + final dynamic errorCode = messageCodec.readValue(buffer); + final dynamic errorMessage = messageCodec.readValue(buffer); + final dynamic errorDetails = messageCodec.readValue(buffer); + if (errorCode is String && + (errorMessage == null || errorMessage is String) && + !buffer.hasRemaining) + throw PlatformException( + code: errorCode, message: errorMessage, details: errorDetails); + else + throw const FormatException('Invalid envelope'); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/services/serialization.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/services/serialization.dart new file mode 100644 index 0000000000..75ffbf7e94 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/services/serialization.dart @@ -0,0 +1,202 @@ +// 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; + +/// Write-only buffer for incrementally building a [ByteData] instance. +/// +/// A WriteBuffer instance can be used only once. Attempts to reuse will result +/// in [NoSuchMethodError]s being thrown. +/// +/// The byte order used is [Endian.host] throughout. +class WriteBuffer { + /// Creates an interface for incrementally building a [ByteData] instance. + WriteBuffer() { + _buffer = Uint8Buffer(); + _eightBytes = ByteData(8); + _eightBytesAsList = _eightBytes.buffer.asUint8List(); + } + + Uint8Buffer _buffer; + ByteData _eightBytes; + Uint8List _eightBytesAsList; + + /// Write a Uint8 into the buffer. + void putUint8(int byte) { + _buffer.add(byte); + } + + /// Write a Uint16 into the buffer. + void putUint16(int value) { + _eightBytes.setUint16(0, value, Endian.host); + _buffer.addAll(_eightBytesAsList, 0, 2); + } + + /// Write a Uint32 into the buffer. + void putUint32(int value) { + _eightBytes.setUint32(0, value, Endian.host); + _buffer.addAll(_eightBytesAsList, 0, 4); + } + + /// Write an Int32 into the buffer. + void putInt32(int value) { + _eightBytes.setInt32(0, value, Endian.host); + _buffer.addAll(_eightBytesAsList, 0, 4); + } + + /// Write an Int64 into the buffer. + void putInt64(int value) { + _eightBytes.setInt64(0, value, Endian.host); + _buffer.addAll(_eightBytesAsList, 0, 8); + } + + /// Write an Float64 into the buffer. + void putFloat64(double value) { + _alignTo(8); + _eightBytes.setFloat64(0, value, Endian.host); + _buffer.addAll(_eightBytesAsList); + } + + /// Write all the values from a [Uint8List] into the buffer. + void putUint8List(Uint8List list) { + _buffer.addAll(list); + } + + /// Write all the values from a [Int32List] into the buffer. + void putInt32List(Int32List list) { + _alignTo(4); + _buffer + .addAll(list.buffer.asUint8List(list.offsetInBytes, 4 * list.length)); + } + + /// Write all the values from an [Int64List] into the buffer. + void putInt64List(Int64List list) { + _alignTo(8); + _buffer + .addAll(list.buffer.asUint8List(list.offsetInBytes, 8 * list.length)); + } + + /// Write all the values from a [Float64List] into the buffer. + void putFloat64List(Float64List list) { + _alignTo(8); + _buffer + .addAll(list.buffer.asUint8List(list.offsetInBytes, 8 * list.length)); + } + + void _alignTo(int alignment) { + final int mod = _buffer.length % alignment; + if (mod != 0) { + for (int i = 0; i < alignment - mod; i++) { + _buffer.add(0); + } + } + } + + /// Finalize and return the written [ByteData]. + ByteData done() { + final ByteData result = _buffer.buffer.asByteData(0, _buffer.lengthInBytes); + _buffer = null; + return result; + } +} + +/// Read-only buffer for reading sequentially from a [ByteData] instance. +/// +/// The byte order used is [Endian.host] throughout. +class ReadBuffer { + /// Creates a [ReadBuffer] for reading from the specified [data]. + ReadBuffer(this.data) : assert(data != null); + + /// The underlying data being read. + final ByteData data; + + /// The position to read next. + int _position = 0; + + /// Whether the buffer has data remaining to read. + bool get hasRemaining => _position < data.lengthInBytes; + + /// Reads a Uint8 from the buffer. + int getUint8() { + return data.getUint8(_position++); + } + + /// Reads a Uint16 from the buffer. + int getUint16() { + final int value = data.getUint16(_position, Endian.host); + _position += 2; + return value; + } + + /// Reads a Uint32 from the buffer. + int getUint32() { + final int value = data.getUint32(_position, Endian.host); + _position += 4; + return value; + } + + /// Reads an Int32 from the buffer. + int getInt32() { + final int value = data.getInt32(_position, Endian.host); + _position += 4; + return value; + } + + /// Reads an Int64 from the buffer. + int getInt64() { + final int value = data.getInt64(_position, Endian.host); + _position += 8; + return value; + } + + /// Reads a Float64 from the buffer. + double getFloat64() { + _alignTo(8); + final double value = data.getFloat64(_position, Endian.host); + _position += 8; + return value; + } + + /// Reads the given number of Uint8s from the buffer. + Uint8List getUint8List(int length) { + final Uint8List list = + data.buffer.asUint8List(data.offsetInBytes + _position, length); + _position += length; + return list; + } + + /// Reads the given number of Int32s from the buffer. + Int32List getInt32List(int length) { + _alignTo(4); + final Int32List list = + data.buffer.asInt32List(data.offsetInBytes + _position, length); + _position += 4 * length; + return list; + } + + /// Reads the given number of Int64s from the buffer. + Int64List getInt64List(int length) { + _alignTo(8); + final Int64List list = + data.buffer.asInt64List(data.offsetInBytes + _position, length); + _position += 8 * length; + return list; + } + + /// Reads the given number of Float64s from the buffer. + Float64List getFloat64List(int length) { + _alignTo(8); + final Float64List list = + data.buffer.asFloat64List(data.offsetInBytes + _position, length); + _position += 8 * length; + return list; + } + + void _alignTo(int alignment) { + final int mod = _position % alignment; + if (mod != 0) { + _position += alignment - mod; + } + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/shadow.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/shadow.dart new file mode 100644 index 0000000000..fb6786a742 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/shadow.dart @@ -0,0 +1,369 @@ +// 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; + +/// This code is ported from the AngularDart SCSS. +/// +/// See: https://github.com/dart-lang/angular_components/blob/master/lib/css/material/_shadow.scss +class ElevationShadow { + /// Applies a standard transition style for box-shadow to box-shadow. + static void applyShadowTransition(html.CssStyleDeclaration style) { + style.transition = 'box-shadow .28s cubic-bezier(.4, 0, .2, 1)'; + } + + /// Disables box-shadow. + static void applyShadowNone(html.CssStyleDeclaration style) { + style.boxShadow = 'none'; + } + + /// Applies a standard shadow to the selected element(s). + /// + /// This rule is great for things that need a static shadow. If the elevation + /// of the shadow needs to be changed dynamically, use [applyShadow]. + /// + /// Valid values: 2, 3, 4, 6, 8, 12, 16, 24 + static void applyShadowElevation(html.CssStyleDeclaration style, + {@required int dp, @required ui.Color color}) { + const double keyUmbraOpacity = 0.2; + const double keyPenumbraOpacity = 0.14; + const double ambientShadowOpacity = 0.12; + + final String rgb = '${color.red}, ${color.green}, ${color.blue}'; + if (dp == 2) { + style.boxShadow = '0 2px 2px 0 rgba($rgb, $keyPenumbraOpacity), ' + '0 3px 1px -2px rgba($rgb, $ambientShadowOpacity), ' + '0 1px 5px 0 rgba($rgb, $keyUmbraOpacity)'; + } else if (dp == 3) { + style.boxShadow = '0 3px 4px 0 rgba($rgb, $keyPenumbraOpacity), ' + '0 3px 3px -2px rgba($rgb, $ambientShadowOpacity), ' + '0 1px 8px 0 rgba($rgb, $keyUmbraOpacity)'; + } else if (dp == 4) { + style.boxShadow = '0 4px 5px 0 rgba($rgb, $keyPenumbraOpacity), ' + '0 1px 10px 0 rgba($rgb, $ambientShadowOpacity), ' + '0 2px 4px -1px rgba($rgb, $keyUmbraOpacity)'; + } else if (dp == 6) { + style.boxShadow = '0 6px 10px 0 rgba($rgb, $keyPenumbraOpacity), ' + '0 1px 18px 0 rgba($rgb, $ambientShadowOpacity), ' + '0 3px 5px -1px rgba($rgb, $keyUmbraOpacity)'; + } else if (dp == 8) { + style.boxShadow = '0 8px 10px 1px rgba($rgb, $keyPenumbraOpacity), ' + '0 3px 14px 2px rgba($rgb, $ambientShadowOpacity), ' + '0 5px 5px -3px rgba($rgb, $keyUmbraOpacity)'; + } else if (dp == 12) { + style.boxShadow = '0 12px 17px 2px rgba($rgb, $keyPenumbraOpacity), ' + '0 5px 22px 4px rgba($rgb, $ambientShadowOpacity), ' + '0 7px 8px -4px rgba($rgb, $keyUmbraOpacity)'; + } else if (dp == 16) { + style.boxShadow = '0 16px 24px 2px rgba($rgb, $keyPenumbraOpacity), ' + '0 6px 30px 5px rgba($rgb, $ambientShadowOpacity), ' + '0 8px 10px -5px rgba($rgb, $keyUmbraOpacity)'; + } else { + style.boxShadow = '0 24px 38px 3px rgba($rgb, $keyPenumbraOpacity), ' + '0 9px 46px 8px rgba($rgb, $ambientShadowOpacity), ' + '0 11px 15px -7px rgba($rgb, $keyUmbraOpacity)'; + } + } + + /// Applies the shadow styles to the selected element. + /// + /// Use the attributes below to control the shadow. + /// + /// - `animated` -- Whether to animate the shadow transition. + /// - `elevation` -- Z-elevation of shadow. Valid Values: 1,2,3,4,5 + static void applyShadow( + html.CssStyleDeclaration style, double elevation, ui.Color color) { + applyShadowTransition(style); + + if (elevation <= 0.0) { + applyShadowNone(style); + } else if (elevation <= 1.0) { + applyShadowElevation(style, dp: 2, color: color); + } else if (elevation <= 2.0) { + applyShadowElevation(style, dp: 4, color: color); + } else if (elevation <= 3.0) { + applyShadowElevation(style, dp: 6, color: color); + } else if (elevation <= 4.0) { + applyShadowElevation(style, dp: 8, color: color); + } else if (elevation <= 5.0) { + applyShadowElevation(style, dp: 16, color: color); + } else { + applyShadowElevation(style, dp: 24, color: color); + } + } + + static List computeCanvasShadows( + double elevation, ui.Color color) { + if (elevation <= 0.0) { + return const []; + } else if (elevation <= 1.0) { + return computeShadowElevation(dp: 2, color: color); + } else if (elevation <= 2.0) { + return computeShadowElevation(dp: 4, color: color); + } else if (elevation <= 3.0) { + return computeShadowElevation(dp: 6, color: color); + } else if (elevation <= 4.0) { + return computeShadowElevation(dp: 8, color: color); + } else if (elevation <= 5.0) { + return computeShadowElevation(dp: 16, color: color); + } else { + return computeShadowElevation(dp: 24, color: color); + } + } + + /// Expands rect to include size of shadow. + /// + /// Computed from shadow elevation offset + spread, blur + static ui.Rect computeShadowRect(ui.Rect r, double elevation) { + // We are computing this rect by computing the maximum "reach" of the shadow + // by summing the computed shadow offset and the blur for the given + // elevation. We are assuming that a blur of '1' corresponds to 1 pixel, + // although the web spec says that this is not necessarily the case. + // However, it seems to be a good conservative estimate. + if (elevation <= 0.0) { + return r; + } else if (elevation <= 1.0) { + return ui.Rect.fromLTRB( + r.left - 2.5, r.top - 1.5, r.right + 3, r.bottom + 4); + } else if (elevation <= 2.0) { + return ui.Rect.fromLTRB(r.left - 5, r.top - 3, r.right + 6, r.bottom + 7); + } else if (elevation <= 3.0) { + return ui.Rect.fromLTRB( + r.left - 9, r.top - 8, r.right + 9, r.bottom + 11); + } else if (elevation <= 4.0) { + return ui.Rect.fromLTRB( + r.left - 10, r.top - 6, r.right + 10, r.bottom + 14); + } else if (elevation <= 5.0) { + return ui.Rect.fromLTRB( + r.left - 15, r.top - 9, r.right + 20, r.bottom + 30); + } else { + return ui.Rect.fromLTRB( + r.left - 23, r.top - 14, r.right + 23, r.bottom + 45); + } + } + + static List computeShadowElevation( + {@required int dp, @required ui.Color color}) { + final int red = color.red; + final int green = color.green; + final int blue = color.blue; + + final ui.Color penumbraColor = ui.Color.fromARGB(36, red, green, blue); + final ui.Color ambientShadowColor = ui.Color.fromARGB(31, red, green, blue); + final ui.Color umbraColor = ui.Color.fromARGB(51, red, green, blue); + + final List result = []; + if (dp == 2) { + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 2.0, + blur: 1.0, + spread: 0.0, + color: penumbraColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 3.0, + blur: 0.5, + spread: -2.0, + color: ambientShadowColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 1.0, + blur: 2.5, + spread: 0.0, + color: umbraColor, + )); + } else if (dp == 3) { + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 1.5, + blur: 4.0, + spread: 0.0, + color: penumbraColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 3.0, + blur: 1.5, + spread: -2.0, + color: ambientShadowColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 1.0, + blur: 4.0, + spread: 0.0, + color: umbraColor, + )); + } else if (dp == 4) { + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 4.0, + blur: 2.5, + spread: 0.0, + color: penumbraColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 1.0, + blur: 5.0, + spread: 0.0, + color: ambientShadowColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 2.0, + blur: 2.0, + spread: -1.0, + color: umbraColor, + )); + } else if (dp == 6) { + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 6.0, + blur: 5.0, + spread: 0.0, + color: penumbraColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 1.0, + blur: 9.0, + spread: 0.0, + color: ambientShadowColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 3.0, + blur: 2.5, + spread: -1.0, + color: umbraColor, + )); + } else if (dp == 8) { + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 4.0, + blur: 10.0, + spread: 1.0, + color: penumbraColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 3.0, + blur: 7.0, + spread: 2.0, + color: ambientShadowColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 5.0, + blur: 2.5, + spread: -3.0, + color: umbraColor, + )); + } else if (dp == 12) { + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 12.0, + blur: 8.5, + spread: 2.0, + color: penumbraColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 5.0, + blur: 11.0, + spread: 4.0, + color: ambientShadowColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 7.0, + blur: 4.0, + spread: -4.0, + color: umbraColor, + )); + } else if (dp == 16) { + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 16.0, + blur: 12.0, + spread: 2.0, + color: penumbraColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 6.0, + blur: 15.0, + spread: 5.0, + color: ambientShadowColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 0.0, + blur: 5.0, + spread: -5.0, + color: umbraColor, + )); + } else { + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 24.0, + blur: 18.0, + spread: 3.0, + color: penumbraColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 9.0, + blur: 23.0, + spread: 8.0, + color: ambientShadowColor, + )); + + result.add(CanvasShadow( + offsetX: 0.0, + offsetY: 11.0, + blur: 7.5, + spread: -7.0, + color: umbraColor, + )); + } + return result; + } +} + +class CanvasShadow { + CanvasShadow({ + @required this.offsetX, + @required this.offsetY, + @required this.blur, + @required this.spread, + @required this.color, + }); + + final double offsetX; + final double offsetY; + final double blur; + // TODO(yjbanov): is there a way to implement/emulate spread on Canvas2D? + final double spread; + final ui.Color color; +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/backdrop_filter.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/backdrop_filter.dart new file mode 100644 index 0000000000..4369ae1b46 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/backdrop_filter.dart @@ -0,0 +1,101 @@ +// 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; + +/// A surface that applies an image filter to background. +class PersistedBackdropFilter extends PersistedContainerSurface + implements ui.BackdropFilterEngineLayer { + PersistedBackdropFilter(PersistedBackdropFilter oldLayer, this.filter) + : super(oldLayer); + + final ui.ImageFilter filter; + + /// The dedicated child container element that's separate from the + /// [rootElement] is used to host child in front of [filterElement] that + /// is transformed to cover background. + @override + html.Element get childContainer => _childContainer; + html.Element _childContainer; + html.Element _filterElement; + // Cached inverted transform for _transform. + Matrix4 _invertedTransform; + // Reference to transform last used to cache [_invertedTransform]. + Matrix4 _previousTransform; + + @override + void adoptElements(PersistedBackdropFilter oldSurface) { + super.adoptElements(oldSurface); + _childContainer = oldSurface._childContainer; + _filterElement = oldSurface._filterElement; + oldSurface._childContainer = null; + } + + @override + html.Element createElement() { + final html.Element element = defaultCreateElement('flt-backdrop') + ..style.transformOrigin = '0 0 0'; + _childContainer = html.Element.tag('flt-backdrop-interior'); + _childContainer.style.position = 'absolute'; + if (_debugExplainSurfaceStats) { + // This creates an additional interior element. Count it too. + _surfaceStatsFor(this).allocatedDomNodeCount++; + } + _filterElement = defaultCreateElement('flt-backdrop-filter'); + _filterElement.style.transformOrigin = '0 0 0'; + element..append(_filterElement)..append(_childContainer); + return element; + } + + @override + void discard() { + super.discard(); + // Do not detach the child container from the root. It is permanently + // attached. The elements are reused together and are detached from the DOM + // together. + _childContainer = null; + _filterElement = null; + } + + @override + void apply() { + if (_previousTransform != _transform) { + _invertedTransform = Matrix4.inverted(_transform); + _previousTransform = _transform; + } + final ui.Rect rect = localClipRectToGlobalClip( + localClip: ui.Rect.fromLTRB( + 0, 0, ui.window.physicalSize.width, ui.window.physicalSize.height), + transform: _invertedTransform); + final html.CssStyleDeclaration filterElementStyle = _filterElement.style; + filterElementStyle + ..position = 'absolute' + ..transform = 'translate(${rect.left}px, ${rect.top}px)' + ..width = '${rect.width}px' + ..height = '${rect.height}px'; + if (browserEngine == BrowserEngine.blink) { + // For Chrome render transparent black background. + // TODO(flutter_web): Switch code to use filter when + // https://bugs.chromium.org/p/chromium/issues/detail?id=497522#c213 + // is fixed. + filterElementStyle + ..backgroundColor = '#000' + ..opacity = '0.2'; + } else { + // CSS uses pixel radius for blur. Flutter & SVG use sigma parameters. For + // Gaussian blur with standard deviation (normal distribution), + // the blur will fall within 2 * sigma pixels. + domRenderer.setElementStyle(_filterElement, 'backdrop-filter', + 'blur(${math.max(filter.sigmaX, filter.sigmaY) * 2}px)'); + } + } + + @override + void update(PersistedBackdropFilter oldSurface) { + super.update(oldSurface); + if (filter != oldSurface.filter) { + apply(); + } + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/clip.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/clip.dart new file mode 100644 index 0000000000..4255b73838 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/clip.dart @@ -0,0 +1,381 @@ +// 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; + +/// Mixin used by surfaces that clip their contents using an overflowing DOM +/// element. +mixin _DomClip on PersistedContainerSurface { + /// The dedicated child container element that's separate from the + /// [rootElement] is used to compensate for the coordinate system shift + /// introduced by the [rootElement] translation. + @override + html.Element get childContainer => _childContainer; + html.Element _childContainer; + + @override + void adoptElements(_DomClip oldSurface) { + super.adoptElements(oldSurface); + _childContainer = oldSurface._childContainer; + oldSurface._childContainer = null; + } + + @override + html.Element createElement() { + final html.Element element = defaultCreateElement('flt-clip'); + if (!debugShowClipLayers) { + // Hide overflow in production mode. When debugging we want to see the + // clipped picture in full. + element.style.overflow = 'hidden'; + } else { + // Display the outline of the clipping region. When debugShowClipLayers is + // `true` we don't hide clip overflow (see above). This outline helps + // visualizing clip areas. + element.style.boxShadow = 'inset 0 0 10px green'; + } + _childContainer = html.Element.tag('flt-clip-interior'); + if (_debugExplainSurfaceStats) { + // This creates an additional interior element. Count it too. + _surfaceStatsFor(this).allocatedDomNodeCount++; + } + _childContainer.style.position = 'absolute'; + element.append(_childContainer); + return element; + } + + @override + void discard() { + super.discard(); + + // Do not detach the child container from the root. It is permanently + // attached. The elements are reused together and are detached from the DOM + // together. + _childContainer = null; + } +} + +/// A surface that creates a rectangular clip. +class PersistedClipRect extends PersistedContainerSurface + with _DomClip + implements ui.ClipRectEngineLayer { + PersistedClipRect(PersistedClipRect oldLayer, this.rect) : super(oldLayer); + + final ui.Rect rect; + + @override + void recomputeTransformAndClip() { + _transform = parent._transform; + _globalClip = parent._globalClip.intersect(localClipRectToGlobalClip( + localClip: rect, + transform: _transform, + )); + } + + @override + html.Element createElement() { + return super.createElement()..setAttribute('clip-type', 'rect'); + } + + @override + void apply() { + rootElement.style + ..transform = 'translate(${rect.left}px, ${rect.top}px)' + ..width = '${rect.right - rect.left}px' + ..height = '${rect.bottom - rect.top}px'; + + // Translate the child container in the opposite direction to compensate for + // the shift in the coordinate system introduced by the translation of the + // rootElement. Clipping in Flutter has no effect on the coordinate system. + childContainer.style.transform = + 'translate(${-rect.left}px, ${-rect.top}px)'; + } + + @override + void update(PersistedClipRect oldSurface) { + super.update(oldSurface); + if (rect != oldSurface.rect) { + apply(); + } + } +} + +/// A surface that creates a rounded rectangular clip. +class PersistedClipRRect extends PersistedContainerSurface + with _DomClip + implements ui.ClipRRectEngineLayer { + PersistedClipRRect(ui.EngineLayer oldLayer, this.rrect, this.clipBehavior) + : super(oldLayer); + + final ui.RRect rrect; + // TODO(yjbanov): can this be controlled in the browser? + final ui.Clip clipBehavior; + + @override + void recomputeTransformAndClip() { + _transform = parent._transform; + _globalClip = parent._globalClip.intersect(localClipRectToGlobalClip( + localClip: rrect.outerRect, + transform: _transform, + )); + } + + @override + html.Element createElement() { + return super.createElement()..setAttribute('clip-type', 'rrect'); + } + + @override + void apply() { + rootElement.style + ..transform = 'translate(${rrect.left}px, ${rrect.top}px)' + ..width = '${rrect.width}px' + ..height = '${rrect.height}px' + ..borderTopLeftRadius = '${rrect.tlRadiusX}px' + ..borderTopRightRadius = '${rrect.trRadiusX}px' + ..borderBottomRightRadius = '${rrect.brRadiusX}px' + ..borderBottomLeftRadius = '${rrect.blRadiusX}px'; + + // Translate the child container in the opposite direction to compensate for + // the shift in the coordinate system introduced by the translation of the + // rootElement. Clipping in Flutter has no effect on the coordinate system. + childContainer.style.transform = + 'translate(${-rrect.left}px, ${-rrect.top}px)'; + } + + @override + void update(PersistedClipRRect oldSurface) { + super.update(oldSurface); + if (rrect != oldSurface.rrect) { + apply(); + } + } +} + +class PersistedPhysicalShape extends PersistedContainerSurface + with _DomClip + implements ui.PhysicalShapeEngineLayer { + PersistedPhysicalShape(PersistedPhysicalShape oldLayer, this.path, + this.elevation, int color, int shadowColor, this.clipBehavior) + : color = ui.Color(color), + shadowColor = ui.Color(shadowColor), + super(oldLayer); + + final ui.Path path; + final double elevation; + final ui.Color color; + final ui.Color shadowColor; + final ui.Clip clipBehavior; + html.Element _clipElement; + + @override + void recomputeTransformAndClip() { + _transform = parent._transform; + + final ui.RRect roundRect = path.webOnlyPathAsRoundedRect; + if (roundRect != null) { + _globalClip = parent._globalClip.intersect(localClipRectToGlobalClip( + localClip: roundRect.outerRect, + transform: transform, + )); + } else { + final ui.Rect rect = path.webOnlyPathAsRect; + if (rect != null) { + _globalClip = parent._globalClip.intersect(localClipRectToGlobalClip( + localClip: rect, + transform: transform, + )); + } else { + _globalClip = parent._globalClip; + } + } + } + + void _applyColor() { + rootElement.style.backgroundColor = color.toCssString(); + } + + void _applyShadow() { + ElevationShadow.applyShadow(rootElement.style, elevation, shadowColor); + } + + @override + html.Element createElement() { + return super.createElement()..setAttribute('clip-type', 'physical-shape'); + } + + @override + void apply() { + _applyColor(); + _applyShadow(); + _applyShape(); + } + + void _applyShape() { + if (path == null) { + return; + } + // Handle special case of round rect physical shape mapping to + // rounded div. + final ui.RRect roundRect = path.webOnlyPathAsRoundedRect; + if (roundRect != null) { + final String borderRadius = + '${roundRect.tlRadiusX}px ${roundRect.trRadiusX}px ' + '${roundRect.brRadiusX}px ${roundRect.blRadiusX}px'; + final html.CssStyleDeclaration style = rootElement.style; + style + ..transform = 'translate(${roundRect.left}px, ${roundRect.top}px)' + ..width = '${roundRect.width}px' + ..height = '${roundRect.height}px' + ..borderRadius = borderRadius; + childContainer.style.transform = + 'translate(${-roundRect.left}px, ${-roundRect.top}px)'; + if (clipBehavior != ui.Clip.none) { + style.overflow = 'hidden'; + } + return; + } else { + final ui.Rect rect = path.webOnlyPathAsRect; + if (rect != null) { + final html.CssStyleDeclaration style = rootElement.style; + style + ..transform = 'translate(${rect.left}px, ${rect.top}px)' + ..width = '${rect.width}px' + ..height = '${rect.height}px' + ..borderRadius = ''; + childContainer.style.transform = + 'translate(${-rect.left}px, ${-rect.top}px)'; + if (clipBehavior != ui.Clip.none) { + style.overflow = 'hidden'; + } + return; + } else { + final Ellipse ellipse = path.webOnlyPathAsCircle; + if (ellipse != null) { + final double rx = ellipse.radiusX; + final double ry = ellipse.radiusY; + final String borderRadius = + rx == ry ? '${rx}px ' : '${rx}px ${ry}px '; + final html.CssStyleDeclaration style = rootElement.style; + final double left = ellipse.x - rx; + final double top = ellipse.y - ry; + style + ..transform = 'translate(${left}px, ${top}px)' + ..width = '${rx * 2}px' + ..height = '${ry * 2}px' + ..borderRadius = borderRadius; + childContainer.style.transform = 'translate(${-left}px, ${-top}px)'; + if (clipBehavior != ui.Clip.none) { + style.overflow = 'hidden'; + } + return; + } + } + } + + final ui.Rect bounds = path.getBounds(); + final String svgClipPath = + _pathToSvgClipPath(path, offsetX: -bounds.left, offsetY: -bounds.top); + assert(_clipElement == null); + _clipElement = + html.Element.html(svgClipPath, treeSanitizer: _NullTreeSanitizer()); + domRenderer.append(rootElement, _clipElement); + domRenderer.setElementStyle( + rootElement, 'clip-path', 'url(#svgClip$_clipIdCounter)'); + domRenderer.setElementStyle( + rootElement, '-webkit-clip-path', 'url(#svgClip$_clipIdCounter)'); + final html.CssStyleDeclaration rootElementStyle = rootElement.style; + rootElementStyle + ..overflow = '' + ..transform = 'translate(${bounds.left}px, ${bounds.top}px)' + ..width = '${bounds.width}px' + ..height = '${bounds.height}px' + ..borderRadius = ''; + childContainer.style.transform = + 'translate(${-bounds.left}px, ${-bounds.top}px)'; + } + + @override + void update(PersistedPhysicalShape oldSurface) { + super.update(oldSurface); + if (oldSurface.color != color) { + _applyColor(); + } + if (oldSurface.elevation != elevation || + oldSurface.shadowColor != shadowColor) { + _applyShadow(); + } + if (oldSurface.path != path) { + oldSurface._clipElement?.remove(); + // Reset style on prior element since we may have switched between + // rect/rrect and arbitrary path. + final html.CssStyleDeclaration style = rootElement.style; + style.transform = ''; + style.borderRadius = ''; + domRenderer.setElementStyle(rootElement, 'clip-path', ''); + domRenderer.setElementStyle(rootElement, '-webkit-clip-path', ''); + _applyShape(); + } else { + _clipElement = oldSurface._clipElement; + } + oldSurface._clipElement = null; + } +} + +/// A surface that clips it's children. +class PersistedClipPath extends PersistedContainerSurface + implements ui.ClipPathEngineLayer { + PersistedClipPath( + PersistedClipPath oldLayer, this.clipPath, this.clipBehavior) + : super(oldLayer); + + final ui.Path clipPath; + final ui.Clip clipBehavior; + html.Element _clipElement; + + @override + html.Element createElement() { + return defaultCreateElement('flt-clippath'); + } + + @override + void apply() { + if (clipPath == null) { + if (_clipElement != null) { + domRenderer.setElementStyle(childContainer, 'clip-path', ''); + domRenderer.setElementStyle(childContainer, '-webkit-clip-path', ''); + _clipElement.remove(); + _clipElement = null; + } + return; + } + final String svgClipPath = _pathToSvgClipPath(clipPath); + _clipElement?.remove(); + _clipElement = + html.Element.html(svgClipPath, treeSanitizer: _NullTreeSanitizer()); + domRenderer.append(childContainer, _clipElement); + domRenderer.setElementStyle( + childContainer, 'clip-path', 'url(#svgClip$_clipIdCounter)'); + domRenderer.setElementStyle( + childContainer, '-webkit-clip-path', 'url(#svgClip$_clipIdCounter)'); + } + + @override + void update(PersistedClipPath oldSurface) { + super.update(oldSurface); + if (oldSurface.clipPath != clipPath) { + oldSurface._clipElement?.remove(); + apply(); + } else { + _clipElement = oldSurface._clipElement; + } + oldSurface._clipElement = null; + } + + @override + void discard() { + _clipElement?.remove(); + _clipElement = null; + super.discard(); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/debug_canvas_reuse_overlay.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/debug_canvas_reuse_overlay.dart new file mode 100644 index 0000000000..0e51637e7c --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/debug_canvas_reuse_overlay.dart @@ -0,0 +1,139 @@ +// 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; + +html.HtmlElement _createContainer() { + final html.HtmlElement container = html.DivElement(); + container.style + ..position = 'fixed' + ..top = '0' + ..right = '0' + ..padding = '6px' + ..color = '#fff' + ..backgroundColor = '#000' + ..opacity = '0.8'; + return container; +} + +/// An overlay in the top right corner of the page that shows statistics +/// regarding canvas reuse. +/// +/// This should only be used for development purposes and never included in +/// release builds. +class DebugCanvasReuseOverlay { + DebugCanvasReuseOverlay._() { + final html.HtmlElement container = _createContainer(); + final html.HtmlElement title = html.DivElement(); + title.style + ..fontWeight = 'bold' + ..textDecoration = 'underline'; + title.text = 'Canvas Reuse'; + + html.document.body.append( + container + ..append(title) + ..append( + html.DivElement() + ..appendText('Created: ') + ..append(_created), + ) + ..append( + html.DivElement() + ..appendText('Kept: ') + ..append(_kept), + ) + ..append( + html.DivElement() + ..appendText('Reused: ') + ..append(_reused), + ) + ..append( + html.DivElement() + ..appendText('Disposed: ') + ..append(_disposed), + ) + ..append( + html.DivElement() + ..appendText('In Recycle List: ') + ..append(_inRecycle), + ) + ..append( + html.DivElement() + ..append( + html.ButtonElement() + ..text = 'Reset' + ..addEventListener('click', (_) => _reset()), + ), + ), + ); + } + + static DebugCanvasReuseOverlay _instance; + static DebugCanvasReuseOverlay get instance { + if (_instance == null) { + // Only call the constructor when assertions are enabled to guard against + // mistakingly including this class in a release build. + if (assertionsEnabled) { + _instance = DebugCanvasReuseOverlay._(); + } + } + return _instance; + } + + final html.Text _created = html.Text('0'); + final html.Text _kept = html.Text('0'); + final html.Text _reused = html.Text('0'); + final html.Text _disposed = html.Text('0'); + final html.Text _inRecycle = html.Text('0'); + + int _createdCount = 0; + int get createdCount => _createdCount; + set createdCount(int createdCount) { + _createdCount = createdCount; + _update(); + } + + int _keptCount = 0; + int get keptCount => _keptCount; + set keptCount(int keptCount) { + _keptCount = keptCount; + _update(); + } + + int _reusedCount = 0; + int get reusedCount => _reusedCount; + set reusedCount(int reusedCount) { + _reusedCount = reusedCount; + _update(); + } + + int _disposedCount = 0; + int get disposedCount => _disposedCount; + set disposedCount(int disposedCount) { + _disposedCount = disposedCount; + _update(); + } + + int _inRecycleCount = 0; + int get inRecycleCount => _inRecycleCount; + set inRecycleCount(int inRecycleCount) { + _inRecycleCount = inRecycleCount; + _update(); + } + + void _update() { + _created.text = '$_createdCount'; + _kept.text = '$_keptCount'; + _reused.text = '$_reusedCount'; + _disposed.text = '$_disposedCount'; + _inRecycle.text = '$_inRecycleCount'; + } + + void _reset() { + _createdCount = + _keptCount = _reusedCount = _disposedCount = _inRecycleCount = 0; + _update(); + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/offset.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/offset.dart new file mode 100644 index 0000000000..a239b8b3f4 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/offset.dart @@ -0,0 +1,46 @@ +// 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; + +/// A surface that translates its children using CSS transform and translate. +class PersistedOffset extends PersistedContainerSurface + implements ui.OffsetEngineLayer { + PersistedOffset(PersistedOffset oldLayer, this.dx, this.dy) : super(oldLayer); + + /// Horizontal displacement. + final double dx; + + /// Vertical displacement. + final double dy; + + @override + void recomputeTransformAndClip() { + _transform = parent._transform; + if (dx != 0.0 || dy != 0.0) { + _transform = _transform.clone(); + _transform.translate(dx, dy); + } + _globalClip = parent._globalClip; + } + + @override + html.Element createElement() { + return defaultCreateElement('flt-offset')..style.transformOrigin = '0 0 0'; + } + + @override + void apply() { + rootElement.style.transform = 'translate(${dx}px, ${dy}px)'; + } + + @override + void update(PersistedOffset oldSurface) { + super.update(oldSurface); + + if (oldSurface.dx != dx || oldSurface.dy != dy) { + apply(); + } + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/opacity.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/opacity.dart new file mode 100644 index 0000000000..4c304eb67b --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/opacity.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. + +part of engine; + +/// A surface that makes its children transparent. +class PersistedOpacity extends PersistedContainerSurface + implements ui.OpacityEngineLayer { + PersistedOpacity(PersistedOpacity oldLayer, this.alpha, this.offset) + : super(oldLayer); + + final int alpha; + final ui.Offset offset; + + @override + void recomputeTransformAndClip() { + _transform = parent._transform; + + final double dx = offset.dx; + final double dy = offset.dy; + + if (dx != 0.0 || dy != 0.0) { + _transform = _transform.clone(); + _transform.translate(dx, dy); + } + + _globalClip = parent._globalClip; + } + + @override + html.Element createElement() { + return defaultCreateElement('flt-opacity')..style.transformOrigin = '0 0 0'; + } + + @override + void apply() { + // TODO(yjbanov): evaluate using `filter: opacity(X)`. It is a longer string + // but it reportedly has better hardware acceleration, so may + // be worth the trade-off. + rootElement.style.opacity = '${alpha / 255}'; + rootElement.style.transform = 'translate(${offset.dx}px, ${offset.dy}px)'; + } + + @override + void update(PersistedOpacity oldSurface) { + super.update(oldSurface); + if (alpha != oldSurface.alpha || offset != oldSurface.offset) { + apply(); + } + } +} 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 new file mode 100644 index 0000000000..e9d55a1378 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/picture.dart @@ -0,0 +1,614 @@ +// 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; + +// TODO(yjbanov): this is currently very naive. We probably want to cache +// fewer large canvases than small canvases. We could also +// improve cache hit count if we did not require exact canvas +// size match, but instead could choose a canvas that's big +// enough. The optimal heuristic will need to be figured out. +// For example, we probably don't want to pick a full-screen +// canvas to draw a 10x10 picture. Let's revisit this after +// Harry's layer merging refactor. +/// The maximum number canvases cached. +const int _kCanvasCacheSize = 30; + +/// Canvases available for reuse, capped at [_kCanvasCacheSize]. +final List _recycledCanvases = []; + +/// A request to repaint a canvas. +/// +/// Paint requests are prioritized such that the larger pictures go first. This +/// makes canvas allocation more efficient by letting large pictures claim +/// larger recycled canvases. Otherwise, small pictures would claim the large +/// canvases forcing us to allocate new large canvases. +class _PaintRequest { + _PaintRequest({ + this.canvasSize, + this.paintCallback, + }) : assert(canvasSize != null), + assert(paintCallback != null); + + final ui.Size canvasSize; + final ui.VoidCallback paintCallback; +} + +/// Repaint requests produced by [PersistedPicture]s that actually paint on the +/// canvas. Painting is delayed until the layer tree is updated to maximize +/// the number of reusable canvases. +List<_PaintRequest> _paintQueue = <_PaintRequest>[]; + +void _recycleCanvas(EngineCanvas canvas) { + if (canvas is BitmapCanvas && canvas.isReusable()) { + _recycledCanvases.add(canvas); + if (_recycledCanvases.length > _kCanvasCacheSize) { + final BitmapCanvas removedCanvas = _recycledCanvases.removeAt(0); + removedCanvas.dispose(); + if (_debugShowCanvasReuseStats) { + DebugCanvasReuseOverlay.instance.disposedCount++; + } + } + if (_debugShowCanvasReuseStats) { + DebugCanvasReuseOverlay.instance.inRecycleCount = + _recycledCanvases.length; + } + } +} + +/// Signature of a function that instantiates a [PersistedPicture]. +typedef PersistedPictureFactory = PersistedPicture Function( + double dx, + double dy, + ui.Picture picture, + int hints, +); + +/// Function used by the [SceneBuilder] to instantiate a picture layer. +PersistedPictureFactory persistedPictureFactory = standardPictureFactory; + +/// Instantiates an implementation of a picture layer that uses DOM, CSS, and +/// 2D canvas for painting. +PersistedStandardPicture standardPictureFactory( + double dx, double dy, ui.Picture picture, int hints) { + return PersistedStandardPicture(dx, dy, picture, hints); +} + +/// Instantiates an implementation of a picture layer that uses CSS Paint API +/// (part of Houdini) for painting. +PersistedHoudiniPicture houdiniPictureFactory( + double dx, double dy, ui.Picture picture, int hints) { + return PersistedHoudiniPicture(dx, dy, picture, hints); +} + +class PersistedHoudiniPicture extends PersistedPicture { + PersistedHoudiniPicture(double dx, double dy, ui.Picture picture, int hints) + : super(dx, dy, picture, hints) { + if (!_cssPainterRegistered) { + _registerCssPainter(); + } + } + + static bool _cssPainterRegistered = false; + + @override + double matchForUpdate(PersistedPicture existingSurface) { + // Houdini is display list-based so all pictures are cheap to repaint. + // However, if the picture hasn't changed at all then it's completely + // free. + return existingSurface.picture == picture ? 0.0 : 1.0; + } + + static void _registerCssPainter() { + _cssPainterRegistered = true; + final dynamic css = js_util.getProperty(html.window, 'CSS'); + final dynamic paintWorklet = js_util.getProperty(css, 'paintWorklet'); + if (paintWorklet == null) { + html.window.console.warn( + 'WARNING: CSS.paintWorklet not available. Paint worklets are only ' + 'supported on sites served from https:// or http://localhost.'); + return; + } + js_util.callMethod( + paintWorklet, + 'addModule', + [ + '/packages/flutter_web/assets/houdini_painter.js', + ], + ); + } + + /// Houdini does not paint to bitmap. + @override + int get bitmapPixelCount => 0; + + @override + void applyPaint(EngineCanvas oldCanvas) { + _recycleCanvas(oldCanvas); + final HoudiniCanvas canvas = HoudiniCanvas(_optimalLocalCullRect); + _canvas = canvas; + domRenderer.clearDom(rootElement); + rootElement.append(_canvas.rootElement); + picture.recordingCanvas.apply(_canvas); + canvas.commit(); + } +} + +class PersistedStandardPicture extends PersistedPicture { + PersistedStandardPicture(double dx, double dy, ui.Picture picture, int hints) + : super(dx, dy, picture, hints); + + @override + double matchForUpdate(PersistedStandardPicture existingSurface) { + if (existingSurface.picture == picture) { + // Picture is the same, return perfect score. + return 0.0; + } + + if (!existingSurface.picture.recordingCanvas.didDraw) { + // The previous surface didn't draw anything and therefore has no + // resources to reuse. + return 1.0; + } + + final bool didRequireBitmap = + existingSurface.picture.recordingCanvas.hasArbitraryPaint; + final bool requiresBitmap = picture.recordingCanvas.hasArbitraryPaint; + if (didRequireBitmap != requiresBitmap) { + // Switching canvas types is always expensive. + return 1.0; + } else if (!requiresBitmap) { + // Currently DomCanvas is always expensive to repaint, as we always throw + // out all the DOM we rendered before. This may change in the future, at + // which point we may return other values here. + return 1.0; + } else { + final BitmapCanvas oldCanvas = existingSurface._canvas; + if (!_doesCanvasFitBounds(oldCanvas, _exactLocalCullRect)) { + // The canvas needs to be resized before painting. + return 1.0; + } else { + final double newPixelCount = + _exactLocalCullRect.size.width * _exactLocalCullRect.size.height; + final double oldPixelCount = + oldCanvas.size.width * oldCanvas.size.height; + + if (oldPixelCount == 0) { + return 1.0; + } + + final double pixelCountRatio = newPixelCount / oldPixelCount; + assert(0 <= pixelCountRatio && pixelCountRatio <= 1.0, + 'Invalid pixel count ratio $pixelCountRatio'); + return 1.0 - pixelCountRatio; + } + } + } + + @override + int get bitmapPixelCount { + if (_canvas is! BitmapCanvas) { + return 0; + } + + final BitmapCanvas bitmapCanvas = _canvas; + return bitmapCanvas.bitmapPixelCount; + } + + FrameReference _didApplyPaint = FrameReference(false); + + @override + void applyPaint(EngineCanvas oldCanvas) { + if (picture.recordingCanvas.hasArbitraryPaint) { + _applyBitmapPaint(oldCanvas); + } else { + _applyDomPaint(oldCanvas); + } + _didApplyPaint.value = true; + } + + void _applyDomPaint(EngineCanvas oldCanvas) { + _recycleCanvas(oldCanvas); + _canvas = DomCanvas(); + domRenderer.clearDom(rootElement); + rootElement.append(_canvas.rootElement); + picture.recordingCanvas.apply(_canvas); + } + + static bool _doesCanvasFitBounds(BitmapCanvas canvas, ui.Rect newBounds) { + assert(canvas != null); + assert(newBounds != null); + final ui.Rect canvasBounds = canvas.bounds; + assert(canvasBounds != null); + return canvasBounds.width >= newBounds.width && + canvasBounds.height >= newBounds.height; + } + + void _applyBitmapPaint(EngineCanvas oldCanvas) { + if (oldCanvas is BitmapCanvas && + _doesCanvasFitBounds(oldCanvas, _optimalLocalCullRect) && + oldCanvas.isReusable()) { + if (_debugShowCanvasReuseStats) { + DebugCanvasReuseOverlay.instance.keptCount++; + } + oldCanvas.bounds = _optimalLocalCullRect; + _canvas = oldCanvas; + _canvas.clear(); + picture.recordingCanvas.apply(_canvas); + } else { + // We can't use the old canvas because the size has changed, so we put + // it in a cache for later reuse. + _recycleCanvas(oldCanvas); + // We cannot paint immediately because not all canvases that we may be + // able to reuse have been released yet. So instead we enqueue this + // picture to be painted after the update cycle is done syncing the layer + // tree then reuse canvases that were freed up. + _paintQueue.add(_PaintRequest( + canvasSize: _optimalLocalCullRect.size, + paintCallback: () { + _canvas = _findOrCreateCanvas(_optimalLocalCullRect); + if (_debugExplainSurfaceStats) { + final BitmapCanvas bitmapCanvas = _canvas; + _surfaceStatsFor(this).paintPixelCount += + bitmapCanvas.bitmapPixelCount; + } + domRenderer.clearDom(rootElement); + rootElement.append(_canvas.rootElement); + _canvas.clear(); + picture.recordingCanvas.apply(_canvas); + }, + )); + } + } + + /// Attempts to reuse a canvas from the [_recycledCanvases]. Allocates a new + /// one if unable to reuse. + /// + /// The best recycled canvas is one that: + /// + /// - Fits the requested [canvasSize]. This is a hard requirement. Otherwise + /// we risk clipping the picture. + /// - Is the smallest among all possible reusable canvases. This makes canvas + /// reuse more efficient. + /// - Contains no more than twice the number of requested pixels. This makes + /// sure we do not use too much memory for small canvases. + BitmapCanvas _findOrCreateCanvas(ui.Rect bounds) { + final ui.Size canvasSize = bounds.size; + BitmapCanvas bestRecycledCanvas; + double lastPixelCount = double.infinity; + + for (int i = 0; i < _recycledCanvases.length; i++) { + final BitmapCanvas candidate = _recycledCanvases[i]; + if (!candidate.isReusable()) { + continue; + } + + final ui.Size candidateSize = candidate.size; + final double candidatePixelCount = + candidateSize.width * candidateSize.height; + + final bool fits = _doesCanvasFitBounds(candidate, bounds); + final bool isSmaller = candidatePixelCount < lastPixelCount; + if (fits && isSmaller) { + bestRecycledCanvas = candidate; + lastPixelCount = candidatePixelCount; + final bool fitsExactly = candidateSize.width == canvasSize.width && + candidateSize.height == canvasSize.height; + if (fitsExactly) { + // No need to keep looking any more. + break; + } + } + } + + if (bestRecycledCanvas != null) { + if (_debugExplainSurfaceStats) { + _surfaceStatsFor(this).reuseCanvasCount++; + } + _recycledCanvases.remove(bestRecycledCanvas); + if (_debugShowCanvasReuseStats) { + DebugCanvasReuseOverlay.instance.inRecycleCount = + _recycledCanvases.length; + } + if (_debugShowCanvasReuseStats) { + DebugCanvasReuseOverlay.instance.reusedCount++; + } + bestRecycledCanvas.bounds = bounds; + return bestRecycledCanvas; + } + + if (_debugShowCanvasReuseStats) { + DebugCanvasReuseOverlay.instance.createdCount++; + } + final BitmapCanvas canvas = BitmapCanvas(bounds); + if (_debugExplainSurfaceStats) { + _surfaceStatsFor(this) + ..allocateBitmapCanvasCount += 1 + ..allocatedBitmapSizeInPixels = + canvas.widthInBitmapPixels * canvas.heightInBitmapPixels; + } + return canvas; + } +} + +/// A surface that uses a combination of ``, `
` and `

` elements +/// to draw shapes and text. +abstract class PersistedPicture extends PersistedLeafSurface { + PersistedPicture(this.dx, this.dy, this.picture, this.hints) + : localPaintBounds = picture.recordingCanvas.computePaintBounds(); + + EngineCanvas _canvas; + + final double dx; + final double dy; + final ui.Picture picture; + final ui.Rect localPaintBounds; + final int hints; + + @override + html.Element createElement() { + return defaultCreateElement('flt-picture'); + } + + @override + void recomputeTransformAndClip() { + _transform = parent._transform; + if (dx != 0.0 || dy != 0.0) { + _transform = _transform.clone(); + _transform.translate(dx, dy); + } + _globalClip = parent._globalClip; + _computeExactCullRects(); + } + + /// The rectangle that contains all visible pixels drawn by [picture] inside + /// the current layer hierarchy in local coordinates. + /// + /// This value is a conservative estimate, i.e. it must be big enough to + /// contain everything that's visible, but it may be bigger than necessary. + /// Therefore it should not be used for clipping. It is meant to be used for + /// optimizing canvas allocation. + ui.Rect get optimalLocalCullRect => _optimalLocalCullRect; + ui.Rect _optimalLocalCullRect; + + /// Same as [optimalLocalCullRect] but in screen coordinate system. + ui.Rect get debugExactGlobalCullRect => _exactGlobalCullRect; + ui.Rect _exactGlobalCullRect; + + ui.Rect _exactLocalCullRect; + + /// Computes the canvas paint bounds based on the estimated paint bounds and + /// the scaling produced by transformations. + /// + /// Return `true` if the local cull rect changed, indicating that a repaint + /// may be required. Returns `false` otherwise. Global cull rect changes do + /// not necessarily incur repaints. For example, if the layer sub-tree was + /// translated from one frame to another we may not need to repaint, just + /// translate the canvas. + void _computeExactCullRects() { + assert(transform != null); + assert(localPaintBounds != null); + final ui.Rect globalPaintBounds = localClipRectToGlobalClip( + localClip: localPaintBounds, transform: transform); + + // The exact cull rect required in screen coordinates. + ui.Rect tightGlobalCullRect = globalPaintBounds.intersect(_globalClip); + + // The exact cull rect required in local coordinates. + ui.Rect tightLocalCullRect; + if (tightGlobalCullRect.width <= 0 || tightGlobalCullRect.height <= 0) { + tightGlobalCullRect = ui.Rect.zero; + tightLocalCullRect = ui.Rect.zero; + } else { + final Matrix4 invertedTransform = + Matrix4.fromFloat64List(Float64List(16)); + + // TODO(yjbanov): When we move to our own vector math library, rewrite + // this to check for the case of simple transform before + // inverting. Inversion of simple transforms can be made + // much cheaper. + final double det = invertedTransform.copyInverse(transform); + if (det == 0) { + // Determinant is zero, which means the transform is not invertible. + tightGlobalCullRect = ui.Rect.zero; + tightLocalCullRect = ui.Rect.zero; + } else { + tightLocalCullRect = localClipRectToGlobalClip( + localClip: tightGlobalCullRect, transform: invertedTransform); + } + } + + assert(tightLocalCullRect != null); + _exactLocalCullRect = tightLocalCullRect; + _exactGlobalCullRect = tightGlobalCullRect; + } + + bool _computeOptimalCullRect(PersistedPicture oldSurface) { + assert(_exactLocalCullRect != null); + + if (oldSurface == null || !oldSurface.picture.recordingCanvas.didDraw) { + // First useful paint. + _optimalLocalCullRect = _exactLocalCullRect; + return true; + } + + assert(oldSurface._optimalLocalCullRect != null); + + final bool surfaceBeingRetained = identical(oldSurface, this); + final ui.Rect oldOptimalLocalCullRect = surfaceBeingRetained + ? _optimalLocalCullRect + : oldSurface._optimalLocalCullRect; + + if (_exactLocalCullRect == ui.Rect.zero) { + // The clip collapsed into a zero-sized rectangle. If it was already zero, + // no need to signal cull rect change. + _optimalLocalCullRect = ui.Rect.zero; + return oldOptimalLocalCullRect != ui.Rect.zero; + } + + if (rectContainsOther(oldOptimalLocalCullRect, _exactLocalCullRect)) { + // The cull rect we computed in the past contains the newly computed cull + // rect. This can happen, for example, when the picture is being shrunk by + // a clip when it is scrolled out of the screen. In this case we do not + // repaint the picture. We just let it be shrunk by the outer clip. + _optimalLocalCullRect = oldOptimalLocalCullRect; + return false; + } + + // The new cull rect contains area not covered by a previous rect. Perhaps + // the clip is growing, moving around the picture, or both. In this case + // a part of the picture may not been painted. We will need to + // request a new canvas and paint the picture on it. However, this is also + // a strong signal that the clip will continue growing as typically + // Flutter uses animated transitions. So instead of allocating the canvas + // the size of the currently visible area, we try to allocate a canvas of + // a bigger size. This will prevent any further repaints as future frames + // will hit the above case where the new cull rect is fully contained + // within the cull rect we compute now. + + // If any of the borders moved. + // TODO(yjbanov): consider switching to Mouad's snap-to-10px strategy. It + // might be sufficient, if not more effective. + const double kPredictedGrowthFactor = 3.0; + final double leftwardTrend = kPredictedGrowthFactor * + math.max(oldOptimalLocalCullRect.left - _exactLocalCullRect.left, 0); + final double upwardTrend = kPredictedGrowthFactor * + math.max(oldOptimalLocalCullRect.top - _exactLocalCullRect.top, 0); + final double rightwardTrend = kPredictedGrowthFactor * + math.max(_exactLocalCullRect.right - oldOptimalLocalCullRect.right, 0); + final double bottomwardTrend = kPredictedGrowthFactor * + math.max( + _exactLocalCullRect.bottom - oldOptimalLocalCullRect.bottom, 0); + + final ui.Rect newLocalCullRect = ui.Rect.fromLTRB( + oldOptimalLocalCullRect.left - leftwardTrend, + oldOptimalLocalCullRect.top - upwardTrend, + oldOptimalLocalCullRect.right + rightwardTrend, + oldOptimalLocalCullRect.bottom + bottomwardTrend, + ).intersect(localPaintBounds); + + final bool localCullRectChanged = _optimalLocalCullRect != newLocalCullRect; + _optimalLocalCullRect = newLocalCullRect; + return localCullRectChanged; + } + + /// Number of bitmap pixel painted by this picture. + /// + /// If the implementation does not paint onto a bitmap canvas, it should + /// return zero. + int get bitmapPixelCount; + + void _applyPaint(PersistedPicture oldSurface) { + final EngineCanvas oldCanvas = oldSurface?._canvas; + if (!picture.recordingCanvas.didDraw) { + _recycleCanvas(oldCanvas); + domRenderer.clearDom(rootElement); + return; + } + + if (_debugExplainSurfaceStats) { + _surfaceStatsFor(this).paintCount++; + } + + assert(_optimalLocalCullRect != null); + applyPaint(oldCanvas); + } + + /// Concrete implementations implement this method to do actual painting. + void applyPaint(EngineCanvas oldCanvas); + + void _applyTranslate() { + rootElement.style.transform = 'translate(${dx}px, ${dy}px)'; + } + + @override + void apply() { + _applyTranslate(); + _applyPaint(null); + } + + @override + void build() { + _computeOptimalCullRect(null); + super.build(); + } + + @override + void update(PersistedPicture oldSurface) { + super.update(oldSurface); + + if (dx != oldSurface.dx || dy != oldSurface.dy) { + _applyTranslate(); + } + + final bool cullRectChangeRequiresRepaint = + _computeOptimalCullRect(oldSurface); + if (identical(picture, oldSurface.picture)) { + // The picture is the same. Attempt to avoid repaint. + if (cullRectChangeRequiresRepaint) { + // Cull rect changed such that a repaint is still necessary. + _applyPaint(oldSurface); + } else { + // Cull rect did not change, or changed such in a way that does not + // require a repaint (e.g. it shrunk). + _canvas = oldSurface._canvas; + } + } else { + // We have a new picture. Repaint. + _applyPaint(oldSurface); + } + } + + @override + void retain() { + super.retain(); + final bool cullRectChangeRequiresRepaint = _computeOptimalCullRect(this); + if (cullRectChangeRequiresRepaint) { + _applyPaint(this); + } + } + + @override + void discard() { + _recycleCanvas(_canvas); + super.discard(); + } + + @override + void debugPrintChildren(StringBuffer buffer, int indent) { + super.debugPrintChildren(buffer, indent); + if (rootElement != null && rootElement.firstChild != null) { + final html.Element firstChild = rootElement.firstChild; + final String canvasTag = firstChild.tagName.toLowerCase(); + final int canvasHash = rootElement.firstChild.hashCode; + buffer.writeln('${' ' * (indent + 1)}<$canvasTag @$canvasHash />'); + } else if (rootElement != null) { + buffer.writeln( + '${' ' * (indent + 1)}<${rootElement.tagName.toLowerCase()} @$hashCode />'); + } else { + buffer.writeln('${' ' * (indent + 1)}'); + } + } + + @override + void debugValidate(List validationErrors) { + super.debugValidate(validationErrors); + + if (picture.recordingCanvas.didDraw) { + if (_canvas == null) { + validationErrors + .add('$runtimeType has non-trivial picture but it has null canvas'); + } + if (_optimalLocalCullRect == null) { + validationErrors.add('$runtimeType has null _optimalLocalCullRect'); + } + if (_exactGlobalCullRect == null) { + validationErrors.add('$runtimeType has null _exactGlobalCullRect'); + } + if (_exactLocalCullRect == null) { + validationErrors.add('$runtimeType has null _exactLocalCullRect'); + } + } + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/platform_view.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/platform_view.dart new file mode 100644 index 0000000000..ed470233b9 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/platform_view.dart @@ -0,0 +1,68 @@ +// 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; + +/// A surface containing a platform view, which is an HTML element. +class PersistedPlatformView extends PersistedLeafSurface { + final int viewId; + final double dx; + final double dy; + final double width; + final double height; + + html.HtmlElement _hostElement; + html.ShadowRoot _shadowRoot; + + PersistedPlatformView(this.viewId, this.dx, this.dy, this.width, this.height); + + @override + html.Element createElement() { + _hostElement = defaultCreateElement('flt-platform-view'); + + // Allow the platform view host element to receive pointer events. + // + // This is to allow platform view HTML elements to be interactive. + // + // ACCESSIBILITY NOTE: The way we enable accessibility on Flutter for web + // is to have a full-page button which waits for a double tap. Placing this + // full-page button in front of the scene would cause platform views not + // to receive pointer events. The tradeoff is that by placing the scene in + // front of the semantics placeholder will cause platform views to block + // pointer events from reaching the placeholder. This means that in order + // to enable accessibility, you must double tap the app *outside of a + // platform view*. As a consequence, a full-screen platform view will make + // it impossible to enable accessibility. + _hostElement.style.pointerEvents = 'auto'; + + _shadowRoot = _hostElement.attachShadow({'mode': 'open'}); + final html.StyleElement _styleReset = html.StyleElement(); + _styleReset.innerHtml = ''' + :host { + all: initial; + }'''; + _shadowRoot.append(_styleReset); + final html.Element platformView = + platformViewRegistry.getCreatedView(viewId); + if (platformView != null) { + _shadowRoot.append(platformView); + } else { + html.window.console.warn('No platform view created for id $viewId'); + } + return _hostElement; + } + + @override + void apply() { + _hostElement.style + ..transform = 'translate(${dx}px, ${dy}px)' + ..width = '${width}px' + ..height = '${height}px'; + } + + @override + double matchForUpdate(PersistedPlatformView existingSurface) { + return existingSurface.viewId == viewId ? 0.0 : 1.0; + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/scene.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/scene.dart new file mode 100644 index 0000000000..5d396a63aa --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/scene.dart @@ -0,0 +1,31 @@ +// 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; + +/// A surface that creates a DOM element for whole app. +class PersistedScene extends PersistedContainerSurface { + PersistedScene(PersistedScene oldLayer) : super(oldLayer) { + _transform = Matrix4.identity(); + } + + @override + void recomputeTransformAndClip() { + // The scene clip is the size of the entire window. + // TODO(yjbanov): in the add2app scenario where we might be hosted inside + // a custom element, this will be different. We will need to + // update this code when we add add2app support. + final double screenWidth = html.window.innerWidth.toDouble(); + final double screenHeight = html.window.innerHeight.toDouble(); + _globalClip = ui.Rect.fromLTRB(0, 0, screenWidth, screenHeight); + } + + @override + html.Element createElement() { + return defaultCreateElement('flt-scene'); + } + + @override + void apply() {} +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/surface.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/surface.dart new file mode 100644 index 0000000000..da75a9c599 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/surface.dart @@ -0,0 +1,1368 @@ +// 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; + +/// When `true` prints statistics about what happened to the surface tree when +/// it was composited. +/// +/// Also paints an on-screen overlay with the numbers visualized as a timeline. +const bool _debugExplainSurfaceStats = false; + +/// When `true` shows an overlay that contains stats about canvas reuse. +/// +/// The overlay also includes a button to reset the stats. +const bool _debugShowCanvasReuseStats = false; + +/// When `true` renders the outlines of clip layers on the screen instead of +/// clipping the contents. +/// +/// This is useful when visually debugging clipping behavior. +bool debugShowClipLayers = false; + +/// The threshold for the canvas pixel count to screen pixel count ratio, beyond +/// which in debug mode a warning is issued to the console. +/// +/// As we improve canvas utilization we should decrease this number. It is +/// unlikely that we will hit 1.0, but something around 3.0 should be +/// reasonable. +const double _kScreenPixelRatioWarningThreshold = 6.0; + +/// A monotonically increasing frame number being rendered. +/// +/// Used for debugging only. +int _debugFrameNumber = 1; + +List> _frameReferences = >[]; + +/// A temporary reference to a value of type [V]. +/// +/// The value automatically gets set to null after the current frame is +/// rendered. +/// +/// It is useful to think of this as a weak reference that's scoped to a +/// single frame. +class FrameReference { + /// Creates a frame reference to a value. + FrameReference([this.value]) { + _frameReferences.add(this); + } + + /// The current value of this reference. + V value; +} + +/// Performs any outstanding painting work enqueued by [PersistedPicture]s. +void commitScene(PersistedScene scene) { + if (_paintQueue.isNotEmpty) { + if (_paintQueue.length > 1) { + // Sort paint requests in decreasing canvas size order. Paint requests + // attempt to reuse canvases. For efficiency we want the biggest pictures + // to find canvases before the smaller ones claim them. + _paintQueue.sort((_PaintRequest a, _PaintRequest b) { + final double aSize = a.canvasSize.height * a.canvasSize.width; + final double bSize = b.canvasSize.height * b.canvasSize.width; + return bSize.compareTo(aSize); + }); + } + + for (_PaintRequest request in _paintQueue) { + request.paintCallback(); + } + _paintQueue = <_PaintRequest>[]; + } + + // After the update the retained surfaces are back to active. + if (_retainedSurfaces.isNotEmpty) { + for (int i = 0; i < _retainedSurfaces.length; i++) { + final PersistedSurface retainedSurface = _retainedSurfaces[i]; + assert(retainedSurface.isPendingRetention); + retainedSurface.state = PersistedSurfaceState.active; + } + _retainedSurfaces = []; + } + if (_debugExplainSurfaceStats) { + _debugPrintSurfaceStats(scene, _debugFrameNumber); + _debugRepaintSurfaceStatsOverlay(scene); + } + assert(() { + final List validationErrors = []; + scene.debugValidate(validationErrors); + if (validationErrors.isNotEmpty) { + print('ENGINE LAYER TREE INCONSISTENT:\n' + '${validationErrors.map((String e) => ' - $e\n').join()}'); + } + return true; + }()); + + for (int i = 0; i < _frameReferences.length; i++) { + _frameReferences[i].value = null; + } + _frameReferences = >[]; + + if (_debugExplainSurfaceStats) { + _surfaceStats = {}; + } + assert(() { + _debugFrameNumber++; + return true; + }()); +} + +/// Discards information about previously rendered frames, including DOM +/// elements and cached canvases. +/// +/// After calling this function new canvases will be created for the +/// subsequent scene. This is useful when tests need predictable canvas +/// sizes. If the cache is not cleared, then canvases allocated in one test +/// may be reused in another test. +void debugForgetFrameScene() { + _clipIdCounter = 0; + _recycledCanvases.clear(); +} + +/// Surfaces that were retained this frame. +/// +/// Surfaces should be added to this list directly. Instead, if a surface needs +/// to be retained call [_retainSurface]. +List get debugRetainedSurfaces => _retainedSurfaces; +List _retainedSurfaces = []; + +/// Maps every surface currently active on the screen to debug statistics. +Map _surfaceStats = + {}; + +List> _surfaceStatsTimeline = + >[]; + +/// Returns debug statistics for the given [surface]. +_DebugSurfaceStats _surfaceStatsFor(PersistedSurface surface) { + if (!_debugExplainSurfaceStats) { + throw Exception( + '_surfaceStatsFor is only available when _debugExplainSurfaceStats is set to true.'); + } + return _surfaceStats.putIfAbsent(surface, () => _DebugSurfaceStats(surface)); +} + +/// Compositor information collected for one frame useful for assessing the +/// efficiency of constructing the frame. +/// +/// This information is only available in debug mode. +/// +/// For stats pertaining to a single surface the numeric counter fields are +/// typically either 0 or 1. For aggregated stats, the numbers can be >1. +class _DebugSurfaceStats { + _DebugSurfaceStats(this.surface); + + /// The surface these stats are for, or `null` if these are aggregated stats. + final PersistedSurface surface; + + /// How many times a surface was retained from a previously rendered frame. + int retainSurfaceCount = 0; + + /// How many times a surface reused an HTML element from a previously rendered + /// surface. + int reuseElementCount = 0; + + /// If a surface is a [PersistedPicture], how many times it painted. + int paintCount = 0; + + /// If a surface is a [PersistedPicture], how many pixels it painted. + int paintPixelCount = 0; + + /// If a surface is a [PersistedPicture], how many times it reused a + /// previously allocated `` element when it painted. + int reuseCanvasCount = 0; + + /// If a surface is a [PersistedPicture], how many times it allocated a new + /// bitmap canvas. + int allocateBitmapCanvasCount = 0; + + /// If a surface is a [PersistedPicture], how many pixels it allocated for + /// the bitmap. + /// + /// For aggregated stats, this is the total sum of all pixels across all + /// canvases. + int allocatedBitmapSizeInPixels = 0; + + /// The number of HTML DOM nodes a surface allocated. + /// + /// For aggregated stats, this is the total sum of all DOM nodes across all + /// surfaces. + int allocatedDomNodeCount = 0; + + /// Adds all counters of [oneSurfaceStats] into this object. + void aggregate(_DebugSurfaceStats oneSurfaceStats) { + retainSurfaceCount += oneSurfaceStats.retainSurfaceCount; + reuseElementCount += oneSurfaceStats.reuseElementCount; + paintCount += oneSurfaceStats.paintCount; + paintPixelCount += oneSurfaceStats.paintPixelCount; + reuseCanvasCount += oneSurfaceStats.reuseCanvasCount; + allocateBitmapCanvasCount += oneSurfaceStats.allocateBitmapCanvasCount; + allocatedBitmapSizeInPixels += oneSurfaceStats.allocatedBitmapSizeInPixels; + allocatedDomNodeCount += oneSurfaceStats.allocatedDomNodeCount; + } +} + +html.CanvasRenderingContext2D _debugSurfaceStatsOverlayCtx; + +void _debugRepaintSurfaceStatsOverlay(PersistedScene scene) { + final int overlayWidth = html.window.innerWidth; + const int rowHeight = 30; + const int rowCount = 4; + const int overlayHeight = rowHeight * rowCount; + const int strokeWidth = 2; + + _surfaceStatsTimeline.add(_surfaceStats); + + while (_surfaceStatsTimeline.length > (overlayWidth / strokeWidth)) { + _surfaceStatsTimeline.removeAt(0); + } + + if (_debugSurfaceStatsOverlayCtx == null) { + final html.CanvasElement _debugSurfaceStatsOverlay = html.CanvasElement( + width: overlayWidth, + height: overlayHeight, + ); + _debugSurfaceStatsOverlay.style + ..position = 'fixed' + ..left = '0' + ..top = '0' + ..zIndex = '1000' + ..opacity = '0.8'; + _debugSurfaceStatsOverlayCtx = _debugSurfaceStatsOverlay.context2D; + html.document.body.append(_debugSurfaceStatsOverlay); + } + + _debugSurfaceStatsOverlayCtx + ..fillStyle = 'black' + ..beginPath() + ..rect(0, 0, overlayWidth, overlayHeight) + ..fill(); + + final double physicalScreenWidth = + html.window.innerWidth * html.window.devicePixelRatio; + final double physicalScreenHeight = + html.window.innerHeight * html.window.devicePixelRatio; + final double physicsScreenPixelCount = + physicalScreenWidth * physicalScreenHeight; + + final int totalDomNodeCount = scene.rootElement.querySelectorAll('*').length; + + for (int i = 0; i < _surfaceStatsTimeline.length; i++) { + final Map statsMap = + _surfaceStatsTimeline[i]; + final _DebugSurfaceStats totals = _DebugSurfaceStats(null); + int pixelCount = 0; + for (_DebugSurfaceStats oneSurfaceStats in statsMap.values) { + totals.aggregate(oneSurfaceStats); + if (oneSurfaceStats.surface is PersistedPicture) { + final PersistedPicture picture = oneSurfaceStats.surface; + pixelCount += picture.bitmapPixelCount; + } + } + + final double repaintRate = totals.paintPixelCount / pixelCount; + final double domAllocationRate = + totals.allocatedDomNodeCount / totalDomNodeCount; + final double bitmapAllocationRate = + totals.allocatedBitmapSizeInPixels / physicsScreenPixelCount; + final double surfaceRetainRate = + totals.retainSurfaceCount / _surfaceStatsTimeline[i].length; + + // Repaints + _debugSurfaceStatsOverlayCtx + ..lineWidth = strokeWidth + ..strokeStyle = 'red' + ..beginPath() + ..moveTo(strokeWidth * i, rowHeight) + ..lineTo(strokeWidth * i, rowHeight * (1 - repaintRate)) + ..stroke(); + + // DOM allocations + _debugSurfaceStatsOverlayCtx + ..lineWidth = strokeWidth + ..strokeStyle = 'red' + ..beginPath() + ..moveTo(strokeWidth * i, 2 * rowHeight) + ..lineTo(strokeWidth * i, rowHeight * (2 - domAllocationRate)) + ..stroke(); + + // Bitmap allocations + _debugSurfaceStatsOverlayCtx + ..lineWidth = strokeWidth + ..strokeStyle = 'red' + ..beginPath() + ..moveTo(strokeWidth * i, 3 * rowHeight) + ..lineTo(strokeWidth * i, rowHeight * (3 - bitmapAllocationRate)) + ..stroke(); + + // Surface retentions + _debugSurfaceStatsOverlayCtx + ..lineWidth = strokeWidth + ..strokeStyle = 'green' + ..beginPath() + ..moveTo(strokeWidth * i, 4 * rowHeight) + ..lineTo(strokeWidth * i, rowHeight * (4 - surfaceRetainRate)) + ..stroke(); + } + + _debugSurfaceStatsOverlayCtx + ..font = 'normal normal 14px sans-serif' + ..fillStyle = 'white' + ..fillText('Repaint rate', 5, rowHeight - 5) + ..fillText('DOM alloc rate', 5, 2 * rowHeight - 5) + ..fillText('Bitmap alloc rate', 5, 3 * rowHeight - 5) + ..fillText('Retain rate', 5, 4 * rowHeight - 5); + + for (int i = 1; i <= rowCount; i++) { + _debugSurfaceStatsOverlayCtx + ..lineWidth = 1 + ..strokeStyle = 'blue' + ..beginPath() + ..moveTo(0, overlayHeight - rowHeight * i) + ..lineTo(overlayWidth, overlayHeight - rowHeight * i) + ..stroke(); + } +} + +/// Prints debug statistics for the current frame to the console. +void _debugPrintSurfaceStats(PersistedScene scene, int frameNumber) { + int pictureCount = 0; + int paintCount = 0; + + int bitmapCanvasCount = 0; + int bitmapReuseCount = 0; + int bitmapAllocationCount = 0; + int bitmapPaintCount = 0; + int bitmapPixelsAllocated = 0; + + int domCanvasCount = 0; + int domPaintCount = 0; + + int surfaceRetainCount = 0; + int elementReuseCount = 0; + + int totalAllocatedDomNodeCount = 0; + + void countReusesRecursively(PersistedSurface surface) { + final _DebugSurfaceStats stats = _surfaceStatsFor(surface); + assert(stats != null); + + surfaceRetainCount += stats.retainSurfaceCount; + elementReuseCount += stats.reuseElementCount; + totalAllocatedDomNodeCount += stats.allocatedDomNodeCount; + + if (surface is PersistedStandardPicture) { + pictureCount += 1; + paintCount += stats.paintCount; + + if (surface._canvas is DomCanvas) { + domCanvasCount++; + domPaintCount += stats.paintCount; + } + + if (surface._canvas is BitmapCanvas) { + bitmapCanvasCount++; + bitmapPaintCount += stats.paintCount; + } + + bitmapReuseCount += stats.reuseCanvasCount; + bitmapAllocationCount += stats.allocateBitmapCanvasCount; + bitmapPixelsAllocated += stats.allocatedBitmapSizeInPixels; + } + + surface.visitChildren(countReusesRecursively); + } + + scene.visitChildren(countReusesRecursively); + + final StringBuffer buf = StringBuffer(); + buf + ..writeln( + '---------------------- FRAME #$frameNumber -------------------------') + ..writeln('Surfaces retained: $surfaceRetainCount') + ..writeln('Elements reused: $elementReuseCount') + ..writeln('Elements allocated: $totalAllocatedDomNodeCount') + ..writeln('Pictures: $pictureCount') + ..writeln(' Painted: $paintCount') + ..writeln(' Skipped painting: ${pictureCount - paintCount}') + ..writeln('DOM canvases:') + ..writeln(' Painted: $domPaintCount') + ..writeln(' Skipped painting: ${domCanvasCount - domPaintCount}') + ..writeln('Bitmap canvases: $bitmapCanvasCount') + ..writeln(' Painted: $bitmapPaintCount') + ..writeln(' Skipped painting: ${bitmapCanvasCount - bitmapPaintCount}') + ..writeln(' Reused: $bitmapReuseCount') + ..writeln(' Allocated: $bitmapAllocationCount') + ..writeln(' Allocated pixels: $bitmapPixelsAllocated') + ..writeln(' Available for reuse: ${_recycledCanvases.length}'); + + // A microtask will fire after the DOM is flushed, letting us probe into + // actual tags. + scheduleMicrotask(() { + final List canvasElements = + html.document.querySelectorAll('canvas'); + final StringBuffer canvasInfo = StringBuffer(); + final int pixelCount = canvasElements + .cast() + .map((html.CanvasElement e) { + final int pixels = e.width * e.height; + canvasInfo.writeln(' - ${e.width} x ${e.height} = $pixels pixels'); + return pixels; + }).fold(0, (int total, int pixels) => total + pixels); + final double physicalScreenWidth = + html.window.innerWidth * html.window.devicePixelRatio; + final double physicalScreenHeight = + html.window.innerHeight * html.window.devicePixelRatio; + final double physicsScreenPixelCount = + physicalScreenWidth * physicalScreenHeight; + final double screenPixelRatio = pixelCount / physicsScreenPixelCount; + final String screenDescription = + '1 screen is $physicalScreenWidth x $physicalScreenHeight = $physicsScreenPixelCount pixels'; + final String canvasPixelDescription = + '$pixelCount (${screenPixelRatio.toStringAsFixed(2)} x screens'; + buf + ..writeln(' Elements: ${canvasElements.length}') + ..writeln(canvasInfo) + ..writeln(' Pixels: $canvasPixelDescription; $screenDescription)') + ..writeln('-----------------------------------------------------------'); + final bool screenPixelRatioTooHigh = + screenPixelRatio > _kScreenPixelRatioWarningThreshold; + if (screenPixelRatioTooHigh) { + print( + 'WARNING: pixel/screen ratio too high (${screenPixelRatio.toStringAsFixed(2)}x)'); + } + print(buf); + }); +} + +/// Signature of a function that receives a [PersistedSurface]. +/// +/// This is used to traverse surfaces using [PersistedSurface.visitChildren]. +typedef PersistedSurfaceVisitor = void Function(PersistedSurface); + +/// Controls the algorithm used to reuse a previously rendered surface. +enum PersistedSurfaceState { + /// A new or revived surface that does not have a + /// [PersistedSurface.rootElement]. + /// + /// Surfaces in this state acquire an element either by creating a new element + /// or by adopting an element from an [active] surface. + created, + + /// The surface has DOM resources that are attached to the live DOM tree. + /// + /// During update surfaces in this state come from the previous frame. This is + /// also the state that all surfaces that are attached to the new frame's + /// scene acquire at the end of the frame. + /// + /// In this state the surface has a non-null [PersistedSurface.rootElement]. + /// The element may be adopted by a new surface by matching to it during + /// update (see [PersistedSurface.matchForUpdate]). + active, + + /// The surface object will be reused along with all its descendants. + /// + /// This strategy relies on Flutter's retained-mode layer system (see + /// [EngineLayer]). + pendingRetention, + + /// The surface's DOM elements will be reused and updated. + /// + /// The surface in this state must have been rendered in a previous frame, it + /// must have non-null [PersistedSurface.rootElement], and there must be a new + /// surface that points to this surface via + /// [PersistedContainerSurface.oldLayer]. The new surface will adopt this + /// surface's DOM elements and update them. + pendingUpdate, + + /// This state indicates that all DOM resources of this surface have been + /// released and cannot be reused anymore. + /// + /// There are two ways a surface may be released: + /// + /// - When the surface is updated its DOM elements are adopted by a new + /// surface. This can happen either via [PersistedContainerSurface.oldLayer] + /// or by matching. + /// - When the surface is removed from the tree because it is no longer in the + /// scene, nor its elements are reused by another surface. + /// + /// A surface may be revived from this state back into [created] state via + /// [PersistedSurface.revive]. + released, +} + +/// A node in the tree built by [SceneBuilder] that contains information used to +/// compute the fewest amount of mutations necessary to update the browser DOM. +abstract class PersistedSurface implements ui.EngineLayer { + /// Creates a persisted surface. + PersistedSurface(); + + /// Controls the algorithm that reuses the DOM resources owned by this + /// surface. + PersistedSurfaceState get state => _state; + set state(PersistedSurfaceState newState) { + assert(newState != null); + assert(newState != _state, + 'Attempted to set state that the surface is already in. This likely indicates a bug in the compositor.'); + assert(_debugValidateStateTransition(newState)); + _state = newState; + } + + PersistedSurfaceState _state = PersistedSurfaceState.created; + + bool _debugValidateStateTransition(PersistedSurfaceState newState) { + if (newState == PersistedSurfaceState.created) { + assert(isReleased, 'Only released surfaces may be revived.'); + } else { + assert(!isReleased, + 'Released surfaces may only be revived, but caught attempt to set $newState.'); + } + if (newState == PersistedSurfaceState.active) { + assert( + isCreated || isPendingRetention || isPendingUpdate, + 'Surface is $state. Only created, pending retention, and pending update surfaces may be activated.', + ); + } + if (newState == PersistedSurfaceState.pendingRetention) { + assert(isActive, + 'Surface is not active. Only active surfaces may be retained.'); + } + if (newState == PersistedSurfaceState.pendingUpdate) { + assert(isActive, + 'Surface is not active. Only active surfaces may be updated.'); + } + if (newState == PersistedSurfaceState.released) { + assert(isActive || isPendingUpdate, + 'A surface may only be released if it is currently active or pending update, but it is in $state.'); + } + return true; + } + + /// Attempts to retain this surface along with its descendants. + /// + /// If the surface is currently active this surface is retained. If the + /// surface is released, it means that the surface's DOM resources have been + /// reused before the request to retain it came in. In this case, the surface + /// is [revive]d and rebuilt from scratch. + void tryRetain() { + assert(isActive || isReleased); + // Request that the layer is retained, but only if it's still active. It + // could have been released. + if (isActive) { + state = PersistedSurfaceState.pendingRetention; + } else { + // The surface is released. This means that by the time addRetained was + // called this surface's DOM elements have been reused for something else. + // In this case, we reset the surface back to "created" state. + revive(); + } + } + + /// Turns a previously released surface and all its descendants into a + /// [PersistedSurfaceState.created] one. + /// + /// This is used to rebuild surfaces that were released before a request to + /// retain came in. + @mustCallSuper + @visibleForTesting + @protected + void revive() { + assert(isReleased); + state = PersistedSurfaceState.created; + } + + /// The surface is in the [PersistedSurfaceState.created] state; + bool get isCreated => _state == PersistedSurfaceState.created; + + /// The surface is in the [PersistedSurfaceState.active] state; + bool get isActive => _state == PersistedSurfaceState.active; + + /// The surface is in the [PersistedSurfaceState.pendingRetention] state; + bool get isPendingRetention => + _state == PersistedSurfaceState.pendingRetention; + + /// The surface is in the [PersistedSurfaceState.pendingUpdate] state; + bool get isPendingUpdate => _state == PersistedSurfaceState.pendingUpdate; + + /// The surface is in the [PersistedSurfaceState.released] state; + bool get isReleased => _state == PersistedSurfaceState.released; + + /// The root element that renders this surface to the DOM. + /// + /// This element can be reused across frames. See also, [childContainer], + /// which is the element used to manage child nodes. + html.Element rootElement; + + /// Whether this surface can update an existing [oldSurface]. + bool canUpdateAsMatch(PersistedSurface oldSurface) { + return oldSurface.isActive && runtimeType == oldSurface.runtimeType; + } + + /// The element that contains child surface elements. + /// + /// By default this is the same as the [rootElement]. However, specialized + /// surface implementations may choose to override this and provide a + /// different element for nesting children. + html.Element get childContainer => rootElement; + + /// This surface's immediate parent. + PersistedContainerSurface parent; + + /// Visits immediate children. + /// + /// Does not recurse. + void visitChildren(PersistedSurfaceVisitor visitor); + + /// Computes how expensive it would be to update an [existingSurface]'s DOM + /// resources using this surface's data. + /// + /// The returned value is a score between 0.0 and 1.0, inclusive. 0.0 is the + /// perfect score, meaning that the update is free. 1.0 is the worst score, + /// indicating that the DOM resources cannot be reused, and if an update is + /// performed, will result in reallocation. + /// + /// Values that fall strictly between 0.0 and 1.0 are used to communicate + /// the efficiency of updates, with lower scores having better efficiency + /// compared to higher scores. For example, when matching a picture with a + /// bitmap canvas the score is higher for a canvas that's bigger in size than + /// a smaller canvas that also fits the picture. + double matchForUpdate(covariant PersistedSurface existingSurface); + + /// Creates a new element and sets the necessary HTML and CSS attributes. + /// + /// This is called when we failed to locate an existing DOM element to reuse, + /// such as on the very first frame. + @protected + @mustCallSuper + void build() { + assert(rootElement == null); + assert(isCreated); + rootElement = createElement(); + if (_debugExplainSurfaceStats) { + _surfaceStatsFor(this).allocatedDomNodeCount++; + } + apply(); + state = PersistedSurfaceState.active; + } + + /// Instructs this surface to adopt HTML DOM elements of another surface. + /// + /// This is done for efficiency. Instead of creating new DOM elements on every + /// frame, we reuse old ones as much as possible. This method should only be + /// called when [isTotalMatchFor] returns true for the [oldSurface]. Otherwise + /// adopting the [oldSurface]'s elements could lead to correctness issues. + @protected + @mustCallSuper + void adoptElements(covariant PersistedSurface oldSurface) { + assert(oldSurface.rootElement != null); + assert(oldSurface.isActive || oldSurface.isPendingUpdate); + assert(() { + if (oldSurface.isPendingUpdate) { + final PersistedContainerSurface self = this; + assert(identical(self.oldLayer, oldSurface)); + } + return true; + }()); + rootElement = oldSurface.rootElement; + if (_debugExplainSurfaceStats) { + _surfaceStatsFor(this).reuseElementCount++; + } + + // We took ownership of the old element. + oldSurface.rootElement = null; + // Make sure the old surface object is no longer usable. + oldSurface.state = PersistedSurfaceState.released; + } + + /// Updates the attributes of this surface's element. + /// + /// Attempts to reuse [oldSurface]'s DOM element, if possible. Otherwise, + /// creates a new element by calling [build]. + @protected + @mustCallSuper + void update(covariant PersistedSurface oldSurface) { + assert(oldSurface != null); + assert(!identical(oldSurface, this)); + assert(isCreated && (oldSurface.isPendingUpdate || oldSurface.isActive)); + + adoptElements(oldSurface); + + if (assertionsEnabled) { + rootElement.setAttribute('flt-layer-state', 'updated'); + } + state = PersistedSurfaceState.active; + assert(rootElement != null); + } + + /// Reuses a [PersistedSurface] rendered in the previous frame. + /// + /// This is different from [update], which reuses another surface's elements, + /// i.e. it was not requested to be retained by the framework. + /// + /// This is also different from [build], which constructs a brand new surface + /// sub-tree. + @protected + @mustCallSuper + void retain() { + assert(rootElement != null); + if (isPendingRetention) { + // Adding to the list of retained surfaces so that at the end of the frame + // it is set to active state. We do not set the state to active + // immediately. Otherwise, another surface could match on it and steal + // this surface's DOM elements. + _retainedSurfaces.add(this); + } + if (assertionsEnabled) { + rootElement.setAttribute('flt-layer-state', 'retained'); + } + if (_debugExplainSurfaceStats) { + _surfaceStatsFor(this).retainSurfaceCount++; + } + } + + /// Removes the [element] of this surface from the tree and makes this + /// surface released. + /// + /// This method may be overridden by concrete implementations, for example, to + /// recycle the resources owned by this surface. + @protected + @mustCallSuper + void discard() { + assert(isActive); + assert(rootElement != null); + // TODO(yjbanov): it may be wasteful to recursively disassemble the DOM tree + // node by node. It should be sufficient to detach the root + // of the tree and let the browser handle the rest. Note, + // element.isConnected might be a poor choice to drive this + // decision because it is sensitive to the timing of when a + // scene's element is attached to the document. We might want + // to use a custom tracking mechanism, such as pass a boolean + // to `discard`, which would be `true` for the root, and + // `false` for children. Or, which might be cleaner, we could + // split this method into two methods. One method will detach + // the DOM, and the second method will disassociate the + // surface from the the DOM and release it irrespective of + // whether the DOM itself gets detached or not. + rootElement.remove(); + rootElement = null; + state = PersistedSurfaceState.released; + } + + @protected + @mustCallSuper + void debugValidate(List validationErrors) { + if (rootElement == null) { + validationErrors.add('${debugIdentify(this)} has null rootElement.'); + } + if (!isActive) { + validationErrors.add('${debugIdentify(this)} is in the wrong state.\n' + 'It is in the live DOM tree expectec to be in ${PersistedSurfaceState.active}.\n' + 'However, it is currently in $state.'); + } + } + + /// Creates a DOM element for this surface. + html.Element createElement(); + + /// Creates a DOM element for this surface preconfigured with common + /// attributes, such as absolute positioning and debug information. + html.Element defaultCreateElement(String tagName) { + final html.Element element = html.Element.tag(tagName); + element.style.position = 'absolute'; + if (assertionsEnabled) { + element.setAttribute('flt-layer-state', 'new'); + } + return element; + } + + /// Sets the HTML and CSS properties appropriate for this surface's + /// implementation. + /// + /// For example, [PersistedTransform] sets the "transform" CSS attribute. + void apply(); + + /// The effective transform at this surface level. + /// + /// This value is computed by concatenating transforms of all ancestor + /// transforms as well as this layer's transform (if any). + /// + /// The value is update by [recomputeTransformAndClip]. + Matrix4 get transform => _transform; + Matrix4 _transform; + + /// The intersection at this surface level. + /// + /// This value is the intersection of clips in the ancestor chain, including + /// the clip added by this layer (if any). + /// + /// The value is update by [recomputeTransformAndClip]. + ui.Rect get globalClip => _globalClip; + ui.Rect _globalClip; + + /// Recomputes [transform] and [globalClip] fields. + /// + /// The default implementation inherits the values from the parent. Concrete + /// surface implementations may override this with their custom transform and + /// clip behaviors. + /// + /// This method is called by the [preroll] method. + @protected + void recomputeTransformAndClip() { + _transform = parent._transform; + _globalClip = parent._globalClip; + } + + /// Performs computations before [build], [update], or [retain] are called. + /// + /// The computations prepare data needed for efficient scene diffing. For + /// example, as part of a preroll we compute transforms and cull rects, which + /// are used to find the best matching canvases. + /// + /// This method recursively walks the surface tree calling `preroll` on all + /// descendants. + void preroll() { + recomputeTransformAndClip(); + } + + /// Prints this surface into a [buffer] in a human-readable format. + void debugPrint(StringBuffer buffer, int indent) { + if (rootElement != null) { + buffer.write('${' ' * indent}<${rootElement.tagName.toLowerCase()} '); + } else { + buffer.write('${' ' * indent}<$runtimeType recycled '); + } + debugPrintAttributes(buffer); + buffer.writeln('>'); + debugPrintChildren(buffer, indent); + if (rootElement != null) { + buffer.writeln('${' ' * indent}'); + } else { + buffer.writeln('${' ' * indent}'); + } + } + + @protected + @mustCallSuper + void debugPrintAttributes(StringBuffer buffer) { + if (rootElement != null) { + buffer.write('@${rootElement.hashCode} '); + } + } + + @protected + @mustCallSuper + void debugPrintChildren(StringBuffer buffer, int indent) {} + + @override + String toString() { + if (assertionsEnabled) { + final StringBuffer log = StringBuffer(); + debugPrint(log, 0); + return log.toString(); + } else { + return super.toString(); + } + } +} + +/// A surface that doesn't have child surfaces. +abstract class PersistedLeafSurface extends PersistedSurface { + PersistedLeafSurface(); + + @override + void visitChildren(PersistedSurfaceVisitor visitor) { + // Does not have children. + } +} + +/// A surface that has a flat list of child surfaces. +abstract class PersistedContainerSurface extends PersistedSurface { + /// Creates a container surface. + /// + /// `oldLayer` points to the surface rendered in the previous frame that's + /// being updated by this layer. + PersistedContainerSurface(PersistedSurface oldLayer) + : _oldLayer = FrameReference( + oldLayer != null && oldLayer.isActive ? oldLayer : null) { + assert(oldLayer == null || runtimeType == oldLayer.runtimeType); + } + + /// The surface that is being updated using this surface. + /// + /// If not null this surface will reuse the old surface's HTML [element]. + /// + /// This value is set to null at the end of the frame. + PersistedSurface get oldLayer => _oldLayer.value; + final FrameReference _oldLayer; + + final List _children = []; + + @override + void visitChildren(PersistedSurfaceVisitor visitor) { + _children.forEach(visitor); + } + + /// Adds a child to this container. + void appendChild(PersistedSurface child) { + assert(child.isCreated || child.isPendingRetention || child.isPendingUpdate, + 'Child is in incorrect state ${child.state}'); + _children.add(child); + child.parent = this; + } + + @override + void preroll() { + super.preroll(); + final int length = _children.length; + for (int i = 0; i < length; i += 1) { + _children[i].preroll(); + } + } + + @override + void recomputeTransformAndClip() { + _transform = parent._transform; + _globalClip = parent._globalClip; + } + + @override + void build() { + super.build(); + // Memoize length for efficiency. + final int len = _children.length; + // Memoize container element for efficiency. [childContainer] is polymorphic + final html.Element containerElement = childContainer; + for (int i = 0; i < len; i++) { + final PersistedSurface child = _children[i]; + if (child.isPendingRetention) { + assert(child.rootElement != null); + child.retain(); + } else if (child is PersistedContainerSurface && child.oldLayer != null) { + final PersistedSurface oldLayer = child.oldLayer; + assert(oldLayer.rootElement != null); + assert(oldLayer.isPendingUpdate); + child.update(child.oldLayer); + } else { + assert(child.isCreated); + assert(child.rootElement == null); + child.build(); + } + containerElement.append(child.rootElement); + } + } + + @override + double matchForUpdate(PersistedContainerSurface existingSurface) { + assert(existingSurface.runtimeType == runtimeType); + // Intermediate container nodes don't have many resources worth comparing, + // so we always return 1.0 to signal that it doesn't matter which one to + // choose. + // TODO(yjbanov): while the container doesn't have own resources, imperfect + // matching can lead to unnecessary reparenting of DOM + // subtrees. One trick we could try is to look at children's + // oldLayer values and see if we can use those to match + // intermediate surfaces better. + return 1.0; + } + + @override + void update(PersistedContainerSurface oldSurface) { + assert(oldSurface.isActive || oldSurface.isPendingUpdate); + assert(runtimeType == oldSurface.runtimeType); + super.update(oldSurface); + assert(oldSurface.isReleased); + + if (oldSurface._children.isEmpty) { + _updateZeroToMany(oldSurface); + } else if (_children.length == 1) { + _updateManyToOne(oldSurface); + } else if (_children.isEmpty) { + _discardActiveChildren(oldSurface); + } else { + _updateManyToMany(oldSurface); + } + + if (assertionsEnabled) { + _debugValidateContainerUpdate(oldSurface); + } + } + + void _debugValidateContainerUpdate(PersistedContainerSurface oldSurface) { + // At the end of this all children should have an element each, and it + // should be attached to this container's element. + assert(() { + for (int i = 0; i < oldSurface._children.length; i++) { + final PersistedSurface oldChild = oldSurface._children[i]; + assert(!oldChild.isActive && !oldChild.isCreated, + 'Old child is in incorrect state ${oldChild.state}'); + if (oldChild.isReleased) { + assert(oldChild.rootElement == null); + assert(oldChild.childContainer == null); + } + } + for (int i = 0; i < _children.length; i++) { + final PersistedSurface newChild = _children[i]; + assert(newChild.isActive || newChild.isPendingRetention, + 'New child is in incorrect state ${newChild.state}'); + assert(newChild.rootElement != null); + assert(newChild.rootElement.parent == childContainer); + } + return true; + }()); + } + + /// This is a fast path update for the case when an empty container is being + /// populated with children. + /// + /// This method does not do any matching. + void _updateZeroToMany(PersistedContainerSurface oldSurface) { + assert(oldSurface._children.isEmpty); + + // Memoizing variables for efficiency. + final html.Element containerElement = childContainer; + final int length = _children.length; + + for (int i = 0; i < length; i++) { + final PersistedSurface newChild = _children[i]; + if (newChild.isPendingRetention) { + newChild.retain(); + assert(newChild.isPendingRetention); + } else if (newChild is PersistedContainerSurface && + newChild.oldLayer != null) { + final PersistedContainerSurface oldLayer = newChild.oldLayer; + assert(oldLayer.isPendingUpdate); + newChild.update(oldLayer); + assert(oldLayer.isReleased); + assert(newChild.isActive); + } else { + newChild.build(); + assert(newChild.isActive); + } + assert(newChild.rootElement != null); + containerElement.append(newChild.rootElement); + } + } + + /// Called to release children that were not reused this frame. + static void _discardActiveChildren(PersistedContainerSurface surface) { + final int length = surface._children.length; + for (int i = 0; i < length; i += 1) { + final PersistedSurface child = surface._children[i]; + // Only release active children that are currently active (i.e. they are + // not pending retention or update). + if (child.isActive) { + child.discard(); + } + assert(!child.isCreated && !child.isActive); + } + } + + /// This is a fast path update for the common case when there's only one child + /// active in this frame. + void _updateManyToOne(PersistedContainerSurface oldSurface) { + assert(_children.length == 1); + final PersistedSurface newChild = _children[0]; + + // Retained child is moved to the correct location in the tree; all others + // are released. + if (newChild.isPendingRetention) { + assert(newChild.rootElement != null); + + // Move the HTML node if necessary. + if (newChild.rootElement.parent != childContainer) { + childContainer.append(newChild.rootElement); + } + + newChild.retain(); + + _discardActiveChildren(oldSurface); + assert(newChild.isPendingRetention); + return; + } + + // Updated child is moved to the correct location in the tree; all others + // are released. + if (newChild is PersistedContainerSurface && newChild.oldLayer != null) { + assert(newChild.oldLayer.isPendingUpdate); + assert(newChild.rootElement == null); + assert(newChild.oldLayer.rootElement != null); + + final PersistedContainerSurface oldLayer = newChild.oldLayer; + + // Move the HTML node if necessary. + if (oldLayer.rootElement.parent != childContainer) { + childContainer.append(oldLayer.rootElement); + } + + newChild.update(oldLayer); + _discardActiveChildren(oldSurface); + assert(oldLayer.isReleased); + assert(newChild.isActive); + return; + } + + assert(newChild.isCreated); + + PersistedSurface bestMatch; + double bestScore = 2.0; + for (int i = 0; i < oldSurface._children.length; i++) { + final PersistedSurface candidate = oldSurface._children[i]; + if (!newChild.canUpdateAsMatch(candidate)) { + continue; + } + final double score = newChild.matchForUpdate(candidate); + if (score < bestScore) { + bestMatch = candidate; + bestScore = score; + } + } + + if (bestMatch != null) { + assert(bestMatch.isActive); + newChild.update(bestMatch); + + // Move the HTML node if necessary. + if (newChild.rootElement.parent != childContainer) { + childContainer.append(newChild.rootElement); + } + + assert(bestMatch.isReleased); + } else { + newChild.build(); + childContainer.append(newChild.rootElement); + assert(newChild.isActive); + } + + // Child nodes that were not used this frame that are still active and not + // explicitly retained or updated are discarded. + for (int i = 0; i < oldSurface._children.length; i++) { + final PersistedSurface oldChild = oldSurface._children[i]; + if (!identical(oldChild, bestMatch) && oldChild.isActive) { + oldChild.discard(); + } + assert(!oldChild.isCreated && !oldChild.isActive); + } + } + + /// This is the general case when multiple children are matched against + /// multiple children. + void _updateManyToMany(PersistedContainerSurface oldSurface) { + assert(_children.isNotEmpty && oldSurface._children.isNotEmpty); + + // Memoize container element for efficiency. [childContainer] is polymorphic + final html.Element containerElement = childContainer; + + PersistedSurface nextSibling; + + // Inserts the DOM node of the child before the DOM node of the next sibling + // if it has moved as a result of the update. Does nothing if the new child + // is already in the right location in the DOM tree. + void insertDomNodeIfMoved(PersistedSurface newChild) { + assert(newChild.rootElement != null); + assert(newChild.parent == this); + final bool reparented = newChild.rootElement.parent != containerElement; + // Do not check for sibling if reparented. It's obvious that we moved. + final bool moved = reparented || + newChild.rootElement.nextElementSibling != nextSibling?.rootElement; + if (moved) { + if (nextSibling == null) { + // We're at the end of the list. + containerElement.append(newChild.rootElement); + } else { + // We're in the middle of the list. + containerElement.insertBefore( + newChild.rootElement, nextSibling.rootElement); + } + } + } + + final Map matches = + _matchChildren(oldSurface); + + for (int bottomInNew = _children.length - 1; + bottomInNew >= 0; + bottomInNew--) { + final PersistedSurface newChild = _children[bottomInNew]; + if (newChild.isPendingRetention) { + newChild.retain(); + assert(newChild.isPendingRetention); + } else if (newChild is PersistedContainerSurface && + newChild.oldLayer != null) { + final PersistedContainerSurface oldLayer = newChild.oldLayer; + assert(oldLayer.isPendingUpdate); + newChild.update(oldLayer); + assert(oldLayer.isReleased); + assert(newChild.isActive); + } else { + final PersistedSurface matchedOldChild = matches[newChild]; + if (matchedOldChild != null) { + assert(matchedOldChild.isActive); + newChild.update(matchedOldChild); + assert(matchedOldChild.isReleased); + assert(newChild.isActive); + } else { + newChild.build(); + assert(newChild.isActive); + } + } + insertDomNodeIfMoved(newChild); + assert(newChild.rootElement != null); + assert(newChild.isActive || newChild.isPendingRetention); + nextSibling = newChild; + } + + // Remove elements that were not reused this frame. + _discardActiveChildren(oldSurface); + } + + Map _matchChildren( + PersistedContainerSurface oldSurface) { + final int newUnfilteredChildCount = _children.length; + final int oldUnfilteredChildCount = oldSurface._children.length; + + // Extract new nodes that need to be matched. + final List newChildren = []; + for (int i = 0; i < newUnfilteredChildCount; i++) { + final PersistedSurface child = _children[i]; + if (child.isCreated) { + newChildren.add(child); + } + } + + // Extract old nodes that can be matched against. + final List oldChildren = []; + for (int i = 0; i < oldUnfilteredChildCount; i++) { + final PersistedSurface child = oldSurface._children[i]; + if (child.isActive) { + oldChildren.add(child); + } + } + + final int newChildCount = newChildren.length; + final int oldChildCount = oldChildren.length; + + if (newChildCount == 0 || oldChildCount == 0) { + // Nothing to match. + return const {}; + } + + final List<_PersistedSurfaceMatch> allMatches = <_PersistedSurfaceMatch>[]; + + // This is worst-case O(N*M) but it only happens when: + // - most of the children are newly created (N) + // - the old container is not empty (M) + // + // The choice here is between recreating all DOM nodes from scratch, or try + // finding matches and reusing their elements. + for (int indexInNew = 0; indexInNew < newChildCount; indexInNew += 1) { + final PersistedSurface newChild = newChildren[indexInNew]; + for (int indexInOld = 0; indexInOld < oldChildCount; indexInOld += 1) { + final PersistedSurface oldChild = oldChildren[indexInOld]; + final bool childAlreadyClaimed = oldChild == null; + if (childAlreadyClaimed || !newChild.canUpdateAsMatch(oldChild)) { + continue; + } + allMatches.add(_PersistedSurfaceMatch( + matchQuality: newChild.matchForUpdate(oldChild), + newChild: newChild, + oldChildIndex: indexInOld, + )); + } + } + + allMatches.sort((_PersistedSurfaceMatch m1, _PersistedSurfaceMatch m2) { + return m1.matchQuality.compareTo(m2.matchQuality); + }); + + final Map result = + {}; + for (int i = 0; i < allMatches.length; i += 1) { + final _PersistedSurfaceMatch match = allMatches[i]; + // This may be null if it has been claimed. + final PersistedSurface matchedChild = oldChildren[match.oldChildIndex]; + if (matchedChild != null) { + oldChildren[match.oldChildIndex] = null; + result[match.newChild] = matchedChild; // claim it + } + } + + assert(result.length == Set.from(result.values).length); + return result; + } + + @override + void retain() { + super.retain(); + final int len = _children.length; + for (int i = 0; i < len; i++) { + _children[i].retain(); + } + } + + @override + void revive() { + super.revive(); + final int len = _children.length; + for (int i = 0; i < len; i++) { + _children[i].revive(); + } + } + + @override + void discard() { + super.discard(); + _discardActiveChildren(this); + } + + @override + @protected + @mustCallSuper + void debugValidate(List validationErrors) { + super.debugValidate(validationErrors); + for (int i = 0; i < _children.length; i++) { + final PersistedSurface child = _children[i]; + if (child.parent != this) { + validationErrors.add( + '${debugIdentify(child)} parent is ${debugIdentify(child.parent)} but expected the parent to be ${debugIdentify(this)}'); + } + } + for (int i = 0; i < _children.length; i++) { + _children[i].debugValidate(validationErrors); + } + } + + @override + void debugPrintChildren(StringBuffer buffer, int indent) { + super.debugPrintChildren(buffer, indent); + for (int i = 0; i < _children.length; i++) { + _children[i].debugPrint(buffer, indent + 1); + } + } +} + +/// A custom class used by [PersistedContainerSurface._matchChildren]. +class _PersistedSurfaceMatch { + _PersistedSurfaceMatch({ + this.newChild, + this.oldChildIndex, + this.matchQuality, + }); + + /// The child in the new scene who we are trying to match to an existing + /// child. + final PersistedSurface newChild; + + /// The index pointing at the old child that matched [newChild] in the old + /// child list. + /// + /// The indirection is intentional because when matches are traversed old + /// children are claimed and nulled out in the array. + final int oldChildIndex; + + /// The score of how well [newChild] matched the old child as computed by + /// [PersistedSurface.matchForUpdate]. + final double matchQuality; +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/surface/transform.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/transform.dart new file mode 100644 index 0000000000..abf6f1ff8c --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/surface/transform.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. + +part of engine; + +/// A surface that transforms its children using CSS transform. +class PersistedTransform extends PersistedContainerSurface + implements ui.TransformEngineLayer { + PersistedTransform(PersistedTransform oldLayer, this.matrix4) + : super(oldLayer); + + final Float64List matrix4; + + @override + void recomputeTransformAndClip() { + _transform = parent._transform.multiplied(Matrix4.fromFloat64List(matrix4)); + _globalClip = parent._globalClip; + } + + @override + html.Element createElement() { + return defaultCreateElement('flt-transform') + ..style.transformOrigin = '0 0 0'; + } + + @override + void apply() { + rootElement.style.transform = float64ListToCssTransform(matrix4); + } + + @override + void update(PersistedTransform oldSurface) { + super.update(oldSurface); + + if (identical(oldSurface.matrix4, matrix4)) { + return; + } + + bool matrixChanged = false; + for (int i = 0; i < matrix4.length; i++) { + if (matrix4[i] != oldSurface.matrix4[i]) { + matrixChanged = true; + break; + } + } + + if (matrixChanged) { + apply(); + } + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/test_embedding.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/test_embedding.dart new file mode 100644 index 0000000000..fc5f25a4ed --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/test_embedding.dart @@ -0,0 +1,157 @@ +// 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; + +const bool _debugLogHistoryActions = false; + +class _HistoryEntry { + final dynamic state; + final String title; + final String url; + + const _HistoryEntry(this.state, this.title, this.url); + + @override + String toString() { + return '$runtimeType(state:$state, title:"$title", url:"$url")'; + } +} + +/// This location strategy mimics the browser's history as closely as possible +/// while doing it all in memory with no interaction with the browser. +/// +/// It keeps a list of history entries and event listeners in memory and +/// manipulates them in order to achieve the desired functionality. +class TestLocationStrategy extends LocationStrategy { + /// Passing a [defaultRouteName] will make the app start at that route. The + /// way it does it is by using it as a path on the first history entry. + TestLocationStrategy([String defaultRouteName = '']) + : _currentEntryIndex = 0, + history = <_HistoryEntry>[_HistoryEntry(null, null, defaultRouteName)]; + + @override + String get path => ensureLeading(currentEntry.url, '/'); + + int _currentEntryIndex; + final List<_HistoryEntry> history; + + _HistoryEntry get currentEntry { + assert(withinAppHistory); + return history[_currentEntryIndex]; + } + + set currentEntry(_HistoryEntry entry) { + assert(withinAppHistory); + history[_currentEntryIndex] = entry; + } + + /// Whether we are still within the history of the Flutter Web app. This + /// remains true until we go back in history beyond the entry where the app + /// started. + bool get withinAppHistory => _currentEntryIndex >= 0; + + @override + void pushState(dynamic state, String title, String url) { + assert(withinAppHistory); + _currentEntryIndex++; + // When pushing a new state, we need to remove all entries that exist after + // the current entry. + // + // If the user goes A -> B -> C -> D, then goes back to B and pushes a new + // entry called E, we should end up with: A -> B -> E in the history list. + history.removeRange(_currentEntryIndex, history.length); + history.add(_HistoryEntry(state, title, url)); + + if (_debugLogHistoryActions) { + print('$runtimeType.pushState(...) -> $this'); + } + } + + @override + void replaceState(dynamic state, String title, String url) { + assert(withinAppHistory); + currentEntry = _HistoryEntry(state, title, url); + + if (_debugLogHistoryActions) { + print('$runtimeType.replaceState(...) -> $this'); + } + } + + /// This simulates the case where a user types in a url manually. It causes + /// a new state to be pushed, and all event listeners will be invoked. + Future simulateUserTypingUrl(String url) { + assert(withinAppHistory); + return _nextEventLoop(() { + pushState(null, '', url); + _firePopStateEvent(); + }); + } + + @override + Future back() { + assert(withinAppHistory); + // Browsers don't move back in history immediately. They do it at the next + // event loop. So let's simulate that. + return _nextEventLoop(() { + _currentEntryIndex--; + if (withinAppHistory) { + _firePopStateEvent(); + } + + if (_debugLogHistoryActions) { + print('$runtimeType.back() -> $this'); + } + }); + } + + final List listeners = []; + + @override + ui.VoidCallback onPopState(html.EventListener fn) { + listeners.add(fn); + return () { + // Schedule a micro task here to avoid removing the listener during + // iteration in [_firePopStateEvent]. + scheduleMicrotask(() => listeners.remove(fn)); + }; + } + + /// Simulates the scheduling of a new event loop by creating a delayed future. + /// Details explained here: https://webdev.dartlang.org/articles/performance/event-loop + Future _nextEventLoop(ui.VoidCallback callback) { + return Future.delayed(Duration.zero).then((_) => callback()); + } + + /// Invokes all the attached event listeners in order of + /// attaching. This method should be called asynchronously to make it behave + /// like a real browser. + void _firePopStateEvent() { + assert(withinAppHistory); + final html.PopStateEvent event = html.PopStateEvent( + 'popstate', + {'state': currentEntry.state}, + ); + for (int i = 0; i < listeners.length; i++) { + listeners[i](event); + } + + if (_debugLogHistoryActions) { + print('$runtimeType: fired popstate event $event'); + } + } + + @override + String prepareExternalUrl(String internalUrl) => internalUrl; + + @override + String toString() { + final List lines = List(history.length); + for (int i = 0; i < history.length; i++) { + final _HistoryEntry entry = history[i]; + lines[i] = _currentEntryIndex == i ? '* $entry' : ' $entry'; + } + return '$runtimeType: [\n${lines.join('\n')}\n]'; + } +} 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 new file mode 100644 index 0000000000..d3c1b284e7 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/font_collection.dart @@ -0,0 +1,231 @@ +// 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; + +const String _testFontFamily = 'Ahem'; +const String _testFontUrl = 'packages/flutter_web/assets/Ahem.ttf'; +const String _robotoFontUrl = + 'packages/flutter_web_ui/assets/Roboto-Regular.ttf'; + +/// This class is responsible for registering and loading fonts. +/// +/// Once an asset manager has been set in the framework, call +/// [registerFonts] with it to register fonts declared in the +/// font manifest. If test fonts are enabled, then call +/// [registerTestFonts] as well. +class FontCollection { + _FontManager _assetFontManager; + _FontManager _testFontManager; + + /// Reads the font manifest using the [assetManager] and registers all of the + /// fonts declared within. + 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'); + } + + if (supportsFontLoadingApi) { + _assetFontManager = _FontManager(); + } else { + _assetFontManager = _PolyfillFontManager(); + } + + // If not on Chrome, add Roboto to the bundled fonts since it is provided + // by default by Flutter. + if (browserEngine != BrowserEngine.blink) { + _assetFontManager + .registerAsset('Roboto', 'url($_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]}'; + } + } + _assetFontManager.registerAsset( + family, 'url(${assetManager.getAssetUrl(asset)})', descriptors); + } + } + } + + /// Registers fonts that are used by tests. + void debugRegisterTestFonts() { + _testFontManager = _FontManager(); + _testFontManager.registerAsset( + _testFontFamily, 'url($_testFontUrl)', const {}); + } + + /// Returns a [Future] that completes when the registered fonts are loaded + /// and ready to be used. + Future ensureFontsLoaded() async { + await _assetFontManager?.ensureFontsLoaded(); + await _testFontManager?.ensureFontsLoaded(); + } + + /// Unregister all fonts that have been registered. + void clear() { + _assetFontManager = null; + _testFontManager = null; + if (supportsFontLoadingApi) { + html.document.fonts.clear(); + } + } +} + +/// Manages a collection of fonts and ensures they are loaded. +class _FontManager { + final List> _fontLoadingFutures = >[]; + + factory _FontManager() { + if (supportsFontLoadingApi) { + return _FontManager._(); + } else { + return _PolyfillFontManager(); + } + } + + _FontManager._(); + + void registerAsset( + String family, + String asset, + Map descriptors, + ) { + final html.FontFace fontFace = html.FontFace(family, asset, descriptors); + _fontLoadingFutures.add(fontFace + .load() + .then((_) => html.document.fonts.add(fontFace), onError: (dynamic e) { + html.window.console + .warn('Error while trying to load font family "$family":\n$e'); + return null; + })); + } + + /// Returns a [Future] that completes when all fonts that have been + /// registered with this font manager have been loaded and are ready to use. + Future ensureFontsLoaded() { + return Future.wait(_fontLoadingFutures); + } +} + +/// A font manager that works without using the CSS Font Loading API. +/// +/// The CSS Font Loading API is not implemented in IE 11 or Edge. To tell if a +/// font is loaded, we continuously measure some text using that font until the +/// width changes. +class _PolyfillFontManager extends _FontManager { + _PolyfillFontManager() : super._(); + + /// A String containing characters whose width varies greatly between fonts. + static const String _testString = 'giItT1WQy@!-/#'; + + static const Duration _fontLoadTimeout = Duration(seconds: 2); + static const Duration _fontLoadRetryDuration = Duration(milliseconds: 50); + + @override + void registerAsset( + String family, + String asset, + Map descriptors, + ) { + final html.ParagraphElement paragraph = html.ParagraphElement(); + paragraph.style.position = 'absolute'; + paragraph.style.visibility = 'hidden'; + paragraph.style.fontSize = '72px'; + paragraph.style.fontFamily = 'sans-serif'; + if (descriptors['style'] != null) { + paragraph.style.fontStyle = descriptors['style']; + } + if (descriptors['weight'] != null) { + paragraph.style.fontWeight = descriptors['weight']; + } + paragraph.text = _testString; + + html.document.body.append(paragraph); + final int sansSerifWidth = paragraph.offsetWidth; + + paragraph.style.fontFamily = '$family, sans-serif'; + + final Completer completer = Completer(); + + DateTime _fontLoadStart; + + void _watchWidth() { + if (paragraph.offsetWidth != sansSerifWidth) { + paragraph.remove(); + completer.complete(); + } else { + if (DateTime.now().difference(_fontLoadStart) > _fontLoadTimeout) { + completer.completeError( + Exception('Timed out trying to load font: $family')); + } else { + Timer(_fontLoadRetryDuration, _watchWidth); + } + } + } + + final Map fontStyleMap = {}; + fontStyleMap['font-family'] = "'$family'"; + fontStyleMap['src'] = asset; + if (descriptors['style'] != null) { + fontStyleMap['font-style'] = descriptors['style']; + } + if (descriptors['weight'] != null) { + fontStyleMap['font-weight'] = descriptors['weight']; + } + final String fontFaceDeclaration = fontStyleMap.keys + .map((String name) => '$name: ${fontStyleMap[name]};') + .join(' '); + final html.StyleElement fontLoadStyle = html.StyleElement(); + fontLoadStyle.type = 'text/css'; + fontLoadStyle.innerHtml = '@font-face { $fontFaceDeclaration }'; + html.document.head.append(fontLoadStyle); + + // HACK: If this is an icon font, then when it loads it won't change the + // width of our test string. So we just have to hope it loads before the + // layout phase. + if (family.toLowerCase().contains('icon')) { + paragraph.remove(); + return; + } + + _fontLoadStart = DateTime.now(); + _watchWidth(); + + _fontLoadingFutures.add(completer.future); + } +} + +final bool supportsFontLoadingApi = html.document.fonts != null; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/text/line_breaker.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/text/line_breaker.dart new file mode 100644 index 0000000000..7447ff9e5d --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/line_breaker.dart @@ -0,0 +1,105 @@ +// 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; + +/// Various types of line breaks as defined by the Unicode spec. +enum LineBreakType { + /// Indicates that a line break is possible but not mandatory. + opportunity, + + /// Indicates that this is a hard line break that can't be skipped. + mandatory, + + /// Indicates the end of the text (which is also considered a line break in + /// the Unicode spec). This is the same as [mandatory] but it's needed in our + /// implementation to distinguish between the universal [endOfText] and the + /// line break caused by "\n" at the end of the text. + endOfText, +} + +class CharCode { + // New line characters. + static const int lf = 0x0A; + static const int bk1 = 0x0B; + static const int bk2 = 0x0C; + static const int cr = 0x0D; + static const int nl = 0x85; + + // Space characters. + static const int tab = 0x09; + static const int space = 0x20; + + static const int hyphen = 0x2D; +} + +/// Acts as a tuple that encapsulates information about a line break. +class LineBreakResult { + LineBreakResult(this.index, this.type); + + final int index; + final LineBreakType type; +} + +/// Finds the next line break in the given [text] starting from [index]. +/// +/// Useful resources: +/// +/// * http://www.unicode.org/reports/tr14/#Algorithm +/// * https://www.unicode.org/Public/11.0.0/ucd/LineBreak.txt +LineBreakResult nextLineBreak(String text, int index) { + // TODO(flutter_web): https://github.com/flutter/flutter/issues/33523 + // This is a hacky/temporary/throw-away implementation to enable us to move fast + // with the rest of the line-splitting project. + + // Always break at the end of text. + // LB3: ÷ eot + while (index++ < text.length) { + final int curr = index < text.length ? text.codeUnitAt(index) : null; + final int prev = index > 0 ? text.codeUnitAt(index - 1) : null; + + // Always break after hard line breaks. + // LB4: BK ! + if (prev == CharCode.bk1 || prev == CharCode.bk2) { + return LineBreakResult(index, LineBreakType.mandatory); + } + + // Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks. + // LB5: CR × LF + // CR ! + // LF ! + // NL ! + if (prev == CharCode.cr && curr == CharCode.lf) { + continue; + } + if (prev == CharCode.cr || prev == CharCode.lf || prev == CharCode.nl) { + return LineBreakResult(index, LineBreakType.mandatory); + } + + // Do not break before hard line breaks. + // LB6: × ( BK | CR | LF | NL ) + if (curr == CharCode.bk1 || + curr == CharCode.bk2 || + curr == CharCode.cr || + curr == CharCode.lf || + curr == CharCode.nl) { + continue; + } + + if (index >= text.length) { + return LineBreakResult(text.length, LineBreakType.endOfText); + } + + if (curr == CharCode.space || curr == CharCode.tab) { + continue; + } + + if (prev == CharCode.space || + prev == CharCode.tab || + prev == CharCode.hyphen) { + return LineBreakResult(index, LineBreakType.opportunity); + } + } + return LineBreakResult(text.length, LineBreakType.endOfText); +} 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 new file mode 100644 index 0000000000..20ec23dbc5 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/measurement.dart @@ -0,0 +1,835 @@ +// 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; + +// TODO(yjbanov): this is a hack we use to compute ideographic baseline; this +// number is the ratio ideographic/alphabetic for font Ahem, +// which matches the Flutter number. It may be completely wrong +// for any other font. We'll need to eventually fix this. That +// said Flutter doesn't seem to use ideographic baseline for +// anything as of this writing. +const double _baselineRatioHack = 1.1662499904632568; + +/// Signature of a function that takes a character and returns true or false. +typedef CharPredicate = bool Function(int char); + +bool _whitespacePredicate(int char) => + char == CharCode.space || char == CharCode.tab || _newlinePredicate(char); +bool _newlinePredicate(int char) => + char == CharCode.cr || char == CharCode.lf || char == CharCode.nl; + +/// Manages [ParagraphRuler] instances and caches them per unique +/// [ParagraphGeometricStyle]. +/// +/// All instances of [ParagraphRuler] should be created through this class. +class RulerManager { + RulerManager({@required this.rulerCacheCapacity}) { + _rulerHost.style + ..position = 'fixed' + ..visibility = 'hidden' + ..overflow = 'hidden' + ..top = '0' + ..left = '0' + ..width = '0' + ..height = '0'; + html.document.body.append(_rulerHost); + registerHotRestartListener(dispose); + } + + final int rulerCacheCapacity; + + /// Hosts a cache of rulers that measure text. + /// + /// This element exists purely for organizational purposes. Otherwise the + /// rulers would be attached to the `` element polluting the element + /// tree and making it hard to navigate. It does not serve any functional + /// purpose. + final html.Element _rulerHost = html.Element.tag('flt-ruler-host'); + + /// The cache of rulers used to measure text. + /// + /// Each ruler is keyed by paragraph style. This allows us to setup the + /// ruler's DOM structure once during the very first measurement of a given + /// paragraph style. Subsequent measurements could reuse the same ruler and + /// only swap the text contents. This minimizes the amount of work a browser + /// needs to do when measure many pieces of text with the same style. + /// + /// What makes this cache effective is the fact that a typical application + /// only uses a limited number of text styles. Using too many text styles on + /// the same screen is considered bad for user experience. + Map get rulers => _rulers; + Map _rulers = + {}; + + bool _rulerCacheCleanupScheduled = false; + + void _scheduleRulerCacheCleanup() { + if (!_rulerCacheCleanupScheduled) { + _rulerCacheCleanupScheduled = true; + scheduleMicrotask(() { + _rulerCacheCleanupScheduled = false; + cleanUpRulerCache(); + }); + } + } + + /// Releases the resources used by this [RulerManager]. + /// + /// After this is called, this object is no longer usable. + void dispose() { + _rulerHost?.remove(); + } + + /// If ruler cache size exceeds [rulerCacheCapacity], evicts those rulers that + /// were used the least. + /// + /// Resets hit counts back to zero. + @visibleForTesting + void cleanUpRulerCache() { + if (_rulers.length > rulerCacheCapacity) { + final List sortedByUsage = _rulers.values.toList(); + sortedByUsage.sort((ParagraphRuler a, ParagraphRuler b) { + return b.hitCount - a.hitCount; + }); + _rulers = {}; + for (int i = 0; i < sortedByUsage.length; i++) { + final ParagraphRuler ruler = sortedByUsage[i]; + ruler.resetHitCount(); + if (i < rulerCacheCapacity) { + // Retain this ruler. + _rulers[ruler.style] = ruler; + } else { + // This ruler did not have enough usage this frame to be retained. + ruler.dispose(); + } + } + } + } + + /// Adds an element used for measuring text as a child of [_rulerHost]. + void addHostElement(html.DivElement element) { + _rulerHost.append(element); + } + + /// Performs a cache lookup to find an existing [ParagraphRuler] for the given + /// [style] and if it can't find one in the cache, it would create one. + /// + /// The returned ruler is marked as hit so there's no need to do that + /// elsewhere. + @visibleForTesting + ParagraphRuler findOrCreateRuler(ParagraphGeometricStyle style) { + ParagraphRuler ruler = _rulers[style]; + if (ruler == null) { + if (assertionsEnabled) { + domRenderer.debugRulerCacheMiss(); + } + ruler = _rulers[style] = ParagraphRuler(style, this); + _scheduleRulerCacheCleanup(); + } else { + if (assertionsEnabled) { + domRenderer.debugRulerCacheHit(); + } + } + ruler.hit(); + return ruler; + } +} + +/// Provides various text measurement APIs using either a dom-based approach +/// in [DomTextMeasurementService], or a canvas-based approach in +/// [CanvasTextMeasurementService]. +abstract class TextMeasurementService { + /// Initializes the text measurement service with a specific + /// [rulerCacheCapacity] that gets passed to the [RulerManager]. + static void initialize({@required int rulerCacheCapacity}) { + clearCache(); + rulerManager = RulerManager(rulerCacheCapacity: rulerCacheCapacity); + } + + @visibleForTesting + static RulerManager rulerManager; + + /// The DOM-based text measurement service. + @visibleForTesting + static TextMeasurementService get domInstance => + DomTextMeasurementService.instance; + + /// The canvas-based text measurement service. + @visibleForTesting + static TextMeasurementService get canvasInstance => + CanvasTextMeasurementService.instance; + + /// Whether the new experimental implementation of canvas-based text + /// measurement is enabled or not. + /// + /// This is only used for testing at the moment. Once the implementation is + /// complete and production-ready, we'll get rid of this flag. + static bool enableExperimentalCanvasImplementation = false; + + /// Gets the appropriate [TextMeasurementService] instance for the given + /// [paragraph]. + static TextMeasurementService forParagraph(ui.Paragraph paragraph) { + // TODO(flutter_web): https://github.com/flutter/flutter/issues/33523 + // When the canvas-based implementation is complete and passes all the + // tests, get rid of [_experimentalEnableCanvasImplementation]. + if (enableExperimentalCanvasImplementation && + _canUseCanvasMeasurement(paragraph)) { + return canvasInstance; + } + return domInstance; + } + + /// Clears the cache of paragraph rulers. + @visibleForTesting + static void clearCache() { + rulerManager?.dispose(); + rulerManager = null; + } + + static bool _canUseCanvasMeasurement(EngineParagraph paragraph) { + // Currently, the canvas-based approach only works on plain text that + // doesn't have any of the following styles: + // - decoration + // - word spacing + final ParagraphGeometricStyle style = paragraph._geometricStyle; + return paragraph._plainText != null && + style.decoration == null && + style.wordSpacing == null; + } + + /// Measures the paragraph and returns a [MeasurementResult] object. + MeasurementResult measure( + EngineParagraph paragraph, + ui.ParagraphConstraints constraints, + ) { + assert(rulerManager != null); + final ParagraphGeometricStyle style = paragraph._geometricStyle; + final ParagraphRuler ruler = + TextMeasurementService.rulerManager.findOrCreateRuler(style); + + if (assertionsEnabled) { + if (paragraph._plainText == null) { + domRenderer.debugRichTextLayout(); + } else { + domRenderer.debugPlainTextLayout(); + } + } + + MeasurementResult result = ruler.cacheLookup(paragraph, constraints); + if (result != null) { + return result; + } + + result = _doMeasure(paragraph, constraints, ruler); + ruler.cacheMeasurement(paragraph, result); + return result; + } + + /// Measures the width of a substring of the given [paragraph] with no + /// constraints. + double measureSubstringWidth(EngineParagraph paragraph, int start, int end); + + /// Delegates to a [ParagraphRuler] to measure a list of text boxes that + /// enclose the given range of text. + List measureBoxesForRange( + EngineParagraph paragraph, + ui.ParagraphConstraints constraints, { + int start, + int end, + double alignOffset, + ui.TextDirection textDirection, + }) { + final ParagraphGeometricStyle style = paragraph._geometricStyle; + final ParagraphRuler ruler = + TextMeasurementService.rulerManager.findOrCreateRuler(style); + + return ruler.measureBoxesForRange( + paragraph._plainText, + constraints, + start: start, + end: end, + alignOffset: alignOffset, + textDirection: textDirection, + ); + } + + /// Performs the actual measurement of the following values for the given + /// paragraph: + /// + /// * isSingleLine: whether the paragraph can be rendered in a single line. + /// * height: constrained measure of the entire paragraph's height. + /// * lineHeight: the height of a single line of the paragraph. + /// * alphabeticBaseline: single line measure. + /// * ideographicBaseline: based on [alphabeticBaseline]. + /// * maxIntrinsicWidth: the width of the paragraph with no line-wrapping. + /// * minIntrinsicWidth: the min width the paragraph fits in without overflowing. + /// + /// [MeasurementResult.width] is set to the same value of [constraints.width]. + /// + /// It also optionally computes [MeasurementResult.lines] in the given + /// paragraph. When that's available, it can be used by a canvas to render + /// the text line. + MeasurementResult _doMeasure( + EngineParagraph paragraph, + ui.ParagraphConstraints constraints, + ParagraphRuler ruler, + ); +} + +/// A DOM-based text measurement implementation. +/// +/// This implementation is slower than [CanvasTextMeasurementService] but it's +/// needed for some cases that aren't yet supported in the canvas-based +/// implementation such as letter-spacing, word-spacing, etc. +class DomTextMeasurementService extends TextMeasurementService { + /// The text measurement service singleton. + static DomTextMeasurementService get instance => + _instance ??= DomTextMeasurementService(); + + static DomTextMeasurementService _instance; + + @override + MeasurementResult _doMeasure( + EngineParagraph paragraph, + ui.ParagraphConstraints constraints, + ParagraphRuler ruler, + ) { + ruler.willMeasure(paragraph); + final String plainText = paragraph._plainText; + + ruler.measureAll(constraints); + + MeasurementResult result; + // When the text has a new line, we should always use multi-line mode. + final bool hasNewline = plainText?.contains('\n') ?? false; + if (!hasNewline && ruler.singleLineDimensions.width <= constraints.width) { + result = _measureSingleLineParagraph(ruler, paragraph, constraints); + } else { + // Assert: If text doesn't have new line for infinite constraints we + // should have called single line measure paragraph instead. + assert(hasNewline || constraints.width != double.infinity); + result = _measureMultiLineParagraph(ruler, paragraph, constraints); + } + ruler.didMeasure(); + return result; + } + + @override + double measureSubstringWidth(EngineParagraph paragraph, int start, int end) { + final ParagraphGeometricStyle style = paragraph._geometricStyle; + final ParagraphRuler ruler = + TextMeasurementService.rulerManager.findOrCreateRuler(style); + + final String text = paragraph._plainText.substring(start, end); + final ui.Paragraph substringParagraph = paragraph._cloneWithText(text); + + ruler.willMeasure(substringParagraph); + ruler.measureAsSingleLine(); + final TextDimensions dimensions = ruler.singleLineDimensions; + ruler.didMeasure(); + return dimensions.width; + } + + /// Called when we have determined that the paragraph fits the [constraints] + /// without wrapping. + /// + /// This means that: + /// * `width == maxIntrinsicWidth` - we gave it more horizontal space than + /// it needs and so the paragraph won't expand beyond `maxIntrinsicWidth`. + /// * `height` is the height computed by `measureAsSingleLine`; giving the + /// paragraph the width constraint won't change its height as we already + /// determined that it fits within the constraint without wrapping. + /// * `alphabeticBaseline` is also final for the same reason as the `height` + /// value. + /// + /// This method still needs to measure `minIntrinsicWidth`. + MeasurementResult _measureSingleLineParagraph(ParagraphRuler ruler, + ui.Paragraph paragraph, ui.ParagraphConstraints constraints) { + final double width = constraints.width; + final double minIntrinsicWidth = ruler.minIntrinsicDimensions.width; + double maxIntrinsicWidth = ruler.singleLineDimensions.width; + final double alphabeticBaseline = ruler.alphabeticBaseline; + final double height = ruler.singleLineDimensions.height; + + maxIntrinsicWidth = + _applySubPixelRoundingHack(minIntrinsicWidth, maxIntrinsicWidth); + final double ideographicBaseline = alphabeticBaseline * _baselineRatioHack; + return MeasurementResult( + constraints.width, + isSingleLine: true, + width: width, + height: height, + naturalHeight: height, + lineHeight: height, + minIntrinsicWidth: minIntrinsicWidth, + maxIntrinsicWidth: maxIntrinsicWidth, + alphabeticBaseline: alphabeticBaseline, + ideographicBaseline: ideographicBaseline, + lines: null, + ); + } + + /// Called when we have determined that the paragraph needs to wrap into + /// multiple lines to fit the [constraints], i.e. its `maxIntrinsicWidth` is + /// bigger than the available horizontal space. + /// + /// While `maxIntrinsicWidth` is still good from the call to + /// `measureAsSingleLine`, we need to re-measure with the width constraint + /// and get new values for width, height and alphabetic baseline. We also need + /// to measure `minIntrinsicWidth`. + MeasurementResult _measureMultiLineParagraph(ParagraphRuler ruler, + EngineParagraph paragraph, ui.ParagraphConstraints constraints) { + // If constraint is infinite, we must use _measureSingleLineParagraph + final double width = constraints.width; + final double minIntrinsicWidth = ruler.minIntrinsicDimensions.width; + double maxIntrinsicWidth = ruler.singleLineDimensions.width; + final double alphabeticBaseline = ruler.alphabeticBaseline; + // Natural height is the full height of text ignoring height constraints. + final double naturalHeight = ruler.constrainedDimensions.height; + + double height; + double lineHeight; + final int maxLines = paragraph._geometricStyle.maxLines; + if (maxLines == null) { + height = naturalHeight; + } else { + // Lazily compute [lineHeight] when [maxLines] is not null. + lineHeight = ruler.lineHeightDimensions.height; + height = math.min(naturalHeight, maxLines * lineHeight); + } + + maxIntrinsicWidth = + _applySubPixelRoundingHack(minIntrinsicWidth, maxIntrinsicWidth); + assert(minIntrinsicWidth <= maxIntrinsicWidth); + final double ideographicBaseline = alphabeticBaseline * _baselineRatioHack; + return MeasurementResult( + constraints.width, + isSingleLine: false, + width: width, + height: height, + lineHeight: lineHeight, + naturalHeight: naturalHeight, + minIntrinsicWidth: minIntrinsicWidth, + maxIntrinsicWidth: maxIntrinsicWidth, + alphabeticBaseline: alphabeticBaseline, + ideographicBaseline: ideographicBaseline, + lines: null, + ); + } + + /// This hack is needed because `offsetWidth` rounds the value to the nearest + /// whole number. On a very rare occasion the minimum intrinsic width reported + /// by the browser is slightly bigger than the reported maximum intrinsic + /// width. If the discrepancy overlaps 0.5 then the rounding happens in + /// opposite directions. + /// + /// For example, if minIntrinsicWidth == 99.5 and maxIntrinsicWidth == 99.48, + /// then minIntrinsicWidth is rounded up to 100, and maxIntrinsicWidth is + /// rounded down to 99. + // TODO(yjbanov): remove the need for this hack. + static double _applySubPixelRoundingHack( + double minIntrinsicWidth, double maxIntrinsicWidth) { + if (minIntrinsicWidth <= maxIntrinsicWidth) { + return maxIntrinsicWidth; + } + + if (minIntrinsicWidth - maxIntrinsicWidth < 2.0) { + return minIntrinsicWidth; + } + + throw Exception('minIntrinsicWidth ($minIntrinsicWidth) is greater than ' + 'maxIntrinsicWidth ($maxIntrinsicWidth).'); + } +} + +/// A canvas-based text measurement implementation. +/// +/// This is a faster implementation than [DomTextMeasurementService] and +/// provides line breaks information that can be useful for multi-line text. +class CanvasTextMeasurementService extends TextMeasurementService { + /// The text measurement service singleton. + static CanvasTextMeasurementService get instance => + _instance ??= CanvasTextMeasurementService(); + + static CanvasTextMeasurementService _instance; + + final html.CanvasRenderingContext2D _canvasContext = + html.CanvasElement().context2D; + + @override + MeasurementResult _doMeasure( + EngineParagraph paragraph, + ui.ParagraphConstraints constraints, + ParagraphRuler ruler, + ) { + final String text = paragraph._plainText; + final ParagraphGeometricStyle style = paragraph._geometricStyle; + assert(text != null); + + // TODO(mdebbar): Check if the whole text can fit in a single-line. Then avoid all this ceremony. + _canvasContext.font = style.cssFontString; + final LinesCalculator linesCalculator = + LinesCalculator(_canvasContext, text, style, constraints.width); + final MinIntrinsicCalculator minIntrinsicCalculator = + MinIntrinsicCalculator(_canvasContext, text, style); + final MaxIntrinsicCalculator maxIntrinsicCalculator = + MaxIntrinsicCalculator(_canvasContext, text, style); + + // Indicates whether we've reached the end of text or not. Even if the index + // [i] reaches the end of text, we don't want to stop looping until we hit + // [LineBreakType.endOfText] because there could be a "\n" at the end of the + // string and that would mess things up. + bool reachedEndOfText = false; + + // TODO(flutter_web): Chrome & Safari return more info from [canvasContext.measureText]. + int i = 0; + while (!reachedEndOfText) { + final LineBreakResult brk = nextLineBreak(text, i); + + linesCalculator.update(brk); + minIntrinsicCalculator.update(brk); + maxIntrinsicCalculator.update(brk); + + i = brk.index; + if (brk.type == LineBreakType.endOfText) { + reachedEndOfText = true; + } + } + + final int lineCount = linesCalculator.lines.length; + final double lineHeight = ruler.lineHeightDimensions.height; + final double naturalHeight = lineCount * lineHeight; + + final double height = style.maxLines == null + ? naturalHeight + : math.min(lineCount, style.maxLines) * lineHeight; + + final MeasurementResult result = MeasurementResult( + constraints.width, + isSingleLine: lineCount == 1, + alphabeticBaseline: ruler.alphabeticBaseline, + ideographicBaseline: ruler.alphabeticBaseline * _baselineRatioHack, + height: height, + naturalHeight: naturalHeight, + lineHeight: lineHeight, + // `minIntrinsicWidth` is the greatest width of text that can't + // be broken down into multiple lines. + minIntrinsicWidth: minIntrinsicCalculator.value, + // `maxIntrinsicWidth` is the width of the widest piece of text + // that doesn't contain mandatory line breaks. + maxIntrinsicWidth: maxIntrinsicCalculator.value, + width: constraints.width, + lines: linesCalculator.lines, + ); + return result; + } + + @override + double measureSubstringWidth(EngineParagraph paragraph, int start, int end) { + final String text = paragraph._plainText; + final ParagraphGeometricStyle style = paragraph._geometricStyle; + _canvasContext.font = style.cssFontString; + return _measureSubstring( + _canvasContext, + paragraph._geometricStyle, + text, + start, + end, + ); + } +} + +// These global variables are used to memoize calls to [_measureSubstring]. They +// are used to remember the last arguments passed to it, and the last return +// value. +// They are being initialized so that the compiler knows they'll never be null. +int _lastStart = -1; +int _lastEnd = -1; +String _lastText = ''; +ParagraphGeometricStyle _lastStyle; +double _lastWidth = -1; + +/// Measures the width of the substring of [text] starting from the index +/// [start] (inclusive) to [end] (exclusive). +/// +/// This method assumes that the correct font has already been set on +/// [_canvasContext]. +double _measureSubstring( + html.CanvasRenderingContext2D _canvasContext, + ParagraphGeometricStyle style, + String text, + int start, + int end, +) { + assert(0 <= start && start <= end && end <= text.length); + + if (start == end) { + return 0; + } + + if (start == _lastStart && + end == _lastEnd && + text == _lastText && + _lastStyle == style) { + return _lastWidth; + } + _lastStart = start; + _lastEnd = end; + _lastText = text; + _lastStyle = style; + + final double letterSpacing = style.letterSpacing ?? 0.0; + final String sub = + start == 0 && end == text.length ? text : text.substring(start, end); + final double width = + _canvasContext.measureText(sub).width + letterSpacing * sub.length; + + // What we are doing here is we are rounding to the nearest 2nd decimal + // point. So 39.999423 becomes 40, and 11.243982 becomes 11.24. + // The reason we are doing this is because we noticed that canvas API has a + // ±0.001 error margin. + return _lastWidth = _roundWidth(width); +} + +double _roundWidth(double width) { + return (width * 100).round() / 100; +} + +/// From the substring defined by [text], [start] (inclusive) and [end] +/// (exclusive), exclude trailing characters that satisfy the given [predicate]. +/// +/// The return value is the new end of the substring after excluding the +/// trailing characters. +int _excludeTrailing(String text, int start, int end, CharPredicate predicate) { + assert(0 <= start && start <= end && end <= text.length); + + while (start < end && predicate(text.codeUnitAt(end - 1))) { + end--; + } + return end; +} + +/// During the text layout phase, this class splits the lines of text so that it +/// ends up fitting into the given width constraint. +/// +/// It mimicks the Flutter engine's behavior when it comes to handling ellipsis +/// and max lines. +class LinesCalculator { + LinesCalculator(this._canvasContext, this._text, this._style, this._maxWidth); + + final html.CanvasRenderingContext2D _canvasContext; + final String _text; + final ParagraphGeometricStyle _style; + final double _maxWidth; + + /// The lines that have been consumed so far. + List lines = []; + + int _lineStart = 0; + int _chunkStart = 0; + bool _reachedMaxLines = false; + + double _cachedEllipsisWidth; + double get _ellipsisWidth => _cachedEllipsisWidth ??= + _roundWidth(_canvasContext.measureText(_style.ellipsis).width); + + bool get hasEllipsis => _style.ellipsis != null; + bool get unlimitedLines => _style.maxLines == null; + + /// Consumes the next line break opportunity in [_text]. + /// + /// This method should be called for every line break. As soon as it reaches + /// the maximum number of lines required + void update(LineBreakResult brk) { + final bool isHardBreak = brk.type == LineBreakType.mandatory || + brk.type == LineBreakType.endOfText; + final int chunkEnd = brk.index; + final int chunkEndWithoutSpace = + _excludeTrailing(_text, _chunkStart, chunkEnd, _whitespacePredicate); + + // A single chunk of text could be force-broken into multiple lines if it + // doesn't fit in a single line. That's why we need a loop. + while (!_reachedMaxLines) { + final double lineWidth = _measureSubstring( + _canvasContext, + _style, + _text, + _lineStart, + chunkEndWithoutSpace, + ); + + // The current chunk doesn't reach the maximum width, so we stop here and + // wait for the next line break. + if (lineWidth <= _maxWidth) { + break; + } + + // If the current chunk starts at the beginning of the line and exceeds + // [maxWidth], then we will need to force-break it. + final bool isChunkTooLong = _chunkStart == _lineStart; + + // When ellipsis is set, and maxLines is null, we stop at the first line + // that exceeds [maxWidth]. + final bool isLastLine = _reachedMaxLines = + (hasEllipsis && unlimitedLines) || + lines.length + 1 == _style.maxLines; + + if (isLastLine && hasEllipsis) { + // When there's an ellipsis, truncate text to leave enough space for + // the ellipsis. + final double availableWidth = _maxWidth - _ellipsisWidth; + final int breakingPoint = _forceBreak( + availableWidth, + _text, + _lineStart, + chunkEndWithoutSpace, + ); + lines.add(_text.substring(_lineStart, breakingPoint) + _style.ellipsis); + } else if (isChunkTooLong) { + final int breakingPoint = + _forceBreak(_maxWidth, _text, _lineStart, chunkEndWithoutSpace); + if (breakingPoint == chunkEndWithoutSpace) { + // We could force-break the chunk any further which means we reached + // the last character and there isn't enough space for it to fit in + // its own line. Since this is the last character in the chunk, we + // don't do anything here and we rely on the next iteration (or the + // [isHardBreak] check below) to break the line. + break; + } + _addLineBreak(lineEnd: breakingPoint); + _chunkStart = breakingPoint; + } else { + // The control case of current line exceeding [_maxWidth], we break the + // line. + _addLineBreak(lineEnd: _chunkStart); + } + } + + if (_reachedMaxLines) { + return; + } + + if (isHardBreak) { + _addLineBreak(lineEnd: chunkEnd); + } + _chunkStart = chunkEnd; + } + + void _addLineBreak({@required int lineEnd}) { + final int indexWithoutNewlines = _excludeTrailing( + _text, + _lineStart, + lineEnd, + _newlinePredicate, + ); + lines.add(_text.substring(_lineStart, indexWithoutNewlines)); + _lineStart = lineEnd; + if (lines.length == _style.maxLines) { + _reachedMaxLines = true; + } + } + + /// In a continuous block of text, finds the point where text can be broken to + /// fit in the given constraint [maxWidth]. + /// + /// This always returns at least one character even if there isn't enough + /// space for it. + int _forceBreak(double maxWidth, String text, int start, int end) { + assert(0 <= start && start < end && end <= text.length); + + int low = hasEllipsis ? start : start + 1; + int high = end; + do { + final int mid = (low + high) ~/ 2; + final double width = + _measureSubstring(_canvasContext, _style, text, start, mid); + if (width < maxWidth) { + low = mid; + } else if (width > maxWidth) { + high = mid; + } else { + low = high = mid; + } + } while (high - low > 1); + + // The breaking point should be at least one character away from [start]. + return low; + } +} + +/// During the text layout phase, this class takes care of calculating the +/// minimum intrinsic width of the given text. +class MinIntrinsicCalculator { + MinIntrinsicCalculator(this._canvasContext, this._text, this._style); + + final html.CanvasRenderingContext2D _canvasContext; + final String _text; + final ParagraphGeometricStyle _style; + + /// The value of minimum intrinsic width calculated so far. + double value = 0.0; + int _lastChunkEnd = 0; + + /// Consumes the next line break opportunity in [_text]. + /// + /// As this method gets called, it updates the [value] to the minimum + /// intrinsic width calculated so far. When the whole text is consumed, + /// [value] will contain the final minimum intrinsic width. + void update(LineBreakResult brk) { + final int chunkEnd = brk.index; + final int chunkEndWithoutSpace = + _excludeTrailing(_text, _lastChunkEnd, chunkEnd, _whitespacePredicate); + final double width = _measureSubstring( + _canvasContext, _style, _text, _lastChunkEnd, chunkEndWithoutSpace); + if (width > value) { + value = width; + } + _lastChunkEnd = chunkEnd; + } +} + +/// During text layout, this class is responsible for calculating the maximum +/// intrinsic width of the given text. +class MaxIntrinsicCalculator { + MaxIntrinsicCalculator(this._canvasContext, this._text, this._style); + + final html.CanvasRenderingContext2D _canvasContext; + final String _text; + final ParagraphGeometricStyle _style; + + /// The value of maximum intrinsic width calculated so far. + double value = 0.0; + int _lastHardLineEnd = 0; + + /// Consumes the next line break opportunity in [_text]. + /// + /// As this method gets called, it updates the [value] to the maximum + /// intrinsic width calculated so far. When the whole text is consumed, + /// [value] will contain the final maximum intrinsic width. + void update(LineBreakResult brk) { + if (brk.type == LineBreakType.opportunity) { + return; + } + + final int hardLineEnd = brk.index; + final int hardLineEndWithoutNewlines = _excludeTrailing( + _text, + _lastHardLineEnd, + hardLineEnd, + _newlinePredicate, + ); + final double lineWidth = _measureSubstring( + _canvasContext, + _style, + _text, + _lastHardLineEnd, + hardLineEndWithoutNewlines, + ); + if (lineWidth > value) { + value = lineWidth; + } + _lastHardLineEnd = hardLineEnd; + } +} 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 new file mode 100644 index 0000000000..448faf8f46 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/paragraph.dart @@ -0,0 +1,1310 @@ +// 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; + +/// The web implementation of [ui.Paragraph]. +class EngineParagraph implements ui.Paragraph { + /// This class is created by the engine, and should not be instantiated + /// or extended directly. + /// + /// To create a [ui.Paragraph] object, use a [ui.ParagraphBuilder]. + EngineParagraph({ + @required html.HtmlElement paragraphElement, + @required ParagraphGeometricStyle geometricStyle, + @required String plainText, + @required ui.Paint paint, + @required ui.TextAlign textAlign, + @required ui.TextDirection textDirection, + @required ui.Paint background, + }) : assert((plainText == null && paint == null) || + (plainText != null && paint != null)), + _paragraphElement = paragraphElement, + _geometricStyle = geometricStyle, + _plainText = plainText, + _textAlign = textAlign, + _textDirection = textDirection, + _paint = paint, + _background = background; + + final html.HtmlElement _paragraphElement; + final ParagraphGeometricStyle _geometricStyle; + final String _plainText; + final ui.Paint _paint; + final ui.TextAlign _textAlign; + final ui.TextDirection _textDirection; + final ui.Paint _background; + + @visibleForTesting + String get plainText => _plainText; + + @visibleForTesting + html.HtmlElement get paragraphElement => _paragraphElement; + + @visibleForTesting + ParagraphGeometricStyle get geometricStyle => _geometricStyle; + + /// The instance of [TextMeasurementService] to be used to measure this + /// paragraph. + TextMeasurementService get _measurementService => + TextMeasurementService.forParagraph(this); + + /// The measurement result of the last layout operation. + MeasurementResult _measurementResult; + + @override + double get width => _measurementResult?.width ?? -1; + + @override + double get height => _measurementResult?.height ?? 0; + + /// {@template dart.ui.paragraph.naturalHeight} + /// The amount of vertical space the paragraph occupies while ignoring the + /// [ParagraphGeometricStyle.maxLines] constraint. + /// {@endtemplate} + /// + /// Valid only after [layout] has been called. + double get _naturalHeight => _measurementResult?.naturalHeight ?? 0; + + /// The amount of vertical space one line of this paragraph occupies. + /// + /// Valid only after [layout] has been called. + double get _lineHeight => _measurementResult?.lineHeight ?? 0; + + // TODO(flutter_web): see https://github.com/flutter/flutter/issues/33613. + @override + double get longestLine => 0; + + @override + double get minIntrinsicWidth => _measurementResult?.minIntrinsicWidth ?? 0; + + @override + double get maxIntrinsicWidth => _measurementResult?.maxIntrinsicWidth ?? 0; + + @override + double get alphabeticBaseline => _measurementResult?.alphabeticBaseline ?? -1; + + @override + double get ideographicBaseline => + _measurementResult?.ideographicBaseline ?? -1; + + @override + bool get didExceedMaxLines => _didExceedMaxLines; + bool _didExceedMaxLines = false; + + ui.ParagraphConstraints _lastUsedConstraints; + + /// Returns horizontal alignment offset for single line text when rendering + /// directly into a canvas without css text alignment styling. + double _alignOffset = 0.0; + + /// If not null, this list would contain the strings representing each line + /// in the paragraph. + List get _lines => _measurementResult?.lines; + + @override + void layout(ui.ParagraphConstraints constraints) { + if (constraints == _lastUsedConstraints) { + return; + } + + _measurementResult = _measurementService.measure(this, constraints); + _lastUsedConstraints = constraints; + + if (_geometricStyle.maxLines != null) { + _didExceedMaxLines = _naturalHeight > height; + } else { + _didExceedMaxLines = false; + } + + if (_measurementResult.isSingleLine && constraints != null) { + switch (_textAlign) { + case ui.TextAlign.center: + _alignOffset = (constraints.width - maxIntrinsicWidth) / 2.0; + break; + case ui.TextAlign.right: + _alignOffset = constraints.width - maxIntrinsicWidth; + break; + case ui.TextAlign.start: + _alignOffset = _textDirection == ui.TextDirection.rtl + ? constraints.width - maxIntrinsicWidth + : 0.0; + break; + case ui.TextAlign.end: + _alignOffset = _textDirection == ui.TextDirection.ltr + ? constraints.width - maxIntrinsicWidth + : 0.0; + break; + default: + _alignOffset = 0.0; + break; + } + } + } + + @override + List getBoxesForPlaceholders() { + return const []; + } + + /// Returns `true` if this paragraph can be directly painted to the canvas. + /// + /// + /// Examples of paragraphs that can't be drawn directly on the canvas: + /// + /// - Rich text where there are multiple pieces of text that have different + /// styles. + /// - Paragraphs that contain decorations. + /// - Paragraphs that have a non-null word-spacing. + /// - Paragraphs with a background. + bool get _drawOnCanvas { + bool canDrawTextOnCanvas; + if (TextMeasurementService.enableExperimentalCanvasImplementation) { + canDrawTextOnCanvas = _lines != null; + } else { + canDrawTextOnCanvas = _measurementResult.isSingleLine && + _plainText != null && + _geometricStyle.ellipsis == null; + } + + return canDrawTextOnCanvas && + _geometricStyle.decoration == null && + _geometricStyle.wordSpacing == null; + } + + /// Whether this paragraph has been laid out. + bool get _isLaidOut => _measurementResult != null; + + /// Asserts that the properties used to measure paragraph layout are the same + /// as the properties of this paragraphs root style. + /// + /// Ignores properties that do not affect layout, such as + /// [ParagraphStyle.textAlign]. + bool _debugHasSameRootStyle(ParagraphGeometricStyle style) { + assert(() { + if (style != _geometricStyle) { + throw Exception('Attempted to measure a paragraph whose style is ' + 'different from the style of the ruler used to measure it.'); + } + return true; + }()); + return true; + } + + @override + List getBoxesForRange( + int start, + int end, { + ui.BoxHeightStyle boxHeightStyle = ui.BoxHeightStyle.tight, + ui.BoxWidthStyle boxWidthStyle = ui.BoxWidthStyle.tight, + }) { + assert(boxHeightStyle != null); + assert(boxWidthStyle != null); + if (_plainText == null) { + return []; + } + + final int length = _plainText.length; + // Ranges that are out of bounds should return an empty list. + if (start < 0 || end < 0 || start > length || end > length) { + return []; + } + + return _measurementService.measureBoxesForRange( + this, + _lastUsedConstraints, + start: start, + end: end, + alignOffset: _alignOffset, + textDirection: _textDirection, + ); + } + + ui.Paragraph _cloneWithText(String plainText) { + return EngineParagraph( + plainText: plainText, + paragraphElement: _paragraphElement.clone(true), + geometricStyle: _geometricStyle, + paint: _paint, + textAlign: _textAlign, + textDirection: _textDirection, + background: _background, + ); + } + + @override + ui.TextPosition getPositionForOffset(ui.Offset offset) { + if (_plainText == null) { + return const ui.TextPosition(offset: 0); + } + + final double dx = offset.dx - _alignOffset; + final TextMeasurementService instance = _measurementService; + + int low = 0; + int high = _plainText.length; + do { + final int current = (low + high) ~/ 2; + final double width = instance.measureSubstringWidth(this, 0, current); + if (width < dx) { + low = current; + } else if (width > dx) { + high = current; + } else { + low = high = current; + } + } while (high - low > 1); + + if (low == high) { + // The offset falls exactly in between the two letters. + return ui.TextPosition(offset: high, affinity: ui.TextAffinity.upstream); + } + + final double lowWidth = instance.measureSubstringWidth(this, 0, low); + final double highWidth = instance.measureSubstringWidth(this, 0, high); + + if (dx - lowWidth < highWidth - dx) { + // The offset is closer to the low index. + return ui.TextPosition(offset: low, affinity: ui.TextAffinity.downstream); + } else { + // The offset is closer to high index. + return ui.TextPosition(offset: high, affinity: ui.TextAffinity.upstream); + } + } + + @override + List getWordBoundary(int offset) { + if (_plainText == null) { + return [offset, offset]; + } + + final int start = WordBreaker.prevBreakIndex(_plainText, offset); + final int end = WordBreaker.nextBreakIndex(_plainText, offset); + return [start, end]; + } +} + +/// The web implementation of [ui.ParagraphStyle]. +class EngineParagraphStyle implements ui.ParagraphStyle { + /// Creates a new instance of [EngineParagraphStyle]. + EngineParagraphStyle({ + ui.TextAlign textAlign, + ui.TextDirection textDirection, + int maxLines, + String fontFamily, + double fontSize, + double height, + ui.FontWeight fontWeight, + ui.FontStyle fontStyle, + ui.StrutStyle strutStyle, + String ellipsis, + ui.Locale locale, + }) : _textAlign = textAlign, + _textDirection = textDirection, + _fontWeight = fontWeight, + _fontStyle = fontStyle, + _maxLines = maxLines, + _fontFamily = fontFamily, + _fontSize = fontSize, + _height = height, + // TODO(b/128317744): add support for strut style. + _strutStyle = strutStyle, + _ellipsis = ellipsis, + _locale = locale; + + final ui.TextAlign _textAlign; + final ui.TextDirection _textDirection; + final ui.FontWeight _fontWeight; + final ui.FontStyle _fontStyle; + final int _maxLines; + final String _fontFamily; + final double _fontSize; + final double _height; + final EngineStrutStyle _strutStyle; + final String _ellipsis; + final ui.Locale _locale; + + String get _effectiveFontFamily { + if (assertionsEnabled) { + // In the flutter tester environment, we use a predictable-size font + // "Ahem". This makes widget tests predictable and less flaky. + if (ui.debugEmulateFlutterTesterEnvironment) { + return 'Ahem'; + } + } + if (_fontFamily == null || _fontFamily.isEmpty) { + return DomRenderer.defaultFontFamily; + } + return _fontFamily; + } + + double get _lineHeight { + if (_strutStyle == null || _strutStyle._height == null) { + // When there's no strut height, always use paragraph style height. + return _height; + } + if (_strutStyle._forceStrutHeight == true) { + // When strut height is forced, ignore paragraph style height. + return _strutStyle._height; + } + // In this case, strut height acts as a minimum height for all parts of the + // paragraph. So we take the max of strut height and paragraph style height. + return math.max(_strutStyle._height, _height ?? 0.0); + } + + @override + bool operator ==(dynamic other) { + if (identical(this, other)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + final EngineParagraphStyle typedOther = other; + return _textAlign == typedOther._textAlign || + _textDirection == typedOther._textDirection || + _fontWeight == typedOther._fontWeight || + _fontStyle == typedOther._fontStyle || + _maxLines == typedOther._maxLines || + _fontFamily == typedOther._fontFamily || + _fontSize == typedOther._fontSize || + _height == typedOther._height || + _ellipsis == typedOther._ellipsis || + _locale == typedOther._locale; + } + + @override + int get hashCode => + ui.hashValues(_fontFamily, _fontSize, _height, _ellipsis, _locale); + + @override + String toString() { + if (assertionsEnabled) { + return 'ParagraphStyle(' + 'textAlign: ${_textAlign ?? "unspecified"}, ' + 'textDirection: ${_textDirection ?? "unspecified"}, ' + 'fontWeight: ${_fontWeight ?? "unspecified"}, ' + 'fontStyle: ${_fontStyle ?? "unspecified"}, ' + 'maxLines: ${_maxLines ?? "unspecified"}, ' + 'fontFamily: ${_fontFamily ?? "unspecified"}, ' + 'fontSize: ${_fontSize != null ? _fontSize.toStringAsFixed(1) : "unspecified"}, ' + 'height: ${_height != null ? "${_height.toStringAsFixed(1)}x" : "unspecified"}, ' + 'ellipsis: ${_ellipsis != null ? "\"$_ellipsis\"" : "unspecified"}, ' + 'locale: ${_locale ?? "unspecified"}' + ')'; + } else { + return super.toString(); + } + } +} + +/// The web implementation of [ui.TextStyle]. +class EngineTextStyle implements ui.TextStyle { + EngineTextStyle({ + ui.Color color, + ui.TextDecoration decoration, + ui.Color decorationColor, + ui.TextDecorationStyle decorationStyle, + double decorationThickness, + ui.FontWeight fontWeight, + ui.FontStyle fontStyle, + ui.TextBaseline textBaseline, + String fontFamily, + List fontFamilyFallback, + double fontSize, + double letterSpacing, + double wordSpacing, + double height, + ui.Locale locale, + ui.Paint background, + ui.Paint foreground, + List shadows, + List fontFeatures, + }) : assert( + color == null || foreground == null, + 'Cannot provide both a color and a foreground\n' + 'The color argument is just a shorthand for "foreground: new Paint()..color = color".'), + _color = color, + _decoration = decoration, + _decorationColor = decorationColor, + _decorationStyle = decorationStyle, + _fontWeight = fontWeight, + _fontStyle = fontStyle, + _textBaseline = textBaseline, + // TODO(b/128311960): when font fallback is supported, we should check + // for it here. + _isFontFamilyProvided = fontFamily != null, + _fontFamily = fontFamily ?? '', + // TODO(b/128311960): add support for font family fallback. + _fontFamilyFallback = fontFamilyFallback, + _fontSize = fontSize, + _letterSpacing = letterSpacing, + _wordSpacing = wordSpacing, + _height = height, + _locale = locale, + _background = background, + _foreground = foreground, + _shadows = shadows; + + final ui.Color _color; + final ui.TextDecoration _decoration; + final ui.Color _decorationColor; + final ui.TextDecorationStyle _decorationStyle; + final ui.FontWeight _fontWeight; + final ui.FontStyle _fontStyle; + final ui.TextBaseline _textBaseline; + final bool _isFontFamilyProvided; + final String _fontFamily; + final List _fontFamilyFallback; + final double _fontSize; + final double _letterSpacing; + final double _wordSpacing; + final double _height; + final ui.Locale _locale; + final ui.Paint _background; + final ui.Paint _foreground; + final List _shadows; + + String get _effectiveFontFamily { + if (assertionsEnabled) { + // In the flutter tester environment, we use a predictable-size font + // "Ahem". This makes widget tests predictable and less flaky. + if (ui.debugEmulateFlutterTesterEnvironment) { + return 'Ahem'; + } + } + if (_fontFamily == null || _fontFamily.isEmpty) { + return DomRenderer.defaultFontFamily; + } + return _fontFamily; + } + + @override + bool operator ==(dynamic other) { + if (identical(this, other)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + final EngineTextStyle typedOther = other; + return _color == typedOther._color && + _decoration == typedOther._decoration && + _decorationColor == typedOther._decorationColor && + _decorationStyle == typedOther._decorationStyle && + _fontWeight == typedOther._fontWeight && + _fontStyle == typedOther._fontStyle && + _textBaseline == typedOther._textBaseline && + _fontFamily == typedOther._fontFamily && + _fontSize == typedOther._fontSize && + _letterSpacing == typedOther._letterSpacing && + _wordSpacing == typedOther._wordSpacing && + _height == typedOther._height && + _locale == typedOther._locale && + _background == typedOther._background && + _foreground == typedOther._foreground && + _listEquals(_shadows, typedOther._shadows) && + _listEquals( + _fontFamilyFallback, typedOther._fontFamilyFallback); + } + + @override + int get hashCode => ui.hashValues( + _color, + _decoration, + _decorationColor, + _decorationStyle, + _fontWeight, + _fontStyle, + _textBaseline, + _fontFamily, + _fontFamilyFallback, + _fontSize, + _letterSpacing, + _wordSpacing, + _height, + _locale, + _background, + _foreground, + _shadows, + ); + + @override + String toString() { + if (assertionsEnabled) { + return 'TextStyle(' + 'color: ${_color != null ? _color : "unspecified"}, ' + 'decoration: ${_decoration ?? "unspecified"}, ' + 'decorationColor: ${_decorationColor ?? "unspecified"}, ' + 'decorationStyle: ${_decorationStyle ?? "unspecified"}, ' + 'fontWeight: ${_fontWeight ?? "unspecified"}, ' + 'fontStyle: ${_fontStyle ?? "unspecified"}, ' + 'textBaseline: ${_textBaseline ?? "unspecified"}, ' + 'fontFamily: ${_isFontFamilyProvided && _fontFamily != null ? _fontFamily : "unspecified"}, ' + 'fontFamilyFallback: ${_isFontFamilyProvided && _fontFamilyFallback != null && _fontFamilyFallback.isNotEmpty ? _fontFamilyFallback : "unspecified"}, ' + 'fontSize: ${_fontSize != null ? _fontSize.toStringAsFixed(1) : "unspecified"}, ' + 'letterSpacing: ${_letterSpacing != null ? "${_letterSpacing}x" : "unspecified"}, ' + 'wordSpacing: ${_wordSpacing != null ? "${_wordSpacing}x" : "unspecified"}, ' + 'height: ${_height != null ? "${_height.toStringAsFixed(1)}x" : "unspecified"}, ' + 'locale: ${_locale ?? "unspecified"}, ' + 'background: ${_background ?? "unspecified"}, ' + 'foreground: ${_foreground ?? "unspecified"}, ' + 'shadows: ${_shadows ?? "unspecified"}' + ')'; + } else { + return super.toString(); + } + } +} + +/// The web implementation of [ui.StrutStyle]. +class EngineStrutStyle implements ui.StrutStyle { + /// Creates a new StrutStyle object. + /// + /// * `fontFamily`: The name of the font to use when painting the text (e.g., + /// Roboto). + /// + /// * `fontFamilyFallback`: An ordered list of font family names that will be searched for when + /// the font in `fontFamily` cannot be found. + /// + /// * `fontSize`: The size of glyphs (in logical pixels) to use when painting + /// the text. + /// + /// * `lineHeight`: The minimum height of the line boxes, as a multiple of the + /// font size. The lines of the paragraph will be at least + /// `(lineHeight + leading) * fontSize` tall when fontSize + /// is not null. When fontSize is null, there is no minimum line height. Tall + /// glyphs due to baseline alignment or large [TextStyle.fontSize] may cause + /// the actual line height after layout to be taller than specified here. + /// [fontSize] must be provided for this property to take effect. + /// + /// * `leading`: The minimum amount of leading between lines as a multiple of + /// the font size. [fontSize] must be provided for this property to take effect. + /// + /// * `fontWeight`: The typeface thickness to use when painting the text + /// (e.g., bold). + /// + /// * `fontStyle`: The typeface variant to use when drawing the letters (e.g., + /// italics). + /// + /// * `forceStrutHeight`: When true, the paragraph will force all lines to be exactly + /// `(lineHeight + leading) * fontSize` tall from baseline to baseline. + /// [TextStyle] is no longer able to influence the line height, and any tall + /// glyphs may overlap with lines above. If a [fontFamily] is specified, the + /// total ascent of the first line will be the min of the `Ascent + half-leading` + /// of the [fontFamily] and `(lineHeight + leading) * fontSize`. Otherwise, it + /// will be determined by the Ascent + half-leading of the first text. + EngineStrutStyle({ + String fontFamily, + List fontFamilyFallback, + double fontSize, + double height, + double leading, + ui.FontWeight fontWeight, + ui.FontStyle fontStyle, + bool forceStrutHeight, + }) : _fontFamily = fontFamily, + _fontFamilyFallback = fontFamilyFallback, + _fontSize = fontSize, + _height = height, + _leading = leading, + _fontWeight = fontWeight, + _fontStyle = fontStyle, + _forceStrutHeight = forceStrutHeight; + + final String _fontFamily; + final List _fontFamilyFallback; + final double _fontSize; + final double _height; + final double _leading; + final ui.FontWeight _fontWeight; + final ui.FontStyle _fontStyle; + final bool _forceStrutHeight; + + @override + bool operator ==(dynamic other) { + if (identical(this, other)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + final EngineStrutStyle typedOther = other; + return _fontFamily == typedOther._fontFamily && + _fontSize == typedOther._fontSize && + _height == typedOther._height && + _leading == typedOther._leading && + _fontWeight == typedOther._fontWeight && + _fontStyle == typedOther._fontStyle && + _forceStrutHeight == typedOther._forceStrutHeight && + _listEquals( + _fontFamilyFallback, typedOther._fontFamilyFallback); + } + + @override + int get hashCode => ui.hashValues( + _fontFamily, + _fontFamilyFallback, + _fontSize, + _height, + _leading, + _fontWeight, + _fontStyle, + _forceStrutHeight, + ); +} + +/// The web implementation of [ui.ParagraphBuilder]. +class EngineParagraphBuilder implements ui.ParagraphBuilder { + /// Marks a call to the [pop] method in the [_ops] list. + static final Object _paragraphBuilderPop = Object(); + + final html.HtmlElement _paragraphElement = domRenderer.createElement('p'); + final EngineParagraphStyle _paragraphStyle; + final List _ops = []; + + /// Creates an [EngineParagraphBuilder] object, which is used to create a + /// [EngineParagraph]. + EngineParagraphBuilder(EngineParagraphStyle style) : _paragraphStyle = style { + // TODO(b/128317744): Implement support for strut font families. + List strutFontFamilies; + if (style._strutStyle != null) { + strutFontFamilies = []; + if (style._strutStyle._fontFamily != null) { + strutFontFamilies.add(style._strutStyle._fontFamily); + } + if (style._strutStyle._fontFamilyFallback != null) { + strutFontFamilies.addAll(style._strutStyle._fontFamilyFallback); + } + } + _applyParagraphStyleToElement( + element: _paragraphElement, style: _paragraphStyle); + } + + /// Applies the given style to the added text until [pop] is called. + /// + /// See [pop] for details. + @override + void pushStyle(ui.TextStyle style) { + _ops.add(style); + } + + @override + int get placeholderCount => _placeholderCount; + int _placeholderCount; + + @override + List get placeholderScales => _placeholderScales; + List _placeholderScales = []; + + @override + void addPlaceholder( + double width, + double height, + ui.PlaceholderAlignment alignment, { + double scale, + double baselineOffset, + ui.TextBaseline baseline, + }) { + // TODO(garyq): Implement web_ui version of this. + throw UnimplementedError(); + } + + // TODO(yjbanov): do we need to do this? +// static String _encodeLocale(Locale locale) => locale?.toString() ?? ''; + + /// Ends the effect of the most recent call to [pushStyle]. + /// + /// Internally, the paragraph builder maintains a stack of text styles. Text + /// added to the paragraph is affected by all the styles in the stack. Calling + /// [pop] removes the topmost style in the stack, leaving the remaining styles + /// in effect. + @override + void pop() { + _ops.add(_paragraphBuilderPop); + } + + /// Adds the given text to the paragraph. + /// + /// The text will be styled according to the current stack of text styles. + @override + void addText(String text) { + _ops.add(text); + } + + /// Applies the given paragraph style and returns a [Paragraph] containing the + /// added text and associated styling. + /// + /// After calling this function, the paragraph builder object is invalid and + /// cannot be used further. + @override + EngineParagraph build() { + return _tryBuildPlainText() ?? _buildRichText(); + } + + /// Attempts to build a [Paragraph] assuming it is plain text. + /// + /// A paragraph is considered plain if it is built using the following + /// sequence of ops: + /// + /// * Zero-or-more calls to [pushStyle]. + /// * One-or-more calls to [addText]. + /// * Zero-or-more calls to [pop]. + /// + /// Any other sequence will result in `null` and should be treated as rich + /// text. + /// + /// Plain text is not the same as not having style. The text may be styled + /// arbitrarily. However, it may not mix multiple styles in the same + /// paragraph. Plain text is more efficient to lay out and measure than rich + /// text. + EngineParagraph _tryBuildPlainText() { + ui.Color color; + ui.TextDecoration decoration; + ui.Color decorationColor; + ui.TextDecorationStyle decorationStyle; + ui.FontWeight fontWeight = _paragraphStyle._fontWeight; + ui.FontStyle fontStyle = _paragraphStyle._fontStyle; + ui.TextBaseline textBaseline; + String fontFamily = _paragraphStyle._fontFamily; + double fontSize = _paragraphStyle._fontSize; + final ui.TextAlign textAlign = _paragraphStyle._textAlign; + final ui.TextDirection textDirection = _paragraphStyle._textDirection; + double letterSpacing; + double wordSpacing; + double height; + ui.Locale locale = _paragraphStyle._locale; + ui.Paint background; + ui.Paint foreground; + + int i = 0; + + // This loop looks expensive. However, in reality most of plain text + // paragraphs will have no calls to [pushStyle], skipping this loop + // entirely. Occasionally there will be one [pushStyle], which causes this + // loop to run once then move on to aggregating text. + while (i < _ops.length && _ops[i] is EngineTextStyle) { + final EngineTextStyle style = _ops[i]; + if (style._color != null) { + color = style._color; + } + if (style._decoration != null) { + decoration = style._decoration; + } + if (style._decorationColor != null) { + decorationColor = style._decorationColor; + } + if (style._decorationStyle != null) { + decorationStyle = style._decorationStyle; + } + if (style._fontWeight != null) { + fontWeight = style._fontWeight; + } + if (style._fontStyle != null) { + fontStyle = style._fontStyle; + } + if (style._textBaseline != null) { + textBaseline = style._textBaseline; + } + if (style._fontFamily != null) { + fontFamily = style._fontFamily; + } + if (style._fontSize != null) { + fontSize = style._fontSize; + } + if (style._letterSpacing != null) { + letterSpacing = style._letterSpacing; + } + if (style._wordSpacing != null) { + wordSpacing = style._wordSpacing; + } + if (style._height != null) { + height = style._height; + } + if (style._locale != null) { + locale = style._locale; + } + if (style._background != null) { + background = style._background; + } + if (style._foreground != null) { + foreground = style._foreground; + } + i++; + } + + final EngineTextStyle cumulativeStyle = EngineTextStyle( + color: color, + decoration: decoration, + decorationColor: decorationColor, + decorationStyle: decorationStyle, + fontWeight: fontWeight, + fontStyle: fontStyle, + textBaseline: textBaseline, + fontFamily: fontFamily, + fontSize: fontSize, + letterSpacing: letterSpacing, + wordSpacing: wordSpacing, + height: height, + locale: locale, + background: background, + foreground: foreground, + ); + + ui.Paint paint; + if (foreground != null) { + paint = foreground; + } else { + paint = ui.Paint(); + if (color != null) { + paint.color = color; + } + } + + if (i >= _ops.length) { + // Empty paragraph. + _applyTextStyleToElement( + element: _paragraphElement, style: cumulativeStyle); + return EngineParagraph( + paragraphElement: _paragraphElement, + geometricStyle: ParagraphGeometricStyle( + fontFamily: fontFamily, + fontWeight: fontWeight, + fontStyle: fontStyle, + fontSize: fontSize, + lineHeight: height, + maxLines: _paragraphStyle._maxLines, + letterSpacing: letterSpacing, + wordSpacing: wordSpacing, + decoration: _textDecorationToCssString(decoration, decorationStyle), + ellipsis: _paragraphStyle._ellipsis, + ), + plainText: '', + paint: paint, + textAlign: textAlign, + textDirection: textDirection, + background: cumulativeStyle._background, + ); + } + + if (_ops[i] is! String) { + // After a series of [EngineTextStyle] ops there must be at least one text op. + // Otherwise, treat it as rich text. + return null; + } + + // Accumulate text into one contiguous string. + final StringBuffer plainTextBuffer = StringBuffer(); + while (i < _ops.length && _ops[i] is String) { + plainTextBuffer.write(_ops[i]); + i++; + } + + // After a series of [addText] ops there should only be a tail of [pop]s and + // nothing else. Otherwise it's rich text and we return null; + for (; i < _ops.length; i++) { + if (_ops[i] != _paragraphBuilderPop) { + return null; + } + } + + final String plainText = plainTextBuffer.toString(); + domRenderer.appendText(_paragraphElement, plainText); + _applyTextStyleToElement( + element: _paragraphElement, style: cumulativeStyle); + // Since this is a plain paragraph apply background color to paragraph tag + // instead of individual spans. + if (cumulativeStyle._background != null) { + _applyTextBackgroundToElement( + element: _paragraphElement, style: cumulativeStyle); + } + return EngineParagraph( + paragraphElement: _paragraphElement, + geometricStyle: ParagraphGeometricStyle( + fontFamily: fontFamily, + fontWeight: fontWeight, + fontStyle: fontStyle, + fontSize: fontSize, + lineHeight: height, + maxLines: _paragraphStyle._maxLines, + letterSpacing: letterSpacing, + wordSpacing: wordSpacing, + decoration: _textDecorationToCssString(decoration, decorationStyle), + ellipsis: _paragraphStyle._ellipsis, + ), + plainText: plainText, + paint: paint, + textAlign: textAlign, + textDirection: textDirection, + background: cumulativeStyle._background, + ); + } + + /// Builds a [Paragraph] as rich text. + EngineParagraph _buildRichText() { + final List elementStack = []; + dynamic currentElement() => + elementStack.isNotEmpty ? elementStack.last : _paragraphElement; + for (int i = 0; i < _ops.length; i++) { + final dynamic op = _ops[i]; + if (op is EngineTextStyle) { + final html.SpanElement span = domRenderer.createElement('span'); + _applyTextStyleToElement(element: span, style: op); + if (op._background != null) { + _applyTextBackgroundToElement(element: span, style: op); + } + domRenderer.append(currentElement(), span); + elementStack.add(span); + } else if (op is String) { + domRenderer.appendText(currentElement(), op); + } else if (identical(op, _paragraphBuilderPop)) { + elementStack.removeLast(); + } else { + throw UnsupportedError('Unsupported ParagraphBuilder operation: $op'); + } + } + + return EngineParagraph( + paragraphElement: _paragraphElement, + geometricStyle: ParagraphGeometricStyle( + fontFamily: _paragraphStyle._fontFamily, + fontWeight: _paragraphStyle._fontWeight, + fontStyle: _paragraphStyle._fontStyle, + fontSize: _paragraphStyle._fontSize, + lineHeight: _paragraphStyle._height, + maxLines: _paragraphStyle._maxLines, + ellipsis: _paragraphStyle._ellipsis, + ), + plainText: null, + paint: null, + textAlign: _paragraphStyle._textAlign, + textDirection: _paragraphStyle._textDirection, + background: null, + ); + } +} + +/// Converts [fontWeight] to its CSS equivalent value. +String fontWeightToCss(ui.FontWeight fontWeight) { + if (fontWeight == null) { + return null; + } + + switch (fontWeight.index) { + case 0: + return '100'; + case 1: + return '200'; + case 2: + return '300'; + case 3: + return 'normal'; + case 4: + return '500'; + case 5: + return '600'; + case 6: + return 'bold'; + case 7: + return '800'; + case 8: + return '900'; + } + + assert(() { + throw AssertionError( + 'Failed to convert font weight $fontWeight to CSS.', + ); + }()); + + return ''; +} + +/// Applies a paragraph [style] to an [element], translating the properties to +/// their corresponding CSS equivalents. +/// +/// If [previousStyle] is not null, updates only the mismatching attributes. +void _applyParagraphStyleToElement({ + @required html.HtmlElement element, + @required EngineParagraphStyle style, + EngineParagraphStyle previousStyle, +}) { + assert(element != null); + assert(style != null); + // TODO(yjbanov): What do we do about ParagraphStyle._locale and ellipsis? + final html.CssStyleDeclaration cssStyle = element.style; + if (previousStyle == null) { + if (style._textAlign != null) { + cssStyle.textAlign = _textAlignToCssValue( + style._textAlign, style._textDirection ?? ui.TextDirection.ltr); + } + if (style._lineHeight != null) { + cssStyle.lineHeight = '${style._lineHeight}'; + } + if (style._textDirection != null) { + cssStyle.direction = _textDirectionToCssValue(style._textDirection); + } + if (style._fontSize != null) { + cssStyle.fontSize = '${style._fontSize.floor()}px'; + } + if (style._fontWeight != null) { + cssStyle.fontWeight = fontWeightToCss(style._fontWeight); + } + if (style._fontStyle != null) { + cssStyle.fontStyle = + style._fontStyle == ui.FontStyle.normal ? 'normal' : 'italic'; + } + if (style._effectiveFontFamily != null) { + cssStyle.fontFamily = style._effectiveFontFamily; + } + } else { + if (style._textAlign != previousStyle._textAlign) { + cssStyle.textAlign = _textAlignToCssValue( + style._textAlign, style._textDirection ?? ui.TextDirection.ltr); + } + if (style._lineHeight != style._lineHeight) { + cssStyle.lineHeight = '${style._lineHeight}'; + } + if (style._textDirection != previousStyle._textDirection) { + cssStyle.direction = _textDirectionToCssValue(style._textDirection); + } + if (style._fontSize != previousStyle._fontSize) { + cssStyle.fontSize = + style._fontSize != null ? '${style._fontSize.floor()}px' : null; + } + if (style._fontWeight != previousStyle._fontWeight) { + cssStyle.fontWeight = fontWeightToCss(style._fontWeight); + } + if (style._fontStyle != previousStyle._fontStyle) { + cssStyle.fontStyle = style._fontStyle != null + ? (style._fontStyle == ui.FontStyle.normal ? 'normal' : 'italic') + : null; + } + if (style._fontFamily != previousStyle._fontFamily) { + cssStyle.fontFamily = style._fontFamily; + } + } +} + +/// Applies a text [style] to an [element], translating the properties to their +/// corresponding CSS equivalents. +/// +/// If [previousStyle] is not null, updates only the mismatching attributes. +void _applyTextStyleToElement({ + @required html.HtmlElement element, + @required EngineTextStyle style, + EngineTextStyle previousStyle, +}) { + assert(element != null); + assert(style != null); + bool updateDecoration = false; + final html.CssStyleDeclaration cssStyle = element.style; + if (previousStyle == null) { + final ui.Color color = style._foreground?.color ?? style._color; + if (color != null) { + cssStyle.color = color.toCssString(); + } + if (style._fontSize != null) { + cssStyle.fontSize = '${style._fontSize.floor()}px'; + } + if (style._fontWeight != null) { + cssStyle.fontWeight = fontWeightToCss(style._fontWeight); + } + if (style._fontStyle != null) { + cssStyle.fontStyle = + style._fontStyle == ui.FontStyle.normal ? 'normal' : 'italic'; + } + if (style._effectiveFontFamily != null) { + cssStyle.fontFamily = style._effectiveFontFamily; + } + if (style._letterSpacing != null) { + cssStyle.letterSpacing = '${style._letterSpacing}px'; + } + if (style._wordSpacing != null) { + cssStyle.wordSpacing = '${style._wordSpacing}px'; + } + if (style._decoration != null) { + updateDecoration = true; + } + } else { + if (style._color != previousStyle._color || + style._foreground != previousStyle._foreground) { + final ui.Color color = style._foreground?.color ?? style._color; + cssStyle.color = color?.toCssString(); + } + + if (style._fontSize != previousStyle._fontSize) { + cssStyle.fontSize = + style._fontSize != null ? '${style._fontSize.floor()}px' : null; + } + + if (style._fontWeight != previousStyle._fontWeight) { + cssStyle.fontWeight = fontWeightToCss(style._fontWeight); + } + + if (style._fontStyle != previousStyle._fontStyle) { + cssStyle.fontStyle = style._fontStyle != null + ? style._fontStyle == ui.FontStyle.normal ? 'normal' : 'italic' + : null; + } + if (style._fontFamily != previousStyle._fontFamily) { + cssStyle.fontFamily = style._fontFamily; + } + if (style._letterSpacing != previousStyle._letterSpacing) { + cssStyle.letterSpacing = '${style._letterSpacing}px'; + } + if (style._wordSpacing != previousStyle._wordSpacing) { + cssStyle.wordSpacing = '${style._wordSpacing}px'; + } + if (style._decoration != previousStyle._decoration || + style._decorationStyle != previousStyle._decorationStyle || + style._decorationColor != previousStyle._decorationColor) { + updateDecoration = true; + } + } + + if (updateDecoration) { + if (style._decoration != null) { + final String textDecoration = + _textDecorationToCssString(style._decoration, style._decorationStyle); + if (textDecoration != null) { + cssStyle.textDecoration = textDecoration; + final ui.Color decorationColor = style._decorationColor; + if (decorationColor != null) { + cssStyle.textDecorationColor = decorationColor.toCssString(); + } + } + } + } +} + +/// Applies background color properties in text style to paragraph or span +/// elements. +void _applyTextBackgroundToElement({ + @required html.HtmlElement element, + @required EngineTextStyle style, + EngineTextStyle previousStyle, +}) { + final ui.Paint newBackground = style._background; + if (previousStyle == null) { + if (newBackground != null) { + domRenderer.setElementStyle( + element, 'background-color', newBackground.color.toCssString()); + } + } else { + if (newBackground != previousStyle._background) { + domRenderer.setElementStyle( + element, 'background-color', newBackground.color?.toCssString()); + } + } +} + +/// Converts text decoration style to CSS text-decoration-style value. +String _textDecorationToCssString( + ui.TextDecoration decoration, ui.TextDecorationStyle decorationStyle) { + final StringBuffer decorations = StringBuffer(); + if (decoration != null) { + if (decoration.contains(ui.TextDecoration.underline)) { + decorations.write('underline '); + } + if (decoration.contains(ui.TextDecoration.overline)) { + decorations.write('overline '); + } + if (decoration.contains(ui.TextDecoration.lineThrough)) { + decorations.write('line-through '); + } + } + if (decorationStyle != null) { + decorations.write(_decorationStyleToCssString(decorationStyle)); + } + return decorations.isEmpty ? null : decorations.toString(); +} + +String _decorationStyleToCssString(ui.TextDecorationStyle decorationStyle) { + switch (decorationStyle) { + case ui.TextDecorationStyle.dashed: + return 'dashed'; + case ui.TextDecorationStyle.dotted: + return 'dotted'; + case ui.TextDecorationStyle.double: + return 'double'; + case ui.TextDecorationStyle.solid: + return 'solid'; + case ui.TextDecorationStyle.wavy: + return 'wavy'; + default: + return null; + } +} + +/// Converts [textDirection] to its corresponding CSS value. +/// +/// This value is used for the "direction" CSS property, e.g.: +/// +/// ```css +/// direction: rtl; +/// ``` +String _textDirectionToCssValue(ui.TextDirection textDirection) { + return textDirection == ui.TextDirection.ltr + ? null // it's the default + : 'rtl'; +} + +/// Converts [align] to its corresponding CSS value. +/// +/// This value is used as the "text-align" CSS property, e.g.: +/// +/// ```css +/// text-align: right; +/// ``` +String _textAlignToCssValue( + ui.TextAlign align, ui.TextDirection textDirection) { + switch (align) { + case ui.TextAlign.left: + return 'left'; + case ui.TextAlign.right: + return 'right'; + case ui.TextAlign.center: + return 'center'; + case ui.TextAlign.justify: + return 'justify'; + case ui.TextAlign.start: + switch (textDirection) { + case ui.TextDirection.ltr: + return null; // it's the default + case ui.TextDirection.rtl: + return 'right'; + } + break; + case ui.TextAlign.end: + switch (textDirection) { + case ui.TextDirection.ltr: + return 'end'; + case ui.TextDirection.rtl: + return 'left'; + } + break; + } + throw AssertionError('Unsupported TextAlign value $align'); +} + +/// Determines if lists [a] and [b] are deep equivalent. +/// +/// Returns true if the lists are both null, or if they are both non-null, have +/// the same length, and contain the same elements in the same order. Returns +/// false otherwise. +bool _listEquals(List a, List b) { + if (a == null) { + return b == null; + } + if (b == null || a.length != b.length) { + return false; + } + for (int index = 0; index < a.length; index += 1) { + if (a[index] != b[index]) { + return false; + } + } + return true; +} 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 new file mode 100644 index 0000000000..97d12477ff --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/ruler.dart @@ -0,0 +1,787 @@ +// 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; + +/// Contains the subset of [ui.ParagraphStyle] properties that affect layout. +class ParagraphGeometricStyle { + ParagraphGeometricStyle({ + this.fontWeight, + this.fontStyle, + this.fontFamily, + this.fontSize, + this.lineHeight, + this.maxLines, + this.letterSpacing, + this.wordSpacing, + this.decoration, + this.ellipsis, + }); + + final ui.FontWeight fontWeight; + final ui.FontStyle fontStyle; + final String fontFamily; + final double fontSize; + final double lineHeight; + final int maxLines; + final double letterSpacing; + final double wordSpacing; + final String decoration; + final String ellipsis; + + // Since all fields above are primitives, cache hashcode since ruler lookups + // use this style as key. + int _cachedHashCode; + + /// Returns the font-family that should be used to style the paragraph. It may + /// or may not be different from [fontFamily]: + /// + /// - Always returns "Ahem" in tests. + /// - Provides correct defaults when [fontFamily] doesn't have a value. + String get effectiveFontFamily { + if (assertionsEnabled) { + // In widget tests we use a predictable-size font "Ahem". This makes + // widget tests predictable and less flaky. + if (ui.debugEmulateFlutterTesterEnvironment) { + return 'Ahem'; + } + } + if (fontFamily == null || fontFamily.isEmpty) { + return DomRenderer.defaultFontFamily; + } + return fontFamily; + } + + String _cssFontString; + + /// Cached font string that can be used in CSS. + /// + /// See . + String get cssFontString => _cssFontString ??= _buildCssFontString(); + + String _buildCssFontString() { + final StringBuffer result = StringBuffer(); + + // Font style + if (fontStyle != null) { + result.write(fontStyle == ui.FontStyle.normal ? 'normal' : 'italic'); + } else { + result.write(DomRenderer.defaultFontStyle); + } + result.write(' '); + + // Font weight. + if (fontWeight != null) { + result.write(fontWeightToCss(fontWeight)); + } else { + result.write(DomRenderer.defaultFontWeight); + } + result.write(' '); + + if (fontSize != null) { + result.write(fontSize.floor()); + result.write('px'); + } else { + result.write(DomRenderer.defaultFontSize); + } + result.write(' '); + result.write(effectiveFontFamily); + + return result.toString(); + } + + @override + bool operator ==(dynamic other) { + if (identical(this, other)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + final ParagraphGeometricStyle typedOther = other; + return fontWeight == typedOther.fontWeight && + fontStyle == typedOther.fontStyle && + fontFamily == typedOther.fontFamily && + fontSize == typedOther.fontSize && + lineHeight == typedOther.lineHeight && + maxLines == typedOther.maxLines && + letterSpacing == typedOther.letterSpacing && + wordSpacing == typedOther.wordSpacing && + decoration == typedOther.decoration && + ellipsis == typedOther.ellipsis; + } + + @override + int get hashCode => _cachedHashCode ??= ui.hashValues( + fontWeight, + fontStyle, + fontFamily, + fontSize, + lineHeight, + maxLines, + letterSpacing, + wordSpacing, + decoration, + ellipsis, + ); + + @override + String toString() { + if (assertionsEnabled) { + return '$runtimeType(fontWeight: $fontWeight, fontStyle: $fontStyle,' + ' fontFamily: $fontFamily, fontSize: $fontSize,' + ' lineHeight: $lineHeight,' + ' maxLines: $maxLines,' + ' letterSpacing: $letterSpacing,' + ' wordSpacing: $wordSpacing,' + ' decoration: $decoration,' + ' ellipsis: $ellipsis,' + ')'; + } else { + return super.toString(); + } + } +} + +/// Provides text dimensions found on [_element]. The idea behind this class is +/// to allow the [ParagraphRuler] to mutate multiple dom elements and allow +/// consumers to lazily read the measurements. +/// +/// The [ParagraphRuler] would have multiple instances of [TextDimensions] with +/// different backing elements for different types of measurements. When a +/// measurement is needed, the [ParagraphRuler] would mutate all the backing +/// elements at once. The consumer of the ruler can later read those +/// measurements. +/// +/// The rationale behind this is to minimize browser reflows by batching dom +/// writes first, then performing all the reads. +class TextDimensions { + TextDimensions(this._element); + + final html.HtmlElement _element; + html.Rectangle _cachedBoundingClientRect; + + /// Attempts to efficiently copy text from [from]. + /// + /// The primary efficiency gain is from rare occurrence of rich text in + /// typical apps. + void updateText(EngineParagraph from, ParagraphGeometricStyle style) { + assert(from != null); + assert(_element != null); + assert(from._debugHasSameRootStyle(style)); + assert(() { + final bool wasEmptyOrPlainText = _element.childNodes.isEmpty || + (_element.childNodes.length == 1 && + _element.childNodes.first is html.Text); + if (!wasEmptyOrPlainText) { + throw Exception( + 'Failed to copy text into the paragraph measuring element. The ' + 'element already contains rich text "${_element.innerHtml}". It is ' + 'likely that a previous measurement did not clean up after ' + 'itself.'); + } + return true; + }()); + + _invalidateBoundsCache(); + final String plainText = from._plainText; + if (plainText != null) { + // Plain text: just set the string. The paragraph's style is assumed to + // match the style set on the `element`. Setting text as plain string is + // faster because it doesn't change the DOM structure or CSS attributes, + // and therefore doesn't trigger style recalculations in the browser. + _element.text = plainText; + } else { + // Rich text: deeply copy contents. This is the slow case that should be + // avoided if fast layout performance is desired. + final html.Element copy = from._paragraphElement.clone(true); + _element.children.addAll(copy.children); + } + } + + /// Updated element style width. + void updateWidth(String cssWidth) { + _invalidateBoundsCache(); + _element.style.width = cssWidth; + } + + void _invalidateBoundsCache() { + _cachedBoundingClientRect = null; + } + + /// Sets text of contents to a single space character to measure empty text. + void updateTextToSpace() { + _invalidateBoundsCache(); + _element.text = ' '; + } + + /// Applies geometric style properties to the [element]. + void applyStyle(ParagraphGeometricStyle style) { + _element.style + ..fontSize = style.fontSize != null ? '${style.fontSize.floor()}px' : null + ..fontFamily = style.effectiveFontFamily + ..fontWeight = + style.fontWeight != null ? fontWeightToCss(style.fontWeight) : null + ..fontStyle = style.fontStyle != null + ? style.fontStyle == ui.FontStyle.normal ? 'normal' : 'italic' + : null + ..letterSpacing = + style.letterSpacing != null ? '${style.letterSpacing}px' : null + ..wordSpacing = + style.wordSpacing != null ? '${style.wordSpacing}px' : null + ..textDecoration = style.decoration; + if (style.lineHeight != null) { + _element.style.lineHeight = style.lineHeight.toString(); + } + _invalidateBoundsCache(); + } + + /// Appends element and probe to hostElement that is setup for a specific + /// TextStyle. + void appendToHost(html.HtmlElement hostElement) { + hostElement.append(_element); + _invalidateBoundsCache(); + } + + html.Rectangle _readAndCacheMetrics() => + _cachedBoundingClientRect ??= _element.getBoundingClientRect(); + + /// The width of the paragraph being measured. + double get width => _readAndCacheMetrics().width; + + /// The height of the paragraph being measured. + double get height => _readAndCacheMetrics().height; +} + +/// Performs 4 types of measurements: +/// +/// 1. Single line: can be prepared by calling [measureAsSingleLine]. +/// Measurement values will be available at [singleLineDimensions]. +/// +/// 2. Minimum intrinsic width: can be prepared by calling +/// [measureMinIntrinsicWidth]. Measurement values will be available at +/// [minIntrinsicDimensions]. +/// +/// 3. Constrained: can be prepared by calling [measureWithConstraints] and +/// passing the constraints. Measurement values will be available at +/// [constrainedDimensions]. +/// +/// 4. Boxes: within a paragraph, it measures a list of text boxes that enclose +/// a given range of text. +/// +/// For performance reasons, it's advised to use [measureAll] and then reading +/// whatever measurements are needed. This causes the browser to only reflow +/// once instead of many times. +/// +/// The [measureAll] method performs the first 3 stateful measurements but not +/// the 4th one. +/// +/// This class is both reusable and stateful. Use it carefully. The correct +/// usage is as follows: +/// +/// * First, call [willMeasure] passing it the paragraph to be measured. +/// * Call any of the [measureAsSingleLine], [measureMinIntrinsicWidth], +/// [measureWithConstraints], or [measureAll], to prepare the respective +/// measurement. These methods can be called any number of times. +/// * Call [didMeasure] to indicate that you are done with the paragraph passed +/// to the [willMeasure] method. +/// +/// It is safe to reuse this object as long as paragraphs passed to the +/// [measure] method have the same style. +/// +/// The only stateless method provided by this class is [measureBoxesForRange] +/// that doesn't rely on [willMeasure] and [didMeasure] lifecycle methods. +/// +/// This class optimizes for plain text paragraphs, which should constitute the +/// majority of paragraphs in typical apps. +class ParagraphRuler { + /// The only style that this [ParagraphRuler] measures text. + final ParagraphGeometricStyle style; + + /// A [RulerManager] owns the host DOM element that this ruler can add + /// elements to. + /// + /// The [rulerManager] keeps a cache of multiple [ParagraphRuler] instances, + /// but a [ParagraphRuler] can only belong to one [RulerManager]. + final RulerManager rulerManager; + + /// Probe to use for measuring alphabetic base line. + final html.HtmlElement _probe = html.DivElement(); + + /// Cached value of alphabetic base line. + double _cachedAlphabeticBaseline; + + ParagraphRuler(this.style, this.rulerManager) { + _configureSingleLineHostElements(); + // Since alphabeticbaseline will be same regardless of constraints. + // We can measure it using a probe on the single line dimensions + // host. + _singleLineHost.append(_probe); + _configureMinIntrinsicHostElements(); + _configureConstrainedHostElements(); + } + + /// The alphabetic baseline of the paragraph being measured. + double get alphabeticBaseline => + _cachedAlphabeticBaseline ??= _probe.getBoundingClientRect().bottom; + + // Elements used to measure single-line metrics. + final html.DivElement _singleLineHost = html.DivElement(); + final TextDimensions singleLineDimensions = + TextDimensions(html.ParagraphElement()); + + // Elements used to measure minIntrinsicWidth. + final html.DivElement _minIntrinsicHost = html.DivElement(); + TextDimensions minIntrinsicDimensions = + TextDimensions(html.ParagraphElement()); + + // Elements used to measure metrics under a width constraint. + final html.DivElement _constrainedHost = html.DivElement(); + TextDimensions constrainedDimensions = + TextDimensions(html.ParagraphElement()); + + // Elements used to measure the line-height metric. + html.DivElement _lineHeightHost; + TextDimensions _lineHeightDimensions; + TextDimensions get lineHeightDimensions { + // Lazily create the elements for line-height measurement since they are not + // always needed. + if (_lineHeightDimensions == null) { + _lineHeightHost = html.DivElement(); + _lineHeightDimensions = TextDimensions(html.ParagraphElement()); + _configureLineHeightHostElements(); + _lineHeightHost.append(_probe); + } + return _lineHeightDimensions; + } + + /// The number of times this ruler was used this frame. + /// + /// This value is used to determine which rulers are rarely used and should be + /// evicted from the ruler cache. + int get hitCount => _hitCount; + int _hitCount = 0; + + /// This method should be called whenever this ruler is being used to perform + /// measurements. + /// + /// It increases the hit count of this ruler which is used when clearing the + /// [rulerManager]'s cache to find the least used rulers. + void hit() { + _hitCount++; + } + + /// Resets the hit count back to zero. + void resetHitCount() { + _hitCount = 0; + } + + /// Makes sure this ruler is not used again after it has been disposed of, + /// which would indicate a bug. + @visibleForTesting + bool get debugIsDisposed => _debugIsDisposed; + bool _debugIsDisposed = false; + + void _configureSingleLineHostElements() { + _singleLineHost.style + ..visibility = 'hidden' + ..position = 'absolute' + ..top = '0' // this is important as baseline == probe.bottom + ..left = '0' + ..display = 'flex' + ..flexDirection = 'row' + ..alignItems = 'baseline' + ..margin = '0' + ..border = '0' + ..padding = '0'; + + singleLineDimensions.applyStyle(style); + + // Force single-line (even if wider than screen) and preserve whitespaces. + singleLineDimensions._element.style.whiteSpace = 'pre'; + + singleLineDimensions.appendToHost(_singleLineHost); + rulerManager.addHostElement(_singleLineHost); + } + + void _configureMinIntrinsicHostElements() { + // Configure min intrinsic host elements. + _minIntrinsicHost.style + ..visibility = 'hidden' + ..position = 'absolute' + ..top = '0' // this is important as baseline == probe.bottom + ..left = '0' + ..display = 'flex' + ..flexDirection = 'row' + ..margin = '0' + ..border = '0' + ..padding = '0'; + + minIntrinsicDimensions.applyStyle(style); + + // "flex: 0" causes the paragraph element to shrink horizontally, exposing + // its minimum intrinsic width. + minIntrinsicDimensions._element.style + ..flex = '0' + ..display = 'inline' + // Preserve whitespaces. + ..whiteSpace = 'pre-wrap'; + + _minIntrinsicHost.append(minIntrinsicDimensions._element); + rulerManager.addHostElement(_minIntrinsicHost); + } + + void _configureConstrainedHostElements() { + _constrainedHost.style + ..visibility = 'hidden' + ..position = 'absolute' + ..top = '0' // this is important as baseline == probe.bottom + ..left = '0' + ..display = 'flex' + ..flexDirection = 'row' + ..alignItems = 'baseline' + ..margin = '0' + ..border = '0' + ..padding = '0'; + + constrainedDimensions.applyStyle(style); + final html.CssStyleDeclaration elementStyle = + constrainedDimensions._element.style; + elementStyle + ..display = 'block' + ..overflowWrap = 'break-word'; + + // TODO(flutter_web): Implement the ellipsis overflow for multi-line text + // too. As a pre-requisite, we need to be able to programmatically find + // line breaks. + if (style.ellipsis == null) { + elementStyle.whiteSpace = 'pre-wrap'; + } else { + // The height measurement is affected by whether the text has the ellipsis + // overflow property or not. This is because when ellipsis is set, we may + // not render all the lines, but stop at the first line that overflows. + elementStyle + ..whiteSpace = 'pre' + ..overflow = 'hidden' + ..textOverflow = 'ellipsis'; + } + + constrainedDimensions.appendToHost(_constrainedHost); + rulerManager.addHostElement(_constrainedHost); + } + + void _configureLineHeightHostElements() { + _lineHeightHost.style + ..visibility = 'hidden' + ..position = 'absolute' + ..top = '0' + ..left = '0' + ..display = 'flex' + ..flexDirection = 'row' + ..alignItems = 'baseline' + ..margin = '0' + ..border = '0' + ..padding = '0'; + + lineHeightDimensions.applyStyle(style); + + // Force single-line (even if wider than screen) and preserve whitespaces. + lineHeightDimensions._element.style.whiteSpace = 'pre'; + + // To measure line-height, all we need is a whitespace. + lineHeightDimensions.updateTextToSpace(); + + lineHeightDimensions.appendToHost(_lineHeightHost); + rulerManager.addHostElement(_lineHeightHost); + } + + /// The paragraph being measured. + EngineParagraph _paragraph; + + /// Prepares this ruler for measuring the given [paragraph]. + /// + /// This method must be called before calling any of the `measure*` methods. + void willMeasure(EngineParagraph paragraph) { + assert(paragraph != null); + assert(() { + if (_paragraph != null) { + throw Exception( + 'Attempted to reuse a $ParagraphRuler but it is currently ' + 'measuring another paragraph ($_paragraph). It is possible that '); + } + return true; + }()); + assert(paragraph._debugHasSameRootStyle(style)); + _paragraph = paragraph; + } + + /// Prepares all 3 measurements: + /// 1. single line. + /// 2. minimum intrinsic width. + /// 3. constrained. + void measureAll(ui.ParagraphConstraints constraints) { + measureAsSingleLine(); + measureMinIntrinsicWidth(); + measureWithConstraints(constraints); + } + + /// Lays out the paragraph in a single line, giving it infinite amount of + /// horizontal space. + /// + /// Measures [width], [height], and [alphabeticBaseline]. + void measureAsSingleLine() { + assert(!_debugIsDisposed); + assert(_paragraph != null); + + // HACK(mdebbar): TextField uses an empty string to measure the line height, + // which doesn't work. So we need to replace it with a whitespace. The + // correct fix would be to do line height and baseline measurements and + // cache them separately. + if (_paragraph._plainText == '') { + singleLineDimensions.updateTextToSpace(); + } else { + singleLineDimensions.updateText(_paragraph, style); + } + } + + /// Lays out the paragraph inside a flex row and sets "flex: 0", which + /// squeezes the paragraph, forcing it to occupy minimum intrinsic width. + /// + /// Measures [width] and [height]. + void measureMinIntrinsicWidth() { + assert(!_debugIsDisposed); + assert(_paragraph != null); + + minIntrinsicDimensions.updateText(_paragraph, style); + } + + /// Lays out the paragraph giving it a width constraint. + /// + /// Measures [width], [height], and [alphabeticBaseline]. + void measureWithConstraints(ui.ParagraphConstraints constraints) { + assert(!_debugIsDisposed); + assert(_paragraph != null); + + constrainedDimensions.updateText(_paragraph, style); + + // The extra 0.5 is because sometimes the browser needs slightly more space + // than the size it reports back. When that happens the text may be wrap + // when we thought it didn't. + constrainedDimensions.updateWidth('${constraints.width + 0.5}px'); + } + + /// Performs clean-up after a measurement is done, preparing this ruler for + /// a future reuse. + /// + /// Call this method immediately after calling `measure*` methods for a + /// particular [paragraph]. This ruler is not reusable until [didMeasure] is + /// called. + void didMeasure() { + assert(_paragraph != null); + // Remove any rich text we set during layout for the following reasons: + // - there won't be any text for the browser to lay out when we commit the + // current frame. + // - this keeps the cost of removing content together with the measurement + // in the profile. Otherwise, the cost of removing will be paid by a + // random next paragraph measured in the future, and make the performance + // profile hard to understand. + // + // We do not do this for plain text, because replacing plain text is more + // expensive than paying the cost of the DOM mutation to clean it. + if (_paragraph._plainText == null) { + domRenderer + ..clearDom(singleLineDimensions._element) + ..clearDom(minIntrinsicDimensions._element) + ..clearDom(constrainedDimensions._element); + } + _paragraph = null; + } + + /// Performs stateless measurement of text boxes for a given range of text. + /// + /// This method doesn't depend on [willMeasure] and [didMeasure] lifecycle + /// methods. + List measureBoxesForRange( + String plainText, + ui.ParagraphConstraints constraints, { + int start, + int end, + double alignOffset, + ui.TextDirection textDirection, + }) { + assert(!_debugIsDisposed); + assert(start >= 0 && start <= plainText.length); + assert(end >= 0 && end <= plainText.length); + assert(start <= end); + + final String before = plainText.substring(0, start); + final String rangeText = plainText.substring(start, end); + final String after = plainText.substring(end); + + final html.SpanElement rangeSpan = html.SpanElement()..text = rangeText; + + // Setup the [ruler.constrainedDimensions] element to be used for measurement. + domRenderer.clearDom(constrainedDimensions._element); + constrainedDimensions._element + ..appendText(before) + ..append(rangeSpan) + ..appendText(after); + constrainedDimensions.updateWidth('${constraints.width}px'); + + // Measure the rects of [rangeSpan]. + final List> clientRects = rangeSpan.getClientRects(); + final List boxes = []; + + for (html.Rectangle rect in clientRects) { + boxes.add(ui.TextBox.fromLTRBD( + rect.left + alignOffset, + rect.top, + rect.right + alignOffset, + rect.bottom, + textDirection, + )); + } + + // Cleanup after measuring the boxes. + domRenderer.clearDom(constrainedDimensions._element); + return boxes; + } + + /// Detaches this ruler from the DOM and makes it unusable for future + /// measurements. + /// + /// Disposed rulers should be garbage collected after calling this method. + void dispose() { + assert(() { + if (_paragraph != null) { + throw Exception('Attempted to dispose of a ruler in the middle of ' + 'measurement. This is likely a bug in the framework.'); + } + return true; + }()); + _singleLineHost.remove(); + _minIntrinsicHost.remove(); + _constrainedHost.remove(); + _lineHeightHost?.remove(); + assert(() { + _debugIsDisposed = true; + return true; + }()); + } + + // Bounded cache for text measurement for a particular width constraint. + Map> _measurementCache = + >{}; + // Mru list for cache. + final List _mruList = []; + static const int _cacheLimit = 2400; + // Number of items to evict when cache limit is reached. + static const int _cacheBlockFactor = 100; + // Number of constraint results per unique text item. + // This limit prevents growth during animation where the size of a container + // is changing. + static const int _constraintCacheSize = 8; + + void cacheMeasurement(EngineParagraph paragraph, MeasurementResult item) { + final String plainText = paragraph._plainText; + final List constraintCache = + _measurementCache[plainText] ??= []; + constraintCache.add(item); + if (constraintCache.length > _constraintCacheSize) { + constraintCache.removeAt(0); + } + _mruList.add(plainText); + if (_mruList.length > _cacheLimit) { + // Evict a range. + for (int i = 0; i < _cacheBlockFactor; i++) { + _measurementCache.remove(_mruList[i]); + } + _mruList.removeRange(0, _cacheBlockFactor); + } + } + + MeasurementResult cacheLookup( + EngineParagraph paragraph, ui.ParagraphConstraints constraints) { + final List constraintCache = + _measurementCache[paragraph._plainText]; + if (constraintCache == null) { + return null; + } + final int len = constraintCache.length; + for (int i = 0; i < len; i++) { + final MeasurementResult item = constraintCache[i]; + if (item.constraintWidth == constraints.width) { + return item; + } + } + return null; + } +} + +/// The result that contains all measurements of a paragraph at the given +/// constraint width. +@immutable +class MeasurementResult { + /// The width that was given as a constraint when the paragraph was laid out. + final double constraintWidth; + + /// Whether the paragraph can fit in a single line given [constraintWidth]. + final bool isSingleLine; + + /// The amount of horizontal space the paragraph occupies. + final double width; + + /// The amount of vertical space the paragraph occupies. + final double height; + + /// {@macro dart.ui.paragraph.naturalHeight} + /// + /// When [ParagraphGeometricStyle.maxLines] is null, [naturalHeight] and + /// [height] should be equal. + final double naturalHeight; + + /// The amount of vertical space each line of the paragraph occupies. + /// + /// In some cases, measuring [lineHeight] is unnecessary, so it's nullable. If + /// present, it should be equal to [height] when [isSingleLine] is true. + final double lineHeight; + + /// {@macro dart.ui.paragraph.minIntrinsicWidth} + final double minIntrinsicWidth; + + /// {@macro dart.ui.paragraph.maxIntrinsicWidth} + final double maxIntrinsicWidth; + + /// {@macro dart.ui.paragraph.alphabeticBaseline} + final double alphabeticBaseline; + + /// {@macro dart.ui.paragraph.ideographicBaseline} + final double ideographicBaseline; + + /// Substrings that represent how the text should wrap into multiple lines to + /// satisfy [constraintWidth], + final List lines; + + const MeasurementResult( + this.constraintWidth, { + @required this.isSingleLine, + @required this.width, + @required this.height, + @required this.naturalHeight, + @required this.lineHeight, + @required this.minIntrinsicWidth, + @required this.maxIntrinsicWidth, + @required this.alphabeticBaseline, + @required this.ideographicBaseline, + @required this.lines, + }) : assert(constraintWidth != null), + assert(isSingleLine != null), + assert(width != null), + assert(height != null), + assert(naturalHeight != null), + assert(minIntrinsicWidth != null), + assert(maxIntrinsicWidth != null), + assert(alphabeticBaseline != null), + assert(ideographicBaseline != null); +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/text/unicode_range.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/text/unicode_range.dart new file mode 100644 index 0000000000..6d2b967fa5 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/unicode_range.dart @@ -0,0 +1,91 @@ +// 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; + +enum _ComparisonResult { + inside, + higher, + lower, +} + +/// Each instance of [UnicodeRange] represents a range of unicode characters +/// that are assigned a [CharProperty]. For example, the following snippet: +/// +/// ```dart +/// UnicodeRange(0x0041, 0x005A, CharProperty.ALetter); +/// ``` +/// +/// is saying that all characters between 0x0041 ("A") and 0x005A ("Z") are +/// assigned the property [CharProperty.ALetter]. +/// +/// Note that the Unicode spec uses inclusive ranges and we are doing the +/// same here. +class UnicodeRange

{ + const UnicodeRange(this.start, this.end, this.property); + + final int start; + + final int end; + + final P property; + + /// Compare a [value] to this range. + /// + /// The return value is either: + /// - lower: The value is lower than the range. + /// - higher: The value is higher than the range + /// - inside: The value is within the range. + _ComparisonResult compare(int value) { + if (value < start) { + return _ComparisonResult.lower; + } + if (value > end) { + return _ComparisonResult.higher; + } + return _ComparisonResult.inside; + } +} + +/// Given a list of [UnicodeRange]s, this class performs efficient lookup +/// to find which range a value falls into. +/// +/// The lookup algorithm expects the ranges to have the following constraints: +/// - Be sorted. +/// - No overlap between the ranges. +/// - Gaps between ranges are ok. +/// +/// This is used in the context of unicode to find out what property a letter +/// has. The properties are then used to decide word boundaries, line break +/// opportunities, etc. +class UnicodePropertyLookup

{ + const UnicodePropertyLookup(this.ranges); + + final List> ranges; + + P find(int value) { + final int index = _binarySearch(value); + return index == -1 ? null : ranges[index].property; + } + + int _binarySearch(int value) { + int min = 0; + int max = ranges.length; + while (min < max) { + final int mid = min + ((max - min) >> 1); + final UnicodeRange

range = ranges[mid]; + switch (range.compare(value)) { + case _ComparisonResult.higher: + min = mid + 1; + break; + case _ComparisonResult.lower: + max = mid; + break; + case _ComparisonResult.inside: + return mid; + } + } + return -1; + } +} diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/text/word_break_properties.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/text/word_break_properties.dart new file mode 100644 index 0000000000..15444f8ef4 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/word_break_properties.dart @@ -0,0 +1,1020 @@ +// 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. + +// AUTO-GENERATED FILE. +// Generated by: tool/unicode_sync_script.dart +// +// Source: +// # WordBreakProperty-12.1.0.txt +// # Date: 2019-03-10, 10:53:28 GMT +// # © 2019 Unicode®, Inc. +// # Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the U.S. and other countries. +// # For terms of use, see http://www.unicode.org/terms_of_use.html +// # +// # Unicode Character Database +// # For documentation, see http://www.unicode.org/reports/tr44/ + +part of engine; + +CharProperty getCharProperty(String text, int index) { + if (index < 0 || index >= text.length) { + return null; + } + return lookup.find(text.codeUnitAt(index)); +} + +enum CharProperty { + DoubleQuote, + SingleQuote, + HebrewLetter, + CR, + LF, + Newline, + Extend, + RegionalIndicator, + Format, + Katakana, + ALetter, + MidLetter, + MidNum, + MidNumLet, + Numeric, + ExtendNumLet, + ZWJ, + WSegSpace +} + +const UnicodePropertyLookup lookup = + UnicodePropertyLookup(>[ + UnicodeRange(0x000A, 0x000A, CharProperty.LF), + UnicodeRange(0x000B, 0x000C, CharProperty.Newline), + UnicodeRange(0x000D, 0x000D, CharProperty.CR), + UnicodeRange(0x0020, 0x0020, CharProperty.WSegSpace), + UnicodeRange(0x0022, 0x0022, CharProperty.DoubleQuote), + UnicodeRange(0x0027, 0x0027, CharProperty.SingleQuote), + UnicodeRange(0x002C, 0x002C, CharProperty.MidNum), + UnicodeRange(0x002E, 0x002E, CharProperty.MidNumLet), + UnicodeRange(0x0030, 0x0039, CharProperty.Numeric), + UnicodeRange(0x003A, 0x003A, CharProperty.MidLetter), + UnicodeRange(0x003B, 0x003B, CharProperty.MidNum), + UnicodeRange(0x0041, 0x005A, CharProperty.ALetter), + UnicodeRange(0x005F, 0x005F, CharProperty.ExtendNumLet), + UnicodeRange(0x0061, 0x007A, CharProperty.ALetter), + UnicodeRange(0x0085, 0x0085, CharProperty.Newline), + UnicodeRange(0x00AA, 0x00AA, CharProperty.ALetter), + UnicodeRange(0x00AD, 0x00AD, CharProperty.Format), + UnicodeRange(0x00B5, 0x00B5, CharProperty.ALetter), + UnicodeRange(0x00B7, 0x00B7, CharProperty.MidLetter), + UnicodeRange(0x00BA, 0x00BA, CharProperty.ALetter), + UnicodeRange(0x00C0, 0x00D6, CharProperty.ALetter), + UnicodeRange(0x00D8, 0x00F6, CharProperty.ALetter), + UnicodeRange(0x00F8, 0x02D7, CharProperty.ALetter), + UnicodeRange(0x02DE, 0x02E4, CharProperty.ALetter), + UnicodeRange(0x02EC, 0x02FF, CharProperty.ALetter), + UnicodeRange(0x0300, 0x036F, CharProperty.Extend), + UnicodeRange(0x0370, 0x0374, CharProperty.ALetter), + UnicodeRange(0x0376, 0x0377, CharProperty.ALetter), + UnicodeRange(0x037A, 0x037D, CharProperty.ALetter), + UnicodeRange(0x037E, 0x037E, CharProperty.MidNum), + UnicodeRange(0x037F, 0x037F, CharProperty.ALetter), + UnicodeRange(0x0386, 0x0386, CharProperty.ALetter), + UnicodeRange(0x0387, 0x0387, CharProperty.MidLetter), + UnicodeRange(0x0388, 0x038A, CharProperty.ALetter), + UnicodeRange(0x038C, 0x038C, CharProperty.ALetter), + UnicodeRange(0x038E, 0x03A1, CharProperty.ALetter), + UnicodeRange(0x03A3, 0x03F5, CharProperty.ALetter), + UnicodeRange(0x03F7, 0x0481, CharProperty.ALetter), + UnicodeRange(0x0483, 0x0489, CharProperty.Extend), + UnicodeRange(0x048A, 0x052F, CharProperty.ALetter), + UnicodeRange(0x0531, 0x0556, CharProperty.ALetter), + UnicodeRange(0x0559, 0x0559, CharProperty.ALetter), + UnicodeRange(0x055B, 0x055C, CharProperty.ALetter), + UnicodeRange(0x055E, 0x055E, CharProperty.ALetter), + UnicodeRange(0x0560, 0x0588, CharProperty.ALetter), + UnicodeRange(0x0589, 0x0589, CharProperty.MidNum), + UnicodeRange(0x0591, 0x05BD, CharProperty.Extend), + UnicodeRange(0x05BF, 0x05BF, CharProperty.Extend), + UnicodeRange(0x05C1, 0x05C2, CharProperty.Extend), + UnicodeRange(0x05C4, 0x05C5, CharProperty.Extend), + UnicodeRange(0x05C7, 0x05C7, CharProperty.Extend), + UnicodeRange(0x05D0, 0x05EA, CharProperty.HebrewLetter), + UnicodeRange(0x05EF, 0x05F2, CharProperty.HebrewLetter), + UnicodeRange(0x05F3, 0x05F3, CharProperty.ALetter), + UnicodeRange(0x05F4, 0x05F4, CharProperty.MidLetter), + UnicodeRange(0x0600, 0x0605, CharProperty.Format), + UnicodeRange(0x060C, 0x060D, CharProperty.MidNum), + UnicodeRange(0x0610, 0x061A, CharProperty.Extend), + UnicodeRange(0x061C, 0x061C, CharProperty.Format), + UnicodeRange(0x0620, 0x064A, CharProperty.ALetter), + UnicodeRange(0x064B, 0x065F, CharProperty.Extend), + UnicodeRange(0x0660, 0x0669, CharProperty.Numeric), + UnicodeRange(0x066B, 0x066B, CharProperty.Numeric), + UnicodeRange(0x066C, 0x066C, CharProperty.MidNum), + UnicodeRange(0x066E, 0x066F, CharProperty.ALetter), + UnicodeRange(0x0670, 0x0670, CharProperty.Extend), + UnicodeRange(0x0671, 0x06D3, CharProperty.ALetter), + UnicodeRange(0x06D5, 0x06D5, CharProperty.ALetter), + UnicodeRange(0x06D6, 0x06DC, CharProperty.Extend), + UnicodeRange(0x06DD, 0x06DD, CharProperty.Format), + UnicodeRange(0x06DF, 0x06E4, CharProperty.Extend), + UnicodeRange(0x06E5, 0x06E6, CharProperty.ALetter), + UnicodeRange(0x06E7, 0x06E8, CharProperty.Extend), + UnicodeRange(0x06EA, 0x06ED, CharProperty.Extend), + UnicodeRange(0x06EE, 0x06EF, CharProperty.ALetter), + UnicodeRange(0x06F0, 0x06F9, CharProperty.Numeric), + UnicodeRange(0x06FA, 0x06FC, CharProperty.ALetter), + UnicodeRange(0x06FF, 0x06FF, CharProperty.ALetter), + UnicodeRange(0x070F, 0x070F, CharProperty.Format), + UnicodeRange(0x0710, 0x0710, CharProperty.ALetter), + UnicodeRange(0x0711, 0x0711, CharProperty.Extend), + UnicodeRange(0x0712, 0x072F, CharProperty.ALetter), + UnicodeRange(0x0730, 0x074A, CharProperty.Extend), + UnicodeRange(0x074D, 0x07A5, CharProperty.ALetter), + UnicodeRange(0x07A6, 0x07B0, CharProperty.Extend), + UnicodeRange(0x07B1, 0x07B1, CharProperty.ALetter), + UnicodeRange(0x07C0, 0x07C9, CharProperty.Numeric), + UnicodeRange(0x07CA, 0x07EA, CharProperty.ALetter), + UnicodeRange(0x07EB, 0x07F3, CharProperty.Extend), + UnicodeRange(0x07F4, 0x07F5, CharProperty.ALetter), + UnicodeRange(0x07F8, 0x07F8, CharProperty.MidNum), + UnicodeRange(0x07FA, 0x07FA, CharProperty.ALetter), + UnicodeRange(0x07FD, 0x07FD, CharProperty.Extend), + UnicodeRange(0x0800, 0x0815, CharProperty.ALetter), + UnicodeRange(0x0816, 0x0819, CharProperty.Extend), + UnicodeRange(0x081A, 0x081A, CharProperty.ALetter), + UnicodeRange(0x081B, 0x0823, CharProperty.Extend), + UnicodeRange(0x0824, 0x0824, CharProperty.ALetter), + UnicodeRange(0x0825, 0x0827, CharProperty.Extend), + UnicodeRange(0x0828, 0x0828, CharProperty.ALetter), + UnicodeRange(0x0829, 0x082D, CharProperty.Extend), + UnicodeRange(0x0840, 0x0858, CharProperty.ALetter), + UnicodeRange(0x0859, 0x085B, CharProperty.Extend), + UnicodeRange(0x0860, 0x086A, CharProperty.ALetter), + UnicodeRange(0x08A0, 0x08B4, CharProperty.ALetter), + UnicodeRange(0x08B6, 0x08BD, CharProperty.ALetter), + UnicodeRange(0x08D3, 0x08E1, CharProperty.Extend), + UnicodeRange(0x08E2, 0x08E2, CharProperty.Format), + UnicodeRange(0x08E3, 0x0903, CharProperty.Extend), + UnicodeRange(0x0904, 0x0939, CharProperty.ALetter), + UnicodeRange(0x093A, 0x093C, CharProperty.Extend), + UnicodeRange(0x093D, 0x093D, CharProperty.ALetter), + UnicodeRange(0x093E, 0x094F, CharProperty.Extend), + UnicodeRange(0x0950, 0x0950, CharProperty.ALetter), + UnicodeRange(0x0951, 0x0957, CharProperty.Extend), + UnicodeRange(0x0958, 0x0961, CharProperty.ALetter), + UnicodeRange(0x0962, 0x0963, CharProperty.Extend), + UnicodeRange(0x0966, 0x096F, CharProperty.Numeric), + UnicodeRange(0x0971, 0x0980, CharProperty.ALetter), + UnicodeRange(0x0981, 0x0983, CharProperty.Extend), + UnicodeRange(0x0985, 0x098C, CharProperty.ALetter), + UnicodeRange(0x098F, 0x0990, CharProperty.ALetter), + UnicodeRange(0x0993, 0x09A8, CharProperty.ALetter), + UnicodeRange(0x09AA, 0x09B0, CharProperty.ALetter), + UnicodeRange(0x09B2, 0x09B2, CharProperty.ALetter), + UnicodeRange(0x09B6, 0x09B9, CharProperty.ALetter), + UnicodeRange(0x09BC, 0x09BC, CharProperty.Extend), + UnicodeRange(0x09BD, 0x09BD, CharProperty.ALetter), + UnicodeRange(0x09BE, 0x09C4, CharProperty.Extend), + UnicodeRange(0x09C7, 0x09C8, CharProperty.Extend), + UnicodeRange(0x09CB, 0x09CD, CharProperty.Extend), + UnicodeRange(0x09CE, 0x09CE, CharProperty.ALetter), + UnicodeRange(0x09D7, 0x09D7, CharProperty.Extend), + UnicodeRange(0x09DC, 0x09DD, CharProperty.ALetter), + UnicodeRange(0x09DF, 0x09E1, CharProperty.ALetter), + UnicodeRange(0x09E2, 0x09E3, CharProperty.Extend), + UnicodeRange(0x09E6, 0x09EF, CharProperty.Numeric), + UnicodeRange(0x09F0, 0x09F1, CharProperty.ALetter), + UnicodeRange(0x09FC, 0x09FC, CharProperty.ALetter), + UnicodeRange(0x09FE, 0x09FE, CharProperty.Extend), + UnicodeRange(0x0A01, 0x0A03, CharProperty.Extend), + UnicodeRange(0x0A05, 0x0A0A, CharProperty.ALetter), + UnicodeRange(0x0A0F, 0x0A10, CharProperty.ALetter), + UnicodeRange(0x0A13, 0x0A28, CharProperty.ALetter), + UnicodeRange(0x0A2A, 0x0A30, CharProperty.ALetter), + UnicodeRange(0x0A32, 0x0A33, CharProperty.ALetter), + UnicodeRange(0x0A35, 0x0A36, CharProperty.ALetter), + UnicodeRange(0x0A38, 0x0A39, CharProperty.ALetter), + UnicodeRange(0x0A3C, 0x0A3C, CharProperty.Extend), + UnicodeRange(0x0A3E, 0x0A42, CharProperty.Extend), + UnicodeRange(0x0A47, 0x0A48, CharProperty.Extend), + UnicodeRange(0x0A4B, 0x0A4D, CharProperty.Extend), + UnicodeRange(0x0A51, 0x0A51, CharProperty.Extend), + UnicodeRange(0x0A59, 0x0A5C, CharProperty.ALetter), + UnicodeRange(0x0A5E, 0x0A5E, CharProperty.ALetter), + UnicodeRange(0x0A66, 0x0A6F, CharProperty.Numeric), + UnicodeRange(0x0A70, 0x0A71, CharProperty.Extend), + UnicodeRange(0x0A72, 0x0A74, CharProperty.ALetter), + UnicodeRange(0x0A75, 0x0A75, CharProperty.Extend), + UnicodeRange(0x0A81, 0x0A83, CharProperty.Extend), + UnicodeRange(0x0A85, 0x0A8D, CharProperty.ALetter), + UnicodeRange(0x0A8F, 0x0A91, CharProperty.ALetter), + UnicodeRange(0x0A93, 0x0AA8, CharProperty.ALetter), + UnicodeRange(0x0AAA, 0x0AB0, CharProperty.ALetter), + UnicodeRange(0x0AB2, 0x0AB3, CharProperty.ALetter), + UnicodeRange(0x0AB5, 0x0AB9, CharProperty.ALetter), + UnicodeRange(0x0ABC, 0x0ABC, CharProperty.Extend), + UnicodeRange(0x0ABD, 0x0ABD, CharProperty.ALetter), + UnicodeRange(0x0ABE, 0x0AC5, CharProperty.Extend), + UnicodeRange(0x0AC7, 0x0AC9, CharProperty.Extend), + UnicodeRange(0x0ACB, 0x0ACD, CharProperty.Extend), + UnicodeRange(0x0AD0, 0x0AD0, CharProperty.ALetter), + UnicodeRange(0x0AE0, 0x0AE1, CharProperty.ALetter), + UnicodeRange(0x0AE2, 0x0AE3, CharProperty.Extend), + UnicodeRange(0x0AE6, 0x0AEF, CharProperty.Numeric), + UnicodeRange(0x0AF9, 0x0AF9, CharProperty.ALetter), + UnicodeRange(0x0AFA, 0x0AFF, CharProperty.Extend), + UnicodeRange(0x0B01, 0x0B03, CharProperty.Extend), + UnicodeRange(0x0B05, 0x0B0C, CharProperty.ALetter), + UnicodeRange(0x0B0F, 0x0B10, CharProperty.ALetter), + UnicodeRange(0x0B13, 0x0B28, CharProperty.ALetter), + UnicodeRange(0x0B2A, 0x0B30, CharProperty.ALetter), + UnicodeRange(0x0B32, 0x0B33, CharProperty.ALetter), + UnicodeRange(0x0B35, 0x0B39, CharProperty.ALetter), + UnicodeRange(0x0B3C, 0x0B3C, CharProperty.Extend), + UnicodeRange(0x0B3D, 0x0B3D, CharProperty.ALetter), + UnicodeRange(0x0B3E, 0x0B44, CharProperty.Extend), + UnicodeRange(0x0B47, 0x0B48, CharProperty.Extend), + UnicodeRange(0x0B4B, 0x0B4D, CharProperty.Extend), + UnicodeRange(0x0B56, 0x0B57, CharProperty.Extend), + UnicodeRange(0x0B5C, 0x0B5D, CharProperty.ALetter), + UnicodeRange(0x0B5F, 0x0B61, CharProperty.ALetter), + UnicodeRange(0x0B62, 0x0B63, CharProperty.Extend), + UnicodeRange(0x0B66, 0x0B6F, CharProperty.Numeric), + UnicodeRange(0x0B71, 0x0B71, CharProperty.ALetter), + UnicodeRange(0x0B82, 0x0B82, CharProperty.Extend), + UnicodeRange(0x0B83, 0x0B83, CharProperty.ALetter), + UnicodeRange(0x0B85, 0x0B8A, CharProperty.ALetter), + UnicodeRange(0x0B8E, 0x0B90, CharProperty.ALetter), + UnicodeRange(0x0B92, 0x0B95, CharProperty.ALetter), + UnicodeRange(0x0B99, 0x0B9A, CharProperty.ALetter), + UnicodeRange(0x0B9C, 0x0B9C, CharProperty.ALetter), + UnicodeRange(0x0B9E, 0x0B9F, CharProperty.ALetter), + UnicodeRange(0x0BA3, 0x0BA4, CharProperty.ALetter), + UnicodeRange(0x0BA8, 0x0BAA, CharProperty.ALetter), + UnicodeRange(0x0BAE, 0x0BB9, CharProperty.ALetter), + UnicodeRange(0x0BBE, 0x0BC2, CharProperty.Extend), + UnicodeRange(0x0BC6, 0x0BC8, CharProperty.Extend), + UnicodeRange(0x0BCA, 0x0BCD, CharProperty.Extend), + UnicodeRange(0x0BD0, 0x0BD0, CharProperty.ALetter), + UnicodeRange(0x0BD7, 0x0BD7, CharProperty.Extend), + UnicodeRange(0x0BE6, 0x0BEF, CharProperty.Numeric), + UnicodeRange(0x0C00, 0x0C04, CharProperty.Extend), + UnicodeRange(0x0C05, 0x0C0C, CharProperty.ALetter), + UnicodeRange(0x0C0E, 0x0C10, CharProperty.ALetter), + UnicodeRange(0x0C12, 0x0C28, CharProperty.ALetter), + UnicodeRange(0x0C2A, 0x0C39, CharProperty.ALetter), + UnicodeRange(0x0C3D, 0x0C3D, CharProperty.ALetter), + UnicodeRange(0x0C3E, 0x0C44, CharProperty.Extend), + UnicodeRange(0x0C46, 0x0C48, CharProperty.Extend), + UnicodeRange(0x0C4A, 0x0C4D, CharProperty.Extend), + UnicodeRange(0x0C55, 0x0C56, CharProperty.Extend), + UnicodeRange(0x0C58, 0x0C5A, CharProperty.ALetter), + UnicodeRange(0x0C60, 0x0C61, CharProperty.ALetter), + UnicodeRange(0x0C62, 0x0C63, CharProperty.Extend), + UnicodeRange(0x0C66, 0x0C6F, CharProperty.Numeric), + UnicodeRange(0x0C80, 0x0C80, CharProperty.ALetter), + UnicodeRange(0x0C81, 0x0C83, CharProperty.Extend), + UnicodeRange(0x0C85, 0x0C8C, CharProperty.ALetter), + UnicodeRange(0x0C8E, 0x0C90, CharProperty.ALetter), + UnicodeRange(0x0C92, 0x0CA8, CharProperty.ALetter), + UnicodeRange(0x0CAA, 0x0CB3, CharProperty.ALetter), + UnicodeRange(0x0CB5, 0x0CB9, CharProperty.ALetter), + UnicodeRange(0x0CBC, 0x0CBC, CharProperty.Extend), + UnicodeRange(0x0CBD, 0x0CBD, CharProperty.ALetter), + UnicodeRange(0x0CBE, 0x0CC4, CharProperty.Extend), + UnicodeRange(0x0CC6, 0x0CC8, CharProperty.Extend), + UnicodeRange(0x0CCA, 0x0CCD, CharProperty.Extend), + UnicodeRange(0x0CD5, 0x0CD6, CharProperty.Extend), + UnicodeRange(0x0CDE, 0x0CDE, CharProperty.ALetter), + UnicodeRange(0x0CE0, 0x0CE1, CharProperty.ALetter), + UnicodeRange(0x0CE2, 0x0CE3, CharProperty.Extend), + UnicodeRange(0x0CE6, 0x0CEF, CharProperty.Numeric), + UnicodeRange(0x0CF1, 0x0CF2, CharProperty.ALetter), + UnicodeRange(0x0D00, 0x0D03, CharProperty.Extend), + UnicodeRange(0x0D05, 0x0D0C, CharProperty.ALetter), + UnicodeRange(0x0D0E, 0x0D10, CharProperty.ALetter), + UnicodeRange(0x0D12, 0x0D3A, CharProperty.ALetter), + UnicodeRange(0x0D3B, 0x0D3C, CharProperty.Extend), + UnicodeRange(0x0D3D, 0x0D3D, CharProperty.ALetter), + UnicodeRange(0x0D3E, 0x0D44, CharProperty.Extend), + UnicodeRange(0x0D46, 0x0D48, CharProperty.Extend), + UnicodeRange(0x0D4A, 0x0D4D, CharProperty.Extend), + UnicodeRange(0x0D4E, 0x0D4E, CharProperty.ALetter), + UnicodeRange(0x0D54, 0x0D56, CharProperty.ALetter), + UnicodeRange(0x0D57, 0x0D57, CharProperty.Extend), + UnicodeRange(0x0D5F, 0x0D61, CharProperty.ALetter), + UnicodeRange(0x0D62, 0x0D63, CharProperty.Extend), + UnicodeRange(0x0D66, 0x0D6F, CharProperty.Numeric), + UnicodeRange(0x0D7A, 0x0D7F, CharProperty.ALetter), + UnicodeRange(0x0D82, 0x0D83, CharProperty.Extend), + UnicodeRange(0x0D85, 0x0D96, CharProperty.ALetter), + UnicodeRange(0x0D9A, 0x0DB1, CharProperty.ALetter), + UnicodeRange(0x0DB3, 0x0DBB, CharProperty.ALetter), + UnicodeRange(0x0DBD, 0x0DBD, CharProperty.ALetter), + UnicodeRange(0x0DC0, 0x0DC6, CharProperty.ALetter), + UnicodeRange(0x0DCA, 0x0DCA, CharProperty.Extend), + UnicodeRange(0x0DCF, 0x0DD4, CharProperty.Extend), + UnicodeRange(0x0DD6, 0x0DD6, CharProperty.Extend), + UnicodeRange(0x0DD8, 0x0DDF, CharProperty.Extend), + UnicodeRange(0x0DE6, 0x0DEF, CharProperty.Numeric), + UnicodeRange(0x0DF2, 0x0DF3, CharProperty.Extend), + UnicodeRange(0x0E31, 0x0E31, CharProperty.Extend), + UnicodeRange(0x0E34, 0x0E3A, CharProperty.Extend), + UnicodeRange(0x0E47, 0x0E4E, CharProperty.Extend), + UnicodeRange(0x0E50, 0x0E59, CharProperty.Numeric), + UnicodeRange(0x0EB1, 0x0EB1, CharProperty.Extend), + UnicodeRange(0x0EB4, 0x0EBC, CharProperty.Extend), + UnicodeRange(0x0EC8, 0x0ECD, CharProperty.Extend), + UnicodeRange(0x0ED0, 0x0ED9, CharProperty.Numeric), + UnicodeRange(0x0F00, 0x0F00, CharProperty.ALetter), + UnicodeRange(0x0F18, 0x0F19, CharProperty.Extend), + UnicodeRange(0x0F20, 0x0F29, CharProperty.Numeric), + UnicodeRange(0x0F35, 0x0F35, CharProperty.Extend), + UnicodeRange(0x0F37, 0x0F37, CharProperty.Extend), + UnicodeRange(0x0F39, 0x0F39, CharProperty.Extend), + UnicodeRange(0x0F3E, 0x0F3F, CharProperty.Extend), + UnicodeRange(0x0F40, 0x0F47, CharProperty.ALetter), + UnicodeRange(0x0F49, 0x0F6C, CharProperty.ALetter), + UnicodeRange(0x0F71, 0x0F84, CharProperty.Extend), + UnicodeRange(0x0F86, 0x0F87, CharProperty.Extend), + UnicodeRange(0x0F88, 0x0F8C, CharProperty.ALetter), + UnicodeRange(0x0F8D, 0x0F97, CharProperty.Extend), + UnicodeRange(0x0F99, 0x0FBC, CharProperty.Extend), + UnicodeRange(0x0FC6, 0x0FC6, CharProperty.Extend), + UnicodeRange(0x102B, 0x103E, CharProperty.Extend), + UnicodeRange(0x1040, 0x1049, CharProperty.Numeric), + UnicodeRange(0x1056, 0x1059, CharProperty.Extend), + UnicodeRange(0x105E, 0x1060, CharProperty.Extend), + UnicodeRange(0x1062, 0x1064, CharProperty.Extend), + UnicodeRange(0x1067, 0x106D, CharProperty.Extend), + UnicodeRange(0x1071, 0x1074, CharProperty.Extend), + UnicodeRange(0x1082, 0x108D, CharProperty.Extend), + UnicodeRange(0x108F, 0x108F, CharProperty.Extend), + UnicodeRange(0x1090, 0x1099, CharProperty.Numeric), + UnicodeRange(0x109A, 0x109D, CharProperty.Extend), + UnicodeRange(0x10A0, 0x10C5, CharProperty.ALetter), + UnicodeRange(0x10C7, 0x10C7, CharProperty.ALetter), + UnicodeRange(0x10CD, 0x10CD, CharProperty.ALetter), + UnicodeRange(0x10D0, 0x10FA, CharProperty.ALetter), + UnicodeRange(0x10FC, 0x1248, CharProperty.ALetter), + UnicodeRange(0x124A, 0x124D, CharProperty.ALetter), + UnicodeRange(0x1250, 0x1256, CharProperty.ALetter), + UnicodeRange(0x1258, 0x1258, CharProperty.ALetter), + UnicodeRange(0x125A, 0x125D, CharProperty.ALetter), + UnicodeRange(0x1260, 0x1288, CharProperty.ALetter), + UnicodeRange(0x128A, 0x128D, CharProperty.ALetter), + UnicodeRange(0x1290, 0x12B0, CharProperty.ALetter), + UnicodeRange(0x12B2, 0x12B5, CharProperty.ALetter), + UnicodeRange(0x12B8, 0x12BE, CharProperty.ALetter), + UnicodeRange(0x12C0, 0x12C0, CharProperty.ALetter), + UnicodeRange(0x12C2, 0x12C5, CharProperty.ALetter), + UnicodeRange(0x12C8, 0x12D6, CharProperty.ALetter), + UnicodeRange(0x12D8, 0x1310, CharProperty.ALetter), + UnicodeRange(0x1312, 0x1315, CharProperty.ALetter), + UnicodeRange(0x1318, 0x135A, CharProperty.ALetter), + UnicodeRange(0x135D, 0x135F, CharProperty.Extend), + UnicodeRange(0x1380, 0x138F, CharProperty.ALetter), + UnicodeRange(0x13A0, 0x13F5, CharProperty.ALetter), + UnicodeRange(0x13F8, 0x13FD, CharProperty.ALetter), + UnicodeRange(0x1401, 0x166C, CharProperty.ALetter), + UnicodeRange(0x166F, 0x167F, CharProperty.ALetter), + UnicodeRange(0x1680, 0x1680, CharProperty.WSegSpace), + UnicodeRange(0x1681, 0x169A, CharProperty.ALetter), + UnicodeRange(0x16A0, 0x16EA, CharProperty.ALetter), + UnicodeRange(0x16EE, 0x16F8, CharProperty.ALetter), + UnicodeRange(0x1700, 0x170C, CharProperty.ALetter), + UnicodeRange(0x170E, 0x1711, CharProperty.ALetter), + UnicodeRange(0x1712, 0x1714, CharProperty.Extend), + UnicodeRange(0x1720, 0x1731, CharProperty.ALetter), + UnicodeRange(0x1732, 0x1734, CharProperty.Extend), + UnicodeRange(0x1740, 0x1751, CharProperty.ALetter), + UnicodeRange(0x1752, 0x1753, CharProperty.Extend), + UnicodeRange(0x1760, 0x176C, CharProperty.ALetter), + UnicodeRange(0x176E, 0x1770, CharProperty.ALetter), + UnicodeRange(0x1772, 0x1773, CharProperty.Extend), + UnicodeRange(0x17B4, 0x17D3, CharProperty.Extend), + UnicodeRange(0x17DD, 0x17DD, CharProperty.Extend), + UnicodeRange(0x17E0, 0x17E9, CharProperty.Numeric), + UnicodeRange(0x180B, 0x180D, CharProperty.Extend), + UnicodeRange(0x180E, 0x180E, CharProperty.Format), + UnicodeRange(0x1810, 0x1819, CharProperty.Numeric), + UnicodeRange(0x1820, 0x1878, CharProperty.ALetter), + UnicodeRange(0x1880, 0x1884, CharProperty.ALetter), + UnicodeRange(0x1885, 0x1886, CharProperty.Extend), + UnicodeRange(0x1887, 0x18A8, CharProperty.ALetter), + UnicodeRange(0x18A9, 0x18A9, CharProperty.Extend), + UnicodeRange(0x18AA, 0x18AA, CharProperty.ALetter), + UnicodeRange(0x18B0, 0x18F5, CharProperty.ALetter), + UnicodeRange(0x1900, 0x191E, CharProperty.ALetter), + UnicodeRange(0x1920, 0x192B, CharProperty.Extend), + UnicodeRange(0x1930, 0x193B, CharProperty.Extend), + UnicodeRange(0x1946, 0x194F, CharProperty.Numeric), + UnicodeRange(0x19D0, 0x19D9, CharProperty.Numeric), + UnicodeRange(0x1A00, 0x1A16, CharProperty.ALetter), + UnicodeRange(0x1A17, 0x1A1B, CharProperty.Extend), + UnicodeRange(0x1A55, 0x1A5E, CharProperty.Extend), + UnicodeRange(0x1A60, 0x1A7C, CharProperty.Extend), + UnicodeRange(0x1A7F, 0x1A7F, CharProperty.Extend), + UnicodeRange(0x1A80, 0x1A89, CharProperty.Numeric), + UnicodeRange(0x1A90, 0x1A99, CharProperty.Numeric), + UnicodeRange(0x1AB0, 0x1ABE, CharProperty.Extend), + UnicodeRange(0x1B00, 0x1B04, CharProperty.Extend), + UnicodeRange(0x1B05, 0x1B33, CharProperty.ALetter), + UnicodeRange(0x1B34, 0x1B44, CharProperty.Extend), + UnicodeRange(0x1B45, 0x1B4B, CharProperty.ALetter), + UnicodeRange(0x1B50, 0x1B59, CharProperty.Numeric), + UnicodeRange(0x1B6B, 0x1B73, CharProperty.Extend), + UnicodeRange(0x1B80, 0x1B82, CharProperty.Extend), + UnicodeRange(0x1B83, 0x1BA0, CharProperty.ALetter), + UnicodeRange(0x1BA1, 0x1BAD, CharProperty.Extend), + UnicodeRange(0x1BAE, 0x1BAF, CharProperty.ALetter), + UnicodeRange(0x1BB0, 0x1BB9, CharProperty.Numeric), + UnicodeRange(0x1BBA, 0x1BE5, CharProperty.ALetter), + UnicodeRange(0x1BE6, 0x1BF3, CharProperty.Extend), + UnicodeRange(0x1C00, 0x1C23, CharProperty.ALetter), + UnicodeRange(0x1C24, 0x1C37, CharProperty.Extend), + UnicodeRange(0x1C40, 0x1C49, CharProperty.Numeric), + UnicodeRange(0x1C4D, 0x1C4F, CharProperty.ALetter), + UnicodeRange(0x1C50, 0x1C59, CharProperty.Numeric), + UnicodeRange(0x1C5A, 0x1C7D, CharProperty.ALetter), + UnicodeRange(0x1C80, 0x1C88, CharProperty.ALetter), + UnicodeRange(0x1C90, 0x1CBA, CharProperty.ALetter), + UnicodeRange(0x1CBD, 0x1CBF, CharProperty.ALetter), + UnicodeRange(0x1CD0, 0x1CD2, CharProperty.Extend), + UnicodeRange(0x1CD4, 0x1CE8, CharProperty.Extend), + UnicodeRange(0x1CE9, 0x1CEC, CharProperty.ALetter), + UnicodeRange(0x1CED, 0x1CED, CharProperty.Extend), + UnicodeRange(0x1CEE, 0x1CF3, CharProperty.ALetter), + UnicodeRange(0x1CF4, 0x1CF4, CharProperty.Extend), + UnicodeRange(0x1CF5, 0x1CF6, CharProperty.ALetter), + UnicodeRange(0x1CF7, 0x1CF9, CharProperty.Extend), + UnicodeRange(0x1CFA, 0x1CFA, CharProperty.ALetter), + UnicodeRange(0x1D00, 0x1DBF, CharProperty.ALetter), + UnicodeRange(0x1DC0, 0x1DF9, CharProperty.Extend), + UnicodeRange(0x1DFB, 0x1DFF, CharProperty.Extend), + UnicodeRange(0x1E00, 0x1F15, CharProperty.ALetter), + UnicodeRange(0x1F18, 0x1F1D, CharProperty.ALetter), + UnicodeRange(0x1F20, 0x1F45, CharProperty.ALetter), + UnicodeRange(0x1F48, 0x1F4D, CharProperty.ALetter), + UnicodeRange(0x1F50, 0x1F57, CharProperty.ALetter), + UnicodeRange(0x1F59, 0x1F59, CharProperty.ALetter), + UnicodeRange(0x1F5B, 0x1F5B, CharProperty.ALetter), + UnicodeRange(0x1F5D, 0x1F5D, CharProperty.ALetter), + UnicodeRange(0x1F5F, 0x1F7D, CharProperty.ALetter), + UnicodeRange(0x1F80, 0x1FB4, CharProperty.ALetter), + UnicodeRange(0x1FB6, 0x1FBC, CharProperty.ALetter), + UnicodeRange(0x1FBE, 0x1FBE, CharProperty.ALetter), + UnicodeRange(0x1FC2, 0x1FC4, CharProperty.ALetter), + UnicodeRange(0x1FC6, 0x1FCC, CharProperty.ALetter), + UnicodeRange(0x1FD0, 0x1FD3, CharProperty.ALetter), + UnicodeRange(0x1FD6, 0x1FDB, CharProperty.ALetter), + UnicodeRange(0x1FE0, 0x1FEC, CharProperty.ALetter), + UnicodeRange(0x1FF2, 0x1FF4, CharProperty.ALetter), + UnicodeRange(0x1FF6, 0x1FFC, CharProperty.ALetter), + UnicodeRange(0x2000, 0x2006, CharProperty.WSegSpace), + UnicodeRange(0x2008, 0x200A, CharProperty.WSegSpace), + UnicodeRange(0x200C, 0x200C, CharProperty.Extend), + UnicodeRange(0x200D, 0x200D, CharProperty.ZWJ), + UnicodeRange(0x200E, 0x200F, CharProperty.Format), + UnicodeRange(0x2018, 0x2019, CharProperty.MidNumLet), + UnicodeRange(0x2024, 0x2024, CharProperty.MidNumLet), + UnicodeRange(0x2027, 0x2027, CharProperty.MidLetter), + UnicodeRange(0x2028, 0x2029, CharProperty.Newline), + UnicodeRange(0x202A, 0x202E, CharProperty.Format), + UnicodeRange(0x202F, 0x202F, CharProperty.ExtendNumLet), + UnicodeRange(0x203F, 0x2040, CharProperty.ExtendNumLet), + UnicodeRange(0x2044, 0x2044, CharProperty.MidNum), + UnicodeRange(0x2054, 0x2054, CharProperty.ExtendNumLet), + UnicodeRange(0x205F, 0x205F, CharProperty.WSegSpace), + UnicodeRange(0x2060, 0x2064, CharProperty.Format), + UnicodeRange(0x2066, 0x206F, CharProperty.Format), + UnicodeRange(0x2071, 0x2071, CharProperty.ALetter), + UnicodeRange(0x207F, 0x207F, CharProperty.ALetter), + UnicodeRange(0x2090, 0x209C, CharProperty.ALetter), + UnicodeRange(0x20D0, 0x20F0, CharProperty.Extend), + UnicodeRange(0x2102, 0x2102, CharProperty.ALetter), + UnicodeRange(0x2107, 0x2107, CharProperty.ALetter), + UnicodeRange(0x210A, 0x2113, CharProperty.ALetter), + UnicodeRange(0x2115, 0x2115, CharProperty.ALetter), + UnicodeRange(0x2119, 0x211D, CharProperty.ALetter), + UnicodeRange(0x2124, 0x2124, CharProperty.ALetter), + UnicodeRange(0x2126, 0x2126, CharProperty.ALetter), + UnicodeRange(0x2128, 0x2128, CharProperty.ALetter), + UnicodeRange(0x212A, 0x212D, CharProperty.ALetter), + UnicodeRange(0x212F, 0x2139, CharProperty.ALetter), + UnicodeRange(0x213C, 0x213F, CharProperty.ALetter), + UnicodeRange(0x2145, 0x2149, CharProperty.ALetter), + UnicodeRange(0x214E, 0x214E, CharProperty.ALetter), + UnicodeRange(0x2160, 0x2188, CharProperty.ALetter), + UnicodeRange(0x24B6, 0x24E9, CharProperty.ALetter), + UnicodeRange(0x2C00, 0x2C2E, CharProperty.ALetter), + UnicodeRange(0x2C30, 0x2C5E, CharProperty.ALetter), + UnicodeRange(0x2C60, 0x2CE4, CharProperty.ALetter), + UnicodeRange(0x2CEB, 0x2CEE, CharProperty.ALetter), + UnicodeRange(0x2CEF, 0x2CF1, CharProperty.Extend), + UnicodeRange(0x2CF2, 0x2CF3, CharProperty.ALetter), + UnicodeRange(0x2D00, 0x2D25, CharProperty.ALetter), + UnicodeRange(0x2D27, 0x2D27, CharProperty.ALetter), + UnicodeRange(0x2D2D, 0x2D2D, CharProperty.ALetter), + UnicodeRange(0x2D30, 0x2D67, CharProperty.ALetter), + UnicodeRange(0x2D6F, 0x2D6F, CharProperty.ALetter), + UnicodeRange(0x2D7F, 0x2D7F, CharProperty.Extend), + UnicodeRange(0x2D80, 0x2D96, CharProperty.ALetter), + UnicodeRange(0x2DA0, 0x2DA6, CharProperty.ALetter), + UnicodeRange(0x2DA8, 0x2DAE, CharProperty.ALetter), + UnicodeRange(0x2DB0, 0x2DB6, CharProperty.ALetter), + UnicodeRange(0x2DB8, 0x2DBE, CharProperty.ALetter), + UnicodeRange(0x2DC0, 0x2DC6, CharProperty.ALetter), + UnicodeRange(0x2DC8, 0x2DCE, CharProperty.ALetter), + UnicodeRange(0x2DD0, 0x2DD6, CharProperty.ALetter), + UnicodeRange(0x2DD8, 0x2DDE, CharProperty.ALetter), + UnicodeRange(0x2DE0, 0x2DFF, CharProperty.Extend), + UnicodeRange(0x2E2F, 0x2E2F, CharProperty.ALetter), + UnicodeRange(0x3000, 0x3000, CharProperty.WSegSpace), + UnicodeRange(0x3005, 0x3005, CharProperty.ALetter), + UnicodeRange(0x302A, 0x302F, CharProperty.Extend), + UnicodeRange(0x3031, 0x3035, CharProperty.Katakana), + UnicodeRange(0x303B, 0x303C, CharProperty.ALetter), + UnicodeRange(0x3099, 0x309A, CharProperty.Extend), + UnicodeRange(0x309B, 0x309C, CharProperty.Katakana), + UnicodeRange(0x30A0, 0x30FA, CharProperty.Katakana), + UnicodeRange(0x30FC, 0x30FF, CharProperty.Katakana), + UnicodeRange(0x3105, 0x312F, CharProperty.ALetter), + UnicodeRange(0x3131, 0x318E, CharProperty.ALetter), + UnicodeRange(0x31A0, 0x31BA, CharProperty.ALetter), + UnicodeRange(0x31F0, 0x31FF, CharProperty.Katakana), + UnicodeRange(0x32D0, 0x32FE, CharProperty.Katakana), + UnicodeRange(0x3300, 0x3357, CharProperty.Katakana), + UnicodeRange(0xA000, 0xA48C, CharProperty.ALetter), + UnicodeRange(0xA4D0, 0xA4FD, CharProperty.ALetter), + UnicodeRange(0xA500, 0xA60C, CharProperty.ALetter), + UnicodeRange(0xA610, 0xA61F, CharProperty.ALetter), + UnicodeRange(0xA620, 0xA629, CharProperty.Numeric), + UnicodeRange(0xA62A, 0xA62B, CharProperty.ALetter), + UnicodeRange(0xA640, 0xA66E, CharProperty.ALetter), + UnicodeRange(0xA66F, 0xA672, CharProperty.Extend), + UnicodeRange(0xA674, 0xA67D, CharProperty.Extend), + UnicodeRange(0xA67F, 0xA69D, CharProperty.ALetter), + UnicodeRange(0xA69E, 0xA69F, CharProperty.Extend), + UnicodeRange(0xA6A0, 0xA6EF, CharProperty.ALetter), + UnicodeRange(0xA6F0, 0xA6F1, CharProperty.Extend), + UnicodeRange(0xA717, 0xA7BF, CharProperty.ALetter), + UnicodeRange(0xA7C2, 0xA7C6, CharProperty.ALetter), + UnicodeRange(0xA7F7, 0xA801, CharProperty.ALetter), + UnicodeRange(0xA802, 0xA802, CharProperty.Extend), + UnicodeRange(0xA803, 0xA805, CharProperty.ALetter), + UnicodeRange(0xA806, 0xA806, CharProperty.Extend), + UnicodeRange(0xA807, 0xA80A, CharProperty.ALetter), + UnicodeRange(0xA80B, 0xA80B, CharProperty.Extend), + UnicodeRange(0xA80C, 0xA822, CharProperty.ALetter), + UnicodeRange(0xA823, 0xA827, CharProperty.Extend), + UnicodeRange(0xA840, 0xA873, CharProperty.ALetter), + UnicodeRange(0xA880, 0xA881, CharProperty.Extend), + UnicodeRange(0xA882, 0xA8B3, CharProperty.ALetter), + UnicodeRange(0xA8B4, 0xA8C5, CharProperty.Extend), + UnicodeRange(0xA8D0, 0xA8D9, CharProperty.Numeric), + UnicodeRange(0xA8E0, 0xA8F1, CharProperty.Extend), + UnicodeRange(0xA8F2, 0xA8F7, CharProperty.ALetter), + UnicodeRange(0xA8FB, 0xA8FB, CharProperty.ALetter), + UnicodeRange(0xA8FD, 0xA8FE, CharProperty.ALetter), + UnicodeRange(0xA8FF, 0xA8FF, CharProperty.Extend), + UnicodeRange(0xA900, 0xA909, CharProperty.Numeric), + UnicodeRange(0xA90A, 0xA925, CharProperty.ALetter), + UnicodeRange(0xA926, 0xA92D, CharProperty.Extend), + UnicodeRange(0xA930, 0xA946, CharProperty.ALetter), + UnicodeRange(0xA947, 0xA953, CharProperty.Extend), + UnicodeRange(0xA960, 0xA97C, CharProperty.ALetter), + UnicodeRange(0xA980, 0xA983, CharProperty.Extend), + UnicodeRange(0xA984, 0xA9B2, CharProperty.ALetter), + UnicodeRange(0xA9B3, 0xA9C0, CharProperty.Extend), + UnicodeRange(0xA9CF, 0xA9CF, CharProperty.ALetter), + UnicodeRange(0xA9D0, 0xA9D9, CharProperty.Numeric), + UnicodeRange(0xA9E5, 0xA9E5, CharProperty.Extend), + UnicodeRange(0xA9F0, 0xA9F9, CharProperty.Numeric), + UnicodeRange(0xAA00, 0xAA28, CharProperty.ALetter), + UnicodeRange(0xAA29, 0xAA36, CharProperty.Extend), + UnicodeRange(0xAA40, 0xAA42, CharProperty.ALetter), + UnicodeRange(0xAA43, 0xAA43, CharProperty.Extend), + UnicodeRange(0xAA44, 0xAA4B, CharProperty.ALetter), + UnicodeRange(0xAA4C, 0xAA4D, CharProperty.Extend), + UnicodeRange(0xAA50, 0xAA59, CharProperty.Numeric), + UnicodeRange(0xAA7B, 0xAA7D, CharProperty.Extend), + UnicodeRange(0xAAB0, 0xAAB0, CharProperty.Extend), + UnicodeRange(0xAAB2, 0xAAB4, CharProperty.Extend), + UnicodeRange(0xAAB7, 0xAAB8, CharProperty.Extend), + UnicodeRange(0xAABE, 0xAABF, CharProperty.Extend), + UnicodeRange(0xAAC1, 0xAAC1, CharProperty.Extend), + UnicodeRange(0xAAE0, 0xAAEA, CharProperty.ALetter), + UnicodeRange(0xAAEB, 0xAAEF, CharProperty.Extend), + UnicodeRange(0xAAF2, 0xAAF4, CharProperty.ALetter), + UnicodeRange(0xAAF5, 0xAAF6, CharProperty.Extend), + UnicodeRange(0xAB01, 0xAB06, CharProperty.ALetter), + UnicodeRange(0xAB09, 0xAB0E, CharProperty.ALetter), + UnicodeRange(0xAB11, 0xAB16, CharProperty.ALetter), + UnicodeRange(0xAB20, 0xAB26, CharProperty.ALetter), + UnicodeRange(0xAB28, 0xAB2E, CharProperty.ALetter), + UnicodeRange(0xAB30, 0xAB67, CharProperty.ALetter), + UnicodeRange(0xAB70, 0xABE2, CharProperty.ALetter), + UnicodeRange(0xABE3, 0xABEA, CharProperty.Extend), + UnicodeRange(0xABEC, 0xABED, CharProperty.Extend), + UnicodeRange(0xABF0, 0xABF9, CharProperty.Numeric), + UnicodeRange(0xAC00, 0xD7A3, CharProperty.ALetter), + UnicodeRange(0xD7B0, 0xD7C6, CharProperty.ALetter), + UnicodeRange(0xD7CB, 0xD7FB, CharProperty.ALetter), + UnicodeRange(0xFB00, 0xFB06, CharProperty.ALetter), + UnicodeRange(0xFB13, 0xFB17, CharProperty.ALetter), + UnicodeRange(0xFB1D, 0xFB1D, CharProperty.HebrewLetter), + UnicodeRange(0xFB1E, 0xFB1E, CharProperty.Extend), + UnicodeRange(0xFB1F, 0xFB28, CharProperty.HebrewLetter), + UnicodeRange(0xFB2A, 0xFB36, CharProperty.HebrewLetter), + UnicodeRange(0xFB38, 0xFB3C, CharProperty.HebrewLetter), + UnicodeRange(0xFB3E, 0xFB3E, CharProperty.HebrewLetter), + UnicodeRange(0xFB40, 0xFB41, CharProperty.HebrewLetter), + UnicodeRange(0xFB43, 0xFB44, CharProperty.HebrewLetter), + UnicodeRange(0xFB46, 0xFB4F, CharProperty.HebrewLetter), + UnicodeRange(0xFB50, 0xFBB1, CharProperty.ALetter), + UnicodeRange(0xFBD3, 0xFD3D, CharProperty.ALetter), + UnicodeRange(0xFD50, 0xFD8F, CharProperty.ALetter), + UnicodeRange(0xFD92, 0xFDC7, CharProperty.ALetter), + UnicodeRange(0xFDF0, 0xFDFB, CharProperty.ALetter), + UnicodeRange(0xFE00, 0xFE0F, CharProperty.Extend), + UnicodeRange(0xFE10, 0xFE10, CharProperty.MidNum), + UnicodeRange(0xFE13, 0xFE13, CharProperty.MidLetter), + UnicodeRange(0xFE14, 0xFE14, CharProperty.MidNum), + UnicodeRange(0xFE20, 0xFE2F, CharProperty.Extend), + UnicodeRange(0xFE33, 0xFE34, CharProperty.ExtendNumLet), + UnicodeRange(0xFE4D, 0xFE4F, CharProperty.ExtendNumLet), + UnicodeRange(0xFE50, 0xFE50, CharProperty.MidNum), + UnicodeRange(0xFE52, 0xFE52, CharProperty.MidNumLet), + UnicodeRange(0xFE54, 0xFE54, CharProperty.MidNum), + UnicodeRange(0xFE55, 0xFE55, CharProperty.MidLetter), + UnicodeRange(0xFE70, 0xFE74, CharProperty.ALetter), + UnicodeRange(0xFE76, 0xFEFC, CharProperty.ALetter), + UnicodeRange(0xFEFF, 0xFEFF, CharProperty.Format), + UnicodeRange(0xFF07, 0xFF07, CharProperty.MidNumLet), + UnicodeRange(0xFF0C, 0xFF0C, CharProperty.MidNum), + UnicodeRange(0xFF0E, 0xFF0E, CharProperty.MidNumLet), + UnicodeRange(0xFF10, 0xFF19, CharProperty.Numeric), + UnicodeRange(0xFF1A, 0xFF1A, CharProperty.MidLetter), + UnicodeRange(0xFF1B, 0xFF1B, CharProperty.MidNum), + UnicodeRange(0xFF21, 0xFF3A, CharProperty.ALetter), + UnicodeRange(0xFF3F, 0xFF3F, CharProperty.ExtendNumLet), + UnicodeRange(0xFF41, 0xFF5A, CharProperty.ALetter), + UnicodeRange(0xFF66, 0xFF9D, CharProperty.Katakana), + UnicodeRange(0xFF9E, 0xFF9F, CharProperty.Extend), + UnicodeRange(0xFFA0, 0xFFBE, CharProperty.ALetter), + UnicodeRange(0xFFC2, 0xFFC7, CharProperty.ALetter), + UnicodeRange(0xFFCA, 0xFFCF, CharProperty.ALetter), + UnicodeRange(0xFFD2, 0xFFD7, CharProperty.ALetter), + UnicodeRange(0xFFDA, 0xFFDC, CharProperty.ALetter), + UnicodeRange(0xFFF9, 0xFFFB, CharProperty.Format), + UnicodeRange(0x10000, 0x1000B, CharProperty.ALetter), + UnicodeRange(0x1000D, 0x10026, CharProperty.ALetter), + UnicodeRange(0x10028, 0x1003A, CharProperty.ALetter), + UnicodeRange(0x1003C, 0x1003D, CharProperty.ALetter), + UnicodeRange(0x1003F, 0x1004D, CharProperty.ALetter), + UnicodeRange(0x10050, 0x1005D, CharProperty.ALetter), + UnicodeRange(0x10080, 0x100FA, CharProperty.ALetter), + UnicodeRange(0x10140, 0x10174, CharProperty.ALetter), + UnicodeRange(0x101FD, 0x101FD, CharProperty.Extend), + UnicodeRange(0x10280, 0x1029C, CharProperty.ALetter), + UnicodeRange(0x102A0, 0x102D0, CharProperty.ALetter), + UnicodeRange(0x102E0, 0x102E0, CharProperty.Extend), + UnicodeRange(0x10300, 0x1031F, CharProperty.ALetter), + UnicodeRange(0x1032D, 0x1034A, CharProperty.ALetter), + UnicodeRange(0x10350, 0x10375, CharProperty.ALetter), + UnicodeRange(0x10376, 0x1037A, CharProperty.Extend), + UnicodeRange(0x10380, 0x1039D, CharProperty.ALetter), + UnicodeRange(0x103A0, 0x103C3, CharProperty.ALetter), + UnicodeRange(0x103C8, 0x103CF, CharProperty.ALetter), + UnicodeRange(0x103D1, 0x103D5, CharProperty.ALetter), + UnicodeRange(0x10400, 0x1049D, CharProperty.ALetter), + UnicodeRange(0x104A0, 0x104A9, CharProperty.Numeric), + UnicodeRange(0x104B0, 0x104D3, CharProperty.ALetter), + UnicodeRange(0x104D8, 0x104FB, CharProperty.ALetter), + UnicodeRange(0x10500, 0x10527, CharProperty.ALetter), + UnicodeRange(0x10530, 0x10563, CharProperty.ALetter), + UnicodeRange(0x10600, 0x10736, CharProperty.ALetter), + UnicodeRange(0x10740, 0x10755, CharProperty.ALetter), + UnicodeRange(0x10760, 0x10767, CharProperty.ALetter), + UnicodeRange(0x10800, 0x10805, CharProperty.ALetter), + UnicodeRange(0x10808, 0x10808, CharProperty.ALetter), + UnicodeRange(0x1080A, 0x10835, CharProperty.ALetter), + UnicodeRange(0x10837, 0x10838, CharProperty.ALetter), + UnicodeRange(0x1083C, 0x1083C, CharProperty.ALetter), + UnicodeRange(0x1083F, 0x10855, CharProperty.ALetter), + UnicodeRange(0x10860, 0x10876, CharProperty.ALetter), + UnicodeRange(0x10880, 0x1089E, CharProperty.ALetter), + UnicodeRange(0x108E0, 0x108F2, CharProperty.ALetter), + UnicodeRange(0x108F4, 0x108F5, CharProperty.ALetter), + UnicodeRange(0x10900, 0x10915, CharProperty.ALetter), + UnicodeRange(0x10920, 0x10939, CharProperty.ALetter), + UnicodeRange(0x10980, 0x109B7, CharProperty.ALetter), + UnicodeRange(0x109BE, 0x109BF, CharProperty.ALetter), + UnicodeRange(0x10A00, 0x10A00, CharProperty.ALetter), + UnicodeRange(0x10A01, 0x10A03, CharProperty.Extend), + UnicodeRange(0x10A05, 0x10A06, CharProperty.Extend), + UnicodeRange(0x10A0C, 0x10A0F, CharProperty.Extend), + UnicodeRange(0x10A10, 0x10A13, CharProperty.ALetter), + UnicodeRange(0x10A15, 0x10A17, CharProperty.ALetter), + UnicodeRange(0x10A19, 0x10A35, CharProperty.ALetter), + UnicodeRange(0x10A38, 0x10A3A, CharProperty.Extend), + UnicodeRange(0x10A3F, 0x10A3F, CharProperty.Extend), + UnicodeRange(0x10A60, 0x10A7C, CharProperty.ALetter), + UnicodeRange(0x10A80, 0x10A9C, CharProperty.ALetter), + UnicodeRange(0x10AC0, 0x10AC7, CharProperty.ALetter), + UnicodeRange(0x10AC9, 0x10AE4, CharProperty.ALetter), + UnicodeRange(0x10AE5, 0x10AE6, CharProperty.Extend), + UnicodeRange(0x10B00, 0x10B35, CharProperty.ALetter), + UnicodeRange(0x10B40, 0x10B55, CharProperty.ALetter), + UnicodeRange(0x10B60, 0x10B72, CharProperty.ALetter), + UnicodeRange(0x10B80, 0x10B91, CharProperty.ALetter), + UnicodeRange(0x10C00, 0x10C48, CharProperty.ALetter), + UnicodeRange(0x10C80, 0x10CB2, CharProperty.ALetter), + UnicodeRange(0x10CC0, 0x10CF2, CharProperty.ALetter), + UnicodeRange(0x10D00, 0x10D23, CharProperty.ALetter), + UnicodeRange(0x10D24, 0x10D27, CharProperty.Extend), + UnicodeRange(0x10D30, 0x10D39, CharProperty.Numeric), + UnicodeRange(0x10F00, 0x10F1C, CharProperty.ALetter), + UnicodeRange(0x10F27, 0x10F27, CharProperty.ALetter), + UnicodeRange(0x10F30, 0x10F45, CharProperty.ALetter), + UnicodeRange(0x10F46, 0x10F50, CharProperty.Extend), + UnicodeRange(0x10FE0, 0x10FF6, CharProperty.ALetter), + UnicodeRange(0x11000, 0x11002, CharProperty.Extend), + UnicodeRange(0x11003, 0x11037, CharProperty.ALetter), + UnicodeRange(0x11038, 0x11046, CharProperty.Extend), + UnicodeRange(0x11066, 0x1106F, CharProperty.Numeric), + UnicodeRange(0x1107F, 0x11082, CharProperty.Extend), + UnicodeRange(0x11083, 0x110AF, CharProperty.ALetter), + UnicodeRange(0x110B0, 0x110BA, CharProperty.Extend), + UnicodeRange(0x110BD, 0x110BD, CharProperty.Format), + UnicodeRange(0x110CD, 0x110CD, CharProperty.Format), + UnicodeRange(0x110D0, 0x110E8, CharProperty.ALetter), + UnicodeRange(0x110F0, 0x110F9, CharProperty.Numeric), + UnicodeRange(0x11100, 0x11102, CharProperty.Extend), + UnicodeRange(0x11103, 0x11126, CharProperty.ALetter), + UnicodeRange(0x11127, 0x11134, CharProperty.Extend), + UnicodeRange(0x11136, 0x1113F, CharProperty.Numeric), + UnicodeRange(0x11144, 0x11144, CharProperty.ALetter), + UnicodeRange(0x11145, 0x11146, CharProperty.Extend), + UnicodeRange(0x11150, 0x11172, CharProperty.ALetter), + UnicodeRange(0x11173, 0x11173, CharProperty.Extend), + UnicodeRange(0x11176, 0x11176, CharProperty.ALetter), + UnicodeRange(0x11180, 0x11182, CharProperty.Extend), + UnicodeRange(0x11183, 0x111B2, CharProperty.ALetter), + UnicodeRange(0x111B3, 0x111C0, CharProperty.Extend), + UnicodeRange(0x111C1, 0x111C4, CharProperty.ALetter), + UnicodeRange(0x111C9, 0x111CC, CharProperty.Extend), + UnicodeRange(0x111D0, 0x111D9, CharProperty.Numeric), + UnicodeRange(0x111DA, 0x111DA, CharProperty.ALetter), + UnicodeRange(0x111DC, 0x111DC, CharProperty.ALetter), + UnicodeRange(0x11200, 0x11211, CharProperty.ALetter), + UnicodeRange(0x11213, 0x1122B, CharProperty.ALetter), + UnicodeRange(0x1122C, 0x11237, CharProperty.Extend), + UnicodeRange(0x1123E, 0x1123E, CharProperty.Extend), + UnicodeRange(0x11280, 0x11286, CharProperty.ALetter), + UnicodeRange(0x11288, 0x11288, CharProperty.ALetter), + UnicodeRange(0x1128A, 0x1128D, CharProperty.ALetter), + UnicodeRange(0x1128F, 0x1129D, CharProperty.ALetter), + UnicodeRange(0x1129F, 0x112A8, CharProperty.ALetter), + UnicodeRange(0x112B0, 0x112DE, CharProperty.ALetter), + UnicodeRange(0x112DF, 0x112EA, CharProperty.Extend), + UnicodeRange(0x112F0, 0x112F9, CharProperty.Numeric), + UnicodeRange(0x11300, 0x11303, CharProperty.Extend), + UnicodeRange(0x11305, 0x1130C, CharProperty.ALetter), + UnicodeRange(0x1130F, 0x11310, CharProperty.ALetter), + UnicodeRange(0x11313, 0x11328, CharProperty.ALetter), + UnicodeRange(0x1132A, 0x11330, CharProperty.ALetter), + UnicodeRange(0x11332, 0x11333, CharProperty.ALetter), + UnicodeRange(0x11335, 0x11339, CharProperty.ALetter), + UnicodeRange(0x1133B, 0x1133C, CharProperty.Extend), + UnicodeRange(0x1133D, 0x1133D, CharProperty.ALetter), + UnicodeRange(0x1133E, 0x11344, CharProperty.Extend), + UnicodeRange(0x11347, 0x11348, CharProperty.Extend), + UnicodeRange(0x1134B, 0x1134D, CharProperty.Extend), + UnicodeRange(0x11350, 0x11350, CharProperty.ALetter), + UnicodeRange(0x11357, 0x11357, CharProperty.Extend), + UnicodeRange(0x1135D, 0x11361, CharProperty.ALetter), + UnicodeRange(0x11362, 0x11363, CharProperty.Extend), + UnicodeRange(0x11366, 0x1136C, CharProperty.Extend), + UnicodeRange(0x11370, 0x11374, CharProperty.Extend), + UnicodeRange(0x11400, 0x11434, CharProperty.ALetter), + UnicodeRange(0x11435, 0x11446, CharProperty.Extend), + UnicodeRange(0x11447, 0x1144A, CharProperty.ALetter), + UnicodeRange(0x11450, 0x11459, CharProperty.Numeric), + UnicodeRange(0x1145E, 0x1145E, CharProperty.Extend), + UnicodeRange(0x1145F, 0x1145F, CharProperty.ALetter), + UnicodeRange(0x11480, 0x114AF, CharProperty.ALetter), + UnicodeRange(0x114B0, 0x114C3, CharProperty.Extend), + UnicodeRange(0x114C4, 0x114C5, CharProperty.ALetter), + UnicodeRange(0x114C7, 0x114C7, CharProperty.ALetter), + UnicodeRange(0x114D0, 0x114D9, CharProperty.Numeric), + UnicodeRange(0x11580, 0x115AE, CharProperty.ALetter), + UnicodeRange(0x115AF, 0x115B5, CharProperty.Extend), + UnicodeRange(0x115B8, 0x115C0, CharProperty.Extend), + UnicodeRange(0x115D8, 0x115DB, CharProperty.ALetter), + UnicodeRange(0x115DC, 0x115DD, CharProperty.Extend), + UnicodeRange(0x11600, 0x1162F, CharProperty.ALetter), + UnicodeRange(0x11630, 0x11640, CharProperty.Extend), + UnicodeRange(0x11644, 0x11644, CharProperty.ALetter), + UnicodeRange(0x11650, 0x11659, CharProperty.Numeric), + UnicodeRange(0x11680, 0x116AA, CharProperty.ALetter), + UnicodeRange(0x116AB, 0x116B7, CharProperty.Extend), + UnicodeRange(0x116B8, 0x116B8, CharProperty.ALetter), + UnicodeRange(0x116C0, 0x116C9, CharProperty.Numeric), + UnicodeRange(0x1171D, 0x1172B, CharProperty.Extend), + UnicodeRange(0x11730, 0x11739, CharProperty.Numeric), + UnicodeRange(0x11800, 0x1182B, CharProperty.ALetter), + UnicodeRange(0x1182C, 0x1183A, CharProperty.Extend), + UnicodeRange(0x118A0, 0x118DF, CharProperty.ALetter), + UnicodeRange(0x118E0, 0x118E9, CharProperty.Numeric), + UnicodeRange(0x118FF, 0x118FF, CharProperty.ALetter), + UnicodeRange(0x119A0, 0x119A7, CharProperty.ALetter), + UnicodeRange(0x119AA, 0x119D0, CharProperty.ALetter), + UnicodeRange(0x119D1, 0x119D7, CharProperty.Extend), + UnicodeRange(0x119DA, 0x119E0, CharProperty.Extend), + UnicodeRange(0x119E1, 0x119E1, CharProperty.ALetter), + UnicodeRange(0x119E3, 0x119E3, CharProperty.ALetter), + UnicodeRange(0x119E4, 0x119E4, CharProperty.Extend), + UnicodeRange(0x11A00, 0x11A00, CharProperty.ALetter), + UnicodeRange(0x11A01, 0x11A0A, CharProperty.Extend), + UnicodeRange(0x11A0B, 0x11A32, CharProperty.ALetter), + UnicodeRange(0x11A33, 0x11A39, CharProperty.Extend), + UnicodeRange(0x11A3A, 0x11A3A, CharProperty.ALetter), + UnicodeRange(0x11A3B, 0x11A3E, CharProperty.Extend), + UnicodeRange(0x11A47, 0x11A47, CharProperty.Extend), + UnicodeRange(0x11A50, 0x11A50, CharProperty.ALetter), + UnicodeRange(0x11A51, 0x11A5B, CharProperty.Extend), + UnicodeRange(0x11A5C, 0x11A89, CharProperty.ALetter), + UnicodeRange(0x11A8A, 0x11A99, CharProperty.Extend), + UnicodeRange(0x11A9D, 0x11A9D, CharProperty.ALetter), + UnicodeRange(0x11AC0, 0x11AF8, CharProperty.ALetter), + UnicodeRange(0x11C00, 0x11C08, CharProperty.ALetter), + UnicodeRange(0x11C0A, 0x11C2E, CharProperty.ALetter), + UnicodeRange(0x11C2F, 0x11C36, CharProperty.Extend), + UnicodeRange(0x11C38, 0x11C3F, CharProperty.Extend), + UnicodeRange(0x11C40, 0x11C40, CharProperty.ALetter), + UnicodeRange(0x11C50, 0x11C59, CharProperty.Numeric), + UnicodeRange(0x11C72, 0x11C8F, CharProperty.ALetter), + UnicodeRange(0x11C92, 0x11CA7, CharProperty.Extend), + UnicodeRange(0x11CA9, 0x11CB6, CharProperty.Extend), + UnicodeRange(0x11D00, 0x11D06, CharProperty.ALetter), + UnicodeRange(0x11D08, 0x11D09, CharProperty.ALetter), + UnicodeRange(0x11D0B, 0x11D30, CharProperty.ALetter), + UnicodeRange(0x11D31, 0x11D36, CharProperty.Extend), + UnicodeRange(0x11D3A, 0x11D3A, CharProperty.Extend), + UnicodeRange(0x11D3C, 0x11D3D, CharProperty.Extend), + UnicodeRange(0x11D3F, 0x11D45, CharProperty.Extend), + UnicodeRange(0x11D46, 0x11D46, CharProperty.ALetter), + UnicodeRange(0x11D47, 0x11D47, CharProperty.Extend), + UnicodeRange(0x11D50, 0x11D59, CharProperty.Numeric), + UnicodeRange(0x11D60, 0x11D65, CharProperty.ALetter), + UnicodeRange(0x11D67, 0x11D68, CharProperty.ALetter), + UnicodeRange(0x11D6A, 0x11D89, CharProperty.ALetter), + UnicodeRange(0x11D8A, 0x11D8E, CharProperty.Extend), + UnicodeRange(0x11D90, 0x11D91, CharProperty.Extend), + UnicodeRange(0x11D93, 0x11D97, CharProperty.Extend), + UnicodeRange(0x11D98, 0x11D98, CharProperty.ALetter), + UnicodeRange(0x11DA0, 0x11DA9, CharProperty.Numeric), + UnicodeRange(0x11EE0, 0x11EF2, CharProperty.ALetter), + UnicodeRange(0x11EF3, 0x11EF6, CharProperty.Extend), + UnicodeRange(0x12000, 0x12399, CharProperty.ALetter), + UnicodeRange(0x12400, 0x1246E, CharProperty.ALetter), + UnicodeRange(0x12480, 0x12543, CharProperty.ALetter), + UnicodeRange(0x13000, 0x1342E, CharProperty.ALetter), + UnicodeRange(0x13430, 0x13438, CharProperty.Format), + UnicodeRange(0x14400, 0x14646, CharProperty.ALetter), + UnicodeRange(0x16800, 0x16A38, CharProperty.ALetter), + UnicodeRange(0x16A40, 0x16A5E, CharProperty.ALetter), + UnicodeRange(0x16A60, 0x16A69, CharProperty.Numeric), + UnicodeRange(0x16AD0, 0x16AED, CharProperty.ALetter), + UnicodeRange(0x16AF0, 0x16AF4, CharProperty.Extend), + UnicodeRange(0x16B00, 0x16B2F, CharProperty.ALetter), + UnicodeRange(0x16B30, 0x16B36, CharProperty.Extend), + UnicodeRange(0x16B40, 0x16B43, CharProperty.ALetter), + UnicodeRange(0x16B50, 0x16B59, CharProperty.Numeric), + UnicodeRange(0x16B63, 0x16B77, CharProperty.ALetter), + UnicodeRange(0x16B7D, 0x16B8F, CharProperty.ALetter), + UnicodeRange(0x16E40, 0x16E7F, CharProperty.ALetter), + UnicodeRange(0x16F00, 0x16F4A, CharProperty.ALetter), + UnicodeRange(0x16F4F, 0x16F4F, CharProperty.Extend), + UnicodeRange(0x16F50, 0x16F50, CharProperty.ALetter), + UnicodeRange(0x16F51, 0x16F87, CharProperty.Extend), + UnicodeRange(0x16F8F, 0x16F92, CharProperty.Extend), + UnicodeRange(0x16F93, 0x16F9F, CharProperty.ALetter), + UnicodeRange(0x16FE0, 0x16FE1, CharProperty.ALetter), + UnicodeRange(0x16FE3, 0x16FE3, CharProperty.ALetter), + UnicodeRange(0x1B000, 0x1B000, CharProperty.Katakana), + UnicodeRange(0x1B164, 0x1B167, CharProperty.Katakana), + UnicodeRange(0x1BC00, 0x1BC6A, CharProperty.ALetter), + UnicodeRange(0x1BC70, 0x1BC7C, CharProperty.ALetter), + UnicodeRange(0x1BC80, 0x1BC88, CharProperty.ALetter), + UnicodeRange(0x1BC90, 0x1BC99, CharProperty.ALetter), + UnicodeRange(0x1BC9D, 0x1BC9E, CharProperty.Extend), + UnicodeRange(0x1BCA0, 0x1BCA3, CharProperty.Format), + UnicodeRange(0x1D165, 0x1D169, CharProperty.Extend), + UnicodeRange(0x1D16D, 0x1D172, CharProperty.Extend), + UnicodeRange(0x1D173, 0x1D17A, CharProperty.Format), + UnicodeRange(0x1D17B, 0x1D182, CharProperty.Extend), + UnicodeRange(0x1D185, 0x1D18B, CharProperty.Extend), + UnicodeRange(0x1D1AA, 0x1D1AD, CharProperty.Extend), + UnicodeRange(0x1D242, 0x1D244, CharProperty.Extend), + UnicodeRange(0x1D400, 0x1D454, CharProperty.ALetter), + UnicodeRange(0x1D456, 0x1D49C, CharProperty.ALetter), + UnicodeRange(0x1D49E, 0x1D49F, CharProperty.ALetter), + UnicodeRange(0x1D4A2, 0x1D4A2, CharProperty.ALetter), + UnicodeRange(0x1D4A5, 0x1D4A6, CharProperty.ALetter), + UnicodeRange(0x1D4A9, 0x1D4AC, CharProperty.ALetter), + UnicodeRange(0x1D4AE, 0x1D4B9, CharProperty.ALetter), + UnicodeRange(0x1D4BB, 0x1D4BB, CharProperty.ALetter), + UnicodeRange(0x1D4BD, 0x1D4C3, CharProperty.ALetter), + UnicodeRange(0x1D4C5, 0x1D505, CharProperty.ALetter), + UnicodeRange(0x1D507, 0x1D50A, CharProperty.ALetter), + UnicodeRange(0x1D50D, 0x1D514, CharProperty.ALetter), + UnicodeRange(0x1D516, 0x1D51C, CharProperty.ALetter), + UnicodeRange(0x1D51E, 0x1D539, CharProperty.ALetter), + UnicodeRange(0x1D53B, 0x1D53E, CharProperty.ALetter), + UnicodeRange(0x1D540, 0x1D544, CharProperty.ALetter), + UnicodeRange(0x1D546, 0x1D546, CharProperty.ALetter), + UnicodeRange(0x1D54A, 0x1D550, CharProperty.ALetter), + UnicodeRange(0x1D552, 0x1D6A5, CharProperty.ALetter), + UnicodeRange(0x1D6A8, 0x1D6C0, CharProperty.ALetter), + UnicodeRange(0x1D6C2, 0x1D6DA, CharProperty.ALetter), + UnicodeRange(0x1D6DC, 0x1D6FA, CharProperty.ALetter), + UnicodeRange(0x1D6FC, 0x1D714, CharProperty.ALetter), + UnicodeRange(0x1D716, 0x1D734, CharProperty.ALetter), + UnicodeRange(0x1D736, 0x1D74E, CharProperty.ALetter), + UnicodeRange(0x1D750, 0x1D76E, CharProperty.ALetter), + UnicodeRange(0x1D770, 0x1D788, CharProperty.ALetter), + UnicodeRange(0x1D78A, 0x1D7A8, CharProperty.ALetter), + UnicodeRange(0x1D7AA, 0x1D7C2, CharProperty.ALetter), + UnicodeRange(0x1D7C4, 0x1D7CB, CharProperty.ALetter), + UnicodeRange(0x1D7CE, 0x1D7FF, CharProperty.Numeric), + UnicodeRange(0x1DA00, 0x1DA36, CharProperty.Extend), + UnicodeRange(0x1DA3B, 0x1DA6C, CharProperty.Extend), + UnicodeRange(0x1DA75, 0x1DA75, CharProperty.Extend), + UnicodeRange(0x1DA84, 0x1DA84, CharProperty.Extend), + UnicodeRange(0x1DA9B, 0x1DA9F, CharProperty.Extend), + UnicodeRange(0x1DAA1, 0x1DAAF, CharProperty.Extend), + UnicodeRange(0x1E000, 0x1E006, CharProperty.Extend), + UnicodeRange(0x1E008, 0x1E018, CharProperty.Extend), + UnicodeRange(0x1E01B, 0x1E021, CharProperty.Extend), + UnicodeRange(0x1E023, 0x1E024, CharProperty.Extend), + UnicodeRange(0x1E026, 0x1E02A, CharProperty.Extend), + UnicodeRange(0x1E100, 0x1E12C, CharProperty.ALetter), + UnicodeRange(0x1E130, 0x1E136, CharProperty.Extend), + UnicodeRange(0x1E137, 0x1E13D, CharProperty.ALetter), + UnicodeRange(0x1E140, 0x1E149, CharProperty.Numeric), + UnicodeRange(0x1E14E, 0x1E14E, CharProperty.ALetter), + UnicodeRange(0x1E2C0, 0x1E2EB, CharProperty.ALetter), + UnicodeRange(0x1E2EC, 0x1E2EF, CharProperty.Extend), + UnicodeRange(0x1E2F0, 0x1E2F9, CharProperty.Numeric), + UnicodeRange(0x1E800, 0x1E8C4, CharProperty.ALetter), + UnicodeRange(0x1E8D0, 0x1E8D6, CharProperty.Extend), + UnicodeRange(0x1E900, 0x1E943, CharProperty.ALetter), + UnicodeRange(0x1E944, 0x1E94A, CharProperty.Extend), + UnicodeRange(0x1E94B, 0x1E94B, CharProperty.ALetter), + UnicodeRange(0x1E950, 0x1E959, CharProperty.Numeric), + UnicodeRange(0x1EE00, 0x1EE03, CharProperty.ALetter), + UnicodeRange(0x1EE05, 0x1EE1F, CharProperty.ALetter), + UnicodeRange(0x1EE21, 0x1EE22, CharProperty.ALetter), + UnicodeRange(0x1EE24, 0x1EE24, CharProperty.ALetter), + UnicodeRange(0x1EE27, 0x1EE27, CharProperty.ALetter), + UnicodeRange(0x1EE29, 0x1EE32, CharProperty.ALetter), + UnicodeRange(0x1EE34, 0x1EE37, CharProperty.ALetter), + UnicodeRange(0x1EE39, 0x1EE39, CharProperty.ALetter), + UnicodeRange(0x1EE3B, 0x1EE3B, CharProperty.ALetter), + UnicodeRange(0x1EE42, 0x1EE42, CharProperty.ALetter), + UnicodeRange(0x1EE47, 0x1EE47, CharProperty.ALetter), + UnicodeRange(0x1EE49, 0x1EE49, CharProperty.ALetter), + UnicodeRange(0x1EE4B, 0x1EE4B, CharProperty.ALetter), + UnicodeRange(0x1EE4D, 0x1EE4F, CharProperty.ALetter), + UnicodeRange(0x1EE51, 0x1EE52, CharProperty.ALetter), + UnicodeRange(0x1EE54, 0x1EE54, CharProperty.ALetter), + UnicodeRange(0x1EE57, 0x1EE57, CharProperty.ALetter), + UnicodeRange(0x1EE59, 0x1EE59, CharProperty.ALetter), + UnicodeRange(0x1EE5B, 0x1EE5B, CharProperty.ALetter), + UnicodeRange(0x1EE5D, 0x1EE5D, CharProperty.ALetter), + UnicodeRange(0x1EE5F, 0x1EE5F, CharProperty.ALetter), + UnicodeRange(0x1EE61, 0x1EE62, CharProperty.ALetter), + UnicodeRange(0x1EE64, 0x1EE64, CharProperty.ALetter), + UnicodeRange(0x1EE67, 0x1EE6A, CharProperty.ALetter), + UnicodeRange(0x1EE6C, 0x1EE72, CharProperty.ALetter), + UnicodeRange(0x1EE74, 0x1EE77, CharProperty.ALetter), + UnicodeRange(0x1EE79, 0x1EE7C, CharProperty.ALetter), + UnicodeRange(0x1EE7E, 0x1EE7E, CharProperty.ALetter), + UnicodeRange(0x1EE80, 0x1EE89, CharProperty.ALetter), + UnicodeRange(0x1EE8B, 0x1EE9B, CharProperty.ALetter), + UnicodeRange(0x1EEA1, 0x1EEA3, CharProperty.ALetter), + UnicodeRange(0x1EEA5, 0x1EEA9, CharProperty.ALetter), + UnicodeRange(0x1EEAB, 0x1EEBB, CharProperty.ALetter), + UnicodeRange(0x1F130, 0x1F149, CharProperty.ALetter), + UnicodeRange(0x1F150, 0x1F169, CharProperty.ALetter), + UnicodeRange(0x1F170, 0x1F189, CharProperty.ALetter), + UnicodeRange(0x1F1E6, 0x1F1FF, CharProperty.RegionalIndicator), + UnicodeRange(0x1F3FB, 0x1F3FF, CharProperty.Extend), + UnicodeRange(0xE0001, 0xE0001, CharProperty.Format), + UnicodeRange(0xE0020, 0xE007F, CharProperty.Extend), + UnicodeRange(0xE0100, 0xE01EF, CharProperty.Extend) +]); diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/text/word_breaker.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/text/word_breaker.dart new file mode 100644 index 0000000000..b25e7afea7 --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text/word_breaker.dart @@ -0,0 +1,336 @@ +// 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; + +enum _FindBreakDirection { + /// Indicates to find the word break by looking forward. + forward, + + /// Indicates to find the word break by looking backward. + backward, +} + +/// [WordBreaker] exposes static methods to identify word boundaries. +abstract class WordBreaker { + /// It starts from [index] and tries to find the next word boundary in [text]. + static int nextBreakIndex(String text, int index) => + _findBreakIndex(_FindBreakDirection.forward, text, index); + + /// It starts from [index] and tries to find the previous word boundary in + /// [text]. + static int prevBreakIndex(String text, int index) => + _findBreakIndex(_FindBreakDirection.backward, text, index); + + static int _findBreakIndex( + _FindBreakDirection direction, + String text, + int index, + ) { + int step, min, max; + if (direction == _FindBreakDirection.forward) { + step = 1; + min = 0; + max = text.length - 1; + } else { + step = -1; + min = 1; + max = text.length; + } + + int i = index; + while (i >= min && i <= max) { + i += step; + if (_isBreak(text, i)) { + break; + } + } + return i; + } + + /// Find out if there's a word break between [index - 1] and [index]. + /// http://unicode.org/reports/tr29/#Word_Boundary_Rules + static bool _isBreak(String text, int index) { + // Break at the start and end of text. + // WB1: sot ÷ Any + // WB2: Any ÷ eot + if (index <= 0 || index >= text.length) { + return true; + } + + // Do not break inside surrogate pair + if (_isUtf16Surrogate(text.codeUnitAt(index - 1))) { + return false; + } + + final CharProperty immediateRight = getCharProperty(text, index); + CharProperty immediateLeft = getCharProperty(text, index - 1); + + // Do not break within CRLF. + // WB3: CR × LF + if (immediateLeft == CharProperty.CR && immediateRight == CharProperty.LF) + return false; + + // Otherwise break before and after Newlines (including CR and LF) + // WB3a: (Newline | CR | LF) ÷ + if (_oneOf( + immediateLeft, + CharProperty.Newline, + CharProperty.CR, + CharProperty.LF, + )) { + return true; + } + + // WB3b: ÷ (Newline | CR | LF) + if (_oneOf( + immediateRight, + CharProperty.Newline, + CharProperty.CR, + CharProperty.LF, + )) { + return true; + } + + // WB3c: ZWJ × \p{Extended_Pictographic} + // TODO(flutter_web): What's the right way to implement this? + + // Keep horizontal whitespace together. + // WB3d: WSegSpace × WSegSpace + if (immediateLeft == CharProperty.WSegSpace && + immediateRight == CharProperty.WSegSpace) { + return false; + } + + // Ignore Format and Extend characters, except after sot, CR, LF, and + // Newline. + // WB4: X (Extend | Format | ZWJ)* → X + if (_oneOf( + immediateRight, + CharProperty.Extend, + CharProperty.Format, + CharProperty.ZWJ, + )) { + // The Extend|Format|ZWJ character is to the right, so it is attached + // to a character to the left, don't split here + return false; + } + + // We've reached the end of an Extend|Format|ZWJ sequence, collapse it. + int l = 0; + while (_oneOf( + immediateLeft, + CharProperty.Extend, + CharProperty.Format, + CharProperty.ZWJ, + )) { + l++; + if (index - l - 1 < 0) { + // Reached the beginning of text. + return true; + } + immediateLeft = getCharProperty(text, index - l - 1); + } + + // Do not break between most letters. + // WB5: (ALetter | Hebrew_Letter) × (ALetter | Hebrew_Letter) + if (_isAHLetter(immediateLeft) && _isAHLetter(immediateRight)) { + return false; + } + + // Some tests beyond this point require more context. We need to get that + // context while also respecting rule WB4. So ignore Format, Extend and ZWJ. + + // Skip all Format, Extend and ZWJ to the right. + int r = 0; + CharProperty nextRight; + do { + r++; + nextRight = getCharProperty(text, index + r); + } while (_oneOf( + nextRight, + CharProperty.Extend, + CharProperty.Format, + CharProperty.ZWJ, + )); + + // Skip all Format, Extend and ZWJ to the left. + CharProperty nextLeft; + do { + l++; + nextLeft = getCharProperty(text, index - l - 1); + } while (_oneOf( + nextLeft, + CharProperty.Extend, + CharProperty.Format, + CharProperty.ZWJ, + )); + + // Do not break letters across certain punctuation. + // WB6: (AHLetter) × (MidLetter | MidNumLet | Single_Quote) (AHLetter) + if (_isAHLetter(immediateLeft) && + _oneOf( + immediateRight, + CharProperty.MidLetter, + CharProperty.MidNumLet, + CharProperty.SingleQuote, + ) && + _isAHLetter(nextRight)) { + return false; + } + + // WB7: (AHLetter) (MidLetter | MidNumLet | Single_Quote) × (AHLetter) + if (_isAHLetter(nextLeft) && + _oneOf( + immediateLeft, + CharProperty.MidLetter, + CharProperty.MidNumLet, + CharProperty.SingleQuote, + ) && + _isAHLetter(immediateRight)) { + return false; + } + + // WB7a: Hebrew_Letter × Single_Quote + if (immediateLeft == CharProperty.HebrewLetter && + immediateRight == CharProperty.SingleQuote) { + return false; + } + + // WB7b: Hebrew_Letter × Double_Quote Hebrew_Letter + if (immediateLeft == CharProperty.HebrewLetter && + immediateRight == CharProperty.DoubleQuote && + nextRight == CharProperty.HebrewLetter) { + return false; + } + + // WB7c: Hebrew_Letter Double_Quote × Hebrew_Letter + if (nextLeft == CharProperty.HebrewLetter && + immediateLeft == CharProperty.DoubleQuote && + immediateRight == CharProperty.HebrewLetter) { + return false; + } + + // Do not break within sequences of digits, or digits adjacent to letters + // (“3a”, or “A3”). + // WB8: Numeric × Numeric + if (immediateLeft == CharProperty.Numeric && + immediateRight == CharProperty.Numeric) { + return false; + } + + // WB9: AHLetter × Numeric + if (_isAHLetter(immediateLeft) && immediateRight == CharProperty.Numeric) + return false; + + // WB10: Numeric × AHLetter + if (immediateLeft == CharProperty.Numeric && _isAHLetter(immediateRight)) + return false; + + // Do not break within sequences, such as “3.2” or “3,456.789”. + // WB11: Numeric (MidNum | MidNumLet | Single_Quote) × Numeric + if (nextLeft == CharProperty.Numeric && + _oneOf( + immediateLeft, + CharProperty.MidNum, + CharProperty.MidNumLet, + CharProperty.SingleQuote, + ) && + immediateRight == CharProperty.Numeric) { + return false; + } + + // WB12: Numeric × (MidNum | MidNumLet | Single_Quote) Numeric + if (immediateLeft == CharProperty.Numeric && + _oneOf( + immediateRight, + CharProperty.MidNum, + CharProperty.MidNumLet, + CharProperty.SingleQuote, + ) && + nextRight == CharProperty.Numeric) { + return false; + } + + // Do not break between Katakana. + // WB13: Katakana × Katakana + if (immediateLeft == CharProperty.Katakana && + immediateRight == CharProperty.Katakana) { + return false; + } + + // Do not break from extenders. + // WB13a: (AHLetter | Numeric | Katakana | ExtendNumLet) × ExtendNumLet + if (_oneOf( + immediateLeft, + CharProperty.ALetter, + CharProperty.HebrewLetter, + CharProperty.Numeric, + CharProperty.Katakana, + CharProperty.ExtendNumLet, + ) && + immediateRight == CharProperty.ExtendNumLet) { + return false; + } + + // WB13b: ExtendNumLet × (AHLetter | Numeric | Katakana) + if (immediateLeft == CharProperty.ExtendNumLet && + _oneOf( + immediateRight, + CharProperty.ALetter, + CharProperty.HebrewLetter, + CharProperty.Numeric, + CharProperty.Katakana, + )) { + return false; + } + + // Do not break within emoji flag sequences. That is, do not break between + // regional indicator (RI) symbols if there is an odd number of RI + // characters before the break point. + // WB15: sot (RI RI)* RI × RI + // TODO(mdebbar): implement this. + + // WB16: [^RI] (RI RI)* RI × RI + // TODO(mdebbar): implement this. + + // Otherwise, break everywhere (including around ideographs). + // WB999: Any ÷ Any + return true; + } + + static bool _isUtf16Surrogate(int value) { + return value & 0xF800 == 0xD800; + } + + static bool _oneOf( + CharProperty value, + CharProperty choice1, + CharProperty choice2, [ + CharProperty choice3, + CharProperty choice4, + CharProperty choice5, + ]) { + if (value == choice1) { + return true; + } + if (value == choice2) { + return true; + } + if (choice3 != null && value == choice3) { + return true; + } + if (choice4 != null && value == choice4) { + return true; + } + if (choice5 != null && value == choice5) { + return true; + } + return false; + } + + static bool _isAHLetter(CharProperty property) { + return _oneOf(property, CharProperty.ALetter, CharProperty.HebrewLetter); + } +} 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 new file mode 100644 index 0000000000..cc22d6f26c --- /dev/null +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/text_editing.dart @@ -0,0 +1,622 @@ +// 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; + +/// Make the content editable span visible to facilitate debugging. +const bool _debugVisibleTextEditing = false; + +void _emptyCallback(dynamic _) {} + +void _styleEditingElement(html.HtmlElement domElement) { + domElement.style + ..position = 'fixed' + ..whiteSpace = 'pre'; + if (_debugVisibleTextEditing) { + domElement.style + ..bottom = '0' + ..right = '0' + ..font = '24px sans-serif' + ..color = 'purple' + ..backgroundColor = 'pink'; + } else { + domElement.style + ..overflow = 'hidden' + ..transform = 'translate(-99999px, -99999px)' + // width and height can't be zero because then the element would stop + // receiving edits when its content is empty. + ..width = '1px' + ..height = '1px'; + } + if (browserEngine == BrowserEngine.webkit) { + // TODO(flutter_web): Remove once webkit issue of paragraphs incorrectly + // rendering (shifting up) is resolved. Temporarily force relayout + // a frame after input is created. + html.window.animationFrame.then((num _) { + domElement.style + ..position = 'absolute' + ..bottom = '0' + ..right = '0'; + }); + } +} + +html.InputElement _createInputElement() { + final html.InputElement input = html.InputElement(); + _styleEditingElement(input); + return input; +} + +html.TextAreaElement _createTextAreaElement() { + final html.TextAreaElement textarea = html.TextAreaElement(); + _styleEditingElement(textarea); + return textarea; +} + +/// The current text and selection state of a text field. +class EditingState { + EditingState({this.text, this.baseOffset = 0, this.extentOffset = 0}); + + /// Creates an [EditingState] instance using values from an editing state Map + /// coming from Flutter. + /// + /// The `editingState` Map has the following structure: + /// ```json + /// { + /// "text": "The text here", + /// "selectionBase": 0, + /// "selectionExtent": 0, + /// "selectionAffinity": "TextAffinity.upstream", + /// "selectionIsDirectional": false, + /// "composingBase": -1, + /// "composingExtent": -1 + /// } + /// ``` + EditingState.fromFlutter(Map flutterEditingState) + : text = flutterEditingState['text'], + baseOffset = flutterEditingState['selectionBase'], + extentOffset = flutterEditingState['selectionExtent']; + + /// The counterpart of [EditingState.fromFlutter]. It generates a Map that + /// can be sent to Flutter. + // TODO(mdebbar): Should we get `selectionAffinity` and other properties from flutter's editing state? + Map toFlutter() => { + 'text': text, + 'selectionBase': baseOffset, + 'selectionExtent': extentOffset, + }; + + /// The current text being edited. + final String text; + + /// The offset at which the text selection originates. + final int baseOffset; + + /// The offset at which the text selection terminates. + final int extentOffset; + + /// Whether the current editing state is valid or not. + bool get isValid => baseOffset >= 0 && extentOffset >= 0; + + @override + int get hashCode => ui.hashValues(text, baseOffset, extentOffset); + + @override + bool operator ==(dynamic other) { + if (identical(this, other)) { + return true; + } + if (runtimeType != other.runtimeType) { + return false; + } + final EditingState typedOther = other; + return text == typedOther.text && + baseOffset == typedOther.baseOffset && + extentOffset == typedOther.extentOffset; + } + + @override + String toString() { + return assertionsEnabled + ? 'EditingState("$text", base:$baseOffset, extent:$extentOffset)' + : super.toString(); + } +} + +/// Various types of inputs used in text fields. +/// +/// These types are coming from Flutter's [TextInputType]. Currently, we don't +/// support all the types. We fallback to [InputType.text] when Flutter sends +/// a type that isn't supported. +// TODO(flutter_web): Support more types. +enum InputType { + /// Single-line plain text. + text, + + /// Multi-line text. + multiline, +} + +InputType _getInputTypeFromString(String inputType) { + switch (inputType) { + case 'TextInputType.multiline': + return InputType.multiline; + + case 'TextInputType.text': + default: + return InputType.text; + } +} + +/// Controls the appearance of the input control being edited. +/// +/// For example, [inputType] determines whether we should use `` or +/// `