forked from firka/flutter
rename stub_ui to web_ui (flutter/engine#10776)
* rename stub_ui to web_ui * update licenses
This commit is contained in:
@@ -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
|
||||
|
||||
1
engine/src/flutter/lib/web_ui/analysis_options.yaml
Normal file
1
engine/src/flutter/lib/web_ui/analysis_options.yaml
Normal file
@@ -0,0 +1 @@
|
||||
# Intentionally kept empty.
|
||||
177
engine/src/flutter/lib/web_ui/lib/src/engine.dart
Normal file
177
engine/src/flutter/lib/web_ui/lib/src/engine.dart
Normal file
@@ -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<ui.VoidCallback> _hotRestartListeners = <ui.VoidCallback>[];
|
||||
|
||||
/// 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<developer.ServiceExtensionResponse>.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) {}
|
||||
}
|
||||
110
engine/src/flutter/lib/web_ui/lib/src/engine/alarm_clock.dart
Normal file
110
engine/src/flutter/lib/web_ui/lib/src/engine/alarm_clock.dart
Normal file
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
98
engine/src/flutter/lib/web_ui/lib/src/engine/assets.dart
Normal file
98
engine/src/flutter/lib/web_ui/lib/src/engine/assets.dart
Normal file
@@ -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<ByteData> 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<ByteData> load(String asset) {
|
||||
if (asset == getAssetUrl('AssetManifest.json')) {
|
||||
return Future<ByteData>.value(
|
||||
_toByteData(utf8.encode(defaultAssetManifest)));
|
||||
}
|
||||
if (asset == getAssetUrl('FontManifest.json')) {
|
||||
return Future<ByteData>.value(
|
||||
_toByteData(utf8.encode(defaultFontManifest)));
|
||||
}
|
||||
throw AssetManagerException(asset, 404);
|
||||
}
|
||||
|
||||
ByteData _toByteData(List<int> bytes) {
|
||||
final ByteData byteData = ByteData(bytes.length);
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
byteData.setUint8(i, bytes[i]);
|
||||
}
|
||||
return byteData;
|
||||
}
|
||||
}
|
||||
1087
engine/src/flutter/lib/web_ui/lib/src/engine/bitmap_canvas.dart
Normal file
1087
engine/src/flutter/lib/web_ui/lib/src/engine/bitmap_canvas.dart
Normal file
File diff suppressed because it is too large
Load Diff
@@ -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;
|
||||
}
|
||||
@@ -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<void> 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<void> 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<void> _waitForPopState() {
|
||||
final Completer<void> completer = Completer<void>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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', <js.JsObject>[_makeSkRect(bounds), _makeSkPaint(paint)]);
|
||||
}
|
||||
|
||||
void restore() {
|
||||
skCanvas.callMethod('restore');
|
||||
}
|
||||
|
||||
void restoreToCount(int count) {
|
||||
skCanvas.callMethod('restoreToCount', <int>[count]);
|
||||
}
|
||||
|
||||
void clear() {
|
||||
skCanvas.callMethod('clear', <int>[0xffffffff]);
|
||||
}
|
||||
|
||||
void translate(double dx, double dy) {
|
||||
skCanvas.callMethod('translate', <double>[dx, dy]);
|
||||
}
|
||||
|
||||
void transform(Float64List matrix) {
|
||||
skCanvas.callMethod('concat', <js.JsArray<double>>[toSkMatrix(matrix)]);
|
||||
}
|
||||
|
||||
void clipPath(ui.Path path) {
|
||||
final SkPath skPath = path;
|
||||
skCanvas.callMethod('clipPath', <js.JsObject>[skPath._skPath]);
|
||||
}
|
||||
|
||||
void clipRect(ui.Rect rect) {
|
||||
skCanvas.callMethod('clipRect', <js.JsObject>[_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', <js.JsObject>[skPicture.skPicture]);
|
||||
}
|
||||
|
||||
void drawPath(ui.Path path, ui.Paint paint) {
|
||||
final SkPath skPath = path;
|
||||
skCanvas.callMethod(
|
||||
'drawPath', <js.JsObject>[skPath._skPath, _makeSkPaint(paint)]);
|
||||
}
|
||||
|
||||
void drawPaint(ui.Paint paint) {
|
||||
skCanvas.callMethod('drawPaint', <js.JsObject>[_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'],
|
||||
<double>[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', <int>[paint.color.value]);
|
||||
}
|
||||
return skPaint;
|
||||
}
|
||||
}
|
||||
@@ -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) {}
|
||||
}
|
||||
@@ -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<void> initializeSkia() {
|
||||
final Completer<void> canvasKitCompleter = Completer<void>();
|
||||
StreamSubscription<html.Event> loadSubscription;
|
||||
loadSubscription = domRenderer.canvasKitScript.onLoad.listen((_) {
|
||||
loadSubscription.cancel();
|
||||
final js.JsObject canvasKitInitArgs = js.JsObject.jsify(<dynamic, dynamic>{
|
||||
'locateFile': js.allowInterop((String file) => canvasKitBaseUrl + file)
|
||||
});
|
||||
final js.JsObject canvasKitInit =
|
||||
js.JsObject(js.context['CanvasKitInit'], <dynamic>[canvasKitInitArgs]);
|
||||
final js.JsObject canvasKitInitPromise = canvasKitInit.callMethod('ready');
|
||||
canvasKitInitPromise.callMethod('then', <dynamic>[
|
||||
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;
|
||||
@@ -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<Layer> _layers = <Layer>[];
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
@@ -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<ui.Image> 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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<int> _skMatrixIndexToMatrix4Index = <int>[
|
||||
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<double> toSkMatrix(Float64List matrix4) {
|
||||
js.JsArray<double> skMatrix = new js.JsArray<double>();
|
||||
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;
|
||||
}
|
||||
@@ -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'],
|
||||
<double>[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<ui.Offset> points, bool close) {
|
||||
throw 'addPolygon';
|
||||
}
|
||||
|
||||
@override
|
||||
void addRRect(ui.RRect rrect) {
|
||||
final js.JsObject skRect = _makeSkRect(rrect.outerRect);
|
||||
final List<num> radii = <num>[
|
||||
rrect.tlRadiusX,
|
||||
rrect.tlRadiusY,
|
||||
rrect.trRadiusX,
|
||||
rrect.trRadiusY,
|
||||
rrect.brRadiusX,
|
||||
rrect.brRadiusY,
|
||||
rrect.blRadiusX,
|
||||
rrect.blRadiusY,
|
||||
];
|
||||
_skPath.callMethod('addRoundRect', <dynamic>[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<Subpath> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<ui.Image> toImage(int width, int height) {
|
||||
// TODO: implement toImage
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -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'],
|
||||
<double>[bounds.left, bounds.top, bounds.right, bounds.bottom]);
|
||||
final js.JsObject skCanvas =
|
||||
_recorder.callMethod('beginRecording', <js.JsObject>[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;
|
||||
}
|
||||
@@ -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() {}
|
||||
}
|
||||
@@ -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) {}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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'],
|
||||
<double>[rect.left, rect.top, rect.right, rect.bottom]);
|
||||
}
|
||||
|
||||
js.JsObject _makeSkPaint(ui.Paint paint) {
|
||||
final skPaint = js.JsObject(canvasKit['SkPaint']);
|
||||
|
||||
skPaint.callMethod('setColor', <int>[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', <js.JsObject>[skPaintStyle]);
|
||||
|
||||
skPaint.callMethod('setAntiAlias', <bool>[paint.isAntiAlias]);
|
||||
return skPaint;
|
||||
}
|
||||
|
||||
@override
|
||||
bool _didDraw = true;
|
||||
|
||||
@override
|
||||
bool _hasArbitraryPaint = true;
|
||||
|
||||
@override
|
||||
int saveCount;
|
||||
|
||||
@override
|
||||
// TODO: implement _commands
|
||||
List<PaintCommand> 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', <js.JsObject>[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';
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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', <String>['flt-sk-canvas']);
|
||||
final js.JsObject skCanvas = surface.callMethod('getCanvas');
|
||||
_canvas = SkCanvas(skCanvas, htmlCanvas, surface, size);
|
||||
return _canvas;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
189
engine/src/flutter/lib/web_ui/lib/src/engine/conic.dart
Normal file
189
engine/src/flutter/lib/web_ui/lib/src/engine/conic.dart
Normal file
@@ -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<ui.Offset> toQuads() {
|
||||
final List<ui.Offset> pointList = <ui.Offset>[];
|
||||
// This value specifies error bound.
|
||||
const double conicTolerance = 1.0 / 4.0;
|
||||
|
||||
// Based on error bound, compute how many times we should subdivide
|
||||
final int subdivideCount = _computeSubdivisionCount(conicTolerance);
|
||||
|
||||
// Split conic into quads, writes quad coordinates into [_pointList] and
|
||||
// returns number of quads.
|
||||
assert(subdivideCount > 0);
|
||||
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<Conic> dst = List<Conic>(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<ui.Offset> pointList) {
|
||||
assert(level >= 0);
|
||||
if (0 == level) {
|
||||
// At lowest subdivision point, copy control point and end point to
|
||||
// target.
|
||||
pointList.add(ui.Offset(src.p1x, src.p1y));
|
||||
pointList.add(ui.Offset(src.p2x, src.p2y));
|
||||
return;
|
||||
}
|
||||
final List<Conic> dst = List<Conic>(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<Conic> 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;
|
||||
}
|
||||
}
|
||||
176
engine/src/flutter/lib/web_ui/lib/src/engine/dom_canvas.dart
Normal file
176
engine/src/flutter/lib/web_ui/lib/src/engine/dom_canvas.dart
Normal file
@@ -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);
|
||||
}
|
||||
}
|
||||
503
engine/src/flutter/lib/web_ui/lib/src/engine/dom_renderer.dart
Normal file
503
engine/src/flutter/lib/web_ui/lib/src/engine/dom_renderer.dart
Normal file
@@ -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<html.Event> _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<html.Element> _staleHotRestartState;
|
||||
|
||||
void _setupHotRestart() {
|
||||
// This persists across hot restarts to clear stale DOM.
|
||||
_staleHotRestartState =
|
||||
js_util.getProperty(html.window, _staleHotRestartStore);
|
||||
if (_staleHotRestartState == null) {
|
||||
_staleHotRestartState = <html.Element>[];
|
||||
js_util.setProperty(
|
||||
html.window, _staleHotRestartStore, _staleHotRestartState);
|
||||
}
|
||||
|
||||
registerHotRestartListener(() {
|
||||
_resizeSubscription?.cancel();
|
||||
_staleHotRestartState.addAll(<html.Element>[
|
||||
_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 <meta name="viewport"> 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', <num>[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();
|
||||
274
engine/src/flutter/lib/web_ui/lib/src/engine/engine_canvas.dart
Normal file
274
engine/src/flutter/lib/web_ui/lib/src/engine/engine_canvas.dart
Normal file
@@ -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;
|
||||
}
|
||||
190
engine/src/flutter/lib/web_ui/lib/src/engine/history.dart
Normal file
190
engine/src/flutter/lib/web_ui/lib/src/engine/history.dart
Normal file
@@ -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<String, bool> _originState = <String, bool>{'origin': true};
|
||||
Map<String, bool> _flutterState = <String, bool>{'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<void> back() {
|
||||
if (_locationStrategy != null) {
|
||||
return _locationStrategy.back();
|
||||
}
|
||||
return Future<void>.value();
|
||||
}
|
||||
|
||||
/// This method exits the app and goes to whatever website was active before.
|
||||
Future<void> 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<void> backFuture = _locationStrategy.back();
|
||||
_locationStrategy = null;
|
||||
return backFuture;
|
||||
}
|
||||
return Future<void>.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();
|
||||
}
|
||||
}
|
||||
354
engine/src/flutter/lib/web_ui/lib/src/engine/houdini_canvas.dart
Normal file
354
engine/src/flutter/lib/web_ui/lib/src/engine/houdini_canvas.dart
Normal file
@@ -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 = <List<dynamic>>[];
|
||||
// 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<List<dynamic>> _serializedCommands = <List<dynamic>>[];
|
||||
|
||||
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<html.Element> _elementStack = <html.Element>[];
|
||||
|
||||
/// 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));
|
||||
}
|
||||
}
|
||||
@@ -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<ui.FrameInfo> getNextFrame() async {
|
||||
StreamSubscription<html.Event> loadSubscription;
|
||||
StreamSubscription<html.Event> errorSubscription;
|
||||
final Completer<ui.FrameInfo> completer = Completer<ui.FrameInfo>();
|
||||
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<ByteData> toByteData(
|
||||
{ui.ImageByteFormat format = ui.ImageByteFormat.rawRgba}) {
|
||||
return futurize((Callback<ByteData> 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<Uint8List> callback) => null;
|
||||
}
|
||||
79
engine/src/flutter/lib/web_ui/lib/src/engine/keyboard.dart
Normal file
79
engine/src/flutter/lib/web_ui/lib/src/engine/keyboard.dart
Normal file
@@ -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<String, dynamic> eventData = <String, dynamic>{
|
||||
'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) {}
|
||||
@@ -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<String> 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<String> defaultStackFilter(Iterable<String> frames) {
|
||||
const List<String> filteredPackages = <String>[
|
||||
'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<String> result = <String>[];
|
||||
final List<String> skipped = <String>[];
|
||||
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<String> where = Set<String>.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})';
|
||||
}
|
||||
191
engine/src/flutter/lib/web_ui/lib/src/engine/path_to_svg.dart
Normal file
191
engine/src/flutter/lib/web_ui/lib/src/engine/path_to_svg.dart
Normal file
@@ -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');
|
||||
}
|
||||
@@ -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<String, PlatformViewFactory> _registeredFactories =
|
||||
<String, PlatformViewFactory>{};
|
||||
|
||||
final Map<int, html.Element> _createdViews = <int, html.Element>{};
|
||||
|
||||
/// 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;
|
||||
}
|
||||
@@ -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<ui.PointerData>);
|
||||
|
||||
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<ui.PointerData> 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<String, html.EventListener> _listeners =
|
||||
<String, html.EventListener>{};
|
||||
|
||||
final DomRenderer domRenderer;
|
||||
PointerDataCallback _callback;
|
||||
Map<int, bool> _isDownMap = <int, bool>{};
|
||||
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<ui.PointerData> _convertEventToPointerData(
|
||||
ui.PointerChange change,
|
||||
html.PointerEvent evt,
|
||||
) {
|
||||
final List<html.PointerEvent> allEvents = _expandEvents(evt);
|
||||
final List<ui.PointerData> data = List<ui.PointerData>(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<html.PointerEvent> _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<html.PointerEvent> 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 <html.PointerEvent>[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<ui.PointerData> _convertEventToPointerData(
|
||||
ui.PointerChange change,
|
||||
html.TouchEvent event,
|
||||
) {
|
||||
final html.TouchList touches = event.changedTouches;
|
||||
final List<ui.PointerData> data = List<ui.PointerData>(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<ui.PointerData> _convertEventToPointerData(
|
||||
ui.PointerChange change,
|
||||
html.MouseEvent event,
|
||||
) {
|
||||
return <ui.PointerData>[
|
||||
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<ui.PointerData> _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<ui.PointerData> data = <ui.PointerData>[];
|
||||
// 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', <dynamic>[
|
||||
'wheel',
|
||||
js.allowInterop((html.WheelEvent event) => listener(event)),
|
||||
eventOptions
|
||||
]);
|
||||
}
|
||||
1571
engine/src/flutter/lib/web_ui/lib/src/engine/recording_canvas.dart
Normal file
1571
engine/src/flutter/lib/web_ui/lib/src/engine/recording_canvas.dart
Normal file
File diff suppressed because it is too large
Load Diff
@@ -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<dynamic, dynamic> inputMap =
|
||||
const StandardMessageCodec().decodeMessage(data);
|
||||
final Map<dynamic, dynamic> 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;
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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 `<input type="range">` 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();
|
||||
}
|
||||
}
|
||||
@@ -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 `<input>` 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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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 <body> 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;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 `<flt-semantics>` which should
|
||||
// already be positioned using semantics.rect.
|
||||
//
|
||||
// See also:
|
||||
//
|
||||
// * [SemanticsObject.recomputePositionAndSize], which sets the position
|
||||
// and size of the parent `<flt-semantics>` 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();
|
||||
}
|
||||
}
|
||||
@@ -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<E> extends ListBase<E> {
|
||||
static const int _initialLength = 8;
|
||||
|
||||
/// The underlying data buffer.
|
||||
///
|
||||
/// This is always both a List<E> and a TypedData, which we don't have a type
|
||||
/// for here. For example, for a `Uint8Buffer`, this is a `Uint8List`.
|
||||
List<E> _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<E> 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<E> 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<E> 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<E> 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<Object> 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<E> 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<E> 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<E> 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<E> _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<E> 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<E> source, int skipCount) {
|
||||
if (source is _TypedDataBuffer<E>) {
|
||||
_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<E> _createBuffer(int size);
|
||||
}
|
||||
|
||||
abstract class _IntBuffer extends _TypedDataBuffer<int> {
|
||||
_IntBuffer(List<int> 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);
|
||||
}
|
||||
@@ -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<T> {
|
||||
/// 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)';
|
||||
}
|
||||
@@ -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<ByteData> {
|
||||
/// 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<String> {
|
||||
/// 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<dynamic> {
|
||||
// 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(<String, dynamic>{
|
||||
'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(<dynamic>[result]);
|
||||
}
|
||||
|
||||
@override
|
||||
ByteData encodeErrorEnvelope(
|
||||
{@required String code, String message, dynamic details}) {
|
||||
assert(code != null);
|
||||
return const JSONMessageCodec()
|
||||
.encodeMessage(<dynamic>[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<dynamic>` and `Map<dynamic, dynamic>`
|
||||
/// 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<dynamic> {
|
||||
// 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<int> 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<dynamic>(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
result[i] = readValue(buffer);
|
||||
}
|
||||
break;
|
||||
case _valueMap:
|
||||
final int length = readSize(buffer);
|
||||
result = <dynamic, dynamic>{};
|
||||
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');
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
369
engine/src/flutter/lib/web_ui/lib/src/engine/shadow.dart
Normal file
369
engine/src/flutter/lib/web_ui/lib/src/engine/shadow.dart
Normal file
@@ -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<CanvasShadow> computeCanvasShadows(
|
||||
double elevation, ui.Color color) {
|
||||
if (elevation <= 0.0) {
|
||||
return const <CanvasShadow>[];
|
||||
} 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<CanvasShadow> 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<CanvasShadow> result = <CanvasShadow>[];
|
||||
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;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
381
engine/src/flutter/lib/web_ui/lib/src/engine/surface/clip.dart
Normal file
381
engine/src/flutter/lib/web_ui/lib/src/engine/surface/clip.dart
Normal file
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<BitmapCanvas> _recycledCanvases = <BitmapCanvas>[];
|
||||
|
||||
/// 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',
|
||||
<dynamic>[
|
||||
'/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<bool> _didApplyPaint = FrameReference<bool>(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 `<canvas>`, `<div>` and `<p>` 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)}<recycled-canvas />');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void debugValidate(List<String> 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');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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(<String, String>{'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;
|
||||
}
|
||||
}
|
||||
@@ -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() {}
|
||||
}
|
||||
1368
engine/src/flutter/lib/web_ui/lib/src/engine/surface/surface.dart
Normal file
1368
engine/src/flutter/lib/web_ui/lib/src/engine/surface/surface.dart
Normal file
File diff suppressed because it is too large
Load Diff
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
157
engine/src/flutter/lib/web_ui/lib/src/engine/test_embedding.dart
Normal file
157
engine/src/flutter/lib/web_ui/lib/src/engine/test_embedding.dart
Normal file
@@ -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<void> simulateUserTypingUrl(String url) {
|
||||
assert(withinAppHistory);
|
||||
return _nextEventLoop(() {
|
||||
pushState(null, '', url);
|
||||
_firePopStateEvent();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> 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<html.EventListener> listeners = <html.EventListener>[];
|
||||
|
||||
@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<void> _nextEventLoop(ui.VoidCallback callback) {
|
||||
return Future<void>.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',
|
||||
<String, dynamic>{'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<String> lines = List<String>(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]';
|
||||
}
|
||||
}
|
||||
@@ -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<void> 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<dynamic> 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)', <String, String>{});
|
||||
}
|
||||
|
||||
for (Map<String, dynamic> fontFamily in fontManifest) {
|
||||
final String family = fontFamily['family'];
|
||||
final List<dynamic> fontAssets = fontFamily['fonts'];
|
||||
|
||||
for (dynamic fontAssetItem in fontAssets) {
|
||||
final Map<String, dynamic> fontAsset = fontAssetItem;
|
||||
final String asset = fontAsset['asset'];
|
||||
final Map<String, String> descriptors = <String, String>{};
|
||||
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 <String, String>{});
|
||||
}
|
||||
|
||||
/// Returns a [Future] that completes when the registered fonts are loaded
|
||||
/// and ready to be used.
|
||||
Future<void> 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<Future<void>> _fontLoadingFutures = <Future<void>>[];
|
||||
|
||||
factory _FontManager() {
|
||||
if (supportsFontLoadingApi) {
|
||||
return _FontManager._();
|
||||
} else {
|
||||
return _PolyfillFontManager();
|
||||
}
|
||||
}
|
||||
|
||||
_FontManager._();
|
||||
|
||||
void registerAsset(
|
||||
String family,
|
||||
String asset,
|
||||
Map<String, String> 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<void> 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<String, String> 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<void> completer = Completer<void>();
|
||||
|
||||
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<String, String> fontStyleMap = <String, String>{};
|
||||
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;
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 `<body>` 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<ParagraphGeometricStyle, ParagraphRuler> get rulers => _rulers;
|
||||
Map<ParagraphGeometricStyle, ParagraphRuler> _rulers =
|
||||
<ParagraphGeometricStyle, ParagraphRuler>{};
|
||||
|
||||
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<ParagraphRuler> sortedByUsage = _rulers.values.toList();
|
||||
sortedByUsage.sort((ParagraphRuler a, ParagraphRuler b) {
|
||||
return b.hitCount - a.hitCount;
|
||||
});
|
||||
_rulers = <ParagraphGeometricStyle, ParagraphRuler>{};
|
||||
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<ui.TextBox> 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<String> lines = <String>[];
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
1310
engine/src/flutter/lib/web_ui/lib/src/engine/text/paragraph.dart
Normal file
1310
engine/src/flutter/lib/web_ui/lib/src/engine/text/paragraph.dart
Normal file
File diff suppressed because it is too large
Load Diff
787
engine/src/flutter/lib/web_ui/lib/src/engine/text/ruler.dart
Normal file
787
engine/src/flutter/lib/web_ui/lib/src/engine/text/ruler.dart
Normal file
@@ -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 <https://developer.mozilla.org/en-US/docs/Web/CSS/font>.
|
||||
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<num> _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<num> _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<ui.TextBox> 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<html.Rectangle<num>> clientRects = rangeSpan.getClientRects();
|
||||
final List<ui.TextBox> boxes = <ui.TextBox>[];
|
||||
|
||||
for (html.Rectangle<num> 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<String, List<MeasurementResult>> _measurementCache =
|
||||
<String, List<MeasurementResult>>{};
|
||||
// Mru list for cache.
|
||||
final List<String> _mruList = <String>[];
|
||||
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<MeasurementResult> constraintCache =
|
||||
_measurementCache[plainText] ??= <MeasurementResult>[];
|
||||
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<MeasurementResult> 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<String> 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);
|
||||
}
|
||||
@@ -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<P> {
|
||||
const UnicodeRange(this.start, this.end, this.property);
|
||||
|
||||
final int start;
|
||||
|
||||
final int end;
|
||||
|
||||
final P property;
|
||||
|
||||
/// Compare a [value] to this range.
|
||||
///
|
||||
/// The return value is either:
|
||||
/// - lower: The value is lower than the range.
|
||||
/// - higher: The value is higher than the range
|
||||
/// - inside: The value is within the range.
|
||||
_ComparisonResult compare(int value) {
|
||||
if (value < start) {
|
||||
return _ComparisonResult.lower;
|
||||
}
|
||||
if (value > end) {
|
||||
return _ComparisonResult.higher;
|
||||
}
|
||||
return _ComparisonResult.inside;
|
||||
}
|
||||
}
|
||||
|
||||
/// Given a list of [UnicodeRange]s, this class performs efficient lookup
|
||||
/// to find which range a value falls into.
|
||||
///
|
||||
/// The lookup algorithm expects the ranges to have the following constraints:
|
||||
/// - Be sorted.
|
||||
/// - No overlap between the ranges.
|
||||
/// - Gaps between ranges are ok.
|
||||
///
|
||||
/// This is used in the context of unicode to find out what property a letter
|
||||
/// has. The properties are then used to decide word boundaries, line break
|
||||
/// opportunities, etc.
|
||||
class UnicodePropertyLookup<P> {
|
||||
const UnicodePropertyLookup(this.ranges);
|
||||
|
||||
final List<UnicodeRange<P>> 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<P> 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;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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);
|
||||
}
|
||||
}
|
||||
622
engine/src/flutter/lib/web_ui/lib/src/engine/text_editing.dart
Normal file
622
engine/src/flutter/lib/web_ui/lib/src/engine/text_editing.dart
Normal file
@@ -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<String, dynamic> 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<String, dynamic> toFlutter() => <String, dynamic>{
|
||||
'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 `<input>` or
|
||||
/// `<textarea>` as a backing DOM element.
|
||||
///
|
||||
/// This corresponds to Flutter's [TextInputConfiguration].
|
||||
class InputConfiguration {
|
||||
InputConfiguration({
|
||||
this.inputType,
|
||||
this.obscureText = false,
|
||||
});
|
||||
|
||||
InputConfiguration.fromFlutter(Map<String, dynamic> flutterInputConfiguration)
|
||||
: inputType = _getInputTypeFromString(
|
||||
flutterInputConfiguration['inputType']['name']),
|
||||
obscureText = flutterInputConfiguration['obscureText'];
|
||||
|
||||
/// The type of information being edited in the input control.
|
||||
final InputType inputType;
|
||||
|
||||
/// Whether to hide the text being edited.
|
||||
final bool obscureText;
|
||||
}
|
||||
|
||||
typedef _OnChangeCallback = void Function(EditingState editingState);
|
||||
|
||||
enum ElementType {
|
||||
/// The backing element is an `<input>`.
|
||||
input,
|
||||
|
||||
/// The backing element is a `<textarea>`.
|
||||
textarea,
|
||||
|
||||
/// The backing element is a `<span contenteditable="true">`.
|
||||
contentEditable,
|
||||
}
|
||||
|
||||
ElementType _getTypeFromElement(html.HtmlElement domElement) {
|
||||
if (domElement is html.InputElement) {
|
||||
return ElementType.input;
|
||||
}
|
||||
if (domElement is html.TextAreaElement) {
|
||||
return ElementType.textarea;
|
||||
}
|
||||
final String contentEditable = domElement.contentEditable;
|
||||
if (contentEditable != null &&
|
||||
contentEditable.isNotEmpty &&
|
||||
contentEditable != 'inherit') {
|
||||
return ElementType.contentEditable;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Wraps the DOM element used to provide text editing capabilities.
|
||||
///
|
||||
/// The backing DOM element could be one of:
|
||||
///
|
||||
/// 1. `<input>`.
|
||||
/// 2. `<textarea>`.
|
||||
/// 3. `<span contenteditable="true">`.
|
||||
class TextEditingElement {
|
||||
/// Creates a non-persistent [TextEditingElement].
|
||||
///
|
||||
/// See [TextEditingElement.persistent] to understand what persistent mode is.
|
||||
TextEditingElement();
|
||||
|
||||
bool _enabled = false;
|
||||
|
||||
html.HtmlElement domElement;
|
||||
EditingState _lastEditingState;
|
||||
_OnChangeCallback _onChange;
|
||||
|
||||
final List<StreamSubscription<html.Event>> _subscriptions =
|
||||
<StreamSubscription<html.Event>>[];
|
||||
|
||||
ElementType get _elementType {
|
||||
final ElementType type = _getTypeFromElement(domElement);
|
||||
assert(type != null);
|
||||
return type;
|
||||
}
|
||||
|
||||
/// Enables the element so it can be used to edit text.
|
||||
///
|
||||
/// Register [callback] so that it gets invoked whenever any change occurs in
|
||||
/// the text editing element.
|
||||
///
|
||||
/// Changes could be:
|
||||
/// - Text changes, or
|
||||
/// - Selection changes.
|
||||
void enable(
|
||||
InputConfiguration inputConfig, {
|
||||
@required _OnChangeCallback onChange,
|
||||
}) {
|
||||
assert(!_enabled);
|
||||
|
||||
_initDomElement(inputConfig);
|
||||
_enabled = true;
|
||||
_onChange = onChange;
|
||||
|
||||
// Chrome on Android will hide the onscreen keyboard when you tap outside
|
||||
// the text box. Instead, we want the framework to tell us to hide the
|
||||
// keyboard via `TextInput.clearClient` or `TextInput.hide`.
|
||||
//
|
||||
// Safari on iOS does not hide the keyboard as a side-effect of tapping
|
||||
// outside the editable box. Instead it provides an explicit "done" button,
|
||||
// which is reported as "blur", so we must not reacquire focus when we see
|
||||
// a "blur" event and let the keyboard disappear.
|
||||
if (browserEngine == BrowserEngine.blink ||
|
||||
browserEngine == BrowserEngine.unknown) {
|
||||
_subscriptions.add(domElement.onBlur.listen((_) {
|
||||
if (_enabled) {
|
||||
_refocus();
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
domElement.focus();
|
||||
|
||||
if (_lastEditingState != null) {
|
||||
setEditingState(_lastEditingState);
|
||||
}
|
||||
|
||||
// Subscribe to text and selection changes.
|
||||
_subscriptions
|
||||
..add(html.document.onSelectionChange.listen(_handleChange))
|
||||
..add(domElement.onInput.listen(_handleChange));
|
||||
}
|
||||
|
||||
/// Disables the element so it's no longer used for text editing.
|
||||
///
|
||||
/// Calling [disable] also removes any registered event listeners.
|
||||
void disable() {
|
||||
assert(_enabled);
|
||||
|
||||
_enabled = false;
|
||||
_lastEditingState = null;
|
||||
|
||||
for (int i = 0; i < _subscriptions.length; i++) {
|
||||
_subscriptions[i].cancel();
|
||||
}
|
||||
_subscriptions.clear();
|
||||
_removeDomElement();
|
||||
}
|
||||
|
||||
void _initDomElement(InputConfiguration inputConfig) {
|
||||
switch (inputConfig.inputType) {
|
||||
case InputType.text:
|
||||
domElement = _createInputElement();
|
||||
break;
|
||||
|
||||
case InputType.multiline:
|
||||
domElement = _createTextAreaElement();
|
||||
break;
|
||||
|
||||
default:
|
||||
throw UnsupportedError(
|
||||
'Unsupported input type: ${inputConfig.inputType}');
|
||||
}
|
||||
html.document.body.append(domElement);
|
||||
}
|
||||
|
||||
void _removeDomElement() {
|
||||
domElement.remove();
|
||||
domElement = null;
|
||||
}
|
||||
|
||||
void _refocus() {
|
||||
domElement.focus();
|
||||
}
|
||||
|
||||
void setEditingState(EditingState editingState) {
|
||||
_lastEditingState = editingState;
|
||||
if (!_enabled || !editingState.isValid) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (_elementType) {
|
||||
case ElementType.input:
|
||||
final html.InputElement input = domElement;
|
||||
input.value = editingState.text;
|
||||
input.setSelectionRange(
|
||||
editingState.baseOffset,
|
||||
editingState.extentOffset,
|
||||
);
|
||||
break;
|
||||
|
||||
case ElementType.textarea:
|
||||
final html.TextAreaElement textarea = domElement;
|
||||
textarea.value = editingState.text;
|
||||
textarea.setSelectionRange(
|
||||
editingState.baseOffset,
|
||||
editingState.extentOffset,
|
||||
);
|
||||
break;
|
||||
|
||||
case ElementType.contentEditable:
|
||||
domRenderer.clearDom(domElement);
|
||||
domElement.append(html.Text(editingState.text));
|
||||
html.window.getSelection()
|
||||
..removeAllRanges()
|
||||
..addRange(_createRange(editingState));
|
||||
break;
|
||||
}
|
||||
|
||||
// Safari on iOS requires that we focus explicitly. Otherwise, the on-screen
|
||||
// keyboard won't show up.
|
||||
domElement.focus();
|
||||
}
|
||||
|
||||
/// Swap out the current DOM element and replace it with a new one of type
|
||||
/// [newElementType].
|
||||
///
|
||||
/// Ideally, swapping the underlying DOM element should be seamless to the
|
||||
/// user of this class.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [PersistentTextEditingElement._swapDomElement], which notifies its users
|
||||
/// that the element has been swapped.
|
||||
void _swapDomElement(ElementType newElementType) {
|
||||
// TODO(mdebbar): Create the appropriate dom element and initialize it.
|
||||
}
|
||||
|
||||
void _handleChange(html.Event event) {
|
||||
_lastEditingState = calculateEditingState();
|
||||
_onChange(_lastEditingState);
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
EditingState calculateEditingState() {
|
||||
assert(domElement != null);
|
||||
|
||||
EditingState editingState;
|
||||
switch (_elementType) {
|
||||
case ElementType.input:
|
||||
final html.InputElement inputElement = domElement;
|
||||
editingState = EditingState(
|
||||
text: inputElement.value,
|
||||
baseOffset: inputElement.selectionStart,
|
||||
extentOffset: inputElement.selectionEnd,
|
||||
);
|
||||
break;
|
||||
|
||||
case ElementType.textarea:
|
||||
final html.TextAreaElement textAreaElement = domElement;
|
||||
editingState = EditingState(
|
||||
text: textAreaElement.value,
|
||||
baseOffset: textAreaElement.selectionStart,
|
||||
extentOffset: textAreaElement.selectionEnd,
|
||||
);
|
||||
break;
|
||||
|
||||
case ElementType.contentEditable:
|
||||
// In a contenteditable element, we want `innerText` since it correctly
|
||||
// converts <br> to newline characters, for example.
|
||||
//
|
||||
// If we later decide to use <input> and/or <textarea> then we can go back
|
||||
// to using `textContent` (or `value` in the case of <input>)
|
||||
final String text = js_util.getProperty(domElement, 'innerText');
|
||||
if (domElement.childNodes.length > 1) {
|
||||
// Having multiple child nodes in a content editable element means one of
|
||||
// two things:
|
||||
// 1. Text contains new lines.
|
||||
// 2. User pasted rich text.
|
||||
final int prevSelectionEnd = math.max(
|
||||
_lastEditingState.baseOffset, _lastEditingState.extentOffset);
|
||||
final String prevText = _lastEditingState.text;
|
||||
final int offsetFromEnd = prevText.length - prevSelectionEnd;
|
||||
|
||||
final int newSelectionExtent = text.length - offsetFromEnd;
|
||||
// TODO(mdebbar): we may need to `setEditingState()` here.
|
||||
editingState = EditingState(
|
||||
text: text,
|
||||
baseOffset: newSelectionExtent,
|
||||
extentOffset: newSelectionExtent,
|
||||
);
|
||||
} else {
|
||||
final html.Selection selection = html.window.getSelection();
|
||||
editingState = EditingState(
|
||||
text: text,
|
||||
baseOffset: selection.baseOffset,
|
||||
extentOffset: selection.extentOffset,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
assert(editingState != null);
|
||||
return editingState;
|
||||
}
|
||||
|
||||
html.Range _createRange(EditingState editingState) {
|
||||
final html.Node firstChild = domElement.firstChild;
|
||||
return html.document.createRange()
|
||||
..setStart(firstChild, editingState.baseOffset)
|
||||
..setEnd(firstChild, editingState.extentOffset);
|
||||
}
|
||||
}
|
||||
|
||||
/// The implementation of a persistent mode for [TextEditingElement].
|
||||
///
|
||||
/// Persistent mode assumes the caller will own the creation, insertion and
|
||||
/// disposal of the DOM element.
|
||||
///
|
||||
/// This class is still responsible for hooking up the DOM element with the
|
||||
/// [HybridTextEditing] instance so that changes are communicated to Flutter.
|
||||
///
|
||||
/// Persistent mode is useful for callers that want to have full control over
|
||||
/// the placement and lifecycle of the DOM element. An example of such a caller
|
||||
/// is Semantic's TextField that needs to put the DOM element inside the
|
||||
/// semantic tree. It also requires that the DOM element remains in the tree
|
||||
/// when the user isn't editing.
|
||||
class PersistentTextEditingElement extends TextEditingElement {
|
||||
/// Creates a [PersistentTextEditingElement] that eagerly instantiates
|
||||
/// [domElement] so the caller can insert it before calling
|
||||
/// [PersistentTextEditingElement.enable].
|
||||
PersistentTextEditingElement(
|
||||
html.HtmlElement domElement, {
|
||||
@required html.VoidCallback onDomElementSwap,
|
||||
}) : _onDomElementSwap = onDomElementSwap,
|
||||
// Make sure the dom element is of a type that we support for text editing.
|
||||
assert(_getTypeFromElement(domElement) != null) {
|
||||
this.domElement = domElement;
|
||||
}
|
||||
|
||||
final html.VoidCallback _onDomElementSwap;
|
||||
|
||||
@override
|
||||
void _initDomElement(InputConfiguration inputConfig) {
|
||||
// In persistent mode, the user of this class is supposed to insert the
|
||||
// [domElement] on their own. Let's make sure they did.
|
||||
assert(domElement != null);
|
||||
assert(html.document.body.contains(domElement));
|
||||
}
|
||||
|
||||
@override
|
||||
void _removeDomElement() {
|
||||
// In persistent mode, we don't want to remove the DOM element because the
|
||||
// caller is responsible for that.
|
||||
//
|
||||
// Remove focus from the editable element to cause the keyboard to hide.
|
||||
// Otherwise, the keyboard stays on screen even when the user navigates to
|
||||
// a different screen (e.g. by hitting the "back" button).
|
||||
domElement.blur();
|
||||
}
|
||||
|
||||
@override
|
||||
void _refocus() {
|
||||
// The semantic text field on Android listens to the focus event in order to
|
||||
// switch to a new text field. If we refocus here, we break that
|
||||
// functionality and the user can't switch from one text field to another in
|
||||
// accessibility mode.
|
||||
}
|
||||
|
||||
@override
|
||||
void _swapDomElement(ElementType newElementType) {
|
||||
super._swapDomElement(newElementType);
|
||||
|
||||
// Unfortunately, in persistent mode, the user of this class has to be
|
||||
// notified that the element is being swapped.
|
||||
// TODO(mdebbar): do we need to call `old.replaceWith(new)` here?
|
||||
_onDomElementSwap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Text editing singleton.
|
||||
final HybridTextEditing textEditing = HybridTextEditing();
|
||||
|
||||
/// Should be used as a singleton to provide support for text editing in
|
||||
/// Flutter Web.
|
||||
///
|
||||
/// The approach is "hybrid" because it relies on Flutter for
|
||||
/// displaying, and HTML for user interactions:
|
||||
///
|
||||
/// - HTML's contentEditable feature handles typing and text changes.
|
||||
/// - HTML's selection API handles selection changes and cursor movements.
|
||||
class HybridTextEditing {
|
||||
/// The default HTML element used to manage editing state when a custom
|
||||
/// element is not provided via [useCustomEditableElement].
|
||||
TextEditingElement _defaultEditingElement = TextEditingElement();
|
||||
|
||||
/// The HTML element used to manage editing state.
|
||||
///
|
||||
/// This field is populated using [useCustomEditableElement]. If `null` the
|
||||
/// [_defaultEditableElement] is used instead.
|
||||
TextEditingElement _customEditingElement;
|
||||
|
||||
TextEditingElement get editingElement {
|
||||
if (_customEditingElement != null) {
|
||||
return _customEditingElement;
|
||||
}
|
||||
return _defaultEditingElement;
|
||||
}
|
||||
|
||||
/// Requests that [customEditingElement] is used for managing text editing state
|
||||
/// instead of the hidden default element.
|
||||
///
|
||||
/// Use [stopUsingCustomEditableElement] to switch back to default element.
|
||||
void useCustomEditableElement(TextEditingElement customEditingElement) {
|
||||
if (_isEditing && customEditingElement != _customEditingElement) {
|
||||
_stopEditing();
|
||||
}
|
||||
_customEditingElement = customEditingElement;
|
||||
}
|
||||
|
||||
/// Switches back to using the built-in default element for managing text
|
||||
/// editing state.
|
||||
void stopUsingCustomEditableElement() {
|
||||
useCustomEditableElement(null);
|
||||
}
|
||||
|
||||
int _clientId;
|
||||
bool _isEditing = false;
|
||||
Map<String, dynamic> _configuration;
|
||||
|
||||
/// All "flutter/textinput" platform messages should be sent to this method.
|
||||
void handleTextInput(ByteData data) {
|
||||
final MethodCall call = const JSONMethodCodec().decodeMethodCall(data);
|
||||
switch (call.method) {
|
||||
case 'TextInput.setClient':
|
||||
_clientId = call.arguments[0];
|
||||
_configuration = call.arguments[1];
|
||||
break;
|
||||
|
||||
case 'TextInput.setEditingState':
|
||||
editingElement
|
||||
.setEditingState(EditingState.fromFlutter(call.arguments));
|
||||
break;
|
||||
|
||||
case 'TextInput.show':
|
||||
if (!_isEditing) {
|
||||
_startEditing();
|
||||
}
|
||||
break;
|
||||
|
||||
case 'TextInput.clearClient':
|
||||
case 'TextInput.hide':
|
||||
if (_isEditing) {
|
||||
_stopEditing();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void _startEditing() {
|
||||
assert(!_isEditing);
|
||||
_isEditing = true;
|
||||
editingElement.enable(
|
||||
InputConfiguration.fromFlutter(_configuration),
|
||||
onChange: _syncEditingStateToFlutter,
|
||||
);
|
||||
}
|
||||
|
||||
void _stopEditing() {
|
||||
assert(_isEditing);
|
||||
_isEditing = false;
|
||||
editingElement.disable();
|
||||
}
|
||||
|
||||
void _syncEditingStateToFlutter(EditingState editingState) {
|
||||
ui.window.onPlatformMessage(
|
||||
'flutter/textinput',
|
||||
const JSONMethodCodec().encodeMethodCall(
|
||||
MethodCall('TextInputClient.updateEditingState', <dynamic>[
|
||||
_clientId,
|
||||
editingState.toFlutter(),
|
||||
]),
|
||||
),
|
||||
_emptyCallback,
|
||||
);
|
||||
}
|
||||
}
|
||||
234
engine/src/flutter/lib/web_ui/lib/src/engine/util.dart
Normal file
234
engine/src/flutter/lib/web_ui/lib/src/engine/util.dart
Normal file
@@ -0,0 +1,234 @@
|
||||
// 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;
|
||||
|
||||
/// Generic callback signature, used by [_futurize].
|
||||
typedef Callback<T> = void Function(T result);
|
||||
|
||||
/// Signature for a method that receives a [_Callback].
|
||||
///
|
||||
/// Return value should be null on success, and a string error message on
|
||||
/// failure.
|
||||
typedef Callbacker<T> = String Function(Callback<T> callback);
|
||||
|
||||
/// Converts a method that receives a value-returning callback to a method that
|
||||
/// returns a Future.
|
||||
///
|
||||
/// Return a [String] to cause an [Exception] to be synchronously thrown with
|
||||
/// that string as a message.
|
||||
///
|
||||
/// If the callback is called with null, the future completes with an error.
|
||||
///
|
||||
/// Example usage:
|
||||
///
|
||||
/// ```dart
|
||||
/// typedef IntCallback = void Function(int result);
|
||||
///
|
||||
/// String _doSomethingAndCallback(IntCallback callback) {
|
||||
/// new Timer(new Duration(seconds: 1), () { callback(1); });
|
||||
/// }
|
||||
///
|
||||
/// Future<int> doSomething() {
|
||||
/// return _futurize(_doSomethingAndCallback);
|
||||
/// }
|
||||
/// ```
|
||||
Future<T> futurize<T>(Callbacker<T> callbacker) {
|
||||
final Completer<T> completer = Completer<T>.sync();
|
||||
final String error = callbacker((T t) {
|
||||
if (t == null) {
|
||||
completer.completeError(Exception('operation failed'));
|
||||
} else {
|
||||
completer.complete(t);
|
||||
}
|
||||
});
|
||||
if (error != null) {
|
||||
throw Exception(error);
|
||||
}
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
/// Converts [matrix] to CSS transform value.
|
||||
String matrix4ToCssTransform(Matrix4 matrix) {
|
||||
return float64ListToCssTransform(matrix.storage);
|
||||
}
|
||||
|
||||
/// Returns `true` is the [matrix] describes an identity transformation.
|
||||
bool isIdentityFloat64ListTransform(Float64List matrix) {
|
||||
assert(matrix.length == 16);
|
||||
final Float64List m = matrix;
|
||||
return m[0] == 1.0 &&
|
||||
m[1] == 0.0 &&
|
||||
m[2] == 0.0 &&
|
||||
m[3] == 0.0 &&
|
||||
m[4] == 0.0 &&
|
||||
m[5] == 1.0 &&
|
||||
m[6] == 0.0 &&
|
||||
m[7] == 0.0 &&
|
||||
m[8] == 0.0 &&
|
||||
m[9] == 0.0 &&
|
||||
m[10] == 1.0 &&
|
||||
m[11] == 0.0 &&
|
||||
m[12] == 0.0 &&
|
||||
m[13] == 0.0 &&
|
||||
m[14] == 0.0 &&
|
||||
m[15] == 1.0;
|
||||
}
|
||||
|
||||
/// Converts [matrix] to CSS transform value.
|
||||
String float64ListToCssTransform(Float64List matrix) {
|
||||
assert(matrix.length == 16);
|
||||
final Float64List m = matrix;
|
||||
if (m[0] == 1.0 &&
|
||||
m[1] == 0.0 &&
|
||||
m[2] == 0.0 &&
|
||||
m[3] == 0.0 &&
|
||||
m[4] == 0.0 &&
|
||||
m[5] == 1.0 &&
|
||||
m[6] == 0.0 &&
|
||||
m[7] == 0.0 &&
|
||||
m[8] == 0.0 &&
|
||||
m[9] == 0.0 &&
|
||||
m[10] == 1.0 &&
|
||||
m[11] == 0.0 &&
|
||||
// 12 can be anything
|
||||
// 13 can be anything
|
||||
m[14] == 0.0 &&
|
||||
m[15] == 1.0) {
|
||||
final double tx = m[12];
|
||||
final double ty = m[13];
|
||||
return 'translate(${tx}px, ${ty}px)';
|
||||
} else {
|
||||
return 'matrix3d(${m[0]},${m[1]},${m[2]},${m[3]},${m[4]},${m[5]},${m[6]},${m[7]},${m[8]},${m[9]},${m[10]},${m[11]},${m[12]},${m[13]},${m[14]},${m[15]})';
|
||||
}
|
||||
}
|
||||
|
||||
bool get assertionsEnabled {
|
||||
bool k = false;
|
||||
assert(k = true);
|
||||
return k;
|
||||
}
|
||||
|
||||
/// Converts a rectangular clip specified in local coordinates to screen
|
||||
/// coordinates given the effective [transform].
|
||||
///
|
||||
/// The resulting clip is a rectangle aligned to the pixel grid, i.e. two of
|
||||
/// its sides are vertical and two are horizontal. In the presence of rotations
|
||||
/// the rectangle is inflated such that it fits the rotated rectangle.
|
||||
ui.Rect localClipRectToGlobalClip({ui.Rect localClip, Matrix4 transform}) {
|
||||
return localClipToGlobalClip(
|
||||
localLeft: localClip.left,
|
||||
localTop: localClip.top,
|
||||
localRight: localClip.right,
|
||||
localBottom: localClip.bottom,
|
||||
transform: transform,
|
||||
);
|
||||
}
|
||||
|
||||
/// Converts a rectangular clip specified in local coordinates to screen
|
||||
/// coordinates given the effective [transform].
|
||||
///
|
||||
/// This is the same as [localClipRectToGlobalClip], except that the local clip
|
||||
/// rect is specified in terms of left, top, right, and bottom edge offsets.
|
||||
ui.Rect localClipToGlobalClip({
|
||||
double localLeft,
|
||||
double localTop,
|
||||
double localRight,
|
||||
double localBottom,
|
||||
Matrix4 transform,
|
||||
}) {
|
||||
assert(localLeft != null);
|
||||
assert(localTop != null);
|
||||
assert(localRight != null);
|
||||
assert(localBottom != null);
|
||||
|
||||
// Construct a matrix where each row represents a vector pointing at
|
||||
// one of the four corners of the (left, top, right, bottom) rectangle.
|
||||
// Using the row-major order allows us to multiply the matrix in-place
|
||||
// by the transposed current transformation matrix. The vector_math
|
||||
// library has a convenience function `multiplyTranspose` that performs
|
||||
// the multiplication without copying. This way we compute the positions
|
||||
// of all four points in a single matrix-by-matrix multiplication at the
|
||||
// cost of one `Matrix4` instance and one `Float64List` instance.
|
||||
//
|
||||
// The rejected alternative was to use `Vector3` for each point and
|
||||
// multiply by the current transform. However, that would cost us four
|
||||
// `Vector3` instances, four `Float64List` instances, and four
|
||||
// matrix-by-vector multiplications.
|
||||
//
|
||||
// `Float64List` initializes the array with zeros, so we do not have to
|
||||
// fill in every single element.
|
||||
final Float64List pointData = Float64List(16);
|
||||
|
||||
// Row 0: top-left
|
||||
pointData[0] = localLeft;
|
||||
pointData[4] = localTop;
|
||||
pointData[12] = 1;
|
||||
|
||||
// Row 1: top-right
|
||||
pointData[1] = localRight;
|
||||
pointData[5] = localTop;
|
||||
pointData[13] = 1;
|
||||
|
||||
// Row 2: bottom-left
|
||||
pointData[2] = localLeft;
|
||||
pointData[6] = localBottom;
|
||||
pointData[14] = 1;
|
||||
|
||||
// Row 3: bottom-right
|
||||
pointData[3] = localRight;
|
||||
pointData[7] = localBottom;
|
||||
pointData[15] = 1;
|
||||
|
||||
final Matrix4 pointMatrix = Matrix4.fromFloat64List(pointData);
|
||||
pointMatrix.multiplyTranspose(transform);
|
||||
|
||||
return ui.Rect.fromLTRB(
|
||||
math.min(math.min(math.min(pointData[0], pointData[1]), pointData[2]),
|
||||
pointData[3]),
|
||||
math.min(math.min(math.min(pointData[4], pointData[5]), pointData[6]),
|
||||
pointData[7]),
|
||||
math.max(math.max(math.max(pointData[0], pointData[1]), pointData[2]),
|
||||
pointData[3]),
|
||||
math.max(math.max(math.max(pointData[4], pointData[5]), pointData[6]),
|
||||
pointData[7]),
|
||||
);
|
||||
}
|
||||
|
||||
/// Returns true if [rect] contains every point that is also contained by the
|
||||
/// [other] rect.
|
||||
///
|
||||
/// Points on the edges of both rectangles are also considered. For example,
|
||||
/// this returns true when the two rects are equal to each other.
|
||||
bool rectContainsOther(ui.Rect rect, ui.Rect other) {
|
||||
return rect.left <= other.left &&
|
||||
rect.top <= other.top &&
|
||||
rect.right >= other.right &&
|
||||
rect.bottom >= other.bottom;
|
||||
}
|
||||
|
||||
/// Counter used for generating clip path id inside an svg <defs> tag.
|
||||
int _clipIdCounter = 0;
|
||||
|
||||
/// Converts Path to svg element that contains a clip-path definition.
|
||||
///
|
||||
/// Calling this method updates [_clipIdCounter]. The HTML id of the generated
|
||||
/// clip is set to "svgClip${_clipIdCounter}", e.g. "svgClip123".
|
||||
String _pathToSvgClipPath(ui.Path path,
|
||||
{double offsetX = 0, double offsetY = 0}) {
|
||||
_clipIdCounter += 1;
|
||||
final ui.Rect bounds = path.getBounds();
|
||||
final StringBuffer sb = StringBuffer();
|
||||
sb.write('<svg width="${bounds.right}" height="${bounds.bottom}" '
|
||||
'style="position:absolute">');
|
||||
sb.write('<defs>');
|
||||
|
||||
final String clipId = 'svgClip$_clipIdCounter';
|
||||
sb.write('<clipPath id=$clipId>');
|
||||
|
||||
sb.write('<path fill="#FFFFFF" d="');
|
||||
pathToSvg(path, sb, offsetX: offsetX, offsetY: offsetY);
|
||||
sb.write('"></path></clipPath></defs></svg');
|
||||
return sb.toString();
|
||||
}
|
||||
47
engine/src/flutter/lib/web_ui/lib/src/engine/validators.dart
Normal file
47
engine/src/flutter/lib/web_ui/lib/src/engine/validators.dart
Normal file
@@ -0,0 +1,47 @@
|
||||
// Copyright 2013 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
part of engine;
|
||||
|
||||
bool rectIsValid(ui.Rect rect) {
|
||||
assert(rect != null, 'Rect argument was null.');
|
||||
assert(
|
||||
!(rect.left.isNaN ||
|
||||
rect.right.isNaN ||
|
||||
rect.top.isNaN ||
|
||||
rect.bottom.isNaN),
|
||||
'Rect argument contained a NaN value.');
|
||||
return true;
|
||||
}
|
||||
|
||||
bool rrectIsValid(ui.RRect rrect) {
|
||||
assert(rrect != null, 'RRect argument was null.');
|
||||
assert(
|
||||
!(rrect.left.isNaN ||
|
||||
rrect.right.isNaN ||
|
||||
rrect.top.isNaN ||
|
||||
rrect.bottom.isNaN),
|
||||
'RRect argument contained a NaN value.');
|
||||
return true;
|
||||
}
|
||||
|
||||
bool offsetIsValid(ui.Offset offset) {
|
||||
assert(offset != null, 'Offset argument was null.');
|
||||
assert(!offset.dx.isNaN && !offset.dy.isNaN,
|
||||
'Offset argument contained a NaN value.');
|
||||
return true;
|
||||
}
|
||||
|
||||
bool matrix4IsValid(Float64List matrix4) {
|
||||
assert(matrix4 != null, 'Matrix4 argument was null.');
|
||||
assert(matrix4.length == 16, 'Matrix4 must have 16 entries.');
|
||||
return true;
|
||||
}
|
||||
|
||||
bool radiusIsValid(ui.Radius radius) {
|
||||
assert(radius != null, 'Radius argument was null.');
|
||||
assert(!radius.x.isNaN && !radius.y.isNaN,
|
||||
'Radius argument contained a NaN value.');
|
||||
return true;
|
||||
}
|
||||
1399
engine/src/flutter/lib/web_ui/lib/src/engine/vector_math.dart
Normal file
1399
engine/src/flutter/lib/web_ui/lib/src/engine/vector_math.dart
Normal file
File diff suppressed because it is too large
Load Diff
195
engine/src/flutter/lib/web_ui/lib/src/engine/window.dart
Normal file
195
engine/src/flutter/lib/web_ui/lib/src/engine/window.dart
Normal file
@@ -0,0 +1,195 @@
|
||||
// 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 set to true, all platform messages will be printed to the console.
|
||||
const bool _debugPrintPlatformMessages = false;
|
||||
|
||||
/// The Web implementation of [ui.Window].
|
||||
class EngineWindow extends ui.Window {
|
||||
@override
|
||||
double get devicePixelRatio => _devicePixelRatio;
|
||||
|
||||
/// Overrides the default device pixel ratio.
|
||||
///
|
||||
/// This is useful in tests to emulate screens of different dimensions.
|
||||
void debugOverrideDevicePixelRatio(double value) {
|
||||
assert(() {
|
||||
_devicePixelRatio = value;
|
||||
return true;
|
||||
}());
|
||||
}
|
||||
|
||||
double _devicePixelRatio = 1.0;
|
||||
|
||||
@override
|
||||
ui.Size get physicalSize {
|
||||
bool override = false;
|
||||
|
||||
assert(() {
|
||||
if (webOnlyDebugPhysicalSizeOverride != null) {
|
||||
_physicalSize = webOnlyDebugPhysicalSizeOverride;
|
||||
override = true;
|
||||
}
|
||||
return true;
|
||||
}());
|
||||
|
||||
if (!override) {
|
||||
final int windowInnerWidth = html.window.innerWidth;
|
||||
final int windowInnerHeight = html.window.innerHeight;
|
||||
if (windowInnerWidth != _lastKnownWindowInnerWidth ||
|
||||
windowInnerHeight != _lastKnownWindowInnerHeight) {
|
||||
_lastKnownWindowInnerWidth = windowInnerWidth;
|
||||
_lastKnownWindowInnerHeight = windowInnerHeight;
|
||||
_physicalSize = ui.Size(
|
||||
windowInnerWidth.toDouble(),
|
||||
windowInnerHeight.toDouble(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return _physicalSize;
|
||||
}
|
||||
|
||||
ui.Size _physicalSize = ui.Size.zero;
|
||||
int _lastKnownWindowInnerWidth = -1;
|
||||
int _lastKnownWindowInnerHeight = -1;
|
||||
|
||||
/// Overrides the value of [physicalSize] in tests.
|
||||
ui.Size webOnlyDebugPhysicalSizeOverride;
|
||||
|
||||
@override
|
||||
double get physicalDepth => double.maxFinite;
|
||||
|
||||
/// Handles the browser history integration to allow users to use the back
|
||||
/// button, etc.
|
||||
final BrowserHistory _browserHistory = BrowserHistory();
|
||||
|
||||
/// Simulates clicking the browser's back button.
|
||||
Future<void> webOnlyBack() => _browserHistory.back();
|
||||
|
||||
@override
|
||||
String get defaultRouteName => _browserHistory.currentPath;
|
||||
|
||||
/// Change the strategy to use for handling browser history location.
|
||||
/// Setting this member will automatically update [_browserHistory].
|
||||
///
|
||||
/// By setting this to null, the browser history will be disabled.
|
||||
set webOnlyLocationStrategy(LocationStrategy strategy) {
|
||||
_browserHistory.locationStrategy = strategy;
|
||||
}
|
||||
|
||||
/// This setter is used by [WebNavigatorObserver] to update the url to
|
||||
/// reflect the [Navigator]'s current route name.
|
||||
set webOnlyRouteName(String routeName) {
|
||||
_browserHistory.setRouteName(routeName);
|
||||
}
|
||||
|
||||
@override
|
||||
void sendPlatformMessage(
|
||||
String name,
|
||||
ByteData data,
|
||||
ui.PlatformMessageResponseCallback callback,
|
||||
) {
|
||||
// In widget tests we want to bypass processing of platform messages.
|
||||
if (assertionsEnabled && ui.debugEmulateFlutterTesterEnvironment) {
|
||||
return;
|
||||
}
|
||||
if (_debugPrintPlatformMessages) {
|
||||
print('Sent platform message on channel: "$name"');
|
||||
}
|
||||
switch (name) {
|
||||
case 'flutter/assets':
|
||||
assert(ui.webOnlyAssetManager != null);
|
||||
final String url = utf8.decode(data.buffer.asUint8List());
|
||||
ui.webOnlyAssetManager.load(url).then((ByteData assetData) {
|
||||
_replyToPlatformMessage(callback, assetData);
|
||||
}, onError: (dynamic error) {
|
||||
html.window.console
|
||||
.warn('Error while trying to load an asset: $error');
|
||||
_replyToPlatformMessage(callback, null);
|
||||
});
|
||||
return;
|
||||
|
||||
case 'flutter/platform':
|
||||
const MethodCodec codec = JSONMethodCodec();
|
||||
final MethodCall decoded = codec.decodeMethodCall(data);
|
||||
switch (decoded.method) {
|
||||
case 'SystemNavigator.pop':
|
||||
_browserHistory.exit().then((_) {
|
||||
_replyToPlatformMessage(
|
||||
callback, codec.encodeSuccessEnvelope(true));
|
||||
});
|
||||
return;
|
||||
case 'HapticFeedback.vibrate':
|
||||
final String type = decoded.arguments;
|
||||
domRenderer.vibrate(_getHapticFeedbackDuration(type));
|
||||
return;
|
||||
case 'SystemChrome.setApplicationSwitcherDescription':
|
||||
final Map<String, dynamic> arguments = decoded.arguments;
|
||||
domRenderer.setTitle(arguments['label']);
|
||||
domRenderer.setThemeColor(ui.Color(arguments['primaryColor']));
|
||||
return;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'flutter/textinput':
|
||||
textEditing.handleTextInput(data);
|
||||
return;
|
||||
|
||||
case 'flutter/platform_views':
|
||||
handlePlatformViewCall(data, callback);
|
||||
return;
|
||||
|
||||
case 'flutter/accessibility':
|
||||
// In widget tests we want to bypass processing of platform messages.
|
||||
accessibilityAnnouncements.handleMessage(data);
|
||||
break;
|
||||
}
|
||||
|
||||
// TODO(flutter_web): Some Flutter widgets send platform messages that we
|
||||
// don't handle on web. So for now, let's just ignore them. In the future,
|
||||
// we should consider uncommenting the following "callback(null)" line.
|
||||
|
||||
// Passing [null] to [callback] indicates that the platform message isn't
|
||||
// implemented. Look at [MethodChannel.invokeMethod] to see how [null] is
|
||||
// handled.
|
||||
// callback(null);
|
||||
}
|
||||
|
||||
int _getHapticFeedbackDuration(String type) {
|
||||
switch (type) {
|
||||
case 'HapticFeedbackType.lightImpact':
|
||||
return DomRenderer.vibrateLightImpact;
|
||||
case 'HapticFeedbackType.mediumImpact':
|
||||
return DomRenderer.vibrateMediumImpact;
|
||||
case 'HapticFeedbackType.heavyImpact':
|
||||
return DomRenderer.vibrateHeavyImpact;
|
||||
case 'HapticFeedbackType.selectionClick':
|
||||
return DomRenderer.vibrateSelectionClick;
|
||||
default:
|
||||
return DomRenderer.vibrateLongPress;
|
||||
}
|
||||
}
|
||||
|
||||
/// In Flutter, platform messages are exchanged between threads so the
|
||||
/// messages and responses have to be exchanged asynchronously. We simulate
|
||||
/// that by adding a zero-length delay to the reply.
|
||||
void _replyToPlatformMessage(
|
||||
ui.PlatformMessageResponseCallback callback,
|
||||
ByteData data,
|
||||
) {
|
||||
Future<void>.delayed(Duration.zero).then((_) {
|
||||
callback(data);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The window singleton.
|
||||
///
|
||||
/// `dart:ui` window delegates to this value. However, this value has a wider
|
||||
/// API surface, providing Web-specific functionality that the standard
|
||||
/// `dart:ui` version does not.
|
||||
final EngineWindow window = EngineWindow();
|
||||
2386
engine/src/flutter/lib/web_ui/lib/src/ui/canvas.dart
Normal file
2386
engine/src/flutter/lib/web_ui/lib/src/ui/canvas.dart
Normal file
File diff suppressed because it is too large
Load Diff
628
engine/src/flutter/lib/web_ui/lib/src/ui/compositing.dart
Normal file
628
engine/src/flutter/lib/web_ui/lib/src/ui/compositing.dart
Normal file
@@ -0,0 +1,628 @@
|
||||
// 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 ui;
|
||||
|
||||
/// An opaque object representing a composited scene.
|
||||
///
|
||||
/// To create a Scene object, use a [SceneBuilder].
|
||||
///
|
||||
/// Scene objects can be displayed on the screen using the
|
||||
/// [Window.render] method.
|
||||
class Scene {
|
||||
/// This class is created by the engine, and should not be instantiated
|
||||
/// or extended directly.
|
||||
///
|
||||
/// To create a Scene object, use a [SceneBuilder].
|
||||
Scene._(this.webOnlyRootElement);
|
||||
|
||||
final html.Element webOnlyRootElement;
|
||||
|
||||
/// Creates a raster image representation of the current state of the scene.
|
||||
/// This is a slow operation that is performed on a background thread.
|
||||
Future<Image> toImage(int width, int height) {
|
||||
if (width <= 0 || height <= 0) {
|
||||
throw Exception('Invalid image dimensions.');
|
||||
}
|
||||
throw UnsupportedError('toImage is not supported on the Web');
|
||||
// TODO(flutter_web): Implement [_toImage].
|
||||
// return futurize(
|
||||
// (Callback<Image> callback) => _toImage(width, height, callback));
|
||||
}
|
||||
|
||||
// String _toImage(int width, int height, Callback<Image> callback) => null;
|
||||
|
||||
/// Releases the resources used by this scene.
|
||||
///
|
||||
/// After calling this function, the scene is cannot be used further.
|
||||
void dispose() {}
|
||||
}
|
||||
|
||||
/// An opaque handle to a transform engine layer.
|
||||
///
|
||||
/// Instances of this class are created by [SceneBuilder.pushTransform].
|
||||
///
|
||||
/// {@template dart.ui.sceneBuilder.oldLayerCompatibility}
|
||||
/// `oldLayer` parameter in [SceneBuilder] methods only accepts objects created
|
||||
/// by the engine. [SceneBuilder] will throw an [AssertionError] if you pass it
|
||||
/// a custom implementation of this class.
|
||||
/// {@endtemplate}
|
||||
abstract class TransformEngineLayer implements EngineLayer {}
|
||||
|
||||
/// An opaque handle to an offset engine layer.
|
||||
///
|
||||
/// Instances of this class are created by [SceneBuilder.pushOffset].
|
||||
///
|
||||
/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility}
|
||||
abstract class OffsetEngineLayer implements EngineLayer {}
|
||||
|
||||
/// An opaque handle to a clip rect engine layer.
|
||||
///
|
||||
/// Instances of this class are created by [SceneBuilder.pushClipRect].
|
||||
///
|
||||
/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility}
|
||||
abstract class ClipRectEngineLayer implements EngineLayer {}
|
||||
|
||||
/// An opaque handle to a clip rounded rect engine layer.
|
||||
///
|
||||
/// Instances of this class are created by [SceneBuilder.pushClipRRect].
|
||||
///
|
||||
/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility}
|
||||
abstract class ClipRRectEngineLayer implements EngineLayer {}
|
||||
|
||||
/// An opaque handle to a clip path engine layer.
|
||||
///
|
||||
/// Instances of this class are created by [SceneBuilder.pushClipPath].
|
||||
///
|
||||
/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility}
|
||||
abstract class ClipPathEngineLayer implements EngineLayer {}
|
||||
|
||||
/// An opaque handle to an opacity engine layer.
|
||||
///
|
||||
/// Instances of this class are created by [SceneBuilder.pushOpacity].
|
||||
///
|
||||
/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility}
|
||||
abstract class OpacityEngineLayer implements EngineLayer {}
|
||||
|
||||
/// An opaque handle to a color filter engine layer.
|
||||
///
|
||||
/// Instances of this class are created by [SceneBuilder.pushColorFilter].
|
||||
///
|
||||
/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility}
|
||||
abstract class ColorFilterEngineLayer implements EngineLayer {}
|
||||
|
||||
/// An opaque handle to a backdrop filter engine layer.
|
||||
///
|
||||
/// Instances of this class are created by [SceneBuilder.pushBackdropFilter].
|
||||
///
|
||||
/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility}
|
||||
abstract class BackdropFilterEngineLayer implements EngineLayer {}
|
||||
|
||||
/// An opaque handle to a shader mask engine layer.
|
||||
///
|
||||
/// Instances of this class are created by [SceneBuilder.pushShaderMask].
|
||||
///
|
||||
/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility}
|
||||
abstract class ShaderMaskEngineLayer implements EngineLayer {}
|
||||
|
||||
/// An opaque handle to a physical shape engine layer.
|
||||
///
|
||||
/// Instances of this class are created by [SceneBuilder.pushPhysicalShape].
|
||||
///
|
||||
/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility}
|
||||
abstract class PhysicalShapeEngineLayer implements EngineLayer {}
|
||||
|
||||
/// Builds a [Scene] containing the given visuals.
|
||||
///
|
||||
/// A [Scene] can then be rendered using [Window.render].
|
||||
///
|
||||
/// To draw graphical operations onto a [Scene], first create a
|
||||
/// [Picture] using a [PictureRecorder] and a [Canvas], and then add
|
||||
/// it to the scene using [addPicture].
|
||||
class SceneBuilder {
|
||||
/// Creates an empty [SceneBuilder] object.
|
||||
factory SceneBuilder() {
|
||||
if (engine.experimentalUseSkia) {
|
||||
return engine.LayerSceneBuilder();
|
||||
} else {
|
||||
return SceneBuilder._();
|
||||
}
|
||||
}
|
||||
|
||||
SceneBuilder._() {
|
||||
_surfaceStack.add(engine.PersistedScene(_lastFrameScene));
|
||||
}
|
||||
|
||||
factory SceneBuilder.layer() = engine.LayerSceneBuilder;
|
||||
|
||||
final List<engine.PersistedContainerSurface> _surfaceStack =
|
||||
<engine.PersistedContainerSurface>[];
|
||||
|
||||
/// The scene built by this scene builder.
|
||||
///
|
||||
/// This getter should only be called after all surfaces are built.
|
||||
engine.PersistedScene get _persistedScene {
|
||||
assert(() {
|
||||
if (_surfaceStack.length != 1) {
|
||||
final String surfacePrintout = _surfaceStack
|
||||
.map<Type>((engine.PersistedContainerSurface surface) =>
|
||||
surface.runtimeType)
|
||||
.toList()
|
||||
.join(', ');
|
||||
throw Exception('Incorrect sequence of push/pop operations while '
|
||||
'building scene surfaces. After building the scene the persisted '
|
||||
'surface stack must contain a single element which corresponds '
|
||||
'to the scene itself (_PersistedScene). All other surfaces '
|
||||
'should have been popped off the stack. Found the following '
|
||||
'surfaces in the stack:\n$surfacePrintout');
|
||||
}
|
||||
return true;
|
||||
}());
|
||||
return _surfaceStack.first;
|
||||
}
|
||||
|
||||
/// The surface currently being built.
|
||||
engine.PersistedContainerSurface get _currentSurface => _surfaceStack.last;
|
||||
|
||||
EngineLayer _pushSurface(engine.PersistedContainerSurface surface) {
|
||||
// Only attempt to update if the update is requested and the surface is in
|
||||
// the live tree.
|
||||
if (surface.oldLayer != null) {
|
||||
assert(surface.oldLayer.runtimeType == surface.runtimeType);
|
||||
assert(surface.oldLayer.isActive);
|
||||
surface.oldLayer.state = engine.PersistedSurfaceState.pendingUpdate;
|
||||
}
|
||||
_adoptSurface(surface);
|
||||
_surfaceStack.add(surface);
|
||||
return surface;
|
||||
}
|
||||
|
||||
void _addSurface(engine.PersistedSurface surface) {
|
||||
_adoptSurface(surface);
|
||||
}
|
||||
|
||||
void _adoptSurface(engine.PersistedSurface surface) {
|
||||
_currentSurface.appendChild(surface);
|
||||
}
|
||||
|
||||
/// Pushes an offset operation onto the operation stack.
|
||||
///
|
||||
/// This is equivalent to [pushTransform] with a matrix with only translation.
|
||||
///
|
||||
/// See [pop] for details about the operation stack.
|
||||
OffsetEngineLayer pushOffset(double dx, double dy,
|
||||
{OffsetEngineLayer oldLayer}) {
|
||||
return _pushSurface(engine.PersistedOffset(oldLayer, dx, dy));
|
||||
}
|
||||
|
||||
/// Pushes a transform operation onto the operation stack.
|
||||
///
|
||||
/// The objects are transformed by the given matrix before rasterization.
|
||||
///
|
||||
/// See [pop] for details about the operation stack.
|
||||
TransformEngineLayer pushTransform(Float64List matrix4,
|
||||
{TransformEngineLayer oldLayer}) {
|
||||
if (matrix4 == null) {
|
||||
throw ArgumentError('"matrix4" argument cannot be null');
|
||||
}
|
||||
if (matrix4.length != 16) {
|
||||
throw ArgumentError('"matrix4" must have 16 entries.');
|
||||
}
|
||||
return _pushSurface(engine.PersistedTransform(oldLayer, matrix4));
|
||||
}
|
||||
|
||||
/// Pushes a rectangular clip operation onto the operation stack.
|
||||
///
|
||||
/// Rasterization outside the given rectangle is discarded.
|
||||
///
|
||||
/// See [pop] for details about the operation stack, and [Clip] for different clip modes.
|
||||
/// By default, the clip will be anti-aliased (clip = [Clip.antiAlias]).
|
||||
ClipRectEngineLayer pushClipRect(Rect rect,
|
||||
{Clip clipBehavior = Clip.antiAlias, ClipRectEngineLayer oldLayer}) {
|
||||
assert(clipBehavior != null);
|
||||
assert(clipBehavior != Clip.none);
|
||||
return _pushSurface(engine.PersistedClipRect(oldLayer, rect));
|
||||
}
|
||||
|
||||
/// Pushes a rounded-rectangular clip operation onto the operation stack.
|
||||
///
|
||||
/// Rasterization outside the given rounded rectangle is discarded.
|
||||
///
|
||||
/// See [pop] for details about the operation stack.
|
||||
ClipRRectEngineLayer pushClipRRect(RRect rrect,
|
||||
{Clip clipBehavior, ClipRRectEngineLayer oldLayer}) {
|
||||
return _pushSurface(
|
||||
engine.PersistedClipRRect(oldLayer, rrect, clipBehavior));
|
||||
}
|
||||
|
||||
/// Pushes a path clip operation onto the operation stack.
|
||||
///
|
||||
/// Rasterization outside the given path is discarded.
|
||||
///
|
||||
/// See [pop] for details about the operation stack.
|
||||
ClipPathEngineLayer pushClipPath(Path path,
|
||||
{Clip clipBehavior = Clip.antiAlias, ClipPathEngineLayer oldLayer}) {
|
||||
assert(clipBehavior != null);
|
||||
assert(clipBehavior != Clip.none);
|
||||
return _pushSurface(engine.PersistedClipPath(oldLayer, path, clipBehavior));
|
||||
}
|
||||
|
||||
/// Pushes an opacity operation onto the operation stack.
|
||||
///
|
||||
/// The given alpha value is blended into the alpha value of the objects'
|
||||
/// rasterization. An alpha value of 0 makes the objects entirely invisible.
|
||||
/// An alpha value of 255 has no effect (i.e., the objects retain the current
|
||||
/// opacity).
|
||||
///
|
||||
/// See [pop] for details about the operation stack.
|
||||
OpacityEngineLayer pushOpacity(int alpha,
|
||||
{Offset offset = Offset.zero, OpacityEngineLayer oldLayer}) {
|
||||
return _pushSurface(engine.PersistedOpacity(oldLayer, alpha, offset));
|
||||
}
|
||||
|
||||
/// Pushes a color filter operation onto the operation stack.
|
||||
///
|
||||
/// The given color is applied to the objects' rasterization using the given
|
||||
/// blend mode.
|
||||
///
|
||||
/// See [pop] for details about the operation stack.
|
||||
ColorFilterEngineLayer pushColorFilter(ColorFilter filter,
|
||||
{ColorFilterEngineLayer oldLayer}) {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
|
||||
/// Pushes a backdrop filter operation onto the operation stack.
|
||||
///
|
||||
/// The given filter is applied to the current contents of the scene prior to
|
||||
/// rasterizing the given objects.
|
||||
///
|
||||
/// See [pop] for details about the operation stack.
|
||||
BackdropFilterEngineLayer pushBackdropFilter(ImageFilter filter,
|
||||
{BackdropFilterEngineLayer oldLayer}) {
|
||||
return _pushSurface(engine.PersistedBackdropFilter(oldLayer, filter));
|
||||
}
|
||||
|
||||
/// Pushes a shader mask operation onto the operation stack.
|
||||
///
|
||||
/// The given shader is applied to the object's rasterization in the given
|
||||
/// rectangle using the given blend mode.
|
||||
///
|
||||
/// See [pop] for details about the operation stack.
|
||||
ShaderMaskEngineLayer pushShaderMask(
|
||||
Shader shader, Rect maskRect, BlendMode blendMode,
|
||||
{ShaderMaskEngineLayer oldLayer}) {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
|
||||
/// Pushes a physical layer operation for an arbitrary shape onto the
|
||||
/// operation stack.
|
||||
///
|
||||
/// By default, the layer's content will not be clipped (clip = [Clip.none]).
|
||||
/// If clip equals [Clip.hardEdge], [Clip.antiAlias], or [Clip.antiAliasWithSaveLayer],
|
||||
/// then the content is clipped to the given shape defined by [path].
|
||||
///
|
||||
/// If [elevation] is greater than 0.0, then a shadow is drawn around the layer.
|
||||
/// [shadowColor] defines the color of the shadow if present and [color] defines the
|
||||
/// color of the layer background.
|
||||
///
|
||||
/// See [pop] for details about the operation stack, and [Clip] for different clip modes.
|
||||
PhysicalShapeEngineLayer pushPhysicalShape({
|
||||
Path path,
|
||||
double elevation,
|
||||
Color color,
|
||||
Color shadowColor,
|
||||
Clip clipBehavior = Clip.none,
|
||||
PhysicalShapeEngineLayer oldLayer,
|
||||
}) {
|
||||
return _pushSurface(engine.PersistedPhysicalShape(
|
||||
oldLayer,
|
||||
path,
|
||||
elevation,
|
||||
color.value,
|
||||
shadowColor?.value ?? 0xFF000000,
|
||||
clipBehavior,
|
||||
));
|
||||
}
|
||||
|
||||
/// Add a retained engine layer subtree from previous frames.
|
||||
///
|
||||
/// All the engine layers that are in the subtree of the retained layer will
|
||||
/// be automatically appended to the current engine layer tree.
|
||||
///
|
||||
/// Therefore, when implementing a subclass of the [Layer] concept defined in
|
||||
/// the rendering layer of Flutter's framework, once this is called, there's
|
||||
/// no need to call [addToScene] for its children layers.
|
||||
void addRetained(EngineLayer retainedLayer) {
|
||||
final engine.PersistedContainerSurface retainedSurface = retainedLayer;
|
||||
assert(retainedSurface.isActive || retainedSurface.isReleased);
|
||||
retainedSurface.tryRetain();
|
||||
_adoptSurface(retainedSurface);
|
||||
}
|
||||
|
||||
/// Ends the effect of the most recently pushed operation.
|
||||
///
|
||||
/// Internally the scene builder maintains a stack of operations. Each of the
|
||||
/// operations in the stack applies to each of the objects added to the scene.
|
||||
/// Calling this function removes the most recently added operation from the
|
||||
/// stack.
|
||||
void pop() {
|
||||
assert(_surfaceStack.isNotEmpty);
|
||||
_surfaceStack.removeLast();
|
||||
}
|
||||
|
||||
/// Adds an object to the scene that displays performance statistics.
|
||||
///
|
||||
/// Useful during development to assess the performance of the application.
|
||||
/// The enabledOptions controls which statistics are displayed. The bounds
|
||||
/// controls where the statistics are displayed.
|
||||
///
|
||||
/// enabledOptions is a bit field with the following bits defined:
|
||||
/// - 0x01: displayRasterizerStatistics - show GPU thread frame time
|
||||
/// - 0x02: visualizeRasterizerStatistics - graph GPU thread frame times
|
||||
/// - 0x04: displayEngineStatistics - show UI thread frame time
|
||||
/// - 0x08: visualizeEngineStatistics - graph UI thread frame times
|
||||
/// Set enabledOptions to 0x0F to enable all the currently defined features.
|
||||
///
|
||||
/// The "UI thread" is the thread that includes all the execution of
|
||||
/// the main Dart isolate (the isolate that can call
|
||||
/// [Window.render]). The UI thread frame time is the total time
|
||||
/// spent executing the [Window.onBeginFrame] callback. The "GPU
|
||||
/// thread" is the thread (running on the CPU) that subsequently
|
||||
/// processes the [Scene] provided by the Dart code to turn it into
|
||||
/// GPU commands and send it to the GPU.
|
||||
///
|
||||
/// See also the [PerformanceOverlayOption] enum in the rendering library.
|
||||
/// for more details.
|
||||
void addPerformanceOverlay(int enabledOptions, Rect bounds) {
|
||||
_addPerformanceOverlay(
|
||||
enabledOptions, bounds.left, bounds.right, bounds.top, bounds.bottom);
|
||||
}
|
||||
|
||||
/// Whether we've already warned the user about the lack of the performance
|
||||
/// overlay or not.
|
||||
///
|
||||
/// We use this to avoid spamming the console with redundant warning messages.
|
||||
static bool _webOnlyDidWarnAboutPerformanceOverlay = false;
|
||||
|
||||
void _addPerformanceOverlay(int enabledOptions, double left, double right,
|
||||
double top, double bottom) {
|
||||
if (!_webOnlyDidWarnAboutPerformanceOverlay) {
|
||||
_webOnlyDidWarnAboutPerformanceOverlay = true;
|
||||
html.window.console
|
||||
.warn('The performance overlay isn\'t supported on the web');
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a [Picture] to the scene.
|
||||
///
|
||||
/// The picture is rasterized at the given offset.
|
||||
void addPicture(
|
||||
Offset offset,
|
||||
Picture picture, {
|
||||
bool isComplexHint = false,
|
||||
bool willChangeHint = false,
|
||||
}) {
|
||||
int hints = 0;
|
||||
if (isComplexHint) {
|
||||
hints |= 1;
|
||||
}
|
||||
if (willChangeHint) {
|
||||
hints |= 2;
|
||||
}
|
||||
_addSurface(
|
||||
engine.persistedPictureFactory(offset.dx, offset.dy, picture, hints));
|
||||
}
|
||||
|
||||
/// Adds a backend texture to the scene.
|
||||
///
|
||||
/// The texture is scaled to the given size and rasterized at the given
|
||||
/// offset.
|
||||
void addTexture(int textureId,
|
||||
{Offset offset = Offset.zero,
|
||||
double width = 0.0,
|
||||
double height = 0.0,
|
||||
bool freeze = false}) {
|
||||
assert(offset != null, 'Offset argument was null');
|
||||
_addTexture(offset.dx, offset.dy, width, height, textureId);
|
||||
}
|
||||
|
||||
void _addTexture(
|
||||
double dx, double dy, double width, double height, int textureId) {
|
||||
// In test mode, allow this to be a no-op.
|
||||
if (!debugEmulateFlutterTesterEnvironment) {
|
||||
throw UnimplementedError('Textures are not supported in Flutter Web');
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a platform view (e.g an iOS UIView) to the scene.
|
||||
///
|
||||
/// Only supported on iOS, this is currently a no-op on other platforms.
|
||||
///
|
||||
/// On iOS this layer splits the current output surface into two surfaces, one for the scene nodes
|
||||
/// preceding the platform view, and one for the scene nodes following the platform view.
|
||||
///
|
||||
/// ## Performance impact
|
||||
///
|
||||
/// Adding an additional surface doubles the amount of graphics memory directly used by Flutter
|
||||
/// for output buffers. Quartz might allocated extra buffers for compositing the Flutter surfaces
|
||||
/// and the platform view.
|
||||
///
|
||||
/// With a platform view in the scene, Quartz has to composite the two Flutter surfaces and the
|
||||
/// embedded UIView. In addition to that, on iOS versions greater than 9, the Flutter frames are
|
||||
/// synchronized with the UIView frames adding additional performance overhead.
|
||||
void addPlatformView(
|
||||
int viewId, {
|
||||
Offset offset = Offset.zero,
|
||||
double width = 0.0,
|
||||
double height = 0.0,
|
||||
}) {
|
||||
assert(offset != null, 'Offset argument was null');
|
||||
_addPlatformView(offset.dx, offset.dy, width, height, viewId);
|
||||
}
|
||||
|
||||
void _addPlatformView(
|
||||
double dx,
|
||||
double dy,
|
||||
double width,
|
||||
double height,
|
||||
int viewId,
|
||||
) {
|
||||
_addSurface(engine.PersistedPlatformView(viewId, dx, dy, width, height));
|
||||
}
|
||||
|
||||
/// (Fuchsia-only) Adds a scene rendered by another application to the scene
|
||||
/// for this application.
|
||||
void addChildScene(
|
||||
{Offset offset = Offset.zero,
|
||||
double width = 0.0,
|
||||
double height = 0.0,
|
||||
SceneHost sceneHost,
|
||||
bool hitTestable = true}) {
|
||||
_addChildScene(offset.dx, offset.dy, width, height, sceneHost, hitTestable);
|
||||
}
|
||||
|
||||
void _addChildScene(double dx, double dy, double width, double height,
|
||||
SceneHost sceneHost, bool hitTestable) {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
|
||||
/// Sets a threshold after which additional debugging information should be
|
||||
/// recorded.
|
||||
///
|
||||
/// Currently this interface is difficult to use by end-developers. If you're
|
||||
/// interested in using this feature, please contact [flutter-dev](https://groups.google.com/forum/#!forum/flutter-dev).
|
||||
/// We'll hopefully be able to figure out how to make this feature more useful
|
||||
/// to you.
|
||||
void setRasterizerTracingThreshold(int frameInterval) {}
|
||||
|
||||
/// Sets whether the raster cache should checkerboard cached entries. This is
|
||||
/// only useful for debugging purposes.
|
||||
///
|
||||
/// The compositor can sometimes decide to cache certain portions of the
|
||||
/// widget hierarchy. Such portions typically don't change often from frame to
|
||||
/// frame and are expensive to render. This can speed up overall rendering.
|
||||
/// However, there is certain upfront cost to constructing these cache
|
||||
/// entries. And, if the cache entries are not used very often, this cost may
|
||||
/// not be worth the speedup in rendering of subsequent frames. If the
|
||||
/// developer wants to be certain that populating the raster cache is not
|
||||
/// causing stutters, this option can be set. Depending on the observations
|
||||
/// made, hints can be provided to the compositor that aid it in making better
|
||||
/// decisions about caching.
|
||||
///
|
||||
/// Currently this interface is difficult to use by end-developers. If you're
|
||||
/// interested in using this feature, please contact [flutter-dev](https://groups.google.com/forum/#!forum/flutter-dev).
|
||||
void setCheckerboardRasterCacheImages(bool checkerboard) {}
|
||||
|
||||
/// Sets whether the compositor should checkerboard layers that are rendered
|
||||
/// to offscreen bitmaps.
|
||||
///
|
||||
/// This is only useful for debugging purposes.
|
||||
void setCheckerboardOffscreenLayers(bool checkerboard) {}
|
||||
|
||||
/// The scene recorded in the last frame.
|
||||
///
|
||||
/// This is a surface tree that holds onto the DOM elements that can be reused
|
||||
/// on the next frame.
|
||||
static engine.PersistedScene _lastFrameScene;
|
||||
|
||||
/// Returns the computed persisted scene graph recorded in the last frame.
|
||||
///
|
||||
/// This is only available in debug mode. It returns `null` in profile and
|
||||
/// release modes.
|
||||
static engine.PersistedScene get debugLastFrameScene {
|
||||
engine.PersistedScene result;
|
||||
assert(() {
|
||||
result = _lastFrameScene;
|
||||
return true;
|
||||
}());
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Discards information about previously rendered frames, including DOM
|
||||
/// elements and cached canvases.
|
||||
///
|
||||
/// After calling this function new canvases will be created for the
|
||||
/// subsequent scene. This is useful when tests need predictable canvas
|
||||
/// sizes. If the cache is not cleared, then canvases allocated in one test
|
||||
/// may be reused in another test.
|
||||
static void debugForgetFrameScene() {
|
||||
_lastFrameScene?.rootElement?.remove();
|
||||
_lastFrameScene = null;
|
||||
engine.debugForgetFrameScene();
|
||||
}
|
||||
|
||||
/// Finishes building the scene.
|
||||
///
|
||||
/// Returns a [Scene] containing the objects that have been added to
|
||||
/// this scene builder. The [Scene] can then be displayed on the
|
||||
/// screen with [Window.render].
|
||||
///
|
||||
/// After calling this function, the scene builder object is invalid and
|
||||
/// cannot be used further.
|
||||
Scene build() {
|
||||
_persistedScene.preroll();
|
||||
if (_lastFrameScene == null) {
|
||||
_persistedScene.build();
|
||||
} else {
|
||||
_persistedScene.update(_lastFrameScene);
|
||||
}
|
||||
engine.commitScene(_persistedScene);
|
||||
_lastFrameScene = _persistedScene;
|
||||
return Scene._(_persistedScene.rootElement);
|
||||
}
|
||||
|
||||
/// Set properties on the linked scene. These properties include its bounds,
|
||||
/// as well as whether it can be the target of focus events or not.
|
||||
void setProperties(double width, double height, double insetTop,
|
||||
double insetRight, double insetBottom, double insetLeft, bool focusable) {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
}
|
||||
|
||||
/// A handle for the framework to hold and retain an engine layer across frames.
|
||||
class EngineLayer {}
|
||||
|
||||
//// (Fuchsia-only) Hosts content provided by another application.
|
||||
class SceneHost {
|
||||
/// Creates a host for a child scene's content.
|
||||
///
|
||||
/// The ViewHolder token is bound to a ViewHolder scene graph node which acts
|
||||
/// as a container for the child's content. The creator of the SceneHost is
|
||||
/// responsible for sending the corresponding ViewToken to the child.
|
||||
///
|
||||
/// The ViewHolder token is a dart:zircon Handle, but that type isn't
|
||||
/// available here. This is called by ChildViewConnection in
|
||||
/// //topaz/public/dart/fuchsia_scenic_flutter/.
|
||||
///
|
||||
/// The SceneHost takes ownership of the provided ViewHolder token.
|
||||
SceneHost(
|
||||
dynamic viewHolderToken,
|
||||
void Function() viewConnectedCallback,
|
||||
void Function() viewDisconnectedCallback,
|
||||
void Function(bool) viewStateChangedCallback);
|
||||
|
||||
SceneHost.fromViewHolderToken(
|
||||
dynamic viewHolderToken,
|
||||
void Function() viewConnectedCallback,
|
||||
void Function() viewDisconnectedCallback,
|
||||
void Function(bool) viewStateChangedCallback);
|
||||
|
||||
/// Releases the resources associated with the SceneHost.
|
||||
///
|
||||
/// After calling this function, the SceneHost cannot be used further.
|
||||
void dispose() {}
|
||||
|
||||
/// Set properties on the linked scene. These properties include its bounds,
|
||||
/// as well as whether it can be the target of focus events or not.
|
||||
void setProperties(double width, double height, double insetTop,
|
||||
double insetRight, double insetBottom, double insetLeft, bool focusable) {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
|
||||
/// Set the opacity of the linked scene. This opacity value is applied only
|
||||
/// once, when the child scene is composited into our own.
|
||||
void setOpacity(double opacity) {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
}
|
||||
1816
engine/src/flutter/lib/web_ui/lib/src/ui/geometry.dart
Normal file
1816
engine/src/flutter/lib/web_ui/lib/src/ui/geometry.dart
Normal file
File diff suppressed because it is too large
Load Diff
137
engine/src/flutter/lib/web_ui/lib/src/ui/hash_codes.dart
Normal file
137
engine/src/flutter/lib/web_ui/lib/src/ui/hash_codes.dart
Normal file
@@ -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 ui;
|
||||
|
||||
class _HashEnd {
|
||||
const _HashEnd();
|
||||
}
|
||||
|
||||
const _HashEnd _hashEnd = _HashEnd();
|
||||
|
||||
/// Combine up to twenty values' hashCodes into one value.
|
||||
///
|
||||
/// If you only need to handle one value's hashCode, then just refer to its
|
||||
/// [hashCode] getter directly.
|
||||
///
|
||||
/// If you need to combine an arbitrary number of values from a List or other
|
||||
/// Iterable, use [hashList]. The output of hashList can be used as one of the
|
||||
/// arguments to this function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// int hashCode => hashValues(foo, bar, hashList(quux), baz);
|
||||
int hashValues(Object arg01, Object arg02,
|
||||
[Object arg03 = _hashEnd,
|
||||
Object arg04 = _hashEnd,
|
||||
Object arg05 = _hashEnd,
|
||||
Object arg06 = _hashEnd,
|
||||
Object arg07 = _hashEnd,
|
||||
Object arg08 = _hashEnd,
|
||||
Object arg09 = _hashEnd,
|
||||
Object arg10 = _hashEnd,
|
||||
Object arg11 = _hashEnd,
|
||||
Object arg12 = _hashEnd,
|
||||
Object arg13 = _hashEnd,
|
||||
Object arg14 = _hashEnd,
|
||||
Object arg15 = _hashEnd,
|
||||
Object arg16 = _hashEnd,
|
||||
Object arg17 = _hashEnd,
|
||||
Object arg18 = _hashEnd,
|
||||
Object arg19 = _hashEnd,
|
||||
Object arg20 = _hashEnd]) {
|
||||
int result = 373;
|
||||
assert(arg01 is! Iterable);
|
||||
result = 37 * result + arg01.hashCode;
|
||||
assert(arg02 is! Iterable);
|
||||
result = 37 * result + arg02.hashCode;
|
||||
if (arg03 != _hashEnd) {
|
||||
assert(arg03 is! Iterable);
|
||||
result = 37 * result + arg03.hashCode;
|
||||
if (arg04 != _hashEnd) {
|
||||
assert(arg04 is! Iterable);
|
||||
result = 37 * result + arg04.hashCode;
|
||||
if (arg05 != _hashEnd) {
|
||||
assert(arg05 is! Iterable);
|
||||
result = 37 * result + arg05.hashCode;
|
||||
if (arg06 != _hashEnd) {
|
||||
assert(arg06 is! Iterable);
|
||||
result = 37 * result + arg06.hashCode;
|
||||
if (arg07 != _hashEnd) {
|
||||
assert(arg07 is! Iterable);
|
||||
result = 37 * result + arg07.hashCode;
|
||||
if (arg08 != _hashEnd) {
|
||||
assert(arg08 is! Iterable);
|
||||
result = 37 * result + arg08.hashCode;
|
||||
if (arg09 != _hashEnd) {
|
||||
assert(arg09 is! Iterable);
|
||||
result = 37 * result + arg09.hashCode;
|
||||
if (arg10 != _hashEnd) {
|
||||
assert(arg10 is! Iterable);
|
||||
result = 37 * result + arg10.hashCode;
|
||||
if (arg11 != _hashEnd) {
|
||||
assert(arg11 is! Iterable);
|
||||
result = 37 * result + arg11.hashCode;
|
||||
if (arg12 != _hashEnd) {
|
||||
assert(arg12 is! Iterable);
|
||||
result = 37 * result + arg12.hashCode;
|
||||
if (arg13 != _hashEnd) {
|
||||
assert(arg13 is! Iterable);
|
||||
result = 37 * result + arg13.hashCode;
|
||||
if (arg14 != _hashEnd) {
|
||||
assert(arg14 is! Iterable);
|
||||
result = 37 * result + arg14.hashCode;
|
||||
if (arg15 != _hashEnd) {
|
||||
assert(arg15 is! Iterable);
|
||||
result = 37 * result + arg15.hashCode;
|
||||
if (arg16 != _hashEnd) {
|
||||
assert(arg16 is! Iterable);
|
||||
result = 37 * result + arg16.hashCode;
|
||||
if (arg17 != _hashEnd) {
|
||||
assert(arg17 is! Iterable);
|
||||
result = 37 * result + arg17.hashCode;
|
||||
if (arg18 != _hashEnd) {
|
||||
assert(arg18 is! Iterable);
|
||||
result = 37 * result + arg18.hashCode;
|
||||
if (arg19 != _hashEnd) {
|
||||
assert(arg19 is! Iterable);
|
||||
result = 37 * result + arg19.hashCode;
|
||||
if (arg20 != _hashEnd) {
|
||||
assert(arg20 is! Iterable);
|
||||
result = 37 * result + arg20.hashCode;
|
||||
// I can see my house from here!
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Combine the hashCodes of an arbitrary number of values from an Iterable into
|
||||
/// one value. This function will return the same value if given "null" as if
|
||||
/// given an empty list.
|
||||
int hashList(Iterable<Object> args) {
|
||||
int result = 373;
|
||||
if (args != null) {
|
||||
for (Object arg in args) {
|
||||
assert(arg is! Iterable);
|
||||
result = 37 * result + arg.hashCode;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
82
engine/src/flutter/lib/web_ui/lib/src/ui/initialization.dart
Normal file
82
engine/src/flutter/lib/web_ui/lib/src/ui/initialization.dart
Normal file
@@ -0,0 +1,82 @@
|
||||
// Copyright 2013 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
part of ui;
|
||||
|
||||
/// Initializes the platform.
|
||||
Future<void> webOnlyInitializePlatform({
|
||||
engine.AssetManager assetManager,
|
||||
}) async {
|
||||
if (!debugEmulateFlutterTesterEnvironment) {
|
||||
engine.window.webOnlyLocationStrategy = const engine.HashLocationStrategy();
|
||||
}
|
||||
|
||||
assetManager ??= const engine.AssetManager();
|
||||
await webOnlySetAssetManager(assetManager);
|
||||
await _fontCollection.ensureFontsLoaded();
|
||||
engine.webOnlyInitializeEngine();
|
||||
|
||||
// This needs to be after `webOnlyInitializeEngine` because that is where the
|
||||
// canvaskit script is added to the page.
|
||||
if (engine.experimentalUseSkia) {
|
||||
await engine.initializeSkia();
|
||||
}
|
||||
_webOnlyIsInitialized = true;
|
||||
}
|
||||
|
||||
engine.AssetManager _assetManager;
|
||||
engine.FontCollection _fontCollection;
|
||||
|
||||
bool _webOnlyIsInitialized = false;
|
||||
bool get webOnlyIsInitialized => _webOnlyIsInitialized;
|
||||
|
||||
/// Specifies that the platform should use the given [AssetManager] to load
|
||||
/// assets.
|
||||
///
|
||||
/// The given asset manager is used to initialize the font collection.
|
||||
Future<void> webOnlySetAssetManager(engine.AssetManager assetManager) async {
|
||||
assert(assetManager != null, 'Cannot set assetManager to null');
|
||||
if (assetManager == _assetManager) {
|
||||
return;
|
||||
}
|
||||
|
||||
_assetManager = assetManager;
|
||||
|
||||
_fontCollection ??= engine.FontCollection();
|
||||
_fontCollection.clear();
|
||||
if (_assetManager != null) {
|
||||
await _fontCollection.registerFonts(_assetManager);
|
||||
}
|
||||
|
||||
if (debugEmulateFlutterTesterEnvironment) {
|
||||
_fontCollection.debugRegisterTestFonts();
|
||||
}
|
||||
}
|
||||
|
||||
/// Flag that shows whether the Flutter Testing Behavior is enabled.
|
||||
///
|
||||
/// This flag can be used to decide if the code is running from a Flutter Test
|
||||
/// such as a Widget test.
|
||||
///
|
||||
/// For example in these tests we use a predictable-size font which makes widget
|
||||
/// tests less flaky.
|
||||
bool get debugEmulateFlutterTesterEnvironment =>
|
||||
_debugEmulateFlutterTesterEnvironment;
|
||||
|
||||
set debugEmulateFlutterTesterEnvironment(bool value) {
|
||||
_debugEmulateFlutterTesterEnvironment = value;
|
||||
if (_debugEmulateFlutterTesterEnvironment) {
|
||||
const Size logicalSize = Size(800.0, 600.0);
|
||||
engine.window.webOnlyDebugPhysicalSizeOverride =
|
||||
logicalSize * window.devicePixelRatio;
|
||||
}
|
||||
}
|
||||
|
||||
bool _debugEmulateFlutterTesterEnvironment = false;
|
||||
|
||||
/// This class handles downloading assets over the network.
|
||||
engine.AssetManager get webOnlyAssetManager => _assetManager;
|
||||
|
||||
/// A collection of fonts that may be used by the platform.
|
||||
engine.FontCollection get webOnlyFontCollection => _fontCollection;
|
||||
15
engine/src/flutter/lib/web_ui/lib/src/ui/lerp.dart
Normal file
15
engine/src/flutter/lib/web_ui/lib/src/ui/lerp.dart
Normal file
@@ -0,0 +1,15 @@
|
||||
// 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 ui;
|
||||
|
||||
/// Linearly interpolate between two numbers.
|
||||
double lerpDouble(num a, num b, double t) {
|
||||
if (a == null && b == null) {
|
||||
return null;
|
||||
}
|
||||
a ??= 0.0;
|
||||
b ??= 0.0;
|
||||
return a + (b - a) * t;
|
||||
}
|
||||
25
engine/src/flutter/lib/web_ui/lib/src/ui/natives.dart
Normal file
25
engine/src/flutter/lib/web_ui/lib/src/ui/natives.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
// 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 ui;
|
||||
|
||||
/// Returns runtime Dart compilation trace as a UTF-8 encoded memory buffer.
|
||||
///
|
||||
/// The buffer contains a list of symbols compiled by the Dart JIT at runtime up to the point
|
||||
/// when this function was called. This list can be saved to a text file and passed to tools
|
||||
/// such as `flutter build` or Dart `gen_snapshot` in order to precompile this code offline.
|
||||
///
|
||||
/// The list has one symbol per line of the following format: `<namespace>,<class>,<symbol>\n`.
|
||||
/// Here are some examples:
|
||||
///
|
||||
/// ```
|
||||
/// dart:core,Duration,get:inMilliseconds
|
||||
/// package:flutter/src/widgets/binding.dart,::,runApp
|
||||
/// file:///.../my_app.dart,::,main
|
||||
/// ```
|
||||
///
|
||||
/// This function is only effective in debug and dynamic modes, and will throw in AOT mode.
|
||||
List<int> saveCompilationTrace() {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
2062
engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart
Normal file
2062
engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart
Normal file
File diff suppressed because it is too large
Load Diff
276
engine/src/flutter/lib/web_ui/lib/src/ui/pointer.dart
Normal file
276
engine/src/flutter/lib/web_ui/lib/src/ui/pointer.dart
Normal file
@@ -0,0 +1,276 @@
|
||||
// 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 ui;
|
||||
|
||||
/// How the pointer has changed since the last report.
|
||||
enum PointerChange {
|
||||
/// The input from the pointer is no longer directed towards this receiver.
|
||||
cancel,
|
||||
|
||||
/// The device has started tracking the pointer.
|
||||
///
|
||||
/// For example, the pointer might be hovering above the device, having not yet
|
||||
/// made contact with the surface of the device.
|
||||
add,
|
||||
|
||||
/// The device is no longer tracking the pointer.
|
||||
///
|
||||
/// For example, the pointer might have drifted out of the device's hover
|
||||
/// detection range or might have been disconnected from the system entirely.
|
||||
remove,
|
||||
|
||||
/// The pointer has moved with respect to the device while not in contact with
|
||||
/// the device.
|
||||
hover,
|
||||
|
||||
/// The pointer has made contact with the device.
|
||||
down,
|
||||
|
||||
/// The pointer has moved with respect to the device while in contact with the
|
||||
/// device.
|
||||
move,
|
||||
|
||||
/// The pointer has stopped making contact with the device.
|
||||
up,
|
||||
}
|
||||
|
||||
/// The kind of pointer device.
|
||||
enum PointerDeviceKind {
|
||||
/// A touch-based pointer device.
|
||||
touch,
|
||||
|
||||
/// A mouse-based pointer device.
|
||||
mouse,
|
||||
|
||||
/// A pointer device with a stylus.
|
||||
stylus,
|
||||
|
||||
/// A pointer device with a stylus that has been inverted.
|
||||
invertedStylus,
|
||||
|
||||
/// An unknown pointer device.
|
||||
unknown
|
||||
}
|
||||
|
||||
/// The kind of [PointerDeviceKind.signal].
|
||||
enum PointerSignalKind {
|
||||
/// The event is not associated with a pointer signal.
|
||||
none,
|
||||
|
||||
/// A pointer-generated scroll (e.g., mouse wheel or trackpad scroll).
|
||||
scroll,
|
||||
|
||||
/// An unknown pointer signal kind.
|
||||
unknown
|
||||
}
|
||||
|
||||
/// Information about the state of a pointer.
|
||||
class PointerData {
|
||||
/// Creates an object that represents the state of a pointer.
|
||||
const PointerData({
|
||||
this.timeStamp = Duration.zero,
|
||||
this.change = PointerChange.cancel,
|
||||
this.kind = PointerDeviceKind.touch,
|
||||
this.signalKind,
|
||||
this.device = 0,
|
||||
this.physicalX = 0.0,
|
||||
this.physicalY = 0.0,
|
||||
this.buttons = 0,
|
||||
this.obscured = false,
|
||||
this.pressure = 0.0,
|
||||
this.pressureMin = 0.0,
|
||||
this.pressureMax = 0.0,
|
||||
this.distance = 0.0,
|
||||
this.distanceMax = 0.0,
|
||||
this.size = 0.0,
|
||||
this.radiusMajor = 0.0,
|
||||
this.radiusMinor = 0.0,
|
||||
this.radiusMin = 0.0,
|
||||
this.radiusMax = 0.0,
|
||||
this.orientation = 0.0,
|
||||
this.tilt = 0.0,
|
||||
this.platformData = 0,
|
||||
this.scrollDeltaX = 0.0,
|
||||
this.scrollDeltaY = 0.0,
|
||||
});
|
||||
|
||||
/// Time of event dispatch, relative to an arbitrary timeline.
|
||||
final Duration timeStamp;
|
||||
|
||||
/// How the pointer has changed since the last report.
|
||||
final PointerChange change;
|
||||
|
||||
/// The kind of input device for which the event was generated.
|
||||
final PointerDeviceKind kind;
|
||||
|
||||
/// The kind of signal for a pointer signal event.
|
||||
final PointerSignalKind signalKind;
|
||||
|
||||
/// Unique identifier for the pointing device, reused across interactions.
|
||||
final int device;
|
||||
|
||||
/// X coordinate of the position of the pointer, in physical pixels in the
|
||||
/// global coordinate space.
|
||||
final double physicalX;
|
||||
|
||||
/// Y coordinate of the position of the pointer, in physical pixels in the
|
||||
/// global coordinate space.
|
||||
final double physicalY;
|
||||
|
||||
/// Bit field using the *Button constants (primaryMouseButton,
|
||||
/// secondaryStylusButton, etc). For example, if this has the value 6 and the
|
||||
/// [kind] is [PointerDeviceKind.invertedStylus], then this indicates an
|
||||
/// upside-down stylus with both its primary and secondary buttons pressed.
|
||||
final int buttons;
|
||||
|
||||
/// Set if an application from a different security domain is in any way
|
||||
/// obscuring this application's window. (Aspirational; not currently
|
||||
/// implemented.)
|
||||
final bool obscured;
|
||||
|
||||
/// The pressure of the touch as a number ranging from 0.0, indicating a touch
|
||||
/// with no discernible pressure, to 1.0, indicating a touch with "normal"
|
||||
/// pressure, and possibly beyond, indicating a stronger touch. For devices
|
||||
/// that do not detect pressure (e.g. mice), returns 1.0.
|
||||
final double pressure;
|
||||
|
||||
/// The minimum value that [pressure] can return for this pointer. For devices
|
||||
/// that do not detect pressure (e.g. mice), returns 1.0. This will always be
|
||||
/// a number less than or equal to 1.0.
|
||||
final double pressureMin;
|
||||
|
||||
/// The maximum value that [pressure] can return for this pointer. For devices
|
||||
/// that do not detect pressure (e.g. mice), returns 1.0. This will always be
|
||||
/// a greater than or equal to 1.0.
|
||||
final double pressureMax;
|
||||
|
||||
/// The distance of the detected object from the input surface (e.g. the
|
||||
/// distance of a stylus or finger from a touch screen), in arbitrary units on
|
||||
/// an arbitrary (not necessarily linear) scale. If the pointer is down, this
|
||||
/// is 0.0 by definition.
|
||||
final double distance;
|
||||
|
||||
/// The maximum value that a distance can return for this pointer. If this
|
||||
/// input device cannot detect "hover touch" input events, then this will be
|
||||
/// 0.0.
|
||||
final double distanceMax;
|
||||
|
||||
/// The area of the screen being pressed, scaled to a value between 0 and 1.
|
||||
/// The value of size can be used to determine fat touch events. This value
|
||||
/// is only set on Android, and is a device specific approximation within
|
||||
/// the range of detectable values. So, for example, the value of 0.1 could
|
||||
/// mean a touch with the tip of the finger, 0.2 a touch with full finger,
|
||||
/// and 0.3 the full palm.
|
||||
final double size;
|
||||
|
||||
/// The radius of the contact ellipse along the major axis, in logical pixels.
|
||||
final double radiusMajor;
|
||||
|
||||
/// The radius of the contact ellipse along the minor axis, in logical pixels.
|
||||
final double radiusMinor;
|
||||
|
||||
/// The minimum value that could be reported for radiusMajor and radiusMinor
|
||||
/// for this pointer, in logical pixels.
|
||||
final double radiusMin;
|
||||
|
||||
/// The minimum value that could be reported for radiusMajor and radiusMinor
|
||||
/// for this pointer, in logical pixels.
|
||||
final double radiusMax;
|
||||
|
||||
/// For PointerDeviceKind.touch events:
|
||||
///
|
||||
/// The angle of the contact ellipse, in radius in the range:
|
||||
///
|
||||
/// -pi/2 < orientation <= pi/2
|
||||
///
|
||||
/// ...giving the angle of the major axis of the ellipse with the y-axis
|
||||
/// (negative angles indicating an orientation along the top-left /
|
||||
/// bottom-right diagonal, positive angles indicating an orientation along the
|
||||
/// top-right / bottom-left diagonal, and zero indicating an orientation
|
||||
/// parallel with the y-axis).
|
||||
///
|
||||
/// For PointerDeviceKind.stylus and PointerDeviceKind.invertedStylus events:
|
||||
///
|
||||
/// The angle of the stylus, in radians in the range:
|
||||
///
|
||||
/// -pi < orientation <= pi
|
||||
///
|
||||
/// ...giving the angle of the axis of the stylus projected onto the input
|
||||
/// surface, relative to the positive y-axis of that surface (thus 0.0
|
||||
/// indicates the stylus, if projected onto that surface, would go from the
|
||||
/// contact point vertically up in the positive y-axis direction, pi would
|
||||
/// indicate that the stylus would go down in the negative y-axis direction;
|
||||
/// pi/4 would indicate that the stylus goes up and to the right, -pi/2 would
|
||||
/// indicate that the stylus goes to the left, etc).
|
||||
final double orientation;
|
||||
|
||||
/// For PointerDeviceKind.stylus and PointerDeviceKind.invertedStylus events:
|
||||
///
|
||||
/// The angle of the stylus, in radians in the range:
|
||||
///
|
||||
/// 0 <= tilt <= pi/2
|
||||
///
|
||||
/// ...giving the angle of the axis of the stylus, relative to the axis
|
||||
/// perpendicular to the input surface (thus 0.0 indicates the stylus is
|
||||
/// orthogonal to the plane of the input surface, while pi/2 indicates that
|
||||
/// the stylus is flat on that surface).
|
||||
final double tilt;
|
||||
|
||||
/// Opaque platform-specific data associated with the event.
|
||||
final int platformData;
|
||||
|
||||
/// For events with signalKind of PointerSignalKind.scroll:
|
||||
///
|
||||
/// The amount to scroll in the x direction, in physical pixels.
|
||||
final double scrollDeltaX;
|
||||
|
||||
/// For events with signalKind of PointerSignalKind.scroll:
|
||||
///
|
||||
/// The amount to scroll in the y direction, in physical pixels.
|
||||
final double scrollDeltaY;
|
||||
|
||||
@override
|
||||
String toString() => '$runtimeType(x: $physicalX, y: $physicalY)';
|
||||
|
||||
/// Returns a complete textual description of the information in this object.
|
||||
String toStringFull() {
|
||||
return '$runtimeType('
|
||||
'timeStamp: $timeStamp, '
|
||||
'change: $change, '
|
||||
'kind: $kind, '
|
||||
'signalKind: $signalKind, '
|
||||
'device: $device, '
|
||||
'physicalX: $physicalX, '
|
||||
'physicalY: $physicalY, '
|
||||
'buttons: $buttons, '
|
||||
'pressure: $pressure, '
|
||||
'pressureMin: $pressureMin, '
|
||||
'pressureMax: $pressureMax, '
|
||||
'distance: $distance, '
|
||||
'distanceMax: $distanceMax, '
|
||||
'size: $size, '
|
||||
'radiusMajor: $radiusMajor, '
|
||||
'radiusMinor: $radiusMinor, '
|
||||
'radiusMin: $radiusMin, '
|
||||
'radiusMax: $radiusMax, '
|
||||
'orientation: $orientation, '
|
||||
'tilt: $tilt, '
|
||||
'platformData: $platformData, '
|
||||
'scrollDeltaX: $scrollDeltaX, '
|
||||
'scrollDeltaY: $scrollDeltaY'
|
||||
')';
|
||||
}
|
||||
}
|
||||
|
||||
/// A sequence of reports about the state of pointers.
|
||||
class PointerDataPacket {
|
||||
/// Creates a packet of pointer data reports.
|
||||
const PointerDataPacket({this.data = const <PointerData>[]});
|
||||
|
||||
/// Data about the individual pointers in this packet.
|
||||
///
|
||||
/// This list might contain multiple pieces of data about the same pointer.
|
||||
final List<PointerData> data;
|
||||
}
|
||||
734
engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart
Normal file
734
engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart
Normal file
@@ -0,0 +1,734 @@
|
||||
// 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 ui;
|
||||
|
||||
/// The possible actions that can be conveyed from the operating system
|
||||
/// accessibility APIs to a semantics node.
|
||||
class SemanticsAction {
|
||||
const SemanticsAction._(this.index);
|
||||
|
||||
static const int _kTapIndex = 1 << 0;
|
||||
static const int _kLongPressIndex = 1 << 1;
|
||||
static const int _kScrollLeftIndex = 1 << 2;
|
||||
static const int _kScrollRightIndex = 1 << 3;
|
||||
static const int _kScrollUpIndex = 1 << 4;
|
||||
static const int _kScrollDownIndex = 1 << 5;
|
||||
static const int _kIncreaseIndex = 1 << 6;
|
||||
static const int _kDecreaseIndex = 1 << 7;
|
||||
static const int _kShowOnScreenIndex = 1 << 8;
|
||||
static const int _kMoveCursorForwardByCharacterIndex = 1 << 9;
|
||||
static const int _kMoveCursorBackwardByCharacterIndex = 1 << 10;
|
||||
static const int _kSetSelectionIndex = 1 << 11;
|
||||
static const int _kCopyIndex = 1 << 12;
|
||||
static const int _kCutIndex = 1 << 13;
|
||||
static const int _kPasteIndex = 1 << 14;
|
||||
static const int _kDidGainAccessibilityFocusIndex = 1 << 15;
|
||||
static const int _kDidLoseAccessibilityFocusIndex = 1 << 16;
|
||||
static const int _kCustomAction = 1 << 17;
|
||||
static const int _kDismissIndex = 1 << 18;
|
||||
static const int _kMoveCursorForwardByWordIndex = 1 << 19;
|
||||
static const int _kMoveCursorBackwardByWordIndex = 1 << 20;
|
||||
|
||||
/// The numerical value for this action.
|
||||
///
|
||||
/// Each action has one bit set in this bit field.
|
||||
final int index;
|
||||
|
||||
/// The equivalent of a user briefly tapping the screen with the finger
|
||||
/// without moving it.
|
||||
static const SemanticsAction tap = SemanticsAction._(_kTapIndex);
|
||||
|
||||
/// The equivalent of a user pressing and holding the screen with the finger
|
||||
/// for a few seconds without moving it.
|
||||
static const SemanticsAction longPress = SemanticsAction._(_kLongPressIndex);
|
||||
|
||||
/// The equivalent of a user moving their finger across the screen from right
|
||||
/// to left.
|
||||
///
|
||||
/// This action should be recognized by controls that are horizontally
|
||||
/// scrollable.
|
||||
static const SemanticsAction scrollLeft =
|
||||
SemanticsAction._(_kScrollLeftIndex);
|
||||
|
||||
/// The equivalent of a user moving their finger across the screen from left
|
||||
/// to right.
|
||||
///
|
||||
/// This action should be recognized by controls that are horizontally
|
||||
/// scrollable.
|
||||
static const SemanticsAction scrollRight =
|
||||
SemanticsAction._(_kScrollRightIndex);
|
||||
|
||||
/// The equivalent of a user moving their finger across the screen from
|
||||
/// bottom to top.
|
||||
///
|
||||
/// This action should be recognized by controls that are vertically
|
||||
/// scrollable.
|
||||
static const SemanticsAction scrollUp = SemanticsAction._(_kScrollUpIndex);
|
||||
|
||||
/// The equivalent of a user moving their finger across the screen from top
|
||||
/// to bottom.
|
||||
///
|
||||
/// This action should be recognized by controls that are vertically
|
||||
/// scrollable.
|
||||
static const SemanticsAction scrollDown =
|
||||
SemanticsAction._(_kScrollDownIndex);
|
||||
|
||||
/// A request to increase the value represented by the semantics node.
|
||||
///
|
||||
/// For example, this action might be recognized by a slider control.
|
||||
static const SemanticsAction increase = SemanticsAction._(_kIncreaseIndex);
|
||||
|
||||
/// A request to decrease the value represented by the semantics node.
|
||||
///
|
||||
/// For example, this action might be recognized by a slider control.
|
||||
static const SemanticsAction decrease = SemanticsAction._(_kDecreaseIndex);
|
||||
|
||||
/// A request to fully show the semantics node on screen.
|
||||
///
|
||||
/// For example, this action might be send to a node in a scrollable list that
|
||||
/// is partially off screen to bring it on screen.
|
||||
static const SemanticsAction showOnScreen =
|
||||
SemanticsAction._(_kShowOnScreenIndex);
|
||||
|
||||
/// Move the cursor forward by one character.
|
||||
///
|
||||
/// This is for example used by the cursor control in text fields.
|
||||
///
|
||||
/// The action includes a boolean argument, which indicates whether the cursor
|
||||
/// movement should extend (or start) a selection.
|
||||
static const SemanticsAction moveCursorForwardByCharacter =
|
||||
SemanticsAction._(_kMoveCursorForwardByCharacterIndex);
|
||||
|
||||
/// Move the cursor backward by one character.
|
||||
///
|
||||
/// This is for example used by the cursor control in text fields.
|
||||
///
|
||||
/// The action includes a boolean argument, which indicates whether the cursor
|
||||
/// movement should extend (or start) a selection.
|
||||
static const SemanticsAction moveCursorBackwardByCharacter =
|
||||
SemanticsAction._(_kMoveCursorBackwardByCharacterIndex);
|
||||
|
||||
/// Set the text selection to the given range.
|
||||
///
|
||||
/// The provided argument is a Map<String, int> which includes the keys `base`
|
||||
/// and `extent` indicating where the selection within the `value` of the
|
||||
/// semantics node should start and where it should end. Values for both
|
||||
/// keys can range from 0 to length of `value` (inclusive).
|
||||
///
|
||||
/// Setting `base` and `extent` to the same value will move the cursor to
|
||||
/// that position (without selecting anything).
|
||||
static const SemanticsAction setSelection =
|
||||
SemanticsAction._(_kSetSelectionIndex);
|
||||
|
||||
/// Copy the current selection to the clipboard.
|
||||
static const SemanticsAction copy = SemanticsAction._(_kCopyIndex);
|
||||
|
||||
/// Cut the current selection and place it in the clipboard.
|
||||
static const SemanticsAction cut = SemanticsAction._(_kCutIndex);
|
||||
|
||||
/// Paste the current content of the clipboard.
|
||||
static const SemanticsAction paste = SemanticsAction._(_kPasteIndex);
|
||||
|
||||
/// Indicates that the nodes has gained accessibility focus.
|
||||
///
|
||||
/// This handler is invoked when the node annotated with this handler gains
|
||||
/// the accessibility focus. The accessibility focus is the
|
||||
/// green (on Android with TalkBack) or black (on iOS with VoiceOver)
|
||||
/// rectangle shown on screen to indicate what element an accessibility
|
||||
/// user is currently interacting with.
|
||||
///
|
||||
/// The accessibility focus is different from the input focus. The input focus
|
||||
/// is usually held by the element that currently responds to keyboard inputs.
|
||||
/// Accessibility focus and input focus can be held by two different nodes!
|
||||
static const SemanticsAction didGainAccessibilityFocus =
|
||||
SemanticsAction._(_kDidGainAccessibilityFocusIndex);
|
||||
|
||||
/// Indicates that the nodes has lost accessibility focus.
|
||||
///
|
||||
/// This handler is invoked when the node annotated with this handler
|
||||
/// loses the accessibility focus. The accessibility focus is
|
||||
/// the green (on Android with TalkBack) or black (on iOS with VoiceOver)
|
||||
/// rectangle shown on screen to indicate what element an accessibility
|
||||
/// user is currently interacting with.
|
||||
///
|
||||
/// The accessibility focus is different from the input focus. The input focus
|
||||
/// is usually held by the element that currently responds to keyboard inputs.
|
||||
/// Accessibility focus and input focus can be held by two different nodes!
|
||||
static const SemanticsAction didLoseAccessibilityFocus =
|
||||
SemanticsAction._(_kDidLoseAccessibilityFocusIndex);
|
||||
|
||||
/// Indicates that the user has invoked a custom accessibility action.
|
||||
///
|
||||
/// This handler is added automatically whenever a custom accessibility
|
||||
/// action is added to a semantics node.
|
||||
static const SemanticsAction customAction = SemanticsAction._(_kCustomAction);
|
||||
|
||||
/// A request that the node should be dismissed.
|
||||
///
|
||||
/// A [Snackbar], for example, may have a dismiss action to indicate to the
|
||||
/// user that it can be removed after it is no longer relevant. On Android,
|
||||
/// (with TalkBack) special hint text is spoken when focusing the node and
|
||||
/// a custom action is availible in the local context menu. On iOS,
|
||||
/// (with VoiceOver) users can perform a standard gesture to dismiss it.
|
||||
static const SemanticsAction dismiss = SemanticsAction._(_kDismissIndex);
|
||||
|
||||
/// Move the cursor forward by one word.
|
||||
///
|
||||
/// This is for example used by the cursor control in text fields.
|
||||
///
|
||||
/// The action includes a boolean argument, which indicates whether the cursor
|
||||
/// movement should extend (or start) a selection.
|
||||
static const SemanticsAction moveCursorForwardByWord =
|
||||
SemanticsAction._(_kMoveCursorForwardByWordIndex);
|
||||
|
||||
/// Move the cursor backward by one word.
|
||||
///
|
||||
/// This is for example used by the cursor control in text fields.
|
||||
///
|
||||
/// The action includes a boolean argument, which indicates whether the cursor
|
||||
/// movement should extend (or start) a selection.
|
||||
static const SemanticsAction moveCursorBackwardByWord =
|
||||
SemanticsAction._(_kMoveCursorBackwardByWordIndex);
|
||||
|
||||
/// The possible semantics actions.
|
||||
///
|
||||
/// The map's key is the [index] of the action and the value is the action
|
||||
/// itself.
|
||||
static const Map<int, SemanticsAction> values = <int, SemanticsAction>{
|
||||
_kTapIndex: tap,
|
||||
_kLongPressIndex: longPress,
|
||||
_kScrollLeftIndex: scrollLeft,
|
||||
_kScrollRightIndex: scrollRight,
|
||||
_kScrollUpIndex: scrollUp,
|
||||
_kScrollDownIndex: scrollDown,
|
||||
_kIncreaseIndex: increase,
|
||||
_kDecreaseIndex: decrease,
|
||||
_kShowOnScreenIndex: showOnScreen,
|
||||
_kMoveCursorForwardByCharacterIndex: moveCursorForwardByCharacter,
|
||||
_kMoveCursorBackwardByCharacterIndex: moveCursorBackwardByCharacter,
|
||||
_kSetSelectionIndex: setSelection,
|
||||
_kCopyIndex: copy,
|
||||
_kCutIndex: cut,
|
||||
_kPasteIndex: paste,
|
||||
_kDidGainAccessibilityFocusIndex: didGainAccessibilityFocus,
|
||||
_kDidLoseAccessibilityFocusIndex: didLoseAccessibilityFocus,
|
||||
_kCustomAction: customAction,
|
||||
_kDismissIndex: dismiss,
|
||||
_kMoveCursorForwardByWordIndex: moveCursorForwardByWord,
|
||||
_kMoveCursorBackwardByWordIndex: moveCursorBackwardByWord,
|
||||
};
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
switch (index) {
|
||||
case _kTapIndex:
|
||||
return 'SemanticsAction.tap';
|
||||
case _kLongPressIndex:
|
||||
return 'SemanticsAction.longPress';
|
||||
case _kScrollLeftIndex:
|
||||
return 'SemanticsAction.scrollLeft';
|
||||
case _kScrollRightIndex:
|
||||
return 'SemanticsAction.scrollRight';
|
||||
case _kScrollUpIndex:
|
||||
return 'SemanticsAction.scrollUp';
|
||||
case _kScrollDownIndex:
|
||||
return 'SemanticsAction.scrollDown';
|
||||
case _kIncreaseIndex:
|
||||
return 'SemanticsAction.increase';
|
||||
case _kDecreaseIndex:
|
||||
return 'SemanticsAction.decrease';
|
||||
case _kShowOnScreenIndex:
|
||||
return 'SemanticsAction.showOnScreen';
|
||||
case _kMoveCursorForwardByCharacterIndex:
|
||||
return 'SemanticsAction.moveCursorForwardByCharacter';
|
||||
case _kMoveCursorBackwardByCharacterIndex:
|
||||
return 'SemanticsAction.moveCursorBackwardByCharacter';
|
||||
case _kSetSelectionIndex:
|
||||
return 'SemanticsAction.setSelection';
|
||||
case _kCopyIndex:
|
||||
return 'SemanticsAction.copy';
|
||||
case _kCutIndex:
|
||||
return 'SemanticsAction.cut';
|
||||
case _kPasteIndex:
|
||||
return 'SemanticsAction.paste';
|
||||
case _kDidGainAccessibilityFocusIndex:
|
||||
return 'SemanticsAction.didGainAccessibilityFocus';
|
||||
case _kDidLoseAccessibilityFocusIndex:
|
||||
return 'SemanticsAction.didLoseAccessibilityFocus';
|
||||
case _kCustomAction:
|
||||
return 'SemanticsAction.customAction';
|
||||
case _kDismissIndex:
|
||||
return 'SemanticsAction.dismiss';
|
||||
case _kMoveCursorForwardByWordIndex:
|
||||
return 'SemanticsAction.moveCursorForwardByWord';
|
||||
case _kMoveCursorBackwardByWordIndex:
|
||||
return 'SemanticsAction.moveCursorBackwardByWord';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A Boolean value that can be associated with a semantics node.
|
||||
class SemanticsFlag {
|
||||
static const int _kHasCheckedStateIndex = 1 << 0;
|
||||
static const int _kIsCheckedIndex = 1 << 1;
|
||||
static const int _kIsSelectedIndex = 1 << 2;
|
||||
static const int _kIsButtonIndex = 1 << 3;
|
||||
static const int _kIsTextFieldIndex = 1 << 4;
|
||||
static const int _kIsFocusedIndex = 1 << 5;
|
||||
static const int _kHasEnabledStateIndex = 1 << 6;
|
||||
static const int _kIsEnabledIndex = 1 << 7;
|
||||
static const int _kIsInMutuallyExclusiveGroupIndex = 1 << 8;
|
||||
static const int _kIsHeaderIndex = 1 << 9;
|
||||
static const int _kIsObscuredIndex = 1 << 10;
|
||||
static const int _kScopesRouteIndex = 1 << 11;
|
||||
static const int _kNamesRouteIndex = 1 << 12;
|
||||
static const int _kIsHiddenIndex = 1 << 13;
|
||||
static const int _kIsImageIndex = 1 << 14;
|
||||
static const int _kIsLiveRegionIndex = 1 << 15;
|
||||
static const int _kHasToggledStateIndex = 1 << 16;
|
||||
static const int _kIsToggledIndex = 1 << 17;
|
||||
static const int _kHasImplicitScrollingIndex = 1 << 18;
|
||||
static const int _kIsMultilineIndex = 1 << 19;
|
||||
static const int _kIsReadOnlyIndex = 1 << 20;
|
||||
|
||||
const SemanticsFlag._(this.index);
|
||||
|
||||
/// The numerical value for this flag.
|
||||
///
|
||||
/// Each flag has one bit set in this bit field.
|
||||
final int index;
|
||||
|
||||
/// The semantics node has the quality of either being "checked" or "unchecked".
|
||||
///
|
||||
/// This flag is mutually exclusive with [hasToggledState].
|
||||
///
|
||||
/// For example, a checkbox or a radio button widget has checked state.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [SemanticsFlag.isChecked], which controls whether the node is "checked" or "unchecked".
|
||||
static const SemanticsFlag hasCheckedState =
|
||||
SemanticsFlag._(_kHasCheckedStateIndex);
|
||||
|
||||
/// Whether a semantics node that [hasCheckedState] is checked.
|
||||
///
|
||||
/// If true, the semantics node is "checked". If false, the semantics node is
|
||||
/// "unchecked".
|
||||
///
|
||||
/// For example, if a checkbox has a visible checkmark, [isChecked] is true.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [SemanticsFlag.hasCheckedState], which enables a checked state.
|
||||
static const SemanticsFlag isChecked = SemanticsFlag._(_kIsCheckedIndex);
|
||||
|
||||
/// Whether a semantics node is selected.
|
||||
///
|
||||
/// If true, the semantics node is "selected". If false, the semantics node is
|
||||
/// "unselected".
|
||||
///
|
||||
/// For example, the active tab in a tab bar has [isSelected] set to true.
|
||||
static const SemanticsFlag isSelected = SemanticsFlag._(_kIsSelectedIndex);
|
||||
|
||||
/// Whether the semantic node represents a button.
|
||||
///
|
||||
/// Platforms has special handling for buttons, for example Android's TalkBack
|
||||
/// and iOS's VoiceOver provides an additional hint when the focused object is
|
||||
/// a button.
|
||||
static const SemanticsFlag isButton = SemanticsFlag._(_kIsButtonIndex);
|
||||
|
||||
/// Whether the semantic node represents a text field.
|
||||
///
|
||||
/// Text fields are announced as such and allow text input via accessibility
|
||||
/// affordances.
|
||||
static const SemanticsFlag isTextField = SemanticsFlag._(_kIsTextFieldIndex);
|
||||
|
||||
/// Whether the semantic node currently holds the user's focus.
|
||||
///
|
||||
/// The focused element is usually the current receiver of keyboard inputs.
|
||||
static const SemanticsFlag isFocused = SemanticsFlag._(_kIsFocusedIndex);
|
||||
|
||||
/// The semantics node has the quality of either being "enabled" or
|
||||
/// "disabled".
|
||||
///
|
||||
/// For example, a button can be enabled or disabled and therefore has an
|
||||
/// "enabled" state. Static text is usually neither enabled nor disabled and
|
||||
/// therefore does not have an "enabled" state.
|
||||
static const SemanticsFlag hasEnabledState =
|
||||
SemanticsFlag._(_kHasEnabledStateIndex);
|
||||
|
||||
/// Whether the semantic node is read only.
|
||||
///
|
||||
/// Only applicable when [isTextField] is true.
|
||||
static const SemanticsFlag isReadOnly =
|
||||
const SemanticsFlag._(_kIsReadOnlyIndex);
|
||||
|
||||
/// Whether a semantic node that [hasEnabledState] is currently enabled.
|
||||
///
|
||||
/// A disabled element does not respond to user interaction. For example, a
|
||||
/// button that currently does not respond to user interaction should be
|
||||
/// marked as disabled.
|
||||
static const SemanticsFlag isEnabled = SemanticsFlag._(_kIsEnabledIndex);
|
||||
|
||||
/// Whether a semantic node is in a mutually exclusive group.
|
||||
///
|
||||
/// For example, a radio button is in a mutually exclusive group because
|
||||
/// only one radio button in that group can be marked as [isChecked].
|
||||
static const SemanticsFlag isInMutuallyExclusiveGroup =
|
||||
SemanticsFlag._(_kIsInMutuallyExclusiveGroupIndex);
|
||||
|
||||
/// Whether a semantic node is a header that divides content into sections.
|
||||
///
|
||||
/// For example, headers can be used to divide a list of alphabetically
|
||||
/// sorted words into the sections A, B, C, etc. as can be found in many
|
||||
/// address book applications.
|
||||
static const SemanticsFlag isHeader = SemanticsFlag._(_kIsHeaderIndex);
|
||||
|
||||
/// Whether the value of the semantics node is obscured.
|
||||
///
|
||||
/// This is usually used for text fields to indicate that its content
|
||||
/// is a password or contains other sensitive information.
|
||||
static const SemanticsFlag isObscured = SemanticsFlag._(_kIsObscuredIndex);
|
||||
|
||||
/// Whether the semantics node is the root of a subtree for which a route name
|
||||
/// should be announced.
|
||||
///
|
||||
/// When a node with this flag is removed from the semantics tree, the
|
||||
/// framework will select the last in depth-first, paint order node with this
|
||||
/// flag. When a node with this flag is added to the semantics tree, it is
|
||||
/// selected automatically, unless there were multiple nodes with this flag
|
||||
/// added. In this case, the last added node in depth-first, paint order
|
||||
/// will be selected.
|
||||
///
|
||||
/// From this selected node, the framework will search in depth-first, paint
|
||||
/// order for the first node with a [namesRoute] flag and a non-null,
|
||||
/// non-empty label. The [namesRoute] and [scopesRoute] flags may be on the
|
||||
/// same node. The label of the found node will be announced as an edge
|
||||
/// transition. If no non-empty, non-null label is found then:
|
||||
///
|
||||
/// * VoiceOver will make a chime announcement.
|
||||
/// * TalkBack will make no announcement
|
||||
///
|
||||
/// Semantic nodes annotated with this flag are generally not a11y focusable.
|
||||
///
|
||||
/// This is used in widgets such as Routes, Drawers, and Dialogs to
|
||||
/// communicate significant changes in the visible screen.
|
||||
static const SemanticsFlag scopesRoute = SemanticsFlag._(_kScopesRouteIndex);
|
||||
|
||||
/// Whether the semantics node label is the name of a visually distinct
|
||||
/// route.
|
||||
///
|
||||
/// This is used by certain widgets like Drawers and Dialogs, to indicate
|
||||
/// that the node's semantic label can be used to announce an edge triggered
|
||||
/// semantics update.
|
||||
///
|
||||
/// Semantic nodes annotated with this flag will still recieve a11y focus.
|
||||
///
|
||||
/// Updating this label within the same active route subtree will not cause
|
||||
/// additional announcements.
|
||||
static const SemanticsFlag namesRoute = SemanticsFlag._(_kNamesRouteIndex);
|
||||
|
||||
/// Whether the semantics node is considered hidden.
|
||||
///
|
||||
/// Hidden elements are currently not visible on screen. They may be covered
|
||||
/// by other elements or positioned outside of the visible area of a viewport.
|
||||
///
|
||||
/// Hidden elements cannot gain accessibility focus though regular touch. The
|
||||
/// only way they can be focused is by moving the focus to them via linear
|
||||
/// navigation.
|
||||
///
|
||||
/// Platforms are free to completely ignore hidden elements and new platforms
|
||||
/// are encouraged to do so.
|
||||
///
|
||||
/// Instead of marking an element as hidden it should usually be excluded from
|
||||
/// the semantics tree altogether. Hidden elements are only included in the
|
||||
/// semantics tree to work around platform limitations and they are mainly
|
||||
/// used to implement accessibility scrolling on iOS.
|
||||
static const SemanticsFlag isHidden = SemanticsFlag._(_kIsHiddenIndex);
|
||||
|
||||
/// Whether the semantics node represents an image.
|
||||
///
|
||||
/// Both TalkBack and VoiceOver will inform the user the the semantics node
|
||||
/// represents an image.
|
||||
static const SemanticsFlag isImage = SemanticsFlag._(_kIsImageIndex);
|
||||
|
||||
/// Whether the semantics node is a live region.
|
||||
///
|
||||
/// A live region indicates that updates to semantics node are important.
|
||||
/// Platforms may use this information to make polite announcements to the
|
||||
/// user to inform them of updates to this node.
|
||||
///
|
||||
/// An example of a live region is a [SnackBar] widget. On Android, A live
|
||||
/// region causes a polite announcement to be generated automatically, even
|
||||
/// if the user does not have focus of the widget.
|
||||
static const SemanticsFlag isLiveRegion =
|
||||
SemanticsFlag._(_kIsLiveRegionIndex);
|
||||
|
||||
/// The semantics node has the quality of either being "on" or "off".
|
||||
///
|
||||
/// This flag is mutually exclusive with [hasCheckedState].
|
||||
///
|
||||
/// For example, a switch has toggled state.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [SemanticsFlag.isToggled], which controls whether the node is "on" or "off".
|
||||
static const SemanticsFlag hasToggledState =
|
||||
SemanticsFlag._(_kHasToggledStateIndex);
|
||||
|
||||
/// If true, the semantics node is "on". If false, the semantics node is
|
||||
/// "off".
|
||||
///
|
||||
/// For example, if a switch is in the on position, [isToggled] is true.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [SemanticsFlag.hasToggledState], which enables a toggled state.
|
||||
static const SemanticsFlag isToggled = SemanticsFlag._(_kIsToggledIndex);
|
||||
|
||||
/// Whether the platform can scroll the semantics node when the user attempts
|
||||
/// to move focus to an offscreen child.
|
||||
///
|
||||
/// For example, a [ListView] widget has implicit scrolling so that users can
|
||||
/// easily move to the next visible set of children. A [TabBar] widget does
|
||||
/// not have implicit scrolling, so that users can navigate into the tab
|
||||
/// body when reaching the end of the tab bar.
|
||||
static const SemanticsFlag hasImplicitScrolling =
|
||||
SemanticsFlag._(_kHasImplicitScrollingIndex);
|
||||
|
||||
/// Whether the value of the semantics node is coming from a multi-line text
|
||||
/// field.
|
||||
///
|
||||
/// This isused for text fields to distinguish single-line text field from
|
||||
/// multi-line ones.
|
||||
static const SemanticsFlag isMultiline = SemanticsFlag._(_kIsMultilineIndex);
|
||||
|
||||
/// The possible semantics flags.
|
||||
///
|
||||
/// The map's key is the [index] of the flag and the value is the flag itself.
|
||||
static const Map<int, SemanticsFlag> values = <int, SemanticsFlag>{
|
||||
_kHasCheckedStateIndex: hasCheckedState,
|
||||
_kIsCheckedIndex: isChecked,
|
||||
_kIsSelectedIndex: isSelected,
|
||||
_kIsButtonIndex: isButton,
|
||||
_kIsTextFieldIndex: isTextField,
|
||||
_kIsFocusedIndex: isFocused,
|
||||
_kHasEnabledStateIndex: hasEnabledState,
|
||||
_kIsEnabledIndex: isEnabled,
|
||||
_kIsInMutuallyExclusiveGroupIndex: isInMutuallyExclusiveGroup,
|
||||
_kIsHeaderIndex: isHeader,
|
||||
_kIsObscuredIndex: isObscured,
|
||||
_kScopesRouteIndex: scopesRoute,
|
||||
_kNamesRouteIndex: namesRoute,
|
||||
_kIsHiddenIndex: isHidden,
|
||||
_kIsImageIndex: isImage,
|
||||
_kIsLiveRegionIndex: isLiveRegion,
|
||||
_kHasToggledStateIndex: hasToggledState,
|
||||
_kIsToggledIndex: isToggled,
|
||||
_kHasImplicitScrollingIndex: hasImplicitScrolling,
|
||||
_kIsMultilineIndex: isMultiline,
|
||||
};
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
switch (index) {
|
||||
case _kHasCheckedStateIndex:
|
||||
return 'SemanticsFlag.hasCheckedState';
|
||||
case _kIsCheckedIndex:
|
||||
return 'SemanticsFlag.isChecked';
|
||||
case _kIsSelectedIndex:
|
||||
return 'SemanticsFlag.isSelected';
|
||||
case _kIsButtonIndex:
|
||||
return 'SemanticsFlag.isButton';
|
||||
case _kIsTextFieldIndex:
|
||||
return 'SemanticsFlag.isTextField';
|
||||
case _kIsFocusedIndex:
|
||||
return 'SemanticsFlag.isFocused';
|
||||
case _kHasEnabledStateIndex:
|
||||
return 'SemanticsFlag.hasEnabledState';
|
||||
case _kIsEnabledIndex:
|
||||
return 'SemanticsFlag.isEnabled';
|
||||
case _kIsInMutuallyExclusiveGroupIndex:
|
||||
return 'SemanticsFlag.isInMutuallyExclusiveGroup';
|
||||
case _kIsHeaderIndex:
|
||||
return 'SemanticsFlag.isHeader';
|
||||
case _kIsObscuredIndex:
|
||||
return 'SemanticsFlag.isObscured';
|
||||
case _kScopesRouteIndex:
|
||||
return 'SemanticsFlag.scopesRoute';
|
||||
case _kNamesRouteIndex:
|
||||
return 'SemanticsFlag.namesRoute';
|
||||
case _kIsHiddenIndex:
|
||||
return 'SemanticsFlag.isHidden';
|
||||
case _kIsImageIndex:
|
||||
return 'SemanticsFlag.isImage';
|
||||
case _kIsLiveRegionIndex:
|
||||
return 'SemanticsFlag.isLiveRegion';
|
||||
case _kHasToggledStateIndex:
|
||||
return 'SemanticsFlag.hasToggledState';
|
||||
case _kIsToggledIndex:
|
||||
return 'SemanticsFlag.isToggled';
|
||||
case _kHasImplicitScrollingIndex:
|
||||
return 'SemanticsFlag.hasImplicitScrolling';
|
||||
case _kIsMultilineIndex:
|
||||
return 'SemanticsFlag.isMultiline';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// An object that creates [SemanticsUpdate] objects.
|
||||
///
|
||||
/// Once created, the [SemanticsUpdate] objects can be passed to
|
||||
/// [Window.updateSemantics] to update the semantics conveyed to the user.
|
||||
class SemanticsUpdateBuilder {
|
||||
/// Creates an empty [SemanticsUpdateBuilder] object.
|
||||
SemanticsUpdateBuilder();
|
||||
|
||||
final List<engine.SemanticsNodeUpdate> _nodeUpdates =
|
||||
<engine.SemanticsNodeUpdate>[];
|
||||
|
||||
/// Update the information associated with the node with the given `id`.
|
||||
///
|
||||
/// The semantics nodes form a tree, with the root of the tree always having
|
||||
/// an id of zero. The `childrenInTraversalOrder` and `childrenInHitTestOrder`
|
||||
/// are the ids of the nodes that are immediate children of this node. The
|
||||
/// former enumerates children in traversal order, and the latter enumerates
|
||||
/// the same children in the hit test order. The two lists must have the same
|
||||
/// length and contain the same ids. They may only differ in the order the
|
||||
/// ids are listed in. For more information about different child orders, see
|
||||
/// [DebugSemanticsDumpOrder].
|
||||
///
|
||||
/// The system retains the nodes that are currently reachable from the root.
|
||||
/// A given update need not contain information for nodes that do not change
|
||||
/// in the update. If a node is not reachable from the root after an update,
|
||||
/// the node will be discarded from the tree.
|
||||
///
|
||||
/// The `flags` are a bit field of [SemanticsFlag]s that apply to this node.
|
||||
///
|
||||
/// The `actions` are a bit field of [SemanticsAction]s that can be undertaken
|
||||
/// by this node. If the user wishes to undertake one of these actions on this
|
||||
/// node, the [Window.onSemanticsAction] will be called with `id` and one of
|
||||
/// the possible [SemanticsAction]s. Because the semantics tree is maintained
|
||||
/// asynchronously, the [Window.onSemanticsAction] callback might be called
|
||||
/// with an action that is no longer possible.
|
||||
///
|
||||
/// The `label` is a string that describes this node. The `value` property
|
||||
/// describes the current value of the node as a string. The `increasedValue`
|
||||
/// string will become the `value` string after a [SemanticsAction.increase]
|
||||
/// action is performed. The `decreasedValue` string will become the `value`
|
||||
/// string after a [SemanticsAction.decrease] action is performed. The `hint`
|
||||
/// string describes what result an action performed on this node has. The
|
||||
/// reading direction of all these strings is given by `textDirection`.
|
||||
///
|
||||
/// The fields 'textSelectionBase' and 'textSelectionExtent' describe the
|
||||
/// currently selected text within `value`.
|
||||
///
|
||||
/// For scrollable nodes `scrollPosition` describes the current scroll
|
||||
/// position in logical pixel. `scrollExtentMax` and `scrollExtentMin`
|
||||
/// describe the maximum and minimum in-rage values that `scrollPosition` can
|
||||
/// be. Both or either may be infinity to indicate unbound scrolling. The
|
||||
/// value for `scrollPosition` can (temporarily) be outside this range, for
|
||||
/// example during an overscroll.
|
||||
///
|
||||
/// The `rect` is the region occupied by this node in its own coordinate
|
||||
/// system.
|
||||
///
|
||||
/// The `transform` is a matrix that maps this node's coordinate system into
|
||||
/// its parent's coordinate system.
|
||||
void updateNode({
|
||||
int id,
|
||||
int flags,
|
||||
int actions,
|
||||
int textSelectionBase,
|
||||
int textSelectionExtent,
|
||||
int platformViewId,
|
||||
int scrollChildren,
|
||||
int scrollIndex,
|
||||
double scrollPosition,
|
||||
double scrollExtentMax,
|
||||
double scrollExtentMin,
|
||||
double elevation,
|
||||
double thickness,
|
||||
Rect rect,
|
||||
String label,
|
||||
String hint,
|
||||
String value,
|
||||
String increasedValue,
|
||||
String decreasedValue,
|
||||
TextDirection textDirection,
|
||||
Float64List transform,
|
||||
Int32List childrenInTraversalOrder,
|
||||
Int32List childrenInHitTestOrder,
|
||||
Int32List additionalActions,
|
||||
}) {
|
||||
if (transform.length != 16)
|
||||
throw ArgumentError('transform argument must have 16 entries.');
|
||||
_nodeUpdates.add(engine.SemanticsNodeUpdate(
|
||||
id: id,
|
||||
flags: flags,
|
||||
actions: actions,
|
||||
textSelectionBase: textSelectionBase,
|
||||
textSelectionExtent: textSelectionExtent,
|
||||
scrollChildren: scrollChildren,
|
||||
scrollIndex: scrollIndex,
|
||||
scrollPosition: scrollPosition,
|
||||
scrollExtentMax: scrollExtentMax,
|
||||
scrollExtentMin: scrollExtentMin,
|
||||
rect: rect,
|
||||
label: label,
|
||||
hint: hint,
|
||||
value: value,
|
||||
increasedValue: increasedValue,
|
||||
decreasedValue: decreasedValue,
|
||||
textDirection: textDirection,
|
||||
transform: transform,
|
||||
elevation: elevation,
|
||||
thickness: thickness,
|
||||
childrenInTraversalOrder: childrenInTraversalOrder,
|
||||
childrenInHitTestOrder: childrenInHitTestOrder,
|
||||
additionalActions: additionalActions,
|
||||
platformViewId: platformViewId,
|
||||
));
|
||||
}
|
||||
|
||||
void updateCustomAction(
|
||||
{int id, String label, String hint, int overrideId = -1}) {
|
||||
// TODO(yjbanov): implement.
|
||||
}
|
||||
|
||||
/// Creates a [SemanticsUpdate] object that encapsulates the updates recorded
|
||||
/// by this object.
|
||||
///
|
||||
/// The returned object can be passed to [Window.updateSemantics] to actually
|
||||
/// update the semantics retained by the system.
|
||||
SemanticsUpdate build() {
|
||||
return SemanticsUpdate._(
|
||||
nodeUpdates: _nodeUpdates,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque object representing a batch of semantics updates.
|
||||
///
|
||||
/// To create a SemanticsUpdate object, use a [SemanticsUpdateBuilder].
|
||||
///
|
||||
/// Semantics updates can be applied to the system's retained semantics tree
|
||||
/// using the [Window.updateSemantics] method.
|
||||
abstract class SemanticsUpdate {
|
||||
/// This class is created by the engine, and should not be instantiated
|
||||
/// or extended directly.
|
||||
///
|
||||
/// To create a SemanticsUpdate object, use a [SemanticsUpdateBuilder].
|
||||
factory SemanticsUpdate._({List<engine.SemanticsNodeUpdate> nodeUpdates}) =
|
||||
engine.SemanticsUpdate;
|
||||
|
||||
/// Releases the resources used by this semantics update.
|
||||
///
|
||||
/// After calling this function, the semantics update is cannot be used
|
||||
/// further.
|
||||
void dispose();
|
||||
}
|
||||
61
engine/src/flutter/lib/web_ui/lib/src/ui/test_embedding.dart
Normal file
61
engine/src/flutter/lib/web_ui/lib/src/ui/test_embedding.dart
Normal file
@@ -0,0 +1,61 @@
|
||||
// Copyright 2013 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
// TODO(flutter_web): the Web-only API below need to be cleaned up.
|
||||
|
||||
part of ui;
|
||||
|
||||
/// Used to track when the platform is initialized. This ensures the test fonts
|
||||
/// are available.
|
||||
Future<void> _testPlatformInitializedFuture;
|
||||
|
||||
/// If the platform is already initialized (by a previous test), then run the test
|
||||
/// body immediately. Otherwise, initialize the platform then run the test.
|
||||
Future<dynamic> ensureTestPlatformInitializedThenRunTest(
|
||||
dynamic Function() body) {
|
||||
if (_testPlatformInitializedFuture == null) {
|
||||
debugEmulateFlutterTesterEnvironment = true;
|
||||
|
||||
// Initializing the platform will ensure that the test font is loaded.
|
||||
_testPlatformInitializedFuture = webOnlyInitializePlatform(
|
||||
assetManager: engine.WebOnlyMockAssetManager());
|
||||
}
|
||||
return _testPlatformInitializedFuture.then<dynamic>((_) => body());
|
||||
}
|
||||
|
||||
/// This setter is used by [WebNavigatorObserver] to update the url to
|
||||
/// reflect the [Navigator]'s current route name.
|
||||
set webOnlyRouteName(String routeName) {
|
||||
engine.window.webOnlyRouteName = routeName;
|
||||
}
|
||||
|
||||
/// Used to track when the platform is initialized. This ensures the test fonts
|
||||
/// are available.
|
||||
Future<void> _platformInitializedFuture;
|
||||
|
||||
/// Initializes domRenderer with specific devicePixelRation and physicalSize.
|
||||
Future<void> webOnlyInitializeTestDomRenderer({double devicePixelRatio = 3.0}) {
|
||||
// Force-initialize DomRenderer so it doesn't overwrite test pixel ratio.
|
||||
engine.domRenderer;
|
||||
|
||||
// The following parameters are hard-coded in Flutter's test embedder. Since
|
||||
// we don't have an embedder yet this is the lowest-most layer we can put
|
||||
// this stuff in.
|
||||
engine.window.debugOverrideDevicePixelRatio(devicePixelRatio);
|
||||
engine.window.webOnlyDebugPhysicalSizeOverride =
|
||||
Size(800 * devicePixelRatio, 600 * devicePixelRatio);
|
||||
webOnlyScheduleFrameCallback = () {};
|
||||
debugEmulateFlutterTesterEnvironment = true;
|
||||
|
||||
if (_platformInitializedFuture != null) {
|
||||
return _platformInitializedFuture;
|
||||
}
|
||||
|
||||
// Only load the Ahem font once and await the same future in all tests.
|
||||
return _platformInitializedFuture =
|
||||
webOnlyInitializePlatform(assetManager: engine.WebOnlyMockAssetManager())
|
||||
.timeout(const Duration(seconds: 2), onTimeout: () async {
|
||||
throw Exception('Timed out loading Ahem font.');
|
||||
});
|
||||
}
|
||||
1236
engine/src/flutter/lib/web_ui/lib/src/ui/text.dart
Normal file
1236
engine/src/flutter/lib/web_ui/lib/src/ui/text.dart
Normal file
File diff suppressed because it is too large
Load Diff
56
engine/src/flutter/lib/web_ui/lib/src/ui/tile_mode.dart
Normal file
56
engine/src/flutter/lib/web_ui/lib/src/ui/tile_mode.dart
Normal file
@@ -0,0 +1,56 @@
|
||||
// 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 ui;
|
||||
|
||||
/// Defines what happens at the edge of the gradient.
|
||||
///
|
||||
/// A gradient is defined along a finite inner area. In the case of a linear
|
||||
/// gradient, it's between the parallel lines that are orthogonal to the line
|
||||
/// drawn between two points. In the case of radial gradients, it's the disc
|
||||
/// that covers the circle centered on a particular point up to a given radius.
|
||||
///
|
||||
/// This enum is used to define how the gradient should paint the regions
|
||||
/// outside that defined inner area.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [painting.Gradient], the superclass for [LinearGradient] and
|
||||
/// [RadialGradient], as used by [BoxDecoration] et al, which works in
|
||||
/// relative coordinates and can create a [Shader] representing the gradient
|
||||
/// for a particular [Rect] on demand.
|
||||
/// * [dart:ui.Gradient], the low-level class used when dealing with the
|
||||
/// [Paint.shader] property directly, with its [new Gradient.linear] and [new
|
||||
/// Gradient.radial] constructors.
|
||||
// These enum values must be kept in sync with SkShader::TileMode.
|
||||
enum TileMode {
|
||||
/// Edge is clamped to the final color.
|
||||
///
|
||||
/// The gradient will paint the all the regions outside the inner area with
|
||||
/// the color of the point closest to that region.
|
||||
///
|
||||
/// 
|
||||
clamp,
|
||||
|
||||
/// Edge is repeated from first color to last.
|
||||
///
|
||||
/// This is as if the stop points from 0.0 to 1.0 were then repeated from 1.0
|
||||
/// to 2.0, 2.0 to 3.0, and so forth (and for linear gradients, similarly from
|
||||
/// -1.0 to 0.0, -2.0 to -1.0, etc).
|
||||
///
|
||||
/// 
|
||||
/// 
|
||||
repeated,
|
||||
|
||||
/// Edge is mirrored from last color to first.
|
||||
///
|
||||
/// This is as if the stop points from 0.0 to 1.0 were then repeated backwards
|
||||
/// from 2.0 to 1.0, then forwards from 2.0 to 3.0, then backwards again from
|
||||
/// 4.0 to 3.0, and so forth (and for linear gradients, similarly from in the
|
||||
/// negative direction).
|
||||
///
|
||||
/// 
|
||||
/// 
|
||||
mirror,
|
||||
}
|
||||
1230
engine/src/flutter/lib/web_ui/lib/src/ui/window.dart
Normal file
1230
engine/src/flutter/lib/web_ui/lib/src/ui/window.dart
Normal file
File diff suppressed because it is too large
Load Diff
41
engine/src/flutter/lib/web_ui/lib/ui.dart
Normal file
41
engine/src/flutter/lib/web_ui/lib/ui.dart
Normal file
@@ -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.
|
||||
|
||||
/// This library defines the web equivalent of the native dart:ui.
|
||||
///
|
||||
/// All types in this library are public.
|
||||
library ui;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:collection';
|
||||
import 'dart:html' as html;
|
||||
import 'dart:math' as math;
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'src/engine.dart' as engine;
|
||||
export 'src/engine.dart'
|
||||
show persistedPictureFactory, houdiniPictureFactory, platformViewRegistry;
|
||||
|
||||
part 'src/ui/canvas.dart';
|
||||
part 'src/ui/compositing.dart';
|
||||
part 'src/ui/geometry.dart';
|
||||
part 'src/ui/hash_codes.dart';
|
||||
part 'src/ui/initialization.dart';
|
||||
part 'src/ui/lerp.dart';
|
||||
part 'src/ui/natives.dart';
|
||||
part 'src/ui/painting.dart';
|
||||
part 'src/ui/pointer.dart';
|
||||
part 'src/ui/semantics.dart';
|
||||
part 'src/ui/test_embedding.dart';
|
||||
part 'src/ui/text.dart';
|
||||
part 'src/ui/tile_mode.dart';
|
||||
part 'src/ui/window.dart';
|
||||
|
||||
/// Provides a compile time constant to customize flutter framework and other
|
||||
/// users of ui engine for web runtime.
|
||||
const bool isWeb = true;
|
||||
|
||||
/// Web specific SMI. Used by bitfield. The 0x3FFFFFFFFFFFFFFF used on VM
|
||||
/// is not supported on Web platform.
|
||||
const int kMaxUnsignedSMI = -1;
|
||||
15
engine/src/flutter/lib/web_ui/pubspec.yaml
Normal file
15
engine/src/flutter/lib/web_ui/pubspec.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
name: ui
|
||||
publish_to: none
|
||||
|
||||
environment:
|
||||
sdk: ">=2.2.0 <3.0.0"
|
||||
|
||||
dependencies:
|
||||
meta: ^1.1.5
|
||||
|
||||
dev_dependencies:
|
||||
test: ^1.3.0
|
||||
quiver:
|
||||
build_runner:
|
||||
build_test:
|
||||
build_web_compilers:
|
||||
196
engine/src/flutter/lib/web_ui/test/alarm_clock_test.dart
Normal file
196
engine/src/flutter/lib/web_ui/test/alarm_clock_test.dart
Normal file
@@ -0,0 +1,196 @@
|
||||
// Copyright 2013 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:test/test.dart';
|
||||
import 'package:quiver/testing/async.dart';
|
||||
import 'package:quiver/time.dart';
|
||||
|
||||
import 'package:ui/src/engine.dart';
|
||||
|
||||
void main() {
|
||||
group(AlarmClock, () {
|
||||
_alarmClockTests();
|
||||
});
|
||||
}
|
||||
|
||||
void _alarmClockTests() {
|
||||
int callCount = 0;
|
||||
|
||||
testCallback() {
|
||||
callCount += 1;
|
||||
}
|
||||
|
||||
setUp(() {
|
||||
callCount = 0;
|
||||
});
|
||||
|
||||
testAsync('AlarmClock calls the callback in the future',
|
||||
(FakeAsync fakeAsync) {
|
||||
final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24));
|
||||
final AlarmClock alarm = AlarmClock(clock.now);
|
||||
alarm.callback = testCallback;
|
||||
|
||||
// There should be no timers scheduled until we set a non-null datetime.
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 0);
|
||||
|
||||
alarm.datetime = clock.fromNow(minutes: 1);
|
||||
|
||||
// There should be exactly 1 timer scheduled.
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 1);
|
||||
|
||||
// No time has passed; the callback should not be called.
|
||||
expect(callCount, 0);
|
||||
|
||||
// Not enough time has passed; the callback should not be called.
|
||||
fakeAsync.elapse(Duration(seconds: 30));
|
||||
expect(callCount, 0);
|
||||
|
||||
// Exactly 1 minute has passed; fire the callback.
|
||||
fakeAsync.elapse(Duration(seconds: 30));
|
||||
expect(callCount, 1);
|
||||
|
||||
// Timers should be cleaned up.
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 0);
|
||||
|
||||
// Rescheduling.
|
||||
alarm.datetime = clock.fromNow(minutes: 1);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 1);
|
||||
fakeAsync.elapse(Duration(minutes: 1));
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 0);
|
||||
expect(callCount, 2);
|
||||
});
|
||||
|
||||
testAsync('AlarmClock does nothing when new datetime is the same',
|
||||
(FakeAsync fakeAsync) {
|
||||
final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24));
|
||||
final AlarmClock alarm = AlarmClock(clock.now);
|
||||
alarm.callback = testCallback;
|
||||
|
||||
alarm.datetime = clock.fromNow(minutes: 1);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 1);
|
||||
expect(callCount, 0);
|
||||
|
||||
alarm.datetime = alarm.datetime.add(Duration.zero);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 1);
|
||||
expect(callCount, 0);
|
||||
|
||||
fakeAsync.elapse(Duration(seconds: 30));
|
||||
|
||||
alarm.datetime = alarm.datetime.add(Duration.zero);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 1);
|
||||
expect(callCount, 0);
|
||||
|
||||
fakeAsync.elapse(Duration(seconds: 30));
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 0);
|
||||
expect(callCount, 1);
|
||||
});
|
||||
|
||||
testAsync('AlarmClock does not call the callback in the past',
|
||||
(FakeAsync fakeAsync) {
|
||||
final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24));
|
||||
final AlarmClock alarm = AlarmClock(clock.now);
|
||||
alarm.callback = testCallback;
|
||||
alarm.datetime = clock.ago(minutes: 1);
|
||||
|
||||
// No timers scheduled for past dates.
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 0);
|
||||
expect(callCount, 0);
|
||||
});
|
||||
|
||||
testAsync('AlarmClock reschedules to a future time', (FakeAsync fakeAsync) {
|
||||
final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24));
|
||||
final AlarmClock alarm = AlarmClock(clock.now);
|
||||
alarm.callback = testCallback;
|
||||
|
||||
alarm.datetime = clock.fromNow(minutes: 1);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 1);
|
||||
|
||||
expect(callCount, 0);
|
||||
fakeAsync.elapse(Duration(seconds: 30));
|
||||
expect(callCount, 0);
|
||||
|
||||
// Reschedule.
|
||||
alarm.datetime = alarm.datetime.add(const Duration(minutes: 1));
|
||||
|
||||
fakeAsync.elapse(Duration(minutes: 1));
|
||||
|
||||
// Still no calls because we rescheduled.
|
||||
expect(callCount, 0);
|
||||
|
||||
fakeAsync.elapse(Duration(seconds: 30));
|
||||
expect(callCount, 1);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 0);
|
||||
});
|
||||
|
||||
testAsync('AlarmClock reschedules to an earlier time', (FakeAsync fakeAsync) {
|
||||
final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24));
|
||||
final AlarmClock alarm = AlarmClock(clock.now);
|
||||
alarm.callback = testCallback;
|
||||
|
||||
alarm.datetime = clock.fromNow(minutes: 1);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 1);
|
||||
|
||||
expect(callCount, 0);
|
||||
fakeAsync.elapse(Duration(seconds: 30));
|
||||
expect(callCount, 0);
|
||||
|
||||
// Reschedule to an earlier time that's still in the future.
|
||||
alarm.datetime = alarm.datetime.subtract(const Duration(seconds: 15));
|
||||
|
||||
fakeAsync.elapse(Duration(seconds: 45));
|
||||
expect(callCount, 1);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 0);
|
||||
});
|
||||
|
||||
testAsync('AlarmClock cancels the timer when datetime is null',
|
||||
(FakeAsync fakeAsync) {
|
||||
final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24));
|
||||
final AlarmClock alarm = AlarmClock(clock.now);
|
||||
alarm.callback = testCallback;
|
||||
|
||||
alarm.datetime = clock.fromNow(minutes: 1);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 1);
|
||||
|
||||
// Cancel.
|
||||
alarm.datetime = null;
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 0);
|
||||
expect(callCount, 0);
|
||||
|
||||
// Make sure nothing fires even if we wait long enough.
|
||||
fakeAsync.elapse(Duration(minutes: 2));
|
||||
expect(callCount, 0);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 0);
|
||||
});
|
||||
|
||||
testAsync('AlarmClock cancels the timer when datetime is in the past',
|
||||
(FakeAsync fakeAsync) {
|
||||
final Clock clock = fakeAsync.getClock(DateTime(2019, 1, 24));
|
||||
final AlarmClock alarm = AlarmClock(clock.now);
|
||||
alarm.callback = testCallback;
|
||||
|
||||
alarm.datetime = clock.fromNow(minutes: 1);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 1);
|
||||
fakeAsync.elapse(Duration(seconds: 30));
|
||||
expect(callCount, 0);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 1);
|
||||
|
||||
// Cancel.
|
||||
alarm.datetime = clock.ago(seconds: 1);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 0);
|
||||
expect(callCount, 0);
|
||||
|
||||
// Make sure nothing fires even if we wait long enough.
|
||||
fakeAsync.elapse(Duration(minutes: 2));
|
||||
expect(callCount, 0);
|
||||
expect(fakeAsync.nonPeriodicTimerCount, 0);
|
||||
});
|
||||
}
|
||||
|
||||
typedef FakeAsyncTest = void Function(FakeAsync);
|
||||
|
||||
void testAsync(String description, FakeAsyncTest fn) {
|
||||
test(description, () {
|
||||
FakeAsync().run(fn);
|
||||
});
|
||||
}
|
||||
71
engine/src/flutter/lib/web_ui/test/canvas_test.dart
Normal file
71
engine/src/flutter/lib/web_ui/test/canvas_test.dart
Normal file
@@ -0,0 +1,71 @@
|
||||
// Copyright 2013 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:ui/src/engine.dart';
|
||||
import 'package:ui/ui.dart' as ui;
|
||||
|
||||
import 'package:test/test.dart';
|
||||
|
||||
import 'mock_engine_canvas.dart';
|
||||
|
||||
void main() {
|
||||
group('EngineCanvas', () {
|
||||
MockEngineCanvas mockCanvas;
|
||||
ui.Paragraph paragraph;
|
||||
|
||||
void testCanvas(
|
||||
String description, void Function(EngineCanvas canvas) testFn,
|
||||
{ui.Rect canvasSize, ui.VoidCallback whenDone}) {
|
||||
canvasSize ??= ui.Rect.fromLTWH(0, 0, 100, 100);
|
||||
test(description, () {
|
||||
testFn(BitmapCanvas(canvasSize));
|
||||
testFn(DomCanvas());
|
||||
testFn(HoudiniCanvas(canvasSize));
|
||||
testFn(mockCanvas = MockEngineCanvas());
|
||||
if (whenDone != null) {
|
||||
whenDone();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
testCanvas('draws laid out paragraph', (EngineCanvas canvas) {
|
||||
final RecordingCanvas recordingCanvas =
|
||||
RecordingCanvas(ui.Rect.fromLTWH(0, 0, 100, 100));
|
||||
final ui.ParagraphBuilder builder =
|
||||
ui.ParagraphBuilder(ui.ParagraphStyle());
|
||||
builder.addText('sample');
|
||||
paragraph = builder.build();
|
||||
paragraph.layout(ui.ParagraphConstraints(width: 100));
|
||||
recordingCanvas.drawParagraph(paragraph, const ui.Offset(10, 10));
|
||||
canvas.clear();
|
||||
recordingCanvas.apply(canvas);
|
||||
}, whenDone: () {
|
||||
expect(mockCanvas.methodCallLog, hasLength(2));
|
||||
|
||||
MockCanvasCall call = mockCanvas.methodCallLog[0];
|
||||
expect(call.methodName, 'clear');
|
||||
|
||||
call = mockCanvas.methodCallLog[1];
|
||||
expect(call.methodName, 'drawParagraph');
|
||||
expect(call.arguments['paragraph'], paragraph);
|
||||
expect(call.arguments['offset'], const ui.Offset(10, 10));
|
||||
});
|
||||
|
||||
testCanvas('ignores paragraphs that were not laid out',
|
||||
(EngineCanvas canvas) {
|
||||
final RecordingCanvas recordingCanvas =
|
||||
RecordingCanvas(ui.Rect.fromLTWH(0, 0, 100, 100));
|
||||
final ui.ParagraphBuilder builder =
|
||||
ui.ParagraphBuilder(ui.ParagraphStyle());
|
||||
builder.addText('sample');
|
||||
final ui.Paragraph paragraph = builder.build();
|
||||
recordingCanvas.drawParagraph(paragraph, const ui.Offset(10, 10));
|
||||
canvas.clear();
|
||||
recordingCanvas.apply(canvas);
|
||||
}, whenDone: () {
|
||||
expect(mockCanvas.methodCallLog, hasLength(1));
|
||||
expect(mockCanvas.methodCallLog[0].methodName, 'clear');
|
||||
});
|
||||
});
|
||||
}
|
||||
140
engine/src/flutter/lib/web_ui/test/color_test.dart
Normal file
140
engine/src/flutter/lib/web_ui/test/color_test.dart
Normal file
@@ -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.
|
||||
|
||||
import 'package:ui/ui.dart';
|
||||
|
||||
import 'package:test/test.dart';
|
||||
|
||||
class NotAColor extends Color {
|
||||
const NotAColor(int value) : super(value);
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('color accessors should work', () {
|
||||
const Color foo = Color(0x12345678);
|
||||
expect(foo.alpha, equals(0x12));
|
||||
expect(foo.red, equals(0x34));
|
||||
expect(foo.green, equals(0x56));
|
||||
expect(foo.blue, equals(0x78));
|
||||
});
|
||||
|
||||
test('paint set to black', () {
|
||||
const Color c = Color(0x00000000);
|
||||
final Paint p = new Paint();
|
||||
p.color = c;
|
||||
expect(c.toString(), equals('Color(0x00000000)'));
|
||||
});
|
||||
|
||||
test('color created with out of bounds value', () {
|
||||
try {
|
||||
const Color c = Color(0x100 << 24);
|
||||
final Paint p = new Paint();
|
||||
p.color = c;
|
||||
} catch (e) {
|
||||
expect(e != null, equals(true));
|
||||
}
|
||||
});
|
||||
|
||||
test('color created with wildly out of bounds value', () {
|
||||
try {
|
||||
const Color c = Color(1 << 1000000);
|
||||
final Paint p = new Paint();
|
||||
p.color = c;
|
||||
} catch (e) {
|
||||
expect(e != null, equals(true));
|
||||
}
|
||||
});
|
||||
|
||||
test('two colors are only == if they have the same runtime type', () {
|
||||
expect(const Color(123), equals(const Color(123)));
|
||||
expect(const Color(123),
|
||||
equals(Color(123))); // ignore: prefer_const_constructors
|
||||
expect(const Color(123), isNot(equals(const Color(321))));
|
||||
expect(const Color(123), isNot(equals(const NotAColor(123))));
|
||||
expect(const NotAColor(123), isNot(equals(const Color(123))));
|
||||
expect(const NotAColor(123), equals(const NotAColor(123)));
|
||||
});
|
||||
|
||||
test('Color.lerp', () {
|
||||
expect(
|
||||
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 0.0),
|
||||
const Color(0x00000000),
|
||||
);
|
||||
expect(
|
||||
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 0.5),
|
||||
const Color(0x7F7F7F7F),
|
||||
);
|
||||
expect(
|
||||
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 1.0),
|
||||
const Color(0xFFFFFFFF),
|
||||
);
|
||||
expect(
|
||||
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), -0.1),
|
||||
const Color(0x00000000),
|
||||
);
|
||||
expect(
|
||||
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 1.1),
|
||||
const Color(0xFFFFFFFF),
|
||||
);
|
||||
});
|
||||
|
||||
test('Color.alphaBlend', () {
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x00000000), const Color(0x00000000)),
|
||||
const Color(0x00000000),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x00000000), const Color(0xFFFFFFFF)),
|
||||
const Color(0xFFFFFFFF),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0xFFFFFFFF), const Color(0x00000000)),
|
||||
const Color(0xFFFFFFFF),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0xFFFFFFFF), const Color(0xFFFFFFFF)),
|
||||
const Color(0xFFFFFFFF),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x80FFFFFF), const Color(0xFF000000)),
|
||||
const Color(0xFF808080),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x80808080), const Color(0xFFFFFFFF)),
|
||||
const Color(0xFFBFBFBF),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x80808080), const Color(0xFF000000)),
|
||||
const Color(0xFF404040),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x01020304), const Color(0xFF000000)),
|
||||
const Color(0xFF000000),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x11223344), const Color(0xFF000000)),
|
||||
const Color(0xFF020304),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x11223344), const Color(0x80000000)),
|
||||
const Color(0x88040608),
|
||||
);
|
||||
});
|
||||
|
||||
test('compute gray luminance', () {
|
||||
// Each color component is at 20%.
|
||||
const Color lightGray = Color(0xFF333333);
|
||||
// Relative luminance's formula is just the linearized color value for gray.
|
||||
// ((0.2 + 0.055) / 1.055) ^ 2.4.
|
||||
expect(lightGray.computeLuminance(), equals(0.033104766570885055));
|
||||
});
|
||||
|
||||
test('compute color luminance', () {
|
||||
const Color brightRed = Color(0xFFFF3B30);
|
||||
// 0.2126 * ((1.0 + 0.055) / 1.055) ^ 2.4 +
|
||||
// 0.7152 * ((0.23137254902 +0.055) / 1.055) ^ 2.4 +
|
||||
// 0.0722 * ((0.18823529411 + 0.055) / 1.055) ^ 2.4
|
||||
expect(brightRed.computeLuminance(), equals(0.24601329637099723));
|
||||
});
|
||||
}
|
||||
140
engine/src/flutter/lib/web_ui/test/colors_test.dart
Normal file
140
engine/src/flutter/lib/web_ui/test/colors_test.dart
Normal file
@@ -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.
|
||||
|
||||
import 'package:ui/ui.dart';
|
||||
|
||||
import 'package:test/test.dart';
|
||||
|
||||
class NotAColor extends Color {
|
||||
const NotAColor(int value) : super(value);
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('color accessors should work', () {
|
||||
const Color foo = Color(0x12345678);
|
||||
expect(foo.alpha, equals(0x12));
|
||||
expect(foo.red, equals(0x34));
|
||||
expect(foo.green, equals(0x56));
|
||||
expect(foo.blue, equals(0x78));
|
||||
});
|
||||
|
||||
test('paint set to black', () {
|
||||
const Color c = Color(0x00000000);
|
||||
final Paint p = new Paint();
|
||||
p.color = c;
|
||||
expect(c.toString(), equals('Color(0x00000000)'));
|
||||
});
|
||||
|
||||
test('color created with out of bounds value', () {
|
||||
try {
|
||||
const Color c = Color(0x100 << 24);
|
||||
final Paint p = new Paint();
|
||||
p.color = c;
|
||||
} catch (e) {
|
||||
expect(e != null, equals(true));
|
||||
}
|
||||
});
|
||||
|
||||
test('color created with wildly out of bounds value', () {
|
||||
try {
|
||||
const Color c = Color(1 << 1000000);
|
||||
final Paint p = new Paint();
|
||||
p.color = c;
|
||||
} catch (e) {
|
||||
expect(e != null, equals(true));
|
||||
}
|
||||
});
|
||||
|
||||
test('two colors are only == if they have the same runtime type', () {
|
||||
expect(const Color(123), equals(const Color(123)));
|
||||
expect(const Color(123),
|
||||
equals(Color(123))); // ignore: prefer_const_constructors
|
||||
expect(const Color(123), isNot(equals(const Color(321))));
|
||||
expect(const Color(123), isNot(equals(const NotAColor(123))));
|
||||
expect(const NotAColor(123), isNot(equals(const Color(123))));
|
||||
expect(const NotAColor(123), equals(const NotAColor(123)));
|
||||
});
|
||||
|
||||
test('Color.lerp', () {
|
||||
expect(
|
||||
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 0.0),
|
||||
const Color(0x00000000),
|
||||
);
|
||||
expect(
|
||||
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 0.5),
|
||||
const Color(0x7F7F7F7F),
|
||||
);
|
||||
expect(
|
||||
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 1.0),
|
||||
const Color(0xFFFFFFFF),
|
||||
);
|
||||
expect(
|
||||
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), -0.1),
|
||||
const Color(0x00000000),
|
||||
);
|
||||
expect(
|
||||
Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 1.1),
|
||||
const Color(0xFFFFFFFF),
|
||||
);
|
||||
});
|
||||
|
||||
test('Color.alphaBlend', () {
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x00000000), const Color(0x00000000)),
|
||||
const Color(0x00000000),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x00000000), const Color(0xFFFFFFFF)),
|
||||
const Color(0xFFFFFFFF),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0xFFFFFFFF), const Color(0x00000000)),
|
||||
const Color(0xFFFFFFFF),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0xFFFFFFFF), const Color(0xFFFFFFFF)),
|
||||
const Color(0xFFFFFFFF),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x80FFFFFF), const Color(0xFF000000)),
|
||||
const Color(0xFF808080),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x80808080), const Color(0xFFFFFFFF)),
|
||||
const Color(0xFFBFBFBF),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x80808080), const Color(0xFF000000)),
|
||||
const Color(0xFF404040),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x01020304), const Color(0xFF000000)),
|
||||
const Color(0xFF000000),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x11223344), const Color(0xFF000000)),
|
||||
const Color(0xFF020304),
|
||||
);
|
||||
expect(
|
||||
Color.alphaBlend(const Color(0x11223344), const Color(0x80000000)),
|
||||
const Color(0x88040608),
|
||||
);
|
||||
});
|
||||
|
||||
test('compute gray luminance', () {
|
||||
// Each color component is at 20%.
|
||||
const Color lightGray = Color(0xFF333333);
|
||||
// Relative luminance's formula is just the linearized color value for gray.
|
||||
// ((0.2 + 0.055) / 1.055) ^ 2.4.
|
||||
expect(lightGray.computeLuminance(), equals(0.033104766570885055));
|
||||
});
|
||||
|
||||
test('compute color luminance', () {
|
||||
const Color brightRed = Color(0xFFFF3B30);
|
||||
// 0.2126 * ((1.0 + 0.055) / 1.055) ^ 2.4 +
|
||||
// 0.7152 * ((0.23137254902 +0.055) / 1.055) ^ 2.4 +
|
||||
// 0.0722 * ((0.18823529411 + 0.055) / 1.055) ^ 2.4
|
||||
expect(brightRed.computeLuminance(), equals(0.24601329637099723));
|
||||
});
|
||||
}
|
||||
276
engine/src/flutter/lib/web_ui/test/compositing_test.dart
Normal file
276
engine/src/flutter/lib/web_ui/test/compositing_test.dart
Normal file
@@ -0,0 +1,276 @@
|
||||
// Copyright 2013 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:html' as html;
|
||||
|
||||
import 'package:ui/src/engine.dart';
|
||||
import 'package:ui/ui.dart';
|
||||
|
||||
import 'package:test/test.dart';
|
||||
|
||||
import 'matchers.dart';
|
||||
|
||||
void main() {
|
||||
group('SceneBuilder', () {
|
||||
test('pushOffset implements surface lifecycle', () {
|
||||
testLayerLifeCycle((sceneBuilder, paintedBy) {
|
||||
return sceneBuilder.pushOffset(10, 20);
|
||||
}, () {
|
||||
return '''<s><flt-offset></flt-offset></s>''';
|
||||
});
|
||||
});
|
||||
|
||||
test('pushTransform implements surface lifecycle', () {
|
||||
testLayerLifeCycle((sceneBuilder, paintedBy) {
|
||||
return sceneBuilder.pushTransform(
|
||||
Matrix4.translationValues(10, 20, 0).storage);
|
||||
}, () {
|
||||
return '''<s><flt-transform></flt-transform></s>''';
|
||||
});
|
||||
});
|
||||
|
||||
test('pushClipRect implements surface lifecycle', () {
|
||||
testLayerLifeCycle((sceneBuilder, paintedBy) {
|
||||
return sceneBuilder.pushClipRect(Rect.fromLTRB(10, 20, 30, 40));
|
||||
}, () {
|
||||
return '''
|
||||
<s>
|
||||
<clip><clip-i></clip-i></clip>
|
||||
</s>
|
||||
''';
|
||||
});
|
||||
});
|
||||
|
||||
test('pushClipRRect implements surface lifecycle', () {
|
||||
testLayerLifeCycle((sceneBuilder, paintedBy) {
|
||||
return sceneBuilder.pushClipRRect(
|
||||
RRect.fromLTRBR(10, 20, 30, 40, Radius.circular(3)));
|
||||
}, () {
|
||||
return '''
|
||||
<s>
|
||||
<rclip><clip-i></clip-i></rclip>
|
||||
</s>
|
||||
''';
|
||||
});
|
||||
});
|
||||
|
||||
test('pushClipPath implements surface lifecycle', () {
|
||||
testLayerLifeCycle((sceneBuilder, paintedBy) {
|
||||
final Path path = Path()..addRect(Rect.fromLTRB(10, 20, 30, 40));
|
||||
return sceneBuilder.pushClipPath(path);
|
||||
}, () {
|
||||
return '''
|
||||
<s>
|
||||
<flt-clippath>
|
||||
<svg><defs><clipPath><path></path></clipPath></defs></svg>
|
||||
</flt-clippath>
|
||||
</s>
|
||||
''';
|
||||
});
|
||||
});
|
||||
|
||||
test('pushOpacity implements surface lifecycle', () {
|
||||
testLayerLifeCycle((sceneBuilder, paintedBy) {
|
||||
return sceneBuilder.pushOpacity(10);
|
||||
}, () {
|
||||
return '''<s><o></o></s>''';
|
||||
});
|
||||
});
|
||||
|
||||
test('pushPhysicalShape implements surface lifecycle', () {
|
||||
testLayerLifeCycle((sceneBuilder, paintedBy) {
|
||||
final Path path = Path()..addRect(Rect.fromLTRB(10, 20, 30, 40));
|
||||
return sceneBuilder.pushPhysicalShape(
|
||||
path: path,
|
||||
elevation: 2,
|
||||
color: Color.fromRGBO(0, 0, 0, 1),
|
||||
shadowColor: Color.fromRGBO(0, 0, 0, 1),
|
||||
);
|
||||
}, () {
|
||||
return '''<s><pshape><clip-i></clip-i></pshape></s>''';
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
group('parent child lifecycle', () {
|
||||
test(
|
||||
'build, retain, update, and applyPaint are called the right number of times',
|
||||
() {
|
||||
final Object paintedBy = Object();
|
||||
final PersistedScene scene1 = PersistedScene();
|
||||
final PersistedClipRect clip1 =
|
||||
PersistedClipRect(paintedBy, Rect.fromLTRB(10, 10, 20, 20));
|
||||
final PersistedOpacity opacity =
|
||||
PersistedOpacity(paintedBy, 100, Offset.zero);
|
||||
final MockPersistedPicture picture = MockPersistedPicture(paintedBy);
|
||||
|
||||
scene1.appendChild(clip1);
|
||||
clip1.appendChild(opacity);
|
||||
opacity.appendChild(picture);
|
||||
|
||||
expect(picture.retainCount, 0);
|
||||
expect(picture.buildCount, 0);
|
||||
expect(picture.updateCount, 0);
|
||||
expect(picture.applyPaintCount, 0);
|
||||
|
||||
scene1.build();
|
||||
expect(picture.retainCount, 0);
|
||||
expect(picture.buildCount, 1);
|
||||
expect(picture.updateCount, 0);
|
||||
expect(picture.applyPaintCount, 1);
|
||||
|
||||
// The second scene graph retains the opacity, but not the clip. However,
|
||||
// because the clip didn't change no repaints should happen.
|
||||
final PersistedScene scene2 = PersistedScene();
|
||||
final PersistedClipRect clip2 =
|
||||
PersistedClipRect(paintedBy, Rect.fromLTRB(10, 10, 20, 20));
|
||||
scene2.appendChild(clip2);
|
||||
opacity.reuseStrategy = PersistedSurfaceReuseStrategy.retain;
|
||||
clip2.appendChild(opacity);
|
||||
|
||||
scene2.update(scene1);
|
||||
expect(picture.retainCount, 1);
|
||||
expect(picture.buildCount, 1);
|
||||
expect(picture.updateCount, 0);
|
||||
expect(picture.applyPaintCount, 1);
|
||||
|
||||
// The third scene graph retains the opacity, and produces a new clip.
|
||||
// This should cause the picture to repaint despite being retained.
|
||||
final PersistedScene scene3 = PersistedScene();
|
||||
final PersistedClipRect clip3 =
|
||||
PersistedClipRect(paintedBy, Rect.fromLTRB(10, 10, 50, 50));
|
||||
scene3.appendChild(clip3);
|
||||
opacity.reuseStrategy = PersistedSurfaceReuseStrategy.retain;
|
||||
clip3.appendChild(opacity);
|
||||
|
||||
scene3.update(scene2);
|
||||
expect(picture.retainCount, 2);
|
||||
expect(picture.buildCount, 1);
|
||||
expect(picture.updateCount, 0);
|
||||
expect(picture.applyPaintCount, 2);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
typedef TestLayerBuilder = EngineLayer Function(
|
||||
SceneBuilder sceneBuilder, Object paintedBy);
|
||||
typedef ExpectedHtmlGetter = String Function();
|
||||
|
||||
void testLayerLifeCycle(
|
||||
TestLayerBuilder layerBuilder, ExpectedHtmlGetter expectedHtmlGetter) {
|
||||
// Force scene builder to start from scratch. This guarantees that the first
|
||||
// scene starts from the "build" phase.
|
||||
SceneBuilder.debugForgetFrameScene();
|
||||
|
||||
final Object paintedBy = Object();
|
||||
|
||||
// Build: builds a brand new layer.
|
||||
SceneBuilder sceneBuilder = SceneBuilder();
|
||||
final EngineLayer layer1 = layerBuilder(sceneBuilder, paintedBy);
|
||||
final Type surfaceType = layer1.runtimeType;
|
||||
sceneBuilder.pop();
|
||||
|
||||
SceneTester tester = SceneTester(sceneBuilder.build());
|
||||
tester.expectSceneHtml(expectedHtmlGetter());
|
||||
|
||||
PersistedSurface findSurface() {
|
||||
return enumerateSurfaces()
|
||||
.where((s) => s.runtimeType == surfaceType)
|
||||
.single;
|
||||
}
|
||||
|
||||
final PersistedSurface surface1 = findSurface();
|
||||
final html.Element surfaceElement1 = surface1.rootElement;
|
||||
|
||||
// Retain: reuses a layer as is along with its DOM elements.
|
||||
sceneBuilder = SceneBuilder();
|
||||
sceneBuilder.addRetained(layer1);
|
||||
|
||||
tester = SceneTester(sceneBuilder.build());
|
||||
tester.expectSceneHtml(expectedHtmlGetter());
|
||||
|
||||
final PersistedSurface surface2 = findSurface();
|
||||
final html.Element surfaceElement2 = surface2.rootElement;
|
||||
|
||||
expect(surface2, same(surface1));
|
||||
expect(surfaceElement2, same(surfaceElement1));
|
||||
|
||||
// Reuse: reuses a layer's DOM elements by matching it.
|
||||
sceneBuilder = SceneBuilder();
|
||||
final EngineLayer layer3 = layerBuilder(sceneBuilder, paintedBy);
|
||||
sceneBuilder.pop();
|
||||
expect(layer3, isNot(same(layer1)));
|
||||
tester = SceneTester(sceneBuilder.build());
|
||||
tester.expectSceneHtml(expectedHtmlGetter());
|
||||
|
||||
final PersistedSurface surface3 = findSurface();
|
||||
expect(surface3, same(layer3));
|
||||
final html.Element surfaceElement3 = surface3.rootElement;
|
||||
expect(surface3, isNot(same(surface2)));
|
||||
expect(surfaceElement3, isNotNull);
|
||||
expect(surfaceElement3, same(surfaceElement2));
|
||||
|
||||
// Recycle: discards all the layers.
|
||||
sceneBuilder = SceneBuilder();
|
||||
tester = SceneTester(sceneBuilder.build());
|
||||
tester.expectSceneHtml('<s></s>');
|
||||
|
||||
expect(surface3.rootElement, isNull); // offset3 should be recycled.
|
||||
|
||||
// Retain again: the framework should be able to request that a layer is added
|
||||
// as retained even after it has been recycled. In this case the
|
||||
// engine would "rehydrate" the layer with new DOM elements.
|
||||
sceneBuilder = SceneBuilder();
|
||||
sceneBuilder.addRetained(layer3);
|
||||
tester = SceneTester(sceneBuilder.build());
|
||||
tester.expectSceneHtml(expectedHtmlGetter());
|
||||
expect(surface3.rootElement, isNotNull); // offset3 should be rehydrated.
|
||||
|
||||
// Make sure we clear retained surface list.
|
||||
expect(debugRetainedSurfaces, isEmpty);
|
||||
}
|
||||
|
||||
class MockPersistedPicture extends PersistedPicture {
|
||||
factory MockPersistedPicture(Object paintedBy) {
|
||||
final PictureRecorder recorder = PictureRecorder();
|
||||
// Use the largest cull rect so that layer clips are effective. The tests
|
||||
// rely on this.
|
||||
recorder.beginRecording(Rect.largest)..drawPaint(Paint());
|
||||
return MockPersistedPicture._(paintedBy, recorder.endRecording());
|
||||
}
|
||||
|
||||
MockPersistedPicture._(Object paintedBy, Picture picture)
|
||||
: super(paintedBy, 0, 0, picture, 0);
|
||||
|
||||
int retainCount = 0;
|
||||
int buildCount = 0;
|
||||
int updateCount = 0;
|
||||
int applyPaintCount = 0;
|
||||
|
||||
@override
|
||||
void build() {
|
||||
super.build();
|
||||
buildCount++;
|
||||
}
|
||||
|
||||
@override
|
||||
void retain() {
|
||||
super.retain();
|
||||
retainCount++;
|
||||
}
|
||||
|
||||
@override
|
||||
void applyPaint(EngineCanvas oldCanvas) {
|
||||
applyPaintCount++;
|
||||
}
|
||||
|
||||
@override
|
||||
void update(PersistedPicture oldSurface) {
|
||||
super.update(oldSurface);
|
||||
updateCount++;
|
||||
}
|
||||
|
||||
@override
|
||||
int get bitmapPixelCount => 0;
|
||||
}
|
||||
110
engine/src/flutter/lib/web_ui/test/dom_renderer_test.dart
Normal file
110
engine/src/flutter/lib/web_ui/test/dom_renderer_test.dart
Normal file
@@ -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.
|
||||
|
||||
import 'dart:html' as html;
|
||||
|
||||
import 'package:ui/src/engine.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
test('creating elements works', () {
|
||||
var renderer = new DomRenderer();
|
||||
var element = renderer.createElement('div');
|
||||
expect(element, isNotNull);
|
||||
});
|
||||
test('can append children to parents', () {
|
||||
var renderer = new DomRenderer();
|
||||
var parent = renderer.createElement('div');
|
||||
var child = renderer.createElement('div');
|
||||
renderer.append(parent, child);
|
||||
expect(parent.children, hasLength(1));
|
||||
});
|
||||
test('can set text on elements', () {
|
||||
var renderer = new DomRenderer();
|
||||
var element = renderer.createElement('div');
|
||||
renderer.setText(element, 'Hello World');
|
||||
expect(element.text, 'Hello World');
|
||||
});
|
||||
test('can set attributes on elements', () {
|
||||
var renderer = new DomRenderer();
|
||||
var element = renderer.createElement('div');
|
||||
renderer.setElementAttribute(element, 'id', 'foo');
|
||||
expect(element.id, 'foo');
|
||||
});
|
||||
test('can add classes to elements', () {
|
||||
var renderer = new DomRenderer();
|
||||
var element = renderer.createElement('div');
|
||||
renderer.addElementClass(element, 'foo');
|
||||
renderer.addElementClass(element, 'bar');
|
||||
expect(element.classes, ['foo', 'bar']);
|
||||
});
|
||||
test('can remove classes from elements', () {
|
||||
var renderer = new DomRenderer();
|
||||
var element = renderer.createElement('div');
|
||||
renderer.addElementClass(element, 'foo');
|
||||
renderer.addElementClass(element, 'bar');
|
||||
expect(element.classes, ['foo', 'bar']);
|
||||
renderer.removeElementClass(element, 'foo');
|
||||
expect(element.classes, ['bar']);
|
||||
});
|
||||
test('can set style properties on elements', () {
|
||||
var renderer = new DomRenderer();
|
||||
var element = renderer.createElement('div');
|
||||
renderer.setElementStyle(element, 'color', 'red');
|
||||
expect(element.style.color, 'red');
|
||||
});
|
||||
test('can remove style properties from elements', () {
|
||||
var renderer = new DomRenderer();
|
||||
var element = renderer.createElement('div');
|
||||
renderer.setElementStyle(element, 'color', 'blue');
|
||||
expect(element.style.color, 'blue');
|
||||
renderer.setElementStyle(element, 'color', null);
|
||||
expect(element.style.color, '');
|
||||
});
|
||||
test('elements can have children', () {
|
||||
var renderer = new DomRenderer();
|
||||
var element = renderer.createElement('div');
|
||||
renderer.createElement('div', parent: element);
|
||||
expect(element.children, hasLength(1));
|
||||
});
|
||||
test('can detach elements', () {
|
||||
var renderer = new DomRenderer();
|
||||
var element = renderer.createElement('div');
|
||||
var child = renderer.createElement('div', parent: element);
|
||||
renderer.detachElement(child);
|
||||
expect(element.children, isEmpty);
|
||||
});
|
||||
test('can reattach detached elements', () {
|
||||
var renderer = new DomRenderer();
|
||||
var element = renderer.createElement('div');
|
||||
var child = renderer.createElement('div', parent: element);
|
||||
var otherChild = renderer.createElement('foo', parent: element);
|
||||
renderer.detachElement(child);
|
||||
expect(element.children, hasLength(1));
|
||||
renderer.attachBeforeElement(element, otherChild, child);
|
||||
expect(element.children, hasLength(2));
|
||||
});
|
||||
test('insert two elements in the middle of a child list', () {
|
||||
var renderer = new DomRenderer();
|
||||
var parent = renderer.createElement('div');
|
||||
renderer.createElement('a', parent: parent);
|
||||
var childD = renderer.createElement('d', parent: parent);
|
||||
expect(parent.innerHtml, '<a></a><d></d>');
|
||||
var childB = renderer.createElement('b', parent: parent);
|
||||
var childC = renderer.createElement('c', parent: parent);
|
||||
renderer.attachBeforeElement(parent, childD, childB);
|
||||
renderer.attachBeforeElement(parent, childD, childC);
|
||||
expect(parent.innerHtml, '<a></a><b></b><c></c><d></d>');
|
||||
});
|
||||
test('replaces viewport meta tags during style reset', () {
|
||||
html.MetaElement existingMeta = html.MetaElement()
|
||||
..name = 'viewport'
|
||||
..content = 'foo=bar';
|
||||
html.document.head.append(existingMeta);
|
||||
expect(existingMeta.isConnected, true);
|
||||
|
||||
var renderer = new DomRenderer();
|
||||
renderer.reset();
|
||||
});
|
||||
}
|
||||
146
engine/src/flutter/lib/web_ui/test/geometry_test.dart
Normal file
146
engine/src/flutter/lib/web_ui/test/geometry_test.dart
Normal file
@@ -0,0 +1,146 @@
|
||||
// Copyright 2013 The Flutter Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:math' as math show sqrt;
|
||||
import 'dart:math' show pi;
|
||||
|
||||
import 'package:ui/ui.dart';
|
||||
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('Offset', () {
|
||||
test('Offset.direction', () {
|
||||
expect(const Offset(0.0, 0.0).direction, 0.0);
|
||||
expect(const Offset(0.0, 1.0).direction, pi / 2.0);
|
||||
expect(const Offset(0.0, -1.0).direction, -pi / 2.0);
|
||||
expect(const Offset(1.0, 0.0).direction, 0.0);
|
||||
expect(const Offset(1.0, 1.0).direction, pi / 4.0);
|
||||
expect(const Offset(1.0, -1.0).direction, -pi / 4.0);
|
||||
expect(const Offset(-1.0, 0.0).direction, pi);
|
||||
expect(const Offset(-1.0, 1.0).direction, pi * 3.0 / 4.0);
|
||||
expect(const Offset(-1.0, -1.0).direction, -pi * 3.0 / 4.0);
|
||||
});
|
||||
|
||||
test('Offset.fromDirection', () {
|
||||
expect(Offset.fromDirection(0.0, 0.0), const Offset(0.0, 0.0));
|
||||
expect(Offset.fromDirection(pi / 2.0).dx, closeTo(0.0, 1e-12)); // aah, floating point math. i love you so.
|
||||
expect(Offset.fromDirection(pi / 2.0).dy, 1.0);
|
||||
expect(Offset.fromDirection(-pi / 2.0).dx, closeTo(0.0, 1e-12));
|
||||
expect(Offset.fromDirection(-pi / 2.0).dy, -1.0);
|
||||
expect(Offset.fromDirection(0.0), const Offset(1.0, 0.0));
|
||||
expect(Offset.fromDirection(pi / 4.0).dx, closeTo(1.0 / math.sqrt(2.0), 1e-12));
|
||||
expect(Offset.fromDirection(pi / 4.0).dy, closeTo(1.0 / math.sqrt(2.0), 1e-12));
|
||||
expect(Offset.fromDirection(-pi / 4.0).dx, closeTo(1.0 / math.sqrt(2.0), 1e-12));
|
||||
expect(Offset.fromDirection(-pi / 4.0).dy, closeTo(-1.0 / math.sqrt(2.0), 1e-12));
|
||||
expect(Offset.fromDirection(pi).dx, -1.0);
|
||||
expect(Offset.fromDirection(pi).dy, closeTo(0.0, 1e-12));
|
||||
expect(Offset.fromDirection(pi * 3.0 / 4.0).dx, closeTo(-1.0 / math.sqrt(2.0), 1e-12));
|
||||
expect(Offset.fromDirection(pi * 3.0 / 4.0).dy, closeTo(1.0 / math.sqrt(2.0), 1e-12));
|
||||
expect(Offset.fromDirection(-pi * 3.0 / 4.0).dx, closeTo(-1.0 / math.sqrt(2.0), 1e-12));
|
||||
expect(Offset.fromDirection(-pi * 3.0 / 4.0).dy, closeTo(-1.0 / math.sqrt(2.0), 1e-12));
|
||||
expect(Offset.fromDirection(0.0, 2.0), const Offset(2.0, 0.0));
|
||||
expect(Offset.fromDirection(pi / 6, 2.0).dx, closeTo(math.sqrt(3.0), 1e-12));
|
||||
expect(Offset.fromDirection(pi / 6, 2.0).dy, closeTo(1.0, 1e-12));
|
||||
});
|
||||
});
|
||||
|
||||
group('Size', () {
|
||||
test('Size created from doubles', () {
|
||||
const Size size = Size(5.0, 7.0);
|
||||
expect(size.width, equals(5.0));
|
||||
expect(size.height, equals(7.0));
|
||||
expect(size.shortestSide, equals(5.0));
|
||||
expect(size.longestSide, equals(7.0));
|
||||
});
|
||||
|
||||
test('Size.aspectRatio', () {
|
||||
expect(const Size(0.0, 0.0).aspectRatio, 0.0);
|
||||
expect(const Size(-0.0, 0.0).aspectRatio, 0.0);
|
||||
expect(const Size(0.0, -0.0).aspectRatio, 0.0);
|
||||
expect(const Size(-0.0, -0.0).aspectRatio, 0.0);
|
||||
expect(const Size(0.0, 1.0).aspectRatio, 0.0);
|
||||
expect(const Size(0.0, -1.0).aspectRatio, -0.0);
|
||||
expect(const Size(1.0, 0.0).aspectRatio, double.infinity);
|
||||
expect(const Size(1.0, 1.0).aspectRatio, 1.0);
|
||||
expect(const Size(1.0, -1.0).aspectRatio, -1.0);
|
||||
expect(const Size(-1.0, 0.0).aspectRatio, -double.infinity);
|
||||
expect(const Size(-1.0, 1.0).aspectRatio, -1.0);
|
||||
expect(const Size(-1.0, -1.0).aspectRatio, 1.0);
|
||||
expect(const Size(3.0, 4.0).aspectRatio, 3.0 / 4.0);
|
||||
});
|
||||
});
|
||||
|
||||
group('Rect', () {
|
||||
test('Rect accessors', () {
|
||||
final Rect r = Rect.fromLTRB(1.0, 3.0, 5.0, 7.0);
|
||||
expect(r.left, equals(1.0));
|
||||
expect(r.top, equals(3.0));
|
||||
expect(r.right, equals(5.0));
|
||||
expect(r.bottom, equals(7.0));
|
||||
});
|
||||
|
||||
test('Rect created by width and height', () {
|
||||
final Rect r = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0);
|
||||
expect(r.left, equals(1.0));
|
||||
expect(r.top, equals(3.0));
|
||||
expect(r.right, equals(6.0));
|
||||
expect(r.bottom, equals(10.0));
|
||||
expect(r.shortestSide, equals(5.0));
|
||||
expect(r.longestSide, equals(7.0));
|
||||
});
|
||||
|
||||
test('Rect intersection', () {
|
||||
final Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0);
|
||||
final Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0);
|
||||
final Rect r3 = r1.intersect(r2);
|
||||
expect(r3.left, equals(50.0));
|
||||
expect(r3.top, equals(50.0));
|
||||
expect(r3.right, equals(100.0));
|
||||
expect(r3.bottom, equals(100.0));
|
||||
|
||||
final Rect r4 = r2.intersect(r1);
|
||||
expect(r4, equals(r3));
|
||||
});
|
||||
|
||||
test('Rect expandToInclude overlapping rects', () {
|
||||
final Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0);
|
||||
final Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0);
|
||||
final Rect r3 = r1.expandToInclude(r2);
|
||||
expect(r3.left, equals(0.0));
|
||||
expect(r3.top, equals(0.0));
|
||||
expect(r3.right, equals(200.0));
|
||||
expect(r3.bottom, equals(200.0));
|
||||
|
||||
final Rect r4 = r2.expandToInclude(r1);
|
||||
expect(r4, equals(r3));
|
||||
});
|
||||
|
||||
test('Rect expandToInclude crossing rects', () {
|
||||
final Rect r1 = Rect.fromLTRB(50.0, 0.0, 50.0, 200.0);
|
||||
final Rect r2 = Rect.fromLTRB(0.0, 50.0, 200.0, 50.0);
|
||||
final Rect r3 = r1.expandToInclude(r2);
|
||||
expect(r3.left, equals(0.0));
|
||||
expect(r3.top, equals(0.0));
|
||||
expect(r3.right, equals(200.0));
|
||||
expect(r3.bottom, equals(200.0));
|
||||
|
||||
final Rect r4 = r2.expandToInclude(r1);
|
||||
expect(r4, equals(r3));
|
||||
});
|
||||
});
|
||||
|
||||
group('RRect', () {
|
||||
test('RRect.fromRectXY', () {
|
||||
final Rect baseRect = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0);
|
||||
final RRect r = RRect.fromRectXY(baseRect, 1.0, 1.0);
|
||||
expect(r.left, equals(1.0));
|
||||
expect(r.top, equals(3.0));
|
||||
expect(r.right, equals(6.0));
|
||||
expect(r.bottom, equals(10.0));
|
||||
expect(r.shortestSide, equals(5.0));
|
||||
expect(r.longestSide, equals(7.0));
|
||||
});
|
||||
});
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user