Migrated integration_flutter_test/embedder (scenic integration test) from fuchsia.git (flutter/engine#26880)

This commit is contained in:
Rich Kadel
2021-09-30 19:10:02 -05:00
committed by GitHub
parent baac7db7b4
commit c2ad820db9
39 changed files with 2693 additions and 281 deletions

3
DEPS
View File

@@ -448,6 +448,9 @@ deps = {
'src/third_party/pkg/process_runner':
Var('github_git') + '/google/process_runner.git' + '@' + 'd632ea0bfd814d779fcc53a361ed33eaf3620a0b', # 4.0.1
'src/third_party/pkg/quiver':
Var('github_git') + '/google/quiver-dart.git' + '@' + '66f473cca1332496e34a783ba4527b04388fd561', # 2.1.5
'src/third_party/pkg/vector_math':
Var('github_git') + '/google/vector_math.dart.git' + '@' + 'v2.1.0',

View File

@@ -1438,6 +1438,18 @@ FILE: ../../../flutter/shell/platform/fuchsia/flutter/gfx_platform_view.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/gfx_platform_view.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/gfx_session_connection.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/gfx_session_connection.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/child-view2/child_view2.dart
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/child-view2/meta/child-view2.cmx
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/flutter-embedder-test2.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/flutter-embedder-test2.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/meta/flutter-embedder-test2.cmx
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/parent-view2/meta/parent-view2.cmx
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/parent-view2/parent_view2.dart
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/fuchsia_testing/src/lib/ui/base_view/base_view.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/fuchsia_testing/src/lib/ui/base_view/base_view.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/fuchsia_testing/src/lib/ui/base_view/embedded_view_utils.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/fuchsia_testing/src/lib/ui/base_view/embedded_view_utils.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/fuchsia_testing/src/lib/ui/base_view/math.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/isolate_configurator.cc
FILE: ../../../flutter/shell/platform/fuchsia/flutter/isolate_configurator.h
FILE: ../../../flutter/shell/platform/fuchsia/flutter/kernel/extract_far.dart

View File

@@ -72,6 +72,21 @@ dart_library("async_helper") {
]
}
dart_library("meta") {
package_root = "//third_party/dart/pkg/meta"
package_name = "meta"
language_version = "2.12"
deps = []
sources = [
"dart2js.dart",
"meta.dart",
"meta_meta.dart",
]
}
dart_library("expect") {
package_root = "//third_party/dart/pkg/expect"
package_name = "expect"
@@ -108,17 +123,319 @@ dart_library("litetest") {
]
}
dart_library("meta") {
package_root = "//third_party/dart/pkg/meta"
package_name = "meta"
dart_library("args") {
package_root = "//third_party/dart/third_party/pkg/args"
package_name = "args"
language_version = "2.12"
deps = []
sources = [
"dart2js.dart",
"meta.dart",
"meta_meta.dart",
"args.dart",
"command_runner.dart",
"src/allow_anything_parser.dart",
"src/arg_parser.dart",
"src/arg_parser_exception.dart",
"src/arg_results.dart",
"src/help_command.dart",
"src/option.dart",
"src/parser.dart",
"src/usage.dart",
"src/usage_exception.dart",
"src/utils.dart",
]
}
dart_library("collection") {
package_root = "//third_party/dart/third_party/pkg/collection"
package_name = "collection"
language_version = "2.12"
deps = []
sources = [
"algorithms.dart",
"collection.dart",
"equality.dart",
"iterable_zip.dart",
"priority_queue.dart",
"src/algorithms.dart",
"src/canonicalized_map.dart",
"src/combined_wrappers/combined_iterable.dart",
"src/combined_wrappers/combined_iterator.dart",
"src/combined_wrappers/combined_list.dart",
"src/combined_wrappers/combined_map.dart",
"src/comparators.dart",
"src/empty_unmodifiable_set.dart",
"src/equality.dart",
"src/equality_map.dart",
"src/equality_set.dart",
"src/functions.dart",
"src/iterable_extensions.dart",
"src/iterable_zip.dart",
"src/list_extensions.dart",
"src/priority_queue.dart",
"src/queue_list.dart",
"src/union_set.dart",
"src/union_set_controller.dart",
"src/unmodifiable_wrappers.dart",
"src/utils.dart",
"src/wrappers.dart",
"wrappers.dart",
]
}
dart_library("logging") {
package_root = "//third_party/dart/third_party/pkg/logging"
package_name = "logging"
language_version = "2.12"
deps = []
sources = [
"logging.dart",
"src/level.dart",
"src/log_record.dart",
"src/logger.dart",
]
}
dart_library("path") {
package_root = "//third_party/dart/third_party/pkg/path"
package_name = "path"
language_version = "2.12"
deps = []
sources = [
"path.dart",
"src/characters.dart",
"src/context.dart",
"src/internal_style.dart",
"src/parsed_path.dart",
"src/path_exception.dart",
"src/path_map.dart",
"src/path_set.dart",
"src/style.dart",
"src/style/posix.dart",
"src/style/url.dart",
"src/style/windows.dart",
"src/utils.dart",
]
}
dart_library("stack_trace") {
package_root = "//third_party/dart/third_party/pkg/stack_trace"
package_name = "stack_trace"
language_version = "2.12"
deps = [ ":path" ]
sources = [
"src/chain.dart",
"src/frame.dart",
"src/lazy_chain.dart",
"src/lazy_trace.dart",
"src/stack_zone_specification.dart",
"src/trace.dart",
"src/unparsed_frame.dart",
"src/utils.dart",
"src/vm_trace.dart",
"stack_trace.dart",
]
}
dart_library("matcher") {
package_root = "//third_party/dart/third_party/pkg/matcher"
package_name = "matcher"
language_version = "2.12"
deps = [ ":stack_trace" ]
sources = [
"matcher.dart",
"mirror_matchers.dart",
"src/core_matchers.dart",
"src/custom_matcher.dart",
"src/description.dart",
"src/equals_matcher.dart",
"src/error_matchers.dart",
"src/feature_matcher.dart",
"src/having_matcher.dart",
"src/interfaces.dart",
"src/iterable_matchers.dart",
"src/map_matchers.dart",
"src/numeric_matchers.dart",
"src/operator_matchers.dart",
"src/order_matchers.dart",
"src/pretty_print.dart",
"src/string_matchers.dart",
"src/type_matcher.dart",
"src/util.dart",
]
}
dart_library("quiver") {
package_root = "//third_party/pkg/quiver"
package_name = "quiver"
# The current version of this library is not null safe
language_version = "2.0"
deps = [
":matcher",
":meta",
]
sources = [
"async.dart",
"cache.dart",
"check.dart",
"collection.dart",
"core.dart",
"io.dart",
"iterables.dart",
"mirrors.dart",
"pattern.dart",
"src/async/collect.dart",
"src/async/concat.dart",
"src/async/countdown_timer.dart",
"src/async/enumerate.dart",
"src/async/future_stream.dart",
"src/async/iteration.dart",
"src/async/metronome.dart",
"src/async/stream_buffer.dart",
"src/async/stream_router.dart",
"src/async/string.dart",
"src/cache/cache.dart",
"src/cache/map_cache.dart",
"src/collection/bimap.dart",
"src/collection/delegates/iterable.dart",
"src/collection/delegates/list.dart",
"src/collection/delegates/map.dart",
"src/collection/delegates/queue.dart",
"src/collection/delegates/set.dart",
"src/collection/lru_map.dart",
"src/collection/multimap.dart",
"src/collection/treeset.dart",
"src/core/hash.dart",
"src/core/optional.dart",
"src/iterables/concat.dart",
"src/iterables/count.dart",
"src/iterables/cycle.dart",
"src/iterables/enumerate.dart",
"src/iterables/generating_iterable.dart",
"src/iterables/infinite_iterable.dart",
"src/iterables/merge.dart",
"src/iterables/min_max.dart",
"src/iterables/partition.dart",
"src/iterables/range.dart",
"src/iterables/zip.dart",
"src/time/clock.dart",
"src/time/duration_unit_constants.dart",
"src/time/util.dart",
"strings.dart",
"testing/async.dart",
"testing/equality.dart",
"testing/runtime.dart",
"testing/src/async/fake_async.dart",
"testing/src/equality/equality.dart",
"testing/src/runtime/checked_mode.dart",
"testing/src/time/time.dart",
"testing/time.dart",
"time.dart",
]
}
dart_library("vector_math") {
package_root = "//third_party/pkg/vector_math"
package_name = "vector_math"
language_version = "2.12"
deps = []
sources = [
"hash.dart",
"src/vector_math/aabb2.dart",
"src/vector_math/aabb3.dart",
"src/vector_math/colors.dart",
"src/vector_math/constants.dart",
"src/vector_math/error_helpers.dart",
"src/vector_math/frustum.dart",
"src/vector_math/intersection_result.dart",
"src/vector_math/matrix2.dart",
"src/vector_math/matrix3.dart",
"src/vector_math/matrix4.dart",
"src/vector_math/obb3.dart",
"src/vector_math/opengl.dart",
"src/vector_math/plane.dart",
"src/vector_math/quad.dart",
"src/vector_math/quaternion.dart",
"src/vector_math/ray.dart",
"src/vector_math/sphere.dart",
"src/vector_math/third_party/noise.dart",
"src/vector_math/triangle.dart",
"src/vector_math/utilities.dart",
"src/vector_math/vector.dart",
"src/vector_math/vector2.dart",
"src/vector_math/vector3.dart",
"src/vector_math/vector4.dart",
"src/vector_math_64/aabb2.dart",
"src/vector_math_64/aabb3.dart",
"src/vector_math_64/colors.dart",
"src/vector_math_64/constants.dart",
"src/vector_math_64/error_helpers.dart",
"src/vector_math_64/frustum.dart",
"src/vector_math_64/intersection_result.dart",
"src/vector_math_64/matrix2.dart",
"src/vector_math_64/matrix3.dart",
"src/vector_math_64/matrix4.dart",
"src/vector_math_64/obb3.dart",
"src/vector_math_64/opengl.dart",
"src/vector_math_64/plane.dart",
"src/vector_math_64/quad.dart",
"src/vector_math_64/quaternion.dart",
"src/vector_math_64/ray.dart",
"src/vector_math_64/sphere.dart",
"src/vector_math_64/third_party/noise.dart",
"src/vector_math_64/triangle.dart",
"src/vector_math_64/utilities.dart",
"src/vector_math_64/vector.dart",
"src/vector_math_64/vector2.dart",
"src/vector_math_64/vector3.dart",
"src/vector_math_64/vector4.dart",
"src/vector_math_geometry/filters/barycentric_filter.dart",
"src/vector_math_geometry/filters/color_filter.dart",
"src/vector_math_geometry/filters/flat_shade_filter.dart",
"src/vector_math_geometry/filters/geometry_filter.dart",
"src/vector_math_geometry/filters/invert_filter.dart",
"src/vector_math_geometry/filters/transform_filter.dart",
"src/vector_math_geometry/generators/attribute_generators.dart",
"src/vector_math_geometry/generators/circle_generator.dart",
"src/vector_math_geometry/generators/cube_generator.dart",
"src/vector_math_geometry/generators/cylinder_generator.dart",
"src/vector_math_geometry/generators/geometry_generator.dart",
"src/vector_math_geometry/generators/ring_generator.dart",
"src/vector_math_geometry/generators/sphere_generator.dart",
"src/vector_math_geometry/mesh_geometry.dart",
"src/vector_math_lists/scalar_list_view.dart",
"src/vector_math_lists/vector2_list.dart",
"src/vector_math_lists/vector3_list.dart",
"src/vector_math_lists/vector4_list.dart",
"src/vector_math_lists/vector_list.dart",
"src/vector_math_operations/matrix.dart",
"src/vector_math_operations/vector.dart",
"vector_math.dart",
"vector_math_64.dart",
"vector_math_geometry.dart",
"vector_math_lists.dart",
"vector_math_operations.dart",
]
}

View File

@@ -820,5 +820,6 @@ group("tests") {
":testing_tests",
":txt_tests",
":ui_tests",
"integration_flutter_tests",
]
}

View File

@@ -0,0 +1,9 @@
# 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.
group("integration_flutter_tests") {
testonly = true
deps = [ "embedder:tests" ]
}

View File

@@ -0,0 +1,5 @@
dworsham@google.com
sanjayc@google.com
richkadel@google.com
# COMPONENT: FlutteronFuchsia

View File

@@ -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.
assert(is_fuchsia)
import("//build/fuchsia/sdk.gni")
import("//flutter/tools/fuchsia/fuchsia_archive.gni")
group("tests") {
testonly = true
deps = [
":flutter-embedder-test2",
"//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/child-view2",
"//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/parent-view2",
]
}
executable("flutter-embedder-test2-bin") {
testonly = true
output_name = "flutter-embedder-test2"
sources = [
"flutter-embedder-test2.cc",
"flutter-embedder-test2.h",
]
# This is needed for //third_party/googletest for linking zircon symbols.
libs = [ "$fuchsia_sdk_path/arch/$target_cpu/sysroot/lib/libzircon.so" ]
include_dirs = [ "//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/fuchsia_testing" ]
public_deps = [ "//third_party/googletest:gtest" ]
deps = [
"$fuchsia_sdk_root/fidl:fuchsia.sys",
"$fuchsia_sdk_root/fidl:fuchsia.ui.app",
"$fuchsia_sdk_root/fidl:fuchsia.ui.input",
"$fuchsia_sdk_root/fidl:fuchsia.ui.lifecycle",
"$fuchsia_sdk_root/fidl:fuchsia.ui.policy",
"$fuchsia_sdk_root/fidl:fuchsia.ui.scenic",
"$fuchsia_sdk_root/pkg:async-loop-cpp",
"$fuchsia_sdk_root/pkg:async-loop-default",
"$fuchsia_sdk_root/pkg:fit",
"$fuchsia_sdk_root/pkg:scenic_cpp",
"$fuchsia_sdk_root/pkg:sys_cpp",
"$fuchsia_sdk_root/pkg:sys_cpp_testing",
"$fuchsia_sdk_root/pkg:zx",
"//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/fuchsia_testing/src/lib/ui/base_view",
"//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/fuchsia_testing/src/ui/testing/views",
"//third_party/googletest:gtest_main",
]
}
fuchsia_test_archive("flutter-embedder-test2") {
deps = [
":flutter-embedder-test2-bin",
"//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/child-view2:package",
"//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/parent-view2:package",
]
binary = "$target_name"
cmx_file = rebase_path("meta/$target_name.cmx")
}

View File

@@ -0,0 +1,178 @@
# `flutter scenic embedder tests`
## Configure and build fuchsia
For tests that require scenic, for example, run `fx set` with the required
targets; for example:
```shell
$ cd "$FUCHSIA_DIR"
$ fx set core.x64 \
--with //src/ui/scenic \
--with //src/ui/bin/root_presenter \
--with //src/ui/bin/hardware_display_controller_provider
$ fx build
```
Note 1: You could use `--with-base` here, instead of `--with`, but if so, you
would also need to add
`--with-base //garnet/packages/testing:run_test_component`. More on this below,
under [Start the package servers](#start-the-package-servers).
Note 2: The `fx set` flags, above, offer a minimized fuchsia platform
configuration to successfully execute the test, but some optional services may
be missing. Be aware that the Fuchsia system logs may include multiple
occurrences `WARNING: error resolving ...` messages, such as the following,
which can be ignored:
```
[pkg-resolver] WARNING: error resolving fuchsia-pkg://fuchsia.com/fonts/0 ...
[pkg-resolver] WARNING: error resolving fuchsia-pkg://fuchsia.com/ime_service/0 ...
[pkg-resolver] WARNING: error resolving fuchsia-pkg://fuchsia.com/intl_property_manager/0 ...
```
## Restart and reboot your device
_(Optional)_ If developing with the emulator, launch (or shutdown and relaunch)
the emulator.
```shell
fx vdl start -N
```
NOTE: Do _not_ run the default package server. The instructions below describe
how to launch a flutter-specific package server.
Or if you've rebuilt fuchsia for a device that is already running a version of
fuchsia, you may be able to reboot without restarting the device:
```shell
$ fx reboot -r
```
If you are building a device that launches the UI at startup, you will likely
need to kill Scenic before running the test.
```shell
$ fx shell killall scenic.cmx
```
## Build the test
You can specify the test's package target to build only the test package, with
its dependencies. This will also build the required runner.
```shell
$ cd "$FLUTTER_ENGINE_DIR/src"
$ ./flutter/tools/gn --fuchsia <flags> \
# for example: --goma --fuchsia-cpu=x64 --runtime-mode=debug
$ ninja -C out/fuchsia_debug_x64 \
flutter/shell/platform/fuchsia/flutter/integration_flutter_tests
```
## Publish the test packages to the Fuchsia package server
The tests currently specify the Fuchsia package server's standard domain,
`fuchsia.com`, as the server to use to resolve (locate and load) the test
packages. So, before running the test, the most recently built `.far` files
need to be published to the Fuchsia package repo:
```shell
$ fx pm publish -a -repo "$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files/" \
-f "$FLUTTER_ENGINE_DIR"/src/out/fuchsia_*64/flutter-embedder-test2-0.far
$ fx pm publish -a -repo "$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files/" \
-f $(find "$FLUTTER_ENGINE_DIR"/src/out/fuchsia_*64 -name parent-view2.far)
$ fx pm publish -a -repo "$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files/" \
-f $(find "$FLUTTER_ENGINE_DIR"/src/out/fuchsia_*64 -name child-view2.far)
```
## Run the test (using the package server at `fuchsia.com`)
```shell
$ fx shell run-test-component \
fuchsia-pkg://fuchsia.com/flutter-embedder-test2#meta/flutter-embedder-test2.cmx
```
## Make a change and re-run the test
If, for example, you only make a change to the Dart code in `parent-view2`, you
can rebuild only the parent-view2 package target, republish it, and then re-run
the test, with:
```shell
$ ninja -C out/fuchsia_debug_x64 \
flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/parent-view2:package
$ fx pm publish -a -repo "$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files/" \
-f $(find "$FLUTTER_ENGINE_DIR"/src/out/fuchsia_*64 -name parent-view2.far)
$ fx shell run-test-component \
fuchsia-pkg://fuchsia.com/flutter-embedder-test2#meta/flutter-embedder-test2.cmx
```
From here, you can modify the Flutter test, rebuild flutter, and usually rerun
the test without rebooting, by repeating the commands above.
The embedder tests must be run on a product without a graphical base shell,
such as `core` because it starts and stops Scenic.
## (Alternative) Serving flutter packages from a custom package server
If you want to use a custom package server, you will need to edit these sources:
* `//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/flutter-embedder-test2.cc`
* `//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/parent-view2/parent_view2.dart`
Search for the component URLs with `fuchsia.com`, and change it to `engine`,
which is the domain currently registered with the custom package server in
`//tools/fuchsia/devshell/serve.sh`.
WARNING: Be careful not to check in that change because CI requires using the
`fuchsia.com` domain/package server.
The default fuchsia package server (launched via `fx serve`) is normally
required, unless all of your test's package dependencies are included in the
fuchsia system image. You can force additional packages into the system image
with `fx set ... --with-base <package>` (instead of using `--with`). For
example, in the `fx set` command above, using, `--with-base scenic`, and so on.
Note, however, that the default `core.x64` configuration bundles the test
runner as if it was included via
`--with //garnet/packages/testing:run_test_component`, so to include the test
runner in the system image requires adding that package as well, via
`--with-base`, instead.
In order to serve fuchsia package dependencies (like `run_test_component`,
`scenic`, `root_presenter`, and `hardware-display-controller-provider`),
without forcing them into the system image, you will need to run the fuchsia
default package server, via `fx serve`.
The `flutter/engine` packages (tests and flutter runners, for dart-based tests)
are served from a separate package server. The `flutter/engine` repo's
`serve.sh` script launches this secondary package server, and configures
package URL rewrite rules to redirect fuchsia's requests for flutter- and
dart-runner packages from `fuchsia.com` to flutter's package server instead.
**IMPORTANT:** _The flutter package server must be launched **after** the
default package server, because both `fx serve` and flutter's `serve.sh` set
package URL rewrite rules, and only the last one wins._
Launch each package server in a separate window or shell:
```shell
$ cd "${FUCHSIA_DIR}"
$ fx serve
```
From the flutter engine `src` directory, run the following script to launch the
`engine` package server, to serve the flutter runner and test components.
```shell
$ flutter/tools/fuchsia/devshell/serve.sh --out out/fuchsia_debug_x64 --only-serve-runners
```
## Run the test, using `engine` as the package server domain
```shell
$ fx shell run-test-component \
fuchsia-pkg://engine/flutter-embedder-test2#meta/flutter-embedder-test2.cmx
```
You can recompile and run the test without needing to re-publish the `.far`.

View File

@@ -0,0 +1,38 @@
# 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("//build/fuchsia/sdk.gni")
import("//flutter/tools/fuchsia/dart/dart_library.gni")
import("//flutter/tools/fuchsia/flutter/flutter_component.gni")
import("//flutter/tools/fuchsia/gn-sdk/package.gni")
dart_library("child-view2_dart_library") {
package_name = "child-view2"
source_dir = "."
sources = [ "child_view2.dart" ]
deps = []
}
flutter_component("child-view2_flutter_component") {
main_package = "child-view2"
component_name = "child-view2"
main_dart = "child_view2.dart"
manifest = rebase_path("meta/child-view2.cmx")
deps = [ ":child-view2_dart_library" ]
}
# TODO(richkadel): The target name is set differently compared to fuchsia.git's flutter_app().
# Unlike in fuchsia.git's version of fuchsia_component, the Fuchsia GN SDK
# version passes the component name to fuchsia_component via it's target_name only.
# GN SDK's fuchsia_component doesn't have a `component_name` argument! So I'm forced to set
# the component name via "target_name". This is a problem in fuchsia_package, which uses
# the target_name to name the fuchsia_pm_tool target, creating duplicate target IDs!
# So I have to change the fuchsia_package name to something that is NOT the component name,
# and then set the package_name (which fuchsia_package does support).
fuchsia_package("package") {
package_name = "child-view2"
deps = [ ":child-view2_flutter_component" ]
}

View File

@@ -0,0 +1,55 @@
// 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:ui';
TestApp app;
void main(List<String> args) {
app = TestApp();
app.run();
}
class TestApp {
static const _yellow = Color.fromARGB(255, 255, 255, 0);
static const _pink = Color.fromARGB(255, 255, 0, 255);
Color _backgroundColor = _pink;
void run() {
window.onPointerDataPacket = (PointerDataPacket packet) {
app.pointerDataPacket(packet);
};
window.onBeginFrame = (Duration duration) {
app.beginFrame(duration);
};
window.scheduleFrame();
}
void beginFrame(Duration duration) {
final pixelRatio = window.devicePixelRatio;
final size = window.physicalSize / pixelRatio;
final physicalBounds = Offset.zero & size * pixelRatio;
final recorder = PictureRecorder();
final canvas = Canvas(recorder, physicalBounds);
canvas.scale(pixelRatio, pixelRatio);
final paint = Paint()..color = this._backgroundColor;
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
final picture = recorder.endRecording();
final sceneBuilder = SceneBuilder()
..pushClipRect(physicalBounds)
..addPicture(Offset.zero, picture)
..pop();
window.render(sceneBuilder.build());
}
void pointerDataPacket(PointerDataPacket packet) {
for (final data in packet.data) {
if (data.change == PointerChange.up) {
this._backgroundColor = _yellow;
}
}
window.scheduleFrame();
}
}

View File

@@ -0,0 +1,13 @@
{
"program": {
"data": "data/child-view2"
},
"sandbox": {
"services": [
"fuchsia.fonts.Provider",
"fuchsia.sys.Environment",
"fuchsia.ui.input.ImeService",
"fuchsia.ui.scenic.Scenic"
]
}
}

View File

@@ -0,0 +1,8 @@
# 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.
name: child_view2
environment:
sdk: '>=2.12.0 <3.0.0'

View File

@@ -0,0 +1,220 @@
// 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.
#include "flutter-embedder-test2.h"
namespace flutter_embedder_test2 {
// TODO(richkadel): To run the test serving the runner and test packages from
// the flutter/engine package server (via
// `//flutter/tools/fuchsia/devshell/serve.sh`), change `fuchsia.com` to
// `engine`.
constexpr char kParentViewUrl[] =
"fuchsia-pkg://fuchsia.com/parent-view2#meta/parent-view2.cmx";
constexpr scenic::Color kParentBackgroundColor = {0x00, 0x00, 0xFF,
0xFF}; // Blue
constexpr scenic::Color kParentTappedColor = {0x00, 0x00, 0x00, 0xFF}; // Black
constexpr scenic::Color kChildBackgroundColor = {0xFF, 0x00, 0xFF,
0xFF}; // Pink
constexpr scenic::Color kChildTappedColor = {0xFF, 0xFF, 0x00, 0xFF}; // Yellow
// TODO(fxb/64201): The new flutter renderer draws overlays as a single, large
// layer. Some parts of this layer are fully transparent, so we want the
// compositor to treat the layer as transparent and blend it with the contents
// below.
//
// The gfx Scenic API only provides one way to mark this layer as transparent
// which is to set an opacity < 1.0 for the entire layer. In practice, we use
// 0.9961 (254 / 255) as an opacity value to force transparency. Unfortunately
// this causes the overlay to blend very slightly and it looks wrong.
//
// Flatland allows marking a layer as transparent while still using a 1.0
// opacity value when blending, so migrating flutter to Flatland will fix this
// issue. For now we just hard-code the broken, blended values.
constexpr scenic::Color kOverlayBackgroundColor1 = {
0x00, 0xFF, 0x0E, 0xFF}; // Green, blended with blue (FEMU local)
constexpr scenic::Color kOverlayBackgroundColor2 = {
0x0E, 0xFF, 0x0E, 0xFF}; // Green, blended with pink (FEMU local)
constexpr scenic::Color kOverlayBackgroundColor3 = {
0x00, 0xFF, 0x0D, 0xFF}; // Green, blended with blue (AEMU infra)
constexpr scenic::Color kOverlayBackgroundColor4 = {
0x0D, 0xFF, 0x0D, 0xFF}; // Green, blended with pink (AEMU infra)
constexpr scenic::Color kOverlayBackgroundColor5 = {
0x00, 0xFE, 0x0D, 0xFF}; // Green, blended with blue (NUC)
constexpr scenic::Color kOverlayBackgroundColor6 = {
0x0D, 0xFF, 0x00, 0xFF}; // Green, blended with pink (NUC)
static size_t OverlayPixelCount(std::map<scenic::Color, size_t>& histogram) {
return histogram[kOverlayBackgroundColor1] +
histogram[kOverlayBackgroundColor2] +
histogram[kOverlayBackgroundColor3] +
histogram[kOverlayBackgroundColor4] +
histogram[kOverlayBackgroundColor5] +
histogram[kOverlayBackgroundColor6];
}
/// Defines a list of services that are injected into the test environment.
/// Unlike the injected-services in CMX which are injected per test package,
/// these are injected per test and result in a more hermetic test environment.
const std::vector<std::pair<const char*, const char*>> GetInjectedServices() {
std::vector<std::pair<const char*, const char*>> injected_services = {{
{"fuchsia.accessibility.semantics.SemanticsManager",
"fuchsia-pkg://fuchsia.com/a11y-manager#meta/a11y-manager.cmx"},
{"fuchsia.deprecatedtimezone.Timezone",
"fuchsia-pkg://fuchsia.com/timezone#meta/timezone.cmx"},
{"fuchsia.fonts.Provider",
"fuchsia-pkg://fuchsia.com/fonts#meta/fonts.cmx"},
{"fuchsia.hardware.display.Provider",
"fuchsia-pkg://fuchsia.com/"
"fake-hardware-display-controller-provider#meta/hdcp.cmx"},
{"fuchsia.intl.PropertyProvider",
"fuchsia-pkg://fuchsia.com/intl_property_manager#meta/"
"intl_property_manager.cmx"},
{"fuchsia.netstack.Netstack",
"fuchsia-pkg://fuchsia.com/netstack#meta/netstack.cmx"},
{"fuchsia.posix.socket.Provider",
"fuchsia-pkg://fuchsia.com/netstack#meta/netstack.cmx"},
{"fuchsia.tracing.provider.Registry",
"fuchsia-pkg://fuchsia.com/trace_manager#meta/trace_manager.cmx"},
{"fuchsia.ui.input.ImeService",
"fuchsia-pkg://fuchsia.com/ime_service#meta/ime_service.cmx"},
{"fuchsia.ui.input.ImeVisibilityService",
"fuchsia-pkg://fuchsia.com/ime_service#meta/ime_service.cmx"},
{"fuchsia.ui.scenic.Scenic",
"fuchsia-pkg://fuchsia.com/scenic#meta/scenic.cmx"},
{"fuchsia.ui.pointerinjector.Registry",
"fuchsia-pkg://fuchsia.com/scenic#meta/scenic.cmx"}, // For
// root_presenter
// TODO(fxbug.dev/82655): Remove this after migrating to RealmBuilder.
{"fuchsia.ui.lifecycle.LifecycleController",
"fuchsia-pkg://fuchsia.com/scenic#meta/scenic.cmx"},
{"fuchsia.ui.policy.Presenter",
"fuchsia-pkg://fuchsia.com/root_presenter#meta/root_presenter.cmx"},
{"fuchsia.ui.input.InputDeviceRegistry",
"fuchsia-pkg://fuchsia.com/root_presenter#meta/root_presenter.cmx"},
}};
return injected_services;
}
TEST_F(FlutterScenicEmbedderTests, Embedding) {
RunAppWithArgs(kParentViewUrl);
// Take screenshot until we see the child-view2's embedded color.
ASSERT_TRUE(TakeScreenshotUntil(
kChildBackgroundColor, [](scenic::Screenshot screenshot,
std::map<scenic::Color, size_t> histogram) {
// Expect parent and child background colors, with parent color > child
// color.
EXPECT_GT(histogram[kParentBackgroundColor], 0u);
EXPECT_GT(histogram[kChildBackgroundColor], 0u);
EXPECT_GT(histogram[kParentBackgroundColor],
histogram[kChildBackgroundColor]);
// Expect all corners to be the parent-view2 background color
EXPECT_EQ(kParentBackgroundColor, screenshot.ColorAtPixelXY(10, 10));
EXPECT_EQ(kParentBackgroundColor,
screenshot.ColorAtPixelXY(screenshot.width() - 10, 0));
EXPECT_EQ(kParentBackgroundColor,
screenshot.ColorAtPixelXY(0, screenshot.height() - 10));
EXPECT_EQ(kParentBackgroundColor,
screenshot.ColorAtPixelXY(screenshot.width() - 10,
screenshot.height() - 10));
}));
}
TEST_F(FlutterScenicEmbedderTests, HittestEmbedding) {
RunAppWithArgs(kParentViewUrl);
// Take screenshot until we see the child-view2's embedded color.
ASSERT_TRUE(TakeScreenshotUntil(kChildBackgroundColor));
// Tap the center of child view2.
InjectInput();
// Take screenshot until we see the child-view2's tapped color.
ASSERT_TRUE(TakeScreenshotUntil(
kChildTappedColor, [](scenic::Screenshot screenshot,
std::map<scenic::Color, size_t> histogram) {
// Expect parent and child background colors, with parent color > child
// color.
EXPECT_GT(histogram[kParentBackgroundColor], 0u);
EXPECT_EQ(histogram[kChildBackgroundColor], 0u);
EXPECT_GT(histogram[kChildTappedColor], 0u);
EXPECT_GT(histogram[kParentBackgroundColor],
histogram[kChildTappedColor]);
}));
}
TEST_F(FlutterScenicEmbedderTests, HittestDisabledEmbedding) {
RunAppWithArgs(kParentViewUrl, {"--no-hitTestable"});
// Take screenshots until we see the child-view2's embedded color.
ASSERT_TRUE(TakeScreenshotUntil(kChildBackgroundColor));
// Tap the center of child view2. Since it's not hit-testable, the tap should
// go to the parent.
InjectInput();
// The parent-view2 should change color.
ASSERT_TRUE(TakeScreenshotUntil(
kParentTappedColor, [](scenic::Screenshot screenshot,
std::map<scenic::Color, size_t> histogram) {
// Expect parent and child background colors, with parent color > child
// color.
EXPECT_EQ(histogram[kParentBackgroundColor], 0u);
EXPECT_GT(histogram[kParentTappedColor], 0u);
EXPECT_GT(histogram[kChildBackgroundColor], 0u);
EXPECT_EQ(histogram[kChildTappedColor], 0u);
EXPECT_GT(histogram[kParentTappedColor],
histogram[kChildBackgroundColor]);
}));
}
TEST_F(FlutterScenicEmbedderTests, EmbeddingWithOverlay) {
RunAppWithArgs(kParentViewUrl, {"--showOverlay"});
// Take screenshot until we see the child-view2's embedded color.
ASSERT_TRUE(TakeScreenshotUntil(
kChildBackgroundColor, [](scenic::Screenshot screenshot,
std::map<scenic::Color, size_t> histogram) {
// Expect parent, overlay and child background colors.
// With parent color > child color and overlay color > child color.
const size_t overlay_pixel_count = OverlayPixelCount(histogram);
EXPECT_GT(histogram[kParentBackgroundColor], 0u);
EXPECT_GT(overlay_pixel_count, 0u);
EXPECT_GT(histogram[kChildBackgroundColor], 0u);
EXPECT_GT(histogram[kParentBackgroundColor],
histogram[kChildBackgroundColor]);
EXPECT_GT(overlay_pixel_count, histogram[kChildBackgroundColor]);
}));
}
TEST_F(FlutterScenicEmbedderTests, HittestEmbeddingWithOverlay) {
RunAppWithArgs(kParentViewUrl, {"--showOverlay"});
// Take screenshot until we see the child-view2's embedded color.
ASSERT_TRUE(TakeScreenshotUntil(kChildBackgroundColor));
// Tap the center of child view2.
InjectInput();
// Take screenshot until we see the child-view2's tapped color.
ASSERT_TRUE(TakeScreenshotUntil(
kChildTappedColor, [](scenic::Screenshot screenshot,
std::map<scenic::Color, size_t> histogram) {
// Expect parent, overlay and child background colors.
// With parent color > child color and overlay color > child color.
const size_t overlay_pixel_count = OverlayPixelCount(histogram);
EXPECT_GT(histogram[kParentBackgroundColor], 0u);
EXPECT_GT(overlay_pixel_count, 0u);
EXPECT_EQ(histogram[kChildBackgroundColor], 0u);
EXPECT_GT(histogram[kChildTappedColor], 0u);
EXPECT_GT(histogram[kParentBackgroundColor],
histogram[kChildTappedColor]);
EXPECT_GT(overlay_pixel_count, histogram[kChildTappedColor]);
}));
}
} // namespace flutter_embedder_test2

View 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.
#ifndef SRC_UI_TESTS_INTEGRATION_FLUTTER_TESTS_EMBEDDER_flutter_embedder_test2_H_
#define SRC_UI_TESTS_INTEGRATION_FLUTTER_TESTS_EMBEDDER_flutter_embedder_test2_H_
#include <fuchsia/ui/lifecycle/cpp/fidl.h>
#include <fuchsia/ui/policy/cpp/fidl.h>
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <gtest/gtest.h>
#include <lib/async/cpp/task.h>
#include <lib/fidl/cpp/binding_set.h>
#include <lib/sys/cpp/component_context.h>
#include <lib/sys/cpp/testing/test_with_environment.h>
#include <lib/ui/scenic/cpp/view_token_pair.h>
#include <lib/zx/clock.h>
#include <zircon/status.h>
#include <zircon/time.h>
#include "flutter/fml/logging.h"
#include <vector>
#include "src/lib/ui/base_view/embedded_view_utils.h"
#include "src/ui/testing/views/color.h"
#include "src/ui/testing/views/embedder_view.h"
namespace flutter_embedder_test2 {
/// Defines a list of services that are injected into the test environment.
/// Unlike the injected-services in CMX which are injected per test package,
/// these are injected per test and result in a more hermetic test environment.
const std::vector<std::pair<const char*, const char*>> GetInjectedServices();
// Timeout when waiting on Scenic API calls like |GetDisplayInfo|.
constexpr zx::duration kCallTimeout = zx::sec(5);
// Timeout for Scenic's |TakeScreenshot| FIDL call.
constexpr zx::duration kScreenshotTimeout = zx::sec(10);
// Timeout to fail the test if it goes beyond this duration.
constexpr zx::duration kTestTimeout = zx::min(1);
class FlutterScenicEmbedderTests : public sys::testing::TestWithEnvironment,
public ::testing::Test {
public:
// |testing::Test|
void SetUp() override {
Test::SetUp();
// Create test-specific launchable services.
auto services = TestWithEnvironment::CreateServices();
for (const auto& service_info : GetInjectedServices()) {
zx_status_t status = services->AddServiceWithLaunchInfo(
{.url = service_info.second}, service_info.first);
FML_CHECK(status == ZX_OK)
<< "Failed to add service " << service_info.first;
}
environment_ = CreateNewEnclosingEnvironment(
"flutter-embedder-test2s", std::move(services),
{.inherit_parent_services = true});
WaitForEnclosingEnvToStart(environment());
FML_VLOG(fml::LOG_INFO) << "Created test environment.";
// Connects to scenic lifecycle controller in order to shutdown scenic at
// the end of the test. This ensures the correct ordering of shutdown under
// CFv1: first scenic, then the fake display controller.
//
// TODO(fxbug.dev/82655): Remove this after migrating to RealmBuilder.
environment_->ConnectToService<fuchsia::ui::lifecycle::LifecycleController>(
scenic_lifecycle_controller_.NewRequest());
environment_->ConnectToService(scenic_.NewRequest());
scenic_.set_error_handler([](zx_status_t status) {
FAIL() << "Lost connection to Scenic: " << zx_status_get_string(status);
});
// Post a "just in case" quit task, if the test hangs.
async::PostDelayedTask(
dispatcher(),
[] {
FML_LOG(FATAL)
<< "\n\n>> Test did not complete in time, terminating. <<\n\n";
},
kTestTimeout);
}
// |testing::Test|
void TearDown() override {
// Avoid spurious errors since we are about to kill scenic.
//
// TODO(fxbug.dev/82655): Remove this after migrating to RealmBuilder.
scenic_.set_error_handler(nullptr);
zx_status_t terminate_status = scenic_lifecycle_controller_->Terminate();
FML_CHECK(terminate_status == ZX_OK)
<< "Failed to terminate Scenic with status: "
<< zx_status_get_string(terminate_status);
}
sys::testing::EnclosingEnvironment* environment() {
return environment_.get();
}
fuchsia::ui::views::ViewToken CreatePresentationViewToken() {
auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
auto presenter =
environment()->ConnectToService<fuchsia::ui::policy::Presenter>();
presenter.set_error_handler([](zx_status_t status) {
FAIL() << "presenter: " << zx_status_get_string(status);
});
presenter->PresentView(std::move(view_holder_token), nullptr);
return std::move(view_token);
}
void RunAppWithArgs(const std::string& component_url,
const std::vector<std::string>& component_args = {}) {
scenic::EmbeddedViewInfo flutter_runner =
scenic::LaunchComponentAndCreateView(environment()->launcher_ptr(),
component_url, component_args);
flutter_runner.controller.events().OnTerminated = [](auto...) { FAIL(); };
// Present the view.
embedder_view_.emplace(scenic::ViewContext{
.session_and_listener_request =
scenic::CreateScenicSessionPtrAndListenerRequest(scenic_.get()),
.view_token = CreatePresentationViewToken(),
});
// Embed the view.
bool is_rendering = false;
embedder_view_->EmbedView(
std::move(flutter_runner),
[&is_rendering](fuchsia::ui::gfx::ViewState view_state) {
is_rendering = view_state.is_rendering;
});
RunLoopUntil([&is_rendering] { return is_rendering; });
FML_LOG(INFO) << "Launched component: " << component_url;
}
scenic::Screenshot TakeScreenshot() {
FML_LOG(INFO) << "Taking screenshot... ";
fuchsia::ui::scenic::ScreenshotData screenshot_out;
scenic_->TakeScreenshot(
[this, &screenshot_out](fuchsia::ui::scenic::ScreenshotData screenshot,
bool status) {
EXPECT_TRUE(status) << "Failed to take screenshot";
screenshot_out = std::move(screenshot);
QuitLoop();
});
EXPECT_FALSE(RunLoopWithTimeout(kScreenshotTimeout))
<< "Timed out waiting for screenshot.";
FML_LOG(INFO) << "Screenshot captured.";
return scenic::Screenshot(screenshot_out);
}
bool TakeScreenshotUntil(
scenic::Color color,
fit::function<void(scenic::Screenshot, std::map<scenic::Color, size_t>)>
callback = nullptr,
zx::duration timeout = kTestTimeout) {
return RunLoopWithTimeoutOrUntil(
[this, &callback, &color] {
auto screenshot = TakeScreenshot();
auto histogram = screenshot.Histogram();
bool color_found = histogram[color] > 0;
if (color_found && callback != nullptr) {
callback(std::move(screenshot), std::move(histogram));
}
return color_found;
},
timeout);
}
// Inject directly into Root Presenter, using fuchsia.ui.input FIDLs.
void InjectInput() {
using fuchsia::ui::input::InputReport;
// Device parameters
auto parameters = fuchsia::ui::input::TouchscreenDescriptor::New();
*parameters = {.x = {.range = {.min = -1000, .max = 1000}},
.y = {.range = {.min = -1000, .max = 1000}},
.max_finger_id = 10};
FML_LOG(INFO) << "Injecting input... ";
// Register it against Root Presenter.
fuchsia::ui::input::DeviceDescriptor device{.touchscreen =
std::move(parameters)};
auto registry =
environment()
->ConnectToService<fuchsia::ui::input::InputDeviceRegistry>();
fuchsia::ui::input::InputDevicePtr connection;
registry->RegisterDevice(std::move(device), connection.NewRequest());
{
// Inject one input report, then a conclusion (empty) report.
auto touch = fuchsia::ui::input::TouchscreenReport::New();
*touch = {
.touches = {{.finger_id = 1, .x = 0, .y = 0}}}; // center of display
InputReport report{
.event_time = static_cast<uint64_t>(zx::clock::get_monotonic().get()),
.touchscreen = std::move(touch)};
connection->DispatchReport(std::move(report));
}
{
auto touch = fuchsia::ui::input::TouchscreenReport::New();
InputReport report{
.event_time = static_cast<uint64_t>(zx::clock::get_monotonic().get()),
.touchscreen = std::move(touch)};
connection->DispatchReport(std::move(report));
}
FML_LOG(INFO) << "Input dispatched.";
}
private:
const std::unique_ptr<sys::ComponentContext> component_context_;
std::unique_ptr<sys::testing::EnclosingEnvironment> environment_;
fuchsia::ui::lifecycle::LifecycleControllerSyncPtr
scenic_lifecycle_controller_;
fuchsia::ui::scenic::ScenicPtr scenic_;
// Wrapped in optional since the view is not created until the middle of SetUp
std::optional<scenic::EmbedderView> embedder_view_;
};
} // namespace flutter_embedder_test2
#endif // SRC_UI_TESTS_INTEGRATION_FLUTTER_TESTS_EMBEDDER_flutter_embedder_test2_H_

View File

@@ -0,0 +1,25 @@
{
"facets": {
"fuchsia.test": {
"system-services": [
"fuchsia.scheduler.ProfileProvider",
"fuchsia.sysmem.Allocator",
"fuchsia.vulkan.loader.Loader"
]
}
},
"program": {
"binary": "bin/app"
},
"sandbox": {
"services": [
"fuchsia.logger.LogSink",
"fuchsia.sys.Environment",
"fuchsia.sys.Launcher",
"fuchsia.sys.Loader",
"fuchsia.sysmem.Allocator",
"fuchsia.tracing.provider.Registry",
"fuchsia.vulkan.loader.Loader"
]
}
}

View File

@@ -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.
import("//build/fuchsia/sdk.gni")
import("//flutter/tools/fuchsia/dart/dart_library.gni")
import("//flutter/tools/fuchsia/flutter/flutter_component.gni")
import("//flutter/tools/fuchsia/gn-sdk/package.gni")
dart_library("parent-view2_dart_library") {
package_name = "parent-view2"
source_dir = "."
sources = [ "parent_view2.dart" ]
deps = [
"//flutter/shell/platform/fuchsia/dart:args",
"//flutter/shell/platform/fuchsia/dart:vector_math",
"//flutter/tools/fuchsia/dart:fuchsia_services",
"//flutter/tools/fuchsia/dart:zircon",
"//flutter/tools/fuchsia/fidl:fuchsia.sys",
"//flutter/tools/fuchsia/fidl:fuchsia.ui.app",
"//flutter/tools/fuchsia/fidl:fuchsia.ui.views",
]
}
flutter_component("parent-view2_flutter_component") {
main_package = "parent-view2"
component_name = "parent-view2"
main_dart = "parent_view2.dart"
manifest = rebase_path("meta/parent-view2.cmx")
deps = [ ":parent-view2_dart_library" ]
}
# TODO(richkadel): The target name is set differently compared to fuchsia.git's flutter_app().
# Unlike in fuchsia.git's version of fuchsia_component, the Fuchsia GN SDK
# version passes the component name to fuchsia_component via it's target_name only.
# GN SDK's fuchsia_component doesn't have a `component_name` argument! So I'm forced to set
# the component name via "target_name". This is a problem in fuchsia_package, which uses
# the target_name to name the fuchsia_pm_tool target, creating duplicate target IDs!
# So I have to change the fuchsia_package name to something that is NOT the component name,
# and then set the package_name (which fuchsia_package does support).
fuchsia_package("package") {
package_name = "parent-view2"
deps = [ ":parent-view2_flutter_component" ]
}

View File

@@ -0,0 +1,14 @@
{
"program": {
"data": "data/parent-view2"
},
"sandbox": {
"services": [
"fuchsia.fonts.Provider",
"fuchsia.sys.Environment",
"fuchsia.sys.Launcher",
"fuchsia.ui.input.ImeService",
"fuchsia.ui.scenic.Scenic"
]
}
}

View File

@@ -0,0 +1,229 @@
// 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:convert';
import 'dart:typed_data';
import 'dart:ui';
import 'package:vector_math/vector_math_64.dart' as vector_math_64;
import 'package:args/args.dart';
import 'package:fidl_fuchsia_sys/fidl_async.dart';
import 'package:fidl_fuchsia_ui_app/fidl_async.dart';
import 'package:fidl_fuchsia_ui_views/fidl_async.dart';
import 'package:fuchsia_services/services.dart';
import 'package:zircon/zircon.dart';
// TODO(richkadel): To run the test serving the runner and test packages from
// the flutter/engine package server (via
// `//flutter/tools/fuchsia/devshell/serve.sh`), change `fuchsia.com` to
// `engine`.
const _kChildAppUrl =
'fuchsia-pkg://fuchsia.com/child-view2#meta/child-view2.cmx';
TestApp app;
void main(List<String> args) {
final parser = ArgParser()
..addFlag('showOverlay', defaultsTo: false)
..addFlag('hitTestable', defaultsTo: true)
..addFlag('focusable', defaultsTo: true);
final arguments = parser.parse(args);
for (final option in arguments.options) {
print('parent-view2: $option: ${arguments[option]}');
}
final childViewToken = _launchApp(_kChildAppUrl);
app = TestApp(
ChildView(childViewToken),
showOverlay: arguments['showOverlay'],
hitTestable: arguments['hitTestable'],
focusable: arguments['focusable'],
);
app.run();
}
class TestApp {
static const _black = Color.fromARGB(255, 0, 0, 0);
static const _blue = Color.fromARGB(255, 0, 0, 255);
final ChildView childView;
final bool showOverlay;
final bool hitTestable;
final bool focusable;
Color _backgroundColor = _blue;
TestApp(
this.childView,
{this.showOverlay = false,
this.hitTestable = true,
this.focusable = true}) {
}
void run() {
childView.create(hitTestable, focusable, (ByteData reply) {
// The child-view2 should be attached to Scenic now.
// Ready to build the scene.
window.onPointerDataPacket = (PointerDataPacket packet) {
for (final data in packet.data) {
if (data.change == PointerChange.up) {
this._backgroundColor = _black;
}
}
window.scheduleFrame();
};
window.onBeginFrame = (Duration duration) {
app.beginFrame(duration);
};
window.scheduleFrame();
});
}
void beginFrame(Duration duration) {
final windowPhysicalBounds = Offset.zero & window.physicalSize;
final pixelRatio = window.devicePixelRatio;
final windowSize = window.physicalSize / pixelRatio;
final windowBounds = Offset.zero & windowSize;
final recorder = PictureRecorder();
final canvas = Canvas(recorder, windowPhysicalBounds);
canvas.scale(pixelRatio);
final paint = Paint()..color = this._backgroundColor;
canvas.drawRect(windowBounds, paint);
final picture = recorder.endRecording();
final sceneBuilder = SceneBuilder()
..pushClipRect(windowPhysicalBounds)
..addPicture(Offset.zero, picture);
final childPhysicalSize = window.physicalSize * 0.33;
// Alignment.center
final windowCenter = windowSize.center(Offset.zero);
final windowPhysicalCenter = window.physicalSize.center(Offset.zero);
final childPhysicalOffset = windowPhysicalCenter - childPhysicalSize.center(Offset.zero);
sceneBuilder
..pushTransform(
vector_math_64.Matrix4.translationValues(childPhysicalOffset.dx,
childPhysicalOffset.dy,
0.0).storage)
..addPlatformView(childView.viewId,
width: childPhysicalSize.width,
height: childPhysicalSize.height)
..pop()
;
if (showOverlay) {
final containerSize = windowSize * .66;
// Alignment.center
final containerOffset = windowCenter - containerSize.center(Offset.zero);
final overlaySize = containerSize * 0.5;
// Alignment.topRight
final overlayOffset = Offset(
containerOffset.dx + containerSize.width - overlaySize.width,
containerOffset.dy);
final overlayPhysicalSize = overlaySize * pixelRatio;
final overlayPhysicalOffset = overlayOffset * pixelRatio;
final overlayPhysicalBounds = overlayPhysicalOffset & overlayPhysicalSize;
final recorder = PictureRecorder();
final overlayCullRect = Offset.zero & overlayPhysicalSize; // in canvas physical coordinates
final canvas = Canvas(recorder, overlayCullRect);
canvas.scale(pixelRatio);
final paint = Paint()..color = Color.fromARGB(255, 0, 255, 0);
canvas.drawRect(Offset.zero & overlaySize, paint);
final overlayPicture = recorder.endRecording();
sceneBuilder
..pushClipRect(overlayPhysicalBounds) // in window physical coordinates
..addPicture(overlayPhysicalOffset, overlayPicture)
..pop()
;
}
sceneBuilder.pop();
window.render(sceneBuilder.build());
}
}
ViewHolderToken _launchApp(String componentUrl) {
final incoming = Incoming();
final componentController = ComponentControllerProxy();
final launcher = LauncherProxy();
Incoming.fromSvcPath()
..connectToService(launcher)
..close();
launcher.createComponent(
LaunchInfo(
url: componentUrl,
directoryRequest: incoming.request().passChannel(),
),
componentController.ctrl.request(),
);
launcher.ctrl.close();
ViewProviderProxy viewProvider = ViewProviderProxy();
incoming
..connectToService(viewProvider)
..close();
final viewTokens = EventPairPair();
assert(viewTokens.status == ZX.OK);
final viewHolderToken = ViewHolderToken(value: viewTokens.first);
final viewToken = ViewToken(value: viewTokens.second);
viewProvider.createView(viewToken.value, null, null);
viewProvider.ctrl.close();
return viewHolderToken;
}
class ChildView {
final ViewHolderToken viewToken;
final int viewId;
ChildView(this.viewToken) : viewId = viewToken.value.handle.handle {
assert(viewId != null);
}
void create(
bool hitTestable,
bool focusable,
PlatformMessageResponseCallback callback) {
// Construct the dart:ui platform message to create the view, and when the
// return callback is invoked, build the scene. At that point, it is safe
// to embed the child-view2 in the scene.
final viewOcclusionHint = Rect.zero;
final Map<String, dynamic> args = <String, dynamic>{
'viewId': viewId,
'hitTestable': hitTestable,
'focusable': focusable,
'viewOcclusionHintLTRB': <double>[
viewOcclusionHint.left,
viewOcclusionHint.top,
viewOcclusionHint.right,
viewOcclusionHint.bottom
],
};
final ByteData createViewMessage = utf8.encoder.convert(
json.encode(<String, Object>{
'method': 'View.create',
'args': args,
})
).buffer.asByteData();
final platformViewsChannel = 'flutter/platform_views';
PlatformDispatcher.instance.sendPlatformMessage(
platformViewsChannel,
createViewMessage,
callback);
}
}

View File

@@ -0,0 +1,8 @@
# 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.
name: parent-view2
environment:
sdk: '>=2.12.0 <3.0.0'

View File

@@ -0,0 +1,30 @@
# 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("//build/fuchsia/sdk.gni")
source_set("base_view") {
sources = [
"base_view.cc",
"base_view.h",
"embedded_view_utils.cc",
"embedded_view_utils.h",
"math.h",
]
include_dirs = [ "//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/fuchsia_testing" ]
public_deps = [
"$fuchsia_sdk_root/fidl:fuchsia.sys",
"$fuchsia_sdk_root/fidl:fuchsia.ui.app",
"$fuchsia_sdk_root/fidl:fuchsia.ui.gfx",
"$fuchsia_sdk_root/fidl:fuchsia.ui.input",
"$fuchsia_sdk_root/fidl:fuchsia.ui.views",
"$fuchsia_sdk_root/pkg:scenic_cpp",
"$fuchsia_sdk_root/pkg:sys_cpp",
"//flutter/fml",
]
deps = [ "$fuchsia_sdk_root/pkg:trace" ]
}

View File

@@ -0,0 +1,240 @@
// 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.
#include "src/lib/ui/base_view/base_view.h"
#include <lib/trace/event.h>
#include <lib/ui/scenic/cpp/commands.h>
#include <lib/ui/scenic/cpp/view_token_pair.h>
#include <zircon/status.h>
#include "flutter/fml/logging.h"
namespace scenic {
BaseView::BaseView(ViewContext context, const std::string& debug_name)
: component_context_(context.component_context),
listener_binding_(this,
std::move(context.session_and_listener_request.second)),
session_(std::move(context.session_and_listener_request.first)),
root_node_(&session_),
ime_client_(this),
enable_ime_(context.enable_ime) {
if (!context.view_ref_pair) {
context.view_ref_pair = scenic::ViewRefPair::New();
}
view_.emplace(&session_, std::move(context.view_token),
std::move(context.view_ref_pair->control_ref),
std::move(context.view_ref_pair->view_ref), debug_name);
FML_DCHECK(view_);
session_.SetDebugName(debug_name);
// Listen for metrics events on our top node.
root_node_.SetEventMask(fuchsia::ui::gfx::kMetricsEventMask);
view_->AddChild(root_node_);
if (enable_ime_) {
ime_manager_ =
component_context_->svc()->Connect<fuchsia::ui::input::ImeService>();
ime_.set_error_handler([](zx_status_t status) {
FML_LOG(ERROR) << "Interface error on: Input Method Editor "
<< zx_status_get_string(status);
});
ime_manager_.set_error_handler([](zx_status_t status) {
FML_LOG(ERROR) << "Interface error on: Text Sync Service "
<< zx_status_get_string(status);
});
}
// We must immediately invalidate the scene, otherwise we wouldn't ever hook
// the View up to the ViewHolder. An alternative would be to require
// subclasses to call an Init() method to set up the initial connection.
InvalidateScene();
}
void BaseView::SetReleaseHandler(fit::function<void(zx_status_t)> callback) {
listener_binding_.set_error_handler(std::move(callback));
}
void BaseView::InvalidateScene(PresentCallback present_callback) {
TRACE_DURATION("view", "BaseView::InvalidateScene");
if (present_callback) {
callbacks_for_next_present_.push_back(std::move(present_callback));
}
if (invalidate_pending_)
return;
invalidate_pending_ = true;
// Present the scene ASAP. Pass in the last presentation time; otherwise, if
// presentation_time argument is less than the previous time passed to
// PresentScene, the Session will be closed.
// (We cannot use the current time because the last requested presentation
// time, |last_presentation_time_|, could still be in the future. This is
// because Session.Present() returns after it _begins_ preparing the given
// frame, not after it is presented.)
if (!present_pending_)
PresentScene(last_presentation_time_);
}
void BaseView::PresentScene() {
PresentScene(last_presentation_time_);
}
void BaseView::OnScenicEvent(std::vector<fuchsia::ui::scenic::Event> events) {
TRACE_DURATION("view", "BaseView::OnScenicEvent");
for (auto& event : events) {
switch (event.Which()) {
case ::fuchsia::ui::scenic::Event::Tag::kGfx:
switch (event.gfx().Which()) {
case ::fuchsia::ui::gfx::Event::Tag::kViewPropertiesChanged: {
auto& evt = event.gfx().view_properties_changed();
FML_DCHECK(view_->id() == evt.view_id);
auto old_props = view_properties_;
view_properties_ = evt.properties;
::fuchsia::ui::gfx::BoundingBox layout_box =
ViewPropertiesLayoutBox(view_properties_);
logical_size_ = scenic::Max(layout_box.max - layout_box.min, 0.f);
physical_size_.x = logical_size_.x * metrics_.scale_x;
physical_size_.y = logical_size_.y * metrics_.scale_y;
physical_size_.z = logical_size_.z * metrics_.scale_z;
OnPropertiesChanged(std::move(old_props));
InvalidateScene();
break;
}
case fuchsia::ui::gfx::Event::Tag::kMetrics: {
auto& evt = event.gfx().metrics();
if (evt.node_id == root_node_.id()) {
auto old_metrics = metrics_;
metrics_ = std::move(evt.metrics);
physical_size_.x = logical_size_.x * metrics_.scale_x;
physical_size_.y = logical_size_.y * metrics_.scale_y;
physical_size_.z = logical_size_.z * metrics_.scale_z;
OnMetricsChanged(std::move(old_metrics));
InvalidateScene();
}
break;
}
default: {
OnScenicEvent(std::move(event));
}
}
break;
case ::fuchsia::ui::scenic::Event::Tag::kInput: {
if (event.input().Which() ==
fuchsia::ui::input::InputEvent::Tag::kFocus &&
enable_ime_) {
OnHandleFocusEvent(event.input().focus());
}
OnInputEvent(std::move(event.input()));
break;
}
case ::fuchsia::ui::scenic::Event::Tag::kUnhandled: {
OnUnhandledCommand(std::move(event.unhandled()));
break;
}
default: {
OnScenicEvent(std::move(event));
}
}
}
}
void BaseView::PresentScene(zx_time_t presentation_time) {
TRACE_DURATION("view", "BaseView::PresentScene");
// TODO(fxbug.dev/24406): Remove this when BaseView::PresentScene() is
// deprecated, see fxbug.dev/24573.
if (present_pending_)
return;
present_pending_ = true;
// Keep track of the most recent presentation time we've passed to
// Session.Present(), for use in InvalidateScene().
last_presentation_time_ = presentation_time;
TRACE_FLOW_BEGIN("gfx", "Session::Present", session_present_count_);
++session_present_count_;
session()->Present(
presentation_time,
[this, present_callbacks = std::move(callbacks_for_next_present_)](
fuchsia::images::PresentationInfo info) mutable {
TRACE_DURATION("view", "BaseView::PresentationCallback");
TRACE_FLOW_END("gfx", "present_callback", info.presentation_time);
FML_DCHECK(present_pending_);
zx_time_t next_presentation_time =
info.presentation_time + info.presentation_interval;
bool present_needed = false;
if (invalidate_pending_) {
invalidate_pending_ = false;
OnSceneInvalidated(std::move(info));
present_needed = true;
}
for (auto& callback : present_callbacks) {
callback(info);
}
present_pending_ = false;
if (present_needed)
PresentScene(next_presentation_time);
});
callbacks_for_next_present_.clear();
}
// |fuchsia::ui::input::InputMethodEditorClient|
void BaseView::DidUpdateState(
fuchsia::ui::input::TextInputState state,
std::unique_ptr<fuchsia::ui::input::InputEvent> input_event) {
if (input_event) {
const fuchsia::ui::input::InputEvent& input = *input_event;
fuchsia::ui::input::InputEvent input_event_copy;
fidl::Clone(input, &input_event_copy);
OnInputEvent(std::move(input_event_copy));
}
}
// |fuchsia::ui::input::InputMethodEditorClient|
void BaseView::OnAction(fuchsia::ui::input::InputMethodAction action) {}
bool BaseView::OnHandleFocusEvent(const fuchsia::ui::input::FocusEvent& focus) {
if (focus.focused) {
ActivateIme();
return true;
} else if (!focus.focused) {
DeactivateIme();
return true;
}
return false;
}
void BaseView::ActivateIme() {
ime_manager_->GetInputMethodEditor(
fuchsia::ui::input::KeyboardType::TEXT, // keyboard type
fuchsia::ui::input::InputMethodAction::DONE, // input method action
fuchsia::ui::input::TextInputState{}, // initial state
ime_client_.NewBinding(), // client
ime_.NewRequest() // editor
);
}
void BaseView::DeactivateIme() {
if (ime_) {
ime_manager_->HideKeyboard();
ime_ = nullptr;
}
if (ime_client_.is_bound()) {
ime_client_.Unbind();
}
}
} // namespace scenic

View File

@@ -0,0 +1,210 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_LIB_UI_BASE_VIEW_BASE_VIEW_H_
#define SRC_LIB_UI_BASE_VIEW_BASE_VIEW_H_
#include <fuchsia/ui/gfx/cpp/fidl.h>
#include <fuchsia/ui/input/cpp/fidl.h>
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <lib/sys/cpp/component_context.h>
#include <lib/ui/scenic/cpp/resources.h>
#include <lib/ui/scenic/cpp/session.h>
#include <lib/ui/scenic/cpp/view_ref_pair.h>
#include "src/lib/ui/base_view/embedded_view_utils.h"
#include "src/lib/ui/base_view/math.h"
namespace scenic {
// Parameters for creating a BaseView.
struct ViewContext {
scenic::SessionPtrAndListenerRequest session_and_listener_request;
fuchsia::ui::views::ViewToken view_token;
std::optional<ViewRefPair> view_ref_pair;
sys::ComponentContext* component_context;
bool enable_ime = false;
};
// Abstract base implementation of a view for simple applications.
// Subclasses must handle layout and provide content for the scene by
// overriding the virtual methods defined in this class.
//
// It is not necessary to use this class to implement all Views.
// This class is merely intended to make the simple apps easier to write.
class BaseView : private fuchsia::ui::scenic::SessionListener,
private fuchsia::ui::input::InputMethodEditorClient {
public:
using PresentCallback =
fit::function<void(const fuchsia::images::PresentationInfo& info)>;
// Subclasses are typically created by ViewProviderService::CreateView(),
// which provides the necessary args to pass down to this base class.
BaseView(ViewContext context, const std::string& debug_name);
BaseView(const BaseView&) = delete;
// |root_node| is the node directly under our View; i.e. it's the top-most
// node within the tree under our View. Use it to attach any resources for
// your UI.
scenic::EntityNode& root_node() { return root_node_; }
Session* session() { return &session_; }
sys::ComponentContext* component_context() { return component_context_; }
fuchsia::ui::gfx::ViewProperties view_properties() const {
return view_properties_;
}
// Returns true if the view has a non-empty size in logical pixels.
bool has_logical_size() const {
auto& sz = logical_size();
return sz.x > 0.f && sz.y > 0.f && sz.z > 0.f;
}
// Gets the size of the view in logical pixels.
// This value is zero until the view receives a layout from its parent.
const fuchsia::ui::gfx::vec3& logical_size() const { return logical_size_; }
// Returns true if the view has a non-empty size in physical pixels.
bool has_physical_size() const {
auto& sz = physical_size();
return sz.x > 0.f && sz.y > 0.f && sz.z > 0.f;
}
// Gets the size of the view in physical pixels.
// This value is zero until the view receives a layout from its parent
// and metrics from its session.
const fuchsia::ui::gfx::vec3& physical_size() const { return physical_size_; }
// Returns true if the view has received metrics from its session.
bool has_metrics() const {
return metrics_.scale_x > 0.f && metrics_.scale_y > 0.f &&
metrics_.scale_z > 0.f;
}
// Gets the view's metrics.
// This value is zero until the view receives metrics from its session.
const fuchsia::ui::gfx::Metrics& metrics() const { return metrics_; }
// Sets a callback which is invoked when the view's owner releases the
// view causing the view manager to unregister it.
//
// This should be used to implement cleanup policies to release resources
// associated with the view (including the object itself).
void SetReleaseHandler(fit::function<void(zx_status_t)> callback);
// Invalidates the scene, causing |OnSceneInvalidated()| to be invoked
// during the next frame. When the Present() callback corresponding to this
// invalidate is invoked, the optional |present_callback| will also be
// invoked.
void InvalidateScene(PresentCallback present_callback = nullptr);
// Called when it's time for the view to update its scene contents due to
// invalidation. The new contents are presented once this function returns.
//
// The default implementation does nothing.
virtual void OnSceneInvalidated(
fuchsia::images::PresentationInfo presentation_info) {}
// Called when the view's properties have changed.
//
// The subclass should compare the old and new properties and make note of
// whether these property changes will affect the layout or content of
// the view then update accordingly.
//
// The default implementation does nothing.
virtual void OnPropertiesChanged(
fuchsia::ui::gfx::ViewProperties old_properties) {}
// Called when the view's metrics have changed.
//
// The subclass should compare the old and new metrics and make note of
// whether this change will affect the layout or content of the view then
// update accordingly.
//
// The default implementation does nothing.
virtual void OnMetricsChanged(fuchsia::ui::gfx::Metrics old_metrics){};
// Called to handle an input event.
//
// The default implementation does nothing.
virtual void OnInputEvent(fuchsia::ui::input::InputEvent event) {}
// Called when a command sent by the client was not handled by Scenic.
//
// The default implementation does nothing.
virtual void OnUnhandledCommand(fuchsia::ui::scenic::Command unhandled) {}
// Called when an event that is not handled directly by BaseView is received.
// For example, BaseView handles fuchsia::ui::gfx::ViewPropertiesChangedEvent,
// and notifies the subclass via OnPropertiesChanged(); not all events are
// handled in this way.
//
// The default implementation does nothing.
virtual void OnScenicEvent(fuchsia::ui::scenic::Event) {}
protected:
// An alternative way to update the scene. Provide a faster way to cause a
// present in comparison to InvalidateScene(). Caller should update the
// scene contents before calling this method.
void PresentScene();
private:
// |scenic::SessionListener|
//
// Iterates over the received events and either handles them in a sensible way
// (e.g. fuchsia::ui::gfx::ViewPropertiesChangedEvent is handled by invoking
// the virtual method OnPropertiesChanged()), or delegates handling to the
// subclass via the single-event version of OnEvent() above.
//
// Subclasses should not override this.
void OnScenicEvent(std::vector<fuchsia::ui::scenic::Event> events) override;
// |fuchsia::ui::input::InputMethodEditorClient|
void DidUpdateState(
fuchsia::ui::input::TextInputState state,
std::unique_ptr<fuchsia::ui::input::InputEvent> event) override;
// |fuchsia::ui::input::InputMethodEditorClient|
void OnAction(fuchsia::ui::input::InputMethodAction action) override;
void PresentScene(zx_time_t presentation_time);
// Handles focus event when IME is enabled. This event is used to activate
// or deactivate the IME client.
bool OnHandleFocusEvent(const fuchsia::ui::input::FocusEvent& focus);
// Gets a new input method editor from the IME manager.
void ActivateIme();
// Detaches the input method editor connection, ending the edit session and
// closing the onscreen keyboard.
void DeactivateIme();
sys::ComponentContext* const component_context_;
fidl::Binding<fuchsia::ui::scenic::SessionListener> listener_binding_;
Session session_;
std::optional<scenic::View> view_;
scenic::EntityNode root_node_;
fidl::Binding<fuchsia::ui::input::InputMethodEditorClient> ime_client_;
fuchsia::ui::input::InputMethodEditorPtr ime_;
fuchsia::ui::input::ImeServicePtr ime_manager_;
fuchsia::ui::gfx::vec3 logical_size_;
fuchsia::ui::gfx::vec3 physical_size_;
fuchsia::ui::gfx::ViewProperties view_properties_;
fuchsia::ui::gfx::Metrics metrics_;
zx_time_t last_presentation_time_ = 0;
size_t session_present_count_ = 0;
bool invalidate_pending_ = false;
std::vector<PresentCallback> callbacks_for_next_present_;
bool present_pending_ = false;
bool enable_ime_ = false;
};
} // namespace scenic
#endif // SRC_LIB_UI_BASE_VIEW_BASE_VIEW_H_

View File

@@ -0,0 +1,48 @@
// 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.
#include "src/lib/ui/base_view/embedded_view_utils.h"
#include <lib/ui/scenic/cpp/view_ref_pair.h>
#include <lib/ui/scenic/cpp/view_token_pair.h>
#include "flutter/fml/logging.h"
namespace scenic {
EmbeddedViewInfo LaunchComponentAndCreateView(
const fuchsia::sys::LauncherPtr& launcher,
const std::string& component_url,
const std::vector<std::string>& component_args) {
FML_DCHECK(launcher);
EmbeddedViewInfo info;
// Configure the information to launch the component with.
fuchsia::sys::LaunchInfo launch_info;
info.app_services =
sys::ServiceDirectory::CreateWithRequest(&launch_info.directory_request);
launch_info.url = component_url;
launch_info.arguments = fidl::VectorPtr(
std::vector<std::string>(component_args.begin(), component_args.end()));
launcher->CreateComponent(std::move(launch_info),
info.controller.NewRequest());
info.view_provider =
info.app_services->Connect<fuchsia::ui::app::ViewProvider>();
auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
info.view_holder_token = std::move(view_holder_token);
auto [view_ref_control, view_ref] = scenic::ViewRefPair::New();
fidl::Clone(view_ref, &info.view_ref);
info.view_provider->CreateViewWithViewRef(std::move(view_token.value),
std::move(view_ref_control),
std::move(view_ref));
return info;
}
} // namespace scenic

View File

@@ -0,0 +1,58 @@
// 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.
#ifndef SRC_LIB_UI_BASE_VIEW_EMBEDDED_VIEW_UTILS_H_
#define SRC_LIB_UI_BASE_VIEW_EMBEDDED_VIEW_UTILS_H_
#include <fuchsia/ui/app/cpp/fidl.h>
#include <fuchsia/ui/gfx/cpp/fidl.h>
#include <fuchsia/ui/input/cpp/fidl.h>
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/sys/cpp/service_directory.h>
#include <lib/ui/scenic/cpp/resources.h>
#include <lib/ui/scenic/cpp/session.h>
namespace scenic {
// Serves as the return value for LaunchAppAndCreateView(), below.
struct EmbeddedViewInfo {
// Controls the launched app. The app will be destroyed if this connection
// is closed.
fuchsia::sys::ComponentControllerPtr controller;
// Services provided by the launched app. Must not be destroyed
// immediately, otherwise the |view_provider| connection may not be
// established.
std::shared_ptr<sys::ServiceDirectory> app_services;
// ViewProvider service obtained from the app via |app_services|. Must not
// be destroyed immediately, otherwise the call to CreateView() might not be
// processed.
fuchsia::ui::app::ViewProviderPtr view_provider;
// A token that can be used to create a ViewHolder; the corresponding token
// was provided to |view_provider| via ViewProvider.CreateView(). The
// launched app is expected to create a View, which will be connected to the
// ViewHolder created with this token.
fuchsia::ui::views::ViewHolderToken view_holder_token;
// The ViewRef of the embedded View.
fuchsia::ui::views::ViewRef view_ref;
};
// Launch a component and connect to its ViewProvider service, passing it the
// necessary information to attach itself as a child view2. Populates the
// returned EmbeddedViewInfo, which the caller can use to embed the child.
// For example, an interface to a ViewProvider is obtained, a pair of
// zx::eventpairs is created, CreateView is called, etc. This encapsulates
// the boilerplate the the client would otherwise write themselves.
EmbeddedViewInfo LaunchComponentAndCreateView(
const fuchsia::sys::LauncherPtr& launcher,
const std::string& component_url,
const std::vector<std::string>& component_args = {});
} // namespace scenic
#endif // SRC_LIB_UI_BASE_VIEW_EMBEDDED_VIEW_UTILS_H_

View File

@@ -0,0 +1,92 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_LIB_UI_BASE_VIEW_MATH_H_
#define SRC_LIB_UI_BASE_VIEW_MATH_H_
#include <fuchsia/ui/gfx/cpp/fidl.h>
namespace scenic {
// Return a vec3 consisting of the component-wise sum of the two arguments.
inline fuchsia::ui::gfx::vec3 operator+(const fuchsia::ui::gfx::vec3& a,
const fuchsia::ui::gfx::vec3& b) {
return {.x = a.x + b.x, .y = a.y + b.y, .z = a.z + b.z};
}
// Return a vec3 consisting of the component-wise difference of the two args.
inline fuchsia::ui::gfx::vec3 operator-(const fuchsia::ui::gfx::vec3& a,
const fuchsia::ui::gfx::vec3& b) {
return {.x = a.x - b.x, .y = a.y - b.y, .z = a.z - b.z};
}
// Return true if |point| is contained by |box|, including when it is on the
// box boundary, and false otherwise.
inline bool ContainsPoint(const fuchsia::ui::gfx::BoundingBox& box,
const fuchsia::ui::gfx::vec3& point) {
return point.x >= box.min.x && point.y >= box.min.y && point.z >= box.min.z &&
point.x <= box.max.x && point.y <= box.max.y && point.z <= box.max.z;
}
// Similar to fuchsia::ui::gfx::ViewProperties: adds the inset to box.min, and
// subtracts it from box.max.
inline fuchsia::ui::gfx::BoundingBox InsetBy(
const fuchsia::ui::gfx::BoundingBox& box,
const fuchsia::ui::gfx::vec3& inset) {
return {.min = box.min + inset, .max = box.max - inset};
}
// Similar to fuchsia::ui::gfx::ViewProperties: adds the inset to box.min, and
// subtracts it from box.max.
inline fuchsia::ui::gfx::BoundingBox InsetBy(
const fuchsia::ui::gfx::BoundingBox& box,
const fuchsia::ui::gfx::vec3& inset_from_min,
const fuchsia::ui::gfx::vec3& inset_from_max) {
return {.min = box.min + inset_from_min, .max = box.max - inset_from_max};
}
// Inset the view properties' outer box by its insets.
inline fuchsia::ui::gfx::BoundingBox ViewPropertiesLayoutBox(
const fuchsia::ui::gfx::ViewProperties& view_properties) {
return InsetBy(view_properties.bounding_box, view_properties.inset_from_min,
view_properties.inset_from_max);
}
// Return a vec3 consisting of the maximum x/y/z from the two arguments.
inline fuchsia::ui::gfx::vec3 Max(const fuchsia::ui::gfx::vec3& a,
const fuchsia::ui::gfx::vec3& b) {
return {.x = std::max(a.x, b.x),
.y = std::max(a.y, b.y),
.z = std::max(a.z, b.z)};
}
// Return a vec3 consisting of the maximum of the x/y/z components of |v|,
// compared with |min_val|.
inline fuchsia::ui::gfx::vec3 Max(const fuchsia::ui::gfx::vec3& v,
float min_val) {
return {.x = std::max(v.x, min_val),
.y = std::max(v.y, min_val),
.z = std::max(v.z, min_val)};
}
// Return a vec3 consisting of the minimum x/y/z from the two arguments.
inline fuchsia::ui::gfx::vec3 Min(const fuchsia::ui::gfx::vec3& a,
const fuchsia::ui::gfx::vec3& b) {
return {.x = std::min(a.x, b.x),
.y = std::min(a.y, b.y),
.z = std::min(a.z, b.z)};
}
// Return a vec3 consisting of the minimum of the x/y/z components of |v|,
// compared with |max_val|.
inline fuchsia::ui::gfx::vec3 Min(const fuchsia::ui::gfx::vec3& v,
float max_val) {
return {.x = std::min(v.x, max_val),
.y = std::min(v.y, max_val),
.z = std::min(v.z, max_val)};
}
} // namespace scenic
#endif // SRC_LIB_UI_BASE_VIEW_MATH_H_

View File

@@ -0,0 +1,24 @@
# 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("//build/fuchsia/sdk.gni")
source_set("views") {
testonly = true
sources = [
"color.cc",
"color.h",
"embedder_view.cc",
"embedder_view.h",
]
include_dirs = [ "//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/fuchsia_testing" ]
public_deps = [
"$fuchsia_sdk_root/pkg:scenic_cpp",
"//flutter/fml",
"//flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/fuchsia_testing/src/lib/ui/base_view",
]
}

View File

@@ -0,0 +1,77 @@
// 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.
#include <zircon/status.h>
#include "flutter/fml/logging.h"
#include "src/ui/testing/views/color.h"
namespace scenic {
// RGBA hex dump
std::ostream& operator<<(std::ostream& os, const Color& c) {
char rgba[9] = {};
snprintf(rgba, (sizeof(rgba) / sizeof(char)), "%02X%02X%02X%02X", c.r, c.g,
c.b, c.a);
return os << rgba;
}
Screenshot::Screenshot(
const fuchsia::ui::scenic::ScreenshotData& screenshot_data)
: width_(screenshot_data.info.width), height_(screenshot_data.info.height) {
FML_CHECK(screenshot_data.info.pixel_format ==
fuchsia::images::PixelFormat::BGRA_8)
<< "Non-BGRA_8 pixel formats not supported";
const auto& buffer = screenshot_data.data.vmo;
const auto num_bytes = screenshot_data.data.size;
data_.resize(num_bytes);
if (num_bytes == 0) {
return;
}
zx_status_t status = buffer.read(&data_[0], 0, num_bytes);
if (status < 0) {
FML_LOG(WARNING) << "zx::vmo::read failed " << zx_status_get_string(status);
}
}
const Color* Screenshot::operator[](size_t row) const {
return &begin()[row * width_];
}
const Color& Screenshot::ColorAt(float x, float y) const {
FML_CHECK(x >= 0 && x < 1 && y >= 0 && y < 1)
<< "(" << x << ", " << y << ") is out of bounds [0, 1) x [0, 1)";
const size_t ix = static_cast<size_t>(x * static_cast<float>(width_));
const size_t iy = static_cast<size_t>(y * static_cast<float>(height_));
return (*this)[iy][ix];
}
const Color& Screenshot::ColorAtPixelXY(size_t ix, size_t iy) const {
FML_CHECK(ix < width_ && iy < height_);
return (*this)[iy][ix];
}
const Color* Screenshot::begin() const {
return reinterpret_cast<const Color*>(data_.data());
}
const Color* Screenshot::end() const {
return &begin()[width_ * height_];
}
std::map<Color, size_t> Screenshot::Histogram() const {
std::map<Color, size_t> histogram;
for (const auto color : *this) {
++histogram[color];
}
return histogram;
}
} // namespace scenic

View File

@@ -0,0 +1,77 @@
// 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.
#ifndef SRC_UI_TESTING_VIEWS_COLOR_H_
#define SRC_UI_TESTING_VIEWS_COLOR_H_
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <map>
#include <ostream>
#include <tuple>
namespace scenic {
struct Color {
// Constructor is idiomatic RGBA, but memory layout is native BGRA.
constexpr Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
: b(b), g(g), r(r), a(a) {}
uint8_t b;
uint8_t g;
uint8_t r;
uint8_t a;
};
inline bool operator==(const Color& a, const Color& b) {
return a.r == b.r && a.g == b.g && a.b == b.b && a.a == b.a;
}
inline bool operator<(const Color& a, const Color& b) {
return std::tie(a.r, a.g, a.b, a.a) < std::tie(b.r, b.g, b.b, b.a);
}
// RGBA hex dump. Note that this differs from the internal BGRA memory layout.
std::ostream& operator<<(std::ostream& os, const Color& c);
class Screenshot {
public:
Screenshot(const fuchsia::ui::scenic::ScreenshotData& screenshot_data);
size_t width() const { return width_; }
size_t height() const { return height_; }
bool empty() const { return width_ == 0 || height_ == 0; }
// Notably the indexer behaves like a row-major matrix, whereas the iterator
// behaves like a flat array. *IMPORTANT*: Use caution because index values
// are not validated, and out of bounds indexes can introduce memory errors.
// Also when indexing a specific pixel with |screenshot[a][b]|, note that
// the order of the indexes is non-traditional. The first index is for the
// |y| position (the row), followed by the |x| position. Consider using
// |ColorAtPixelXY()| instead.
const Color* operator[](size_t row) const;
// Coordinates are in the range [0, 1).
const Color& ColorAt(float x, float y) const;
// Returns the color of a pixel at the integer x and y indexes, after
// asserting that the indexes are in range.
const Color& ColorAtPixelXY(size_t ix, size_t iy) const;
// Notably the iterator behaves like a flat array, whereas the indexer behaves
// like a row-major matrix.
const Color* begin() const;
const Color* end() const;
// Counts the frequencies of each color in a screenshot.
std::map<Color, size_t> Histogram() const;
private:
const size_t width_, height_;
std::vector<uint8_t> data_;
};
} // namespace scenic
#endif // SRC_UI_TESTING_VIEWS_COLOR_H_

View File

@@ -0,0 +1,88 @@
// 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.
#include <zircon/status.h>
#include "flutter/fml/logging.h"
#include "src/ui/testing/views/embedder_view.h"
namespace scenic {
EmbedderView::EmbedderView(ViewContext context, const std::string& debug_name)
: binding_(this, std::move(context.session_and_listener_request.second)),
session_(std::move(context.session_and_listener_request.first)),
view_(&session_, std::move(context.view_token), debug_name),
top_node_(&session_) {
binding_.set_error_handler([](zx_status_t status) {
FML_LOG(FATAL) << "Session listener binding: "
<< zx_status_get_string(status);
});
view_.AddChild(top_node_);
// Call |Session::Present| in order to flush events having to do with
// creation of |view_| and |top_node_|.
session_.Present(0, [](auto) {});
}
// Sets the EmbeddedViewInfo and attaches the embedded View to the scene. Any
// callbacks for the embedded View's ViewState are delivered to the supplied
// callback.
void EmbedderView::EmbedView(EmbeddedViewInfo info,
std::function<void(fuchsia::ui::gfx::ViewState)>
view_state_changed_callback) {
// Only one EmbeddedView is currently supported.
FML_CHECK(!embedded_view_);
embedded_view_ = std::make_unique<EmbeddedView>(
std::move(info), &session_, std::move(view_state_changed_callback));
// Attach the embedded view to the scene.
top_node_.Attach(embedded_view_->view_holder);
// Call |Session::Present| to apply the embedded view to the scene graph.
session_.Present(0, [](auto) {});
}
void EmbedderView::OnScenicEvent(
std::vector<fuchsia::ui::scenic::Event> events) {
for (const auto& event : events) {
if (event.Which() == fuchsia::ui::scenic::Event::Tag::kGfx &&
event.gfx().Which() ==
fuchsia::ui::gfx::Event::Tag::kViewPropertiesChanged) {
const auto& evt = event.gfx().view_properties_changed();
// Naively apply the parent's ViewProperties to any EmbeddedViews.
if (embedded_view_) {
embedded_view_->view_holder.SetViewProperties(
std::move(evt.properties));
session_.Present(0, [](auto) {});
}
} else if (event.Which() == fuchsia::ui::scenic::Event::Tag::kGfx &&
event.gfx().Which() ==
fuchsia::ui::gfx::Event::Tag::kViewStateChanged) {
const auto& evt = event.gfx().view_state_changed();
if (embedded_view_ &&
evt.view_holder_id == embedded_view_->view_holder.id()) {
// Clients of |EmbedderView| *must* set a view state changed
// callback. Failure to do so is a usage error.
FML_CHECK(embedded_view_->view_state_changed_callback);
embedded_view_->view_state_changed_callback(evt.state);
}
}
}
}
void EmbedderView::OnScenicError(std::string error) {
FML_LOG(FATAL) << "OnScenicError: " << error;
}
EmbedderView::EmbeddedView::EmbeddedView(
EmbeddedViewInfo info,
Session* session,
std::function<void(fuchsia::ui::gfx::ViewState)> view_state_callback,
const std::string& debug_name)
: embedded_info(std::move(info)),
view_holder(session,
std::move(embedded_info.view_holder_token),
debug_name + " ViewHolder"),
view_state_changed_callback(std::move(view_state_callback)) {}
} // namespace scenic

View File

@@ -0,0 +1,59 @@
// 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.
#ifndef SRC_UI_TESTING_VIEWS_EMBEDDER_VIEW_H_
#define SRC_UI_TESTING_VIEWS_EMBEDDER_VIEW_H_
#include <fuchsia/ui/scenic/cpp/fidl.h>
#include <lib/ui/scenic/cpp/resources.h>
#include <lib/ui/scenic/cpp/session.h>
#include "src/lib/ui/base_view/base_view.h"
namespace scenic {
// This is a simplified |BaseView| that exposes view state events.
//
// See also lib/ui/base_view.
class EmbedderView : public fuchsia::ui::scenic::SessionListener {
public:
EmbedderView(ViewContext context,
const std::string& debug_name = "EmbedderView");
// Sets the EmbeddedViewInfo and attaches the embedded View to the scene. Any
// callbacks for the embedded View's ViewState are delivered to the supplied
// callback.
void EmbedView(EmbeddedViewInfo info,
std::function<void(fuchsia::ui::gfx::ViewState)>
view_state_changed_callback);
private:
// |fuchsia::ui::scenic::SessionListener|
void OnScenicEvent(std::vector<fuchsia::ui::scenic::Event> events) override;
// |fuchsia::ui::scenic::SessionListener|
void OnScenicError(std::string error) override;
struct EmbeddedView {
EmbeddedView(
EmbeddedViewInfo info,
Session* session,
std::function<void(fuchsia::ui::gfx::ViewState)> view_state_callback,
const std::string& debug_name = "EmbedderView");
EmbeddedViewInfo embedded_info;
ViewHolder view_holder;
std::function<void(fuchsia::ui::gfx::ViewState)>
view_state_changed_callback;
};
fidl::Binding<fuchsia::ui::scenic::SessionListener> binding_;
Session session_;
View view_;
EntityNode top_node_;
std::optional<fuchsia::ui::gfx::ViewProperties> embedded_view_properties_;
std::unique_ptr<EmbeddedView> embedded_view_;
};
} // namespace scenic
#endif // SRC_UI_TESTING_VIEWS_EMBEDDER_VIEW_H_

View File

@@ -1,27 +1,36 @@
# This configuration file specifies several test suites with their package and
# test command for femu_test.py.
- package: flutter_runner_tzdata_tests-0.far
test_command: run-test-suite fuchsia-pkg://fuchsia.com/flutter_runner_tzdata_tests#meta/flutter_runner_tzdata_tests.cm
- package: fml_tests-0.far
test_command: run-test-suite fuchsia-pkg://fuchsia.com/fml_tests#meta/fml_tests.cm -- --gtest_filter=-MessageLoop.TimeSensitiveTest_*:FileTest.CanTruncateAndWrite:FileTest.CreateDirectoryStructure
- package: flow_tests-0.far
test_command: run-test-suite fuchsia-pkg://fuchsia.com/flow_tests#meta/flow_tests.cm
- package: runtime_tests-0.far
test_command: run-test-suite fuchsia-pkg://fuchsia.com/runtime_tests#meta/runtime_tests.cm
- package: shell_tests-0.far
test_command: run-test-suite fuchsia-pkg://fuchsia.com/shell_tests#meta/shell_tests.cm -- --gtest_filter=-ShellTest.ReportTimingsIsCalledLaterInReleaseMode:ShellTest.ReportTimingsIsCalledSoonerInNonReleaseMode:ShellTest.DisallowedDartVMFlag:FuchsiaShellTest.LocaltimesVaryOnTimezoneChanges
- package: testing_tests-0.far
test_command: run-test-suite fuchsia-pkg://fuchsia.com/testing_tests#meta/testing_tests.cm
- package: txt_tests-0.far
test_command: run-test-suite fuchsia-pkg://fuchsia.com/txt_tests#meta/txt_tests.cm -- --gtest_filter=-ParagraphTest.*
- package: ui_tests-0.far
test_command: run-test-suite fuchsia-pkg://fuchsia.com/ui_tests#meta/ui_tests.cm
- package: embedder_tests-0.far
test_command: run-test-suite fuchsia-pkg://fuchsia.com/embedder_tests#meta/embedder_tests.cm
- package: dart_utils_tests-0.far
test_command: run-test-suite fuchsia-pkg://fuchsia.com/dart_utils_tests#meta/dart_utils_tests.cm
# Legacy Component Framework v1 components.
- test_command: run-test-component fuchsia-pkg://fuchsia.com/flutter_runner_tests#meta/flutter_runner_tests.cmx
package: flutter_runner_tests-0.far
# TODO(richkadel): Enable this test once the CI fuchsia image for femu tests has been updated to
# meet the test requirements. Changes are in progress to support this test.
# - test_command: run-test-component fuchsia-pkg://fuchsia.com/flutter-embedder-test2#meta/flutter-embedder-test2.cmx
# packages:
# - flutter-embedder-test2-0.far
# - gen/flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/child-view2/child-view2/child-view2.far
# - gen/flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/parent-view2/parent-view2/parent-view2.far
# - flutter_jit_runner-0.far
# Legacy v1 components.
- package: flutter_runner_tests-0.far
test_command: run-test-component fuchsia-pkg://fuchsia.com/flutter_runner_tests#meta/flutter_runner_tests.cmx
# v2 components.
- test_command: run-test-suite fuchsia-pkg://fuchsia.com/flutter_runner_tzdata_tests#meta/flutter_runner_tzdata_tests.cm
package: flutter_runner_tzdata_tests-0.far
- test_command: run-test-suite fuchsia-pkg://fuchsia.com/fml_tests#meta/fml_tests.cm -- --gtest_filter=-MessageLoop.TimeSensitiveTest_*:FileTest.CanTruncateAndWrite:FileTest.CreateDirectoryStructure
package: fml_tests-0.far
- test_command: run-test-suite fuchsia-pkg://fuchsia.com/flow_tests#meta/flow_tests.cm
package: flow_tests-0.far
- test_command: run-test-suite fuchsia-pkg://fuchsia.com/runtime_tests#meta/runtime_tests.cm
package: runtime_tests-0.far
- test_command: run-test-suite fuchsia-pkg://fuchsia.com/shell_tests#meta/shell_tests.cm -- --gtest_filter=-ShellTest.ReportTimingsIsCalledLaterInReleaseMode:ShellTest.ReportTimingsIsCalledSoonerInNonReleaseMode:ShellTest.DisallowedDartVMFlag:FuchsiaShellTest.LocaltimesVaryOnTimezoneChanges
package: shell_tests-0.far
- test_command: run-test-suite fuchsia-pkg://fuchsia.com/testing_tests#meta/testing_tests.cm
package: testing_tests-0.far
- test_command: run-test-suite fuchsia-pkg://fuchsia.com/txt_tests#meta/txt_tests.cm -- --gtest_filter=-ParagraphTest.*
package: txt_tests-0.far
- test_command: run-test-suite fuchsia-pkg://fuchsia.com/ui_tests#meta/ui_tests.cm
package: ui_tests-0.far
- test_command: run-test-suite fuchsia-pkg://fuchsia.com/embedder_tests#meta/embedder_tests.cm
package: embedder_tests-0.far
- test_command: run-test-suite fuchsia-pkg://fuchsia.com/dart_utils_tests#meta/dart_utils_tests.cm
package: dart_utils_tests-0.far

View File

@@ -1,84 +1,17 @@
out/fuchsia_debug_x64/dart_aot_runner_package_manifest.json
out/fuchsia_debug_x64/dart_jit_runner_package_manifest.json
out/fuchsia_debug_x64/embedder_tests_package_manifest.json
out/fuchsia_debug_x64/flow_tests_package_manifest.json
out/fuchsia_debug_x64/flutter_aot_runner_package_manifest.json
out/fuchsia_debug_x64/flutter_jit_runner_package_manifest.json
out/fuchsia_debug_x64/flutter_runner_tests_package_manifest.json
out/fuchsia_debug_x64/flutter_runner_tzdata_tests_package_manifest.json
out/fuchsia_debug_x64/fml_tests_package_manifest.json
out/fuchsia_debug_x64/runtime_tests_package_manifest.json
out/fuchsia_debug_x64/shell_tests_package_manifest.json
out/fuchsia_debug_x64/testing_tests_package_manifest.json
out/fuchsia_debug_x64/txt_tests_package_manifest.json
out/fuchsia_debug_x64/ui_tests_package_manifest.json
out/fuchsia_release_x64/dart_aot_runner_package_manifest.json
out/fuchsia_release_x64/dart_jit_runner_package_manifest.json
out/fuchsia_release_x64/embedder_tests_package_manifest.json
out/fuchsia_release_x64/flow_tests_package_manifest.json
out/fuchsia_release_x64/flutter_aot_runner_package_manifest.json
out/fuchsia_release_x64/flutter_jit_runner_package_manifest.json
out/fuchsia_release_x64/flutter_runner_tests_package_manifest.json
out/fuchsia_release_x64/flutter_runner_tzdata_tests_package_manifest.json
out/fuchsia_release_x64/fml_tests_package_manifest.json
out/fuchsia_release_x64/runtime_tests_package_manifest.json
out/fuchsia_release_x64/shell_tests_package_manifest.json
out/fuchsia_release_x64/testing_tests_package_manifest.json
out/fuchsia_release_x64/txt_tests_package_manifest.json
out/fuchsia_release_x64/ui_tests_package_manifest.json
out/fuchsia_profile_x64/dart_aot_runner_package_manifest.json
out/fuchsia_profile_x64/dart_jit_runner_package_manifest.json
out/fuchsia_profile_x64/embedder_tests_package_manifest.json
out/fuchsia_profile_x64/flow_tests_package_manifest.json
out/fuchsia_profile_x64/flutter_aot_runner_package_manifest.json
out/fuchsia_profile_x64/flutter_jit_runner_package_manifest.json
out/fuchsia_profile_x64/flutter_runner_tests_package_manifest.json
out/fuchsia_profile_x64/flutter_runner_tzdata_tests_package_manifest.json
out/fuchsia_profile_x64/fml_tests_package_manifest.json
out/fuchsia_profile_x64/runtime_tests_package_manifest.json
out/fuchsia_profile_x64/shell_tests_package_manifest.json
out/fuchsia_profile_x64/testing_tests_package_manifest.json
out/fuchsia_profile_x64/txt_tests_package_manifest.json
out/fuchsia_profile_x64/ui_tests_package_manifest.json
out/fuchsia_debug_arm64/dart_aot_runner_package_manifest.json
out/fuchsia_debug_arm64/dart_jit_runner_package_manifest.json
out/fuchsia_debug_arm64/embedder_tests_package_manifest.json
out/fuchsia_debug_arm64/flow_tests_package_manifest.json
out/fuchsia_debug_arm64/flutter_aot_runner_package_manifest.json
out/fuchsia_debug_arm64/flutter_jit_runner_package_manifest.json
out/fuchsia_debug_arm64/flutter_runner_tests_package_manifest.json
out/fuchsia_debug_arm64/flutter_runner_tzdata_tests_package_manifest.json
out/fuchsia_debug_arm64/fml_tests_package_manifest.json
out/fuchsia_debug_arm64/runtime_tests_package_manifest.json
out/fuchsia_debug_arm64/shell_tests_package_manifest.json
out/fuchsia_debug_arm64/testing_tests_package_manifest.json
out/fuchsia_debug_arm64/txt_tests_package_manifest.json
out/fuchsia_debug_arm64/ui_tests_package_manifest.json
out/fuchsia_release_arm64/dart_aot_runner_package_manifest.json
out/fuchsia_release_arm64/dart_jit_runner_package_manifest.json
out/fuchsia_release_arm64/embedder_tests_package_manifest.json
out/fuchsia_release_arm64/flow_tests_package_manifest.json
out/fuchsia_release_arm64/flutter_aot_runner_package_manifest.json
out/fuchsia_release_arm64/flutter_jit_runner_package_manifest.json
out/fuchsia_release_arm64/flutter_runner_tests_package_manifest.json
out/fuchsia_release_arm64/flutter_runner_tzdata_tests_package_manifest.json
out/fuchsia_release_arm64/fml_tests_package_manifest.json
out/fuchsia_release_arm64/runtime_tests_package_manifest.json
out/fuchsia_release_arm64/shell_tests_package_manifest.json
out/fuchsia_release_arm64/testing_tests_package_manifest.json
out/fuchsia_release_arm64/txt_tests_package_manifest.json
out/fuchsia_release_arm64/ui_tests_package_manifest.json
out/fuchsia_profile_arm64/dart_aot_runner_package_manifest.json
out/fuchsia_profile_arm64/dart_jit_runner_package_manifest.json
out/fuchsia_profile_arm64/embedder_tests_package_manifest.json
out/fuchsia_profile_arm64/flow_tests_package_manifest.json
out/fuchsia_profile_arm64/flutter_aot_runner_package_manifest.json
out/fuchsia_profile_arm64/flutter_jit_runner_package_manifest.json
out/fuchsia_profile_arm64/flutter_runner_tests_package_manifest.json
out/fuchsia_profile_arm64/flutter_runner_tzdata_tests_package_manifest.json
out/fuchsia_profile_arm64/fml_tests_package_manifest.json
out/fuchsia_profile_arm64/runtime_tests_package_manifest.json
out/fuchsia_profile_arm64/shell_tests_package_manifest.json
out/fuchsia_profile_arm64/testing_tests_package_manifest.json
out/fuchsia_profile_arm64/txt_tests_package_manifest.json
out/fuchsia_profile_arm64/ui_tests_package_manifest.json
dart_aot_runner_package_manifest.json
dart_jit_runner_package_manifest.json
embedder_tests_package_manifest.json
flow_tests_package_manifest.json
flutter_aot_runner_package_manifest.json
flutter-embedder-test2_package_manifest.json
flutter_jit_runner_package_manifest.json
flutter_runner_tests_package_manifest.json
flutter_runner_tzdata_tests_package_manifest.json
fml_tests_package_manifest.json
gen/flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/child-view2/child-view2/package_manifest.json
gen/flutter/shell/platform/fuchsia/flutter/integration_flutter_tests/embedder/parent-view2/parent-view2/package_manifest.json
runtime_tests_package_manifest.json
shell_tests_package_manifest.json
testing_tests_package_manifest.json
txt_tests_package_manifest.json
ui_tests_package_manifest.json

View File

@@ -47,6 +47,15 @@ function engine-error {
fi
}
# engine-warning prints a line to stderr with a yellow WARNING: prefix.
function engine-warning {
if engine-is-stderr-tty; then
echo -e >&2 "\033[1;33mWARNING:\033[0m $*"
else
echo -e >&2 "WARNING: $*"
fi
}
function ensure_fuchsia_dir() {
if [[ -z "${FUCHSIA_DIR}" ]]; then
engine-error "A valid fuchsia.git checkout is required." \

View File

@@ -21,6 +21,7 @@ ensure_fuchsia_dir
out=""
port="8084"
component_framework_version=2
device_name=""
remote=false
only_serve_runners=false
@@ -30,6 +31,13 @@ while (($#)); do
out="$2"
shift
;;
-c)
component_framework_version="$2"
# for `pm serve` `config.json` and if "2" (the default for this script)
# use `pkgctl add` (which is not supported on older instances of fuchsia)
# instead of `amberctl add_src`.
shift
;;
-p)
port="$2"
shift
@@ -56,15 +64,68 @@ if [[ -z "${out}" ]]; then
exit 1
fi
if [[ ${component_framework_version} != [12] ]]; then
engine-error "valid values for -c are 1 or 2"
exit 1
fi
fuchsia_build_dir="$(<"${FUCHSIA_DIR}/.fx-build-dir")"
if [[ "${fuchsia_build_dir:0:1}" != "/" ]]; then
fuchsia_build_dir="${FUCHSIA_DIR}/${fuchsia_build_dir}"
fi
# If remote, there is currently no equivalent check, but perhaps there could be?
if [[ $remote != true ]]; then
# Warn if the package server for the fuchsia packages is not running. Test
# runners and any fuchsia package dependencies not included in the fuchsia
# system image (via `--with-base` instead of `--with`) typically require
# running `fx serve` (or equivalent commands), for the default `fuchsia.com`
# (`devhost`) package URL domain.
active_fuchsia_repo=$(
ps -eo args \
| sed -nre \
"s#.*\bpm .*\bserve\b.* -repo ($FUCHSIA_DIR/out/.*)/amber-files.*#\1#p"
)
if [[ "${active_fuchsia_repo}" == "" ]]; then
engine-warning 'The default fuchsia package server may not be running.'
echo 'If your test requires packages or test runners from fuchsia, those'
echo 'packages will need to be bundled in the fuchsia system image (such as'
echo 'via `fx set ... --with-base <package_target> ...). If your test'
echo 'includes fuchsia package dependencies that need to be served, kill'
echo 'this flutter "engine" package server first, run `fx serve` (in'
echo 'another window or shell), and then re-run this `serve.sh` script.'
echo '(The launch order is important.)'
elif [[ "${active_fuchsia_repo}" != "${fuchsia_build_dir}" ]]; then
engine-warning 'There default fuchsia package server may be'
echo 'serving packages from the wrong build directory:'
echo " ${active_fuchsia_repo}"
echo 'which does not match your current build directory:'
echo " ${fuchsia_build_dir}"
echo 'It may be serving the wrong packages. If so, kill all package'
echo 'servers, and restart them. Make sure you start the fuchsia package'
echo 'server (for example, via `fx serve`) **before** starting this'
echo '`serve.sh` script'
fi
fi
# Start our package server
# TODO: Need to ask for the out directory to find the package list
# TODO: Generate the all_packages.list file
cd "${FLUTTER_ENGINE_SRC_DIR}" || exit
cd "${FLUTTER_ENGINE_SRC_DIR}/${out}" || exit
if ! [[ -d "${FLUTTER_ENGINE_SRC_DIR}/${out}/tuf" ]]; then
# Create the repository to serve
"${FLUTTER_ENGINE_FUCHSIA_SDK_DIR}/tools/pm" newrepo -vt \
-repo "${FLUTTER_ENGINE_SRC_DIR}/${out}/tuf"
fi
# Serve packages (run as a background process)
"${FLUTTER_ENGINE_FUCHSIA_SDK_DIR}/tools/pm" serve -vt \
-repo "${FLUTTER_ENGINE_FUCHSIA_SDK_DIR}/${out}/tuf" \
-repo "${FLUTTER_ENGINE_SRC_DIR}/${out}/tuf" \
-l ":${port}" \
-c 2 \
-p "${FLUTTER_ENGINE_SRC_DIR}/flutter/tools/fuchsia/all_packages.list"&
-c "${component_framework_version}" \
-p "${FLUTTER_ENGINE_SRC_DIR}/flutter/tools/fuchsia/all_packages.list" \
&
serve_pid=$!
# Add debug symbols to the symbol index.
@@ -119,8 +180,7 @@ run_ssh_command() {
return 1
fi
build_dir="$(<"${FUCHSIA_DIR}/.fx-build-dir")"
ssh_config="${FUCHSIA_DIR}/${build_dir}/ssh-keys/ssh_config"
ssh_config="${fuchsia_build_dir}/ssh-keys/ssh_config"
if [[ ! -e $ssh_config ]]; then
engine-error "No valid ssh_config at $ssh_config"
fi
@@ -132,10 +192,19 @@ run_ssh_command() {
fi
}
if [[ $remote != true && -z "${device_name}" ]]; then
device_name="$(cat ${fuchsia_build_dir}.device)"
fi
echo -n "Connecting to "
if $remote; then
echo -n "remote device via ssh tunnel on port 8022..."
else
echo -n "device '${device_name}', port ${port}..."
fi
# State is used to prevent too much output
state="discover"
while true; do
sleep 1
if ! kill -0 "${serve_pid}" 2> /dev/null; then
echo "Server died, exiting"
serve_pid=
@@ -155,6 +224,7 @@ while true; do
fi
if [[ "$state" == "discover" && "$ping_result" == 0 ]]; then
echo
echo "Device up"
state="config"
fi
@@ -175,9 +245,16 @@ while true; do
fi
config_url="http://${addr}:${port}/config.json"
run_ssh_command pkgctl add \
-n "engine" \
"${config_url}"
if [[ ${component_framework_version} == 2 ]]; then
run_ssh_command pkgctl repo add \
-n "engine" \
"${config_url}"
else
run_ssh_command amberctl add_src \
-n "engine" \
-f "${config_url}"
fi
err=$?
if [[ $err -ne 0 ]]; then
@@ -186,47 +263,51 @@ while true; do
fi
if [[ $only_serve_runners == true ]]; then
run_ssh_command "pkgctl rule replace json '
{
\"version\": \"1\",
\"content\": [
{
\"host_match\": \"fuchsia.com\", \"host_replacement\": \"engine\",
\"path_prefix_match\": \"/flutter_jit_runner/\", \"path_prefix_replacement\": \"/flutter_jit_runner/\"
},
{
\"host_match\": \"fuchsia.com\", \"host_replacement\": \"engine\",
\"path_prefix_match\": \"/flutter_jit_runner\", \"path_prefix_replacement\": \"/flutter_jit_runner\"
},
{
\"host_match\": \"fuchsia.com\", \"host_replacement\": \"engine\",
\"path_prefix_match\": \"/flutter_aot_runner/\", \"path_prefix_replacement\": \"/flutter_aot_runner/\"
},
{
\"host_match\": \"fuchsia.com\", \"host_replacement\": \"engine\",
\"path_prefix_match\": \"/flutter_aot_runner\", \"path_prefix_replacement\": \"/flutter_aot_runner\"
},
{
\"host_match\": \"fuchsia.com\", \"host_replacement\": \"engine\",
\"path_prefix_match\": \"/dart_jit_runner/\", \"path_prefix_replacement\": \"/dart_jit_runner/\"
},
{
\"host_match\": \"fuchsia.com\", \"host_replacement\": \"engine\",
\"path_prefix_match\": \"/dart_jit_runner\", \"path_prefix_replacement\": \"/dart_jit_runner\"
},
{
\"host_match\": \"fuchsia.com\", \"host_replacement\": \"engine\",
\"path_prefix_match\": \"/dart_aot_runner/\", \"path_prefix_replacement\": \"/dart_aot_runner/\"
},
{
\"host_match\": \"fuchsia.com\", \"host_replacement\": \"engine\",
\"path_prefix_match\": \"/dart_aot_runner\", \"path_prefix_replacement\": \"/dart_aot_runner\"
},
{
\"host_match\": \"fuchsia.com\", \"host_replacement\": \"devhost\",
\"path_prefix_match\": \"/\", \"path_prefix_replacement\": \"/\"
}]
}'"
run_ssh_command "pkgctl rule replace json '$(cat <<EOF
{
"version": "1",
"content": [
{
"host_match": "fuchsia.com", "host_replacement": "engine",
"path_prefix_match": "/flutter_jit_runner/", "path_prefix_replacement": "/flutter_jit_runner/"
},
{
"host_match": "fuchsia.com", "host_replacement": "engine",
"path_prefix_match": "/flutter_jit_runner", "path_prefix_replacement": "/flutter_jit_runner"
},
{
"host_match": "fuchsia.com", "host_replacement": "engine",
"path_prefix_match": "/flutter_aot_runner/", "path_prefix_replacement": "/flutter_aot_runner/"
},
{
"host_match": "fuchsia.com", "host_replacement": "engine",
"path_prefix_match": "/flutter_aot_runner", "path_prefix_replacement": "/flutter_aot_runner"
},
{
"host_match": "fuchsia.com", "host_replacement": "engine",
"path_prefix_match": "/dart_jit_runner/", "path_prefix_replacement": "/dart_jit_runner/"
},
{
"host_match": "fuchsia.com", "host_replacement": "engine",
"path_prefix_match": "/dart_jit_runner", "path_prefix_replacement": "/dart_jit_runner"
},
{
"host_match": "fuchsia.com", "host_replacement": "engine",
"path_prefix_match": "/dart_aot_runner/", "path_prefix_replacement": "/dart_aot_runner/"
},
{
"host_match": "fuchsia.com", "host_replacement": "engine",
"path_prefix_match": "/dart_aot_runner", "path_prefix_replacement": "/dart_aot_runner"
},
{
"host_match": "fuchsia.com", "host_replacement": "devhost",
"path_prefix_match": "/", "path_prefix_replacement": "/"
}
]
}
EOF
)'"
err=$?
if [[ $err -ne 0 ]]; then
engine-error "Failed to add runner rewrite rules"
@@ -244,6 +325,8 @@ while true; do
else
sleep 1
fi
else
sleep 1
echo -n "."
fi
done

View File

@@ -77,7 +77,7 @@ def main():
response_file = []
response_file.append('--experimental allow_new_syntax')
response_file.append('--experimental new_syntax_only')
if args.json:
response_file.append("--json %s" % args.json)

View File

@@ -10,7 +10,7 @@
# launch the vm service in the runner.
flutter_debug_build_cfg = {
runtime_meta = "//flutter/shell/platform/fuchsia/flutter/meta/jit_runtime"
runner_dep = "//flutter/shell/platform/fuchsia/flutter:jit"
runner_dep = "//flutter/shell/platform/fuchsia/flutter:flutter_jit_runner"
platform_name = "flutter_runner"
is_aot = false
is_product = false
@@ -26,7 +26,7 @@ flutter_debug_build_cfg = {
# # profile aot runner is built without asserts.
# flutter_aot_debug_build_cfg = {
# runtime_meta = "//flutter/shell/platform/fuchsia/flutter/meta/aot_runtime"
# runner_dep = "//flutter/shell/platform/fuchsia/flutter:aot"
# runner_dep = "//flutter/shell/platform/fuchsia/flutter:flutter_aot_runner"
# platform_name = "flutter_runner"
# is_aot = true
# is_product = false
@@ -39,7 +39,7 @@ flutter_debug_build_cfg = {
# runtime_meta =
# "//flutter/shell/platform/fuchsia/flutter/meta/aot_runtime" # profile
# # runner
# runner_dep = "//flutter/shell/platform/fuchsia/flutter:aot"
# runner_dep = "//flutter/shell/platform/fuchsia/flutter:flutter_aot_runner"
# platform_name = "flutter_runner"
# is_aot = true
# is_product = false
@@ -51,7 +51,7 @@ flutter_debug_build_cfg = {
# flutter_release_build_cfg = {
# runtime_meta =
# "//flutter/shell/platform/fuchsia/flutter/meta/aot_product_runtime"
# runner_dep = "//flutter/shell/platform/fuchsia/flutter:aot_product"
# runner_dep = "//flutter/shell/platform/fuchsia/flutter:flutter_aot_product_runner"
# platform_name = "flutter_runner"
# is_aot = true
# is_product = true

View File

@@ -118,8 +118,10 @@ template("flutter_component") {
_main_dart = "main.dart"
}
# We need to specify the runner as a dependency to be bundled with the dill
# files generated by dart_kernel.
# We need to specify the runner as a dependency (at least when running a
# flutter/engine-built package using a flutter/engine-built runner). Add it
# to `deps` so the runner will also be built, and available to serve to
# fuchsia, alongside the flutter_component's package.
_component_deps += [ _build_cfg.runner_dep ]
flutter_dart_component(target_name) {

View File

@@ -1,96 +0,0 @@
#!/usr/bin/env python3
#
# 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.
""" Resolve a dart third_party library dependency by returning the path to an
existing downloaded version one of a few possible subdirectories under
//third_party. Some of these pre-downloaded libraries may be directly downloaded
via a //flutter/DEPS entry. Others may be bundled with the Dart SDK, in one of
its provided libraries or its third_party packages.
"""
import argparse
import json
import os
import sys
import pkg_resources
THIS_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path += [os.path.join(
THIS_DIR, '..', '..', '..', '..', 'third_party', 'pyyaml', 'lib3')]
import yaml
def find_package(root, local_paths, package, version):
"""Return the package target if found with at least this version"""
needed_version = pkg_resources.parse_version(version)
for local_path in local_paths:
package_path = os.path.join(local_path, package)
pubspec_yaml = os.path.join(root, package_path, 'pubspec.yaml')
if os.path.exists(pubspec_yaml):
with open(pubspec_yaml) as yaml_file:
pubspec = yaml.safe_load(yaml_file)
found_version = pkg_resources.parse_version(pubspec['version'])
if found_version >= needed_version:
return "//" + package_path
return None
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--ignore-missing',
action='store_true',
help=('Return a success exit status, with all matched dart libraries, '
'even if one or more matches were not found'))
parser.add_argument(
'--root',
help='Path to the flutter engine src root',
required=True)
parser.add_argument(
'--target',
help='The name of the target that consolidates the derived deps',
required=True)
parser.add_argument(
'--local-path',
help=('A parent directory of pre-existing third_party dart libraries '
'(multiple --local-path arguments allowed)'),
action='append',
dest='local_paths',
required=True)
(args, versioned_dart_packages) = parser.parse_known_args()
assert os.path.exists(args.root)
for path in args.local_paths:
assert os.path.isdir(os.path.join(args.root, path))
if len(versioned_dart_packages) > 0:
assert len(versioned_dart_packages) % 2 == 0, (
'Each third_party_dep package must be accompanied by a version')
dart_package_paths = []
it = iter(versioned_dart_packages)
for item in it:
(package, version) = item, next(it)
path = find_package(args.root, args.local_paths, package, version)
if path is not None:
dart_package_paths.append(path)
else:
print(
'No package found for %s with version %s' % (package, version),
file=sys.stderr)
if not args.ignore_missing:
return 1
json.dump(dart_package_paths, sys.stdout)
return 0
if __name__ == '__main__':
sys.exit(main())

View File

@@ -63,21 +63,9 @@ template("_fuchsia_dart_library") {
}
foreach(third_party_dep, meta.third_party_deps) {
name = third_party_dep.name
version = third_party_dep.version
args += [
name,
version,
]
_deps += [ "//flutter/shell/platform/fuchsia/dart:" + third_party_dep.name ]
}
third_party_deps_json =
exec_script("//flutter/tools/fuchsia/sdk/find_dart_libraries.py",
args,
"json")
_deps += third_party_deps_json
dart_library(target_name) {
package_root = "${_fuchsia_sdk_path}/${meta.root}"
package_name = _output_name